<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Cartera;
use App\DetalleCartera;
use App\User;
use App\Persona;
use App\Services\CarteraService;

class CarteraController extends Controller
{
    public function index(Request $request)
    {
        if (!$request->ajax()) return redirect('/');

        $carteraService = new CarteraService();
        
        $filtros = [
            'estado' => $request->estado,
            'cliente_id' => $request->cliente_id,
            'fecha_desde' => $request->fecha_desde,
            'fecha_hasta' => $request->fecha_hasta
        ];
        
        $carteras = $carteraService->obtenerCarteras($filtros);
        
        return [
            'pagination' => [
                'total'        => $carteras->total(),
                'current_page' => $carteras->currentPage(),
                'per_page'     => $carteras->perPage(),
                'last_page'    => $carteras->lastPage(),
                'from'         => $carteras->firstItem(),
                'to'           => $carteras->lastItem(),
            ],
            'carteras' => $carteras
        ];
    }

    public function selectCliente(Request $request){
        if (!$request->ajax()) return redirect('/');
        $clientes = Persona::where('tipo_persona','=','Cliente')
        ->select('id','nombre','num_documento')->orderBy('nombre', 'asc')->get();
        return ['clientes' => $clientes];
    }
    
    public function testData(){
        try {
            $totalClientes = Persona::where('tipo_persona', 'Cliente')->count();
            $totalCarteras = Cartera::count();
            $totalVentas = \App\Venta::count();
            
            return [
                'success' => true,
                'data' => [
                    'clientes' => $totalClientes,
                    'carteras' => $totalCarteras,
                    'ventas' => $totalVentas,
                    'sample_clientes' => Persona::where('tipo_persona', 'Cliente')->take(5)->get(['id', 'nombre', 'num_documento']),
                    'sample_carteras' => Cartera::with('cliente')->take(5)->get()
                ]
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }
    
    public function obtenerResumenCliente(Request $request){
        if (!$request->ajax()) return redirect('/');
        
        $carteraService = new CarteraService();
        $resumen = $carteraService->obtenerResumenCliente($request->cliente_id);
        
        return ['resumen' => $resumen];
    }
    
    public function registrarAbono(Request $request){
        if (!$request->ajax()) return redirect('/');
        
        try {
            $carteraService = new CarteraService();
            $cartera = $carteraService->registrarAbono(
                $request->cartera_id, 
                $request->monto_abono, 
                $request->observaciones
            );
            
            // Registrar en el log
            \Log::info("Abono registrado: Cartera #{$request->cartera_id}, Monto: $request->monto_abono, Usuario: " . \Auth::user()->usuario);
            
            return ['success' => true, 'cartera' => $cartera];
        } catch (\Exception $e) {
            \Log::error("Error registrando abono: " . $e->getMessage());
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    public function obtenerDetalle($id){
        $cartera = Cartera::with(['cliente', 'venta', 'detalles.articulo'])->findOrFail($id);
        return ['detalles' => $cartera->detalles];
    }
    
    public function verificarEstado(){
        try {
            $totalCarteras = Cartera::count();
            $totalDetalles = DetalleCartera::count();
            $ultimaCartera = Cartera::latest()->first();
            
            return [
                'success' => true,
                'total_carteras' => $totalCarteras,
                'total_detalles' => $totalDetalles,
                'ultima_cartera' => $ultimaCartera
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }
    
    public function obtenerResumenGeneral(){
        try {
            $totalDeudas = Cartera::sum('total_deuda');
            $totalAbonado = Cartera::sum('total_abono');
            $saldoPendiente = Cartera::sum('saldo_actual');
            $carterasActivas = Cartera::where('estado_cart', '!=', 'Pagado')->count();
            
            return [
                'resumen' => [
                    'total_deudas' => $totalDeudas,
                    'total_abonado' => $totalAbonado,
                    'saldo_pendiente' => $saldoPendiente,
                    'carteras_activas' => $carterasActivas
                ]
            ];
        } catch (\Exception $e) {
            return [
                'resumen' => [
                    'total_deudas' => 0,
                    'total_abonado' => 0,
                    'saldo_pendiente' => 0,
                    'carteras_activas' => 0
                ]
            ];
        }
    }
    
    public function generarPDF($id){
        $cartera = Cartera::with(['cliente', 'venta', 'detalles.articulo'])->findOrFail($id);
        
        $pdf = \PDF::loadView('pdf.cartera', [
            'cartera' => $cartera,
            'detalles' => $cartera->detalles
        ]);
        
        return $pdf->download('cartera-' . $cartera->id . '.pdf');
    }

    public function store(Request $request)
    {
        if (!$request->ajax()) return redirect('/');

        try{
            DB::beginTransaction();

            $mytime= Carbon::now('America/Bogota');

            $cartera = new Cartera();
            $cartera->cliente_id = $request->cliente_id;
            $cartera->total_deuda = $request->total_deuda;
            $cartera->compras = $request->compras;
            $cartera->fecha_compr_pago = $request->fecha_compr_pago;
            $cartera->cuotas = $request->cuotas;
            $cartera->total_abono = $request->total_abono;
            $cartera->descuento = $request->descuento;
            $cartera->devolucion = $request->devolucion;
            $cartera->saldo_actual = $request->saldo_actual;
            $cartera->estado_cart = $request->estado_cart;
            $cartera->save();

            $detallescartera = $request->data;//Array de detalles
            //Recorro todos los elementos

            foreach($detallescartera as $dc=>$detcar)
            {
                $detallecartera = new DetalleCartera();
                $detallecartera->idcartera = $cartera->id;
                $detallecartera->articulo_id = $detcar['articulo_id'];
                $detallecartera->valor_venta_articulo = $detcar['valor_venta_articulo'];
                $detallecartera->cantidad = $detcar['cantidad'];
                $detallecartera->compra = $detcar['compra'];
                $detallecartera->fecha_venta = $detcar['fecha_venta'];
                $detallecartera->pago_incompl = $detcar['pago_incompl'];
                $detallecartera->deuda = $detcar['deuda'];
                $detallecartera->abono = $detcar['abono'];
                $detallecartera->fecha_abono = $detcar['fecha_abono'];
                $detallecartera->descuento = $detcar['descuento'];
                $detallecartera->devolucion = $detcar['devolucion'];
                $detallecartera->saldo_actual = $detcar['saldo_actual'];
                $detallecartera->save();
            }

            DB::commit();
        } catch (Exception $e){
            DB::rollBack();
        }
    }

}
