<?php

namespace App\Traits;

use App\Models\Cobranza;
use App\Models\CobrosHistorial;
use App\Models\PaymentMethod;
use App\Models\Remota;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Attributes\Url;
use Livewire\WithPagination;

trait CobrosMensualidadesTrait
{
    // use LivewireAlert;
    // use WithPagination;

    #[Url()]
    public string $search = '';
    public string $orderBy = 'asc';
    public string $status_cobros = 'pendiente';
    public string  $status_remota = 'activo';
    public $redirect = 'cobros_mensualidades.index';
    public $perPage = 25;


    public $monto_cobro;
    public $payment_method_id;
    public $observaciones = '';





    public function updatingSearch($value)
    {
        // Si la búsqueda está vacía, restablece la página y vuelve a renderizar
        if (empty($value)) {
            $this->resetPage(); // Restablece la paginación a la primera página
            $this->render(); // Vuelve a renderizar el componente
        }
    }
    //==================================================================Funciones
    // ------ PAGAR REMOTA
    public function pagar($remota = null, $payment_method_id = null, $monto_cobro = null)
    {
        $remota = Remota::find($remota);
        $cobro = Cobranza::where('id', $remota->ultimoCobro()->id)->first();


            // Check if payment amount is 0
            if (floatval($monto_cobro) <= 0) {
                return redirect()->route($this->redirect)->with([
                    'type' => 'error',
                    'message' => 'El monto del pago debe ser mayor a 0'
                ]);
            }
        try {
            DB::beginTransaction();
            try {
                if (!$remota->ultimoCobro()->tieneSaldoPendiente()) {
                    throw new Exception('No hay saldo pendiente para esta remota');
                }

                $new_cobro_historial = new CobrosHistorial();
                $new_cobro_historial->cliente_id = $remota->ultimoCobro()->cliente_id;
                $new_cobro_historial->cobro_id = $remota->ultimoCobro()->id;
                $new_cobro_historial->remota_id = $remota->ultimoCobro()->remota_id;
                $new_cobro_historial->fecha_pago = now()->format('Y-m-d');
                $new_cobro_historial->monto = floatval($monto_cobro);
                $new_cobro_historial->payment_method_id = (int)$payment_method_id;

                $cantidadPendiente = $remota->ultimoCobro()->cantidadPendienteDelUltimoCobroPendiente();

                // Log payment amounts for debugging
                Log::info('Payment Debug', [
                    'monto_cobro' => $monto_cobro,
                    'cantidad_pendiente' => $cantidadPendiente
                ]);

                if ($cantidadPendiente > $monto_cobro) {
                    // Partial payment case
                    $new_cobro_historial->concepto = "Abono: " . $remota->ultimoCobro()->concepto;
                } else if ($cantidadPendiente < $monto_cobro) {
                    // Overpayment case
                    $new_cobro_historial->concepto = "Ultimo abono: " . $remota->ultimoCobro()->concepto;
                    $cobro->status = 'pagado';
                    $new_cobro_historial->utilidad = $remota->ultimoCobro()->cantidadPagadaDelUltimoCobroPendiente() + $monto_cobro - $remota->getCostoDeVenta();

                    $Cobro = Cobranza::create([
                        'cliente_id' => $remota->ultimoCobro()->cliente_id,
                        'concepto' => 'Pago de mensualidad',
                        'remota_id' => $remota->ultimoCobro()->remota_id,
                        'monto' => $remota->costo,
                        'fecha' => Carbon::createFromFormat('d/m/Y', $remota->proxima_fecha_cobro)->format('Y-m-d')
                    ]);

                    $remota->dia_corte = Carbon::createFromFormat('d/m/Y', $remota->proxima_fecha_cobro)->format('Y-m-d');
                } else {
                    // Exact payment case
                    $new_cobro_historial->concepto = "Pago completo: " . $remota->ultimoCobro()->concepto;
                    $cobro->status = 'pagado';
                    $new_cobro_historial->utilidad = $remota->getUtilidadEstimada();

                    $Cobro = Cobranza::create([
                        'cliente_id' => $remota->ultimoCobro()->cliente_id,
                        'concepto' => 'Pago de mensualidad',
                        'remota_id' => $remota->ultimoCobro()->remota_id,
                        'monto' => $remota->costo,
                        'fecha' => Carbon::createFromFormat('d/m/Y', $remota->proxima_fecha_cobro)->format('Y-m-d')
                    ]);

                    $remota->dia_corte = Carbon::createFromFormat('d/m/Y', $remota->proxima_fecha_cobro)->format('Y-m-d');
                }

                $cobro->save();
                $remota->save();
                $new_cobro_historial->save();

            } catch (Exception $e) {
                Log::error('Payment Processing Error', [
                    'error' => $e->getMessage(),
                    'remota_id' => $remota->id,
                    'cobro_id' => $cobro->id ?? null
                ]);

                return redirect()->route($this->redirect)->with([
                    'type' => 'error',
                    'message' => 'Error de pago: ' . $e->getMessage()
                ]);
            }

            DB::commit();


            return redirect()->route($this->redirect)->with(
                [
                    'type' => 'success',
                    'message' => 'Pago realizado correctamente'
                ]
            );
        } catch (Exception $e) {
            DB::rollBack();
            dd($e->getMessage());
            return redirect()->route($this->redirect)->with(
                [
                    'type' => 'error',
                    'message' => 'Error al realizar el pago',
                ]
            );
        }
    }
    // ------ EXONERAR REMOTA
    public function exonerarPagoCobroRemota($remota = null)
    {

        $remota = Remota::find($remota);

        $cobro = Cobranza::where('id', $remota->ultimoCobro()->id)->first();

        try {
            DB::beginTransaction();

            if ($cobro->tienePagosRegistrados()) {
                $cobro->status = 'pago_parcial';
            } else {
                $cobro->status = 'cancelado';
            }

            $new_cobro_historial = new CobrosHistorial();
            $new_cobro_historial->cliente_id = $remota->ultimoCobro()->cliente_id;
            $new_cobro_historial->cobro_id = $cobro->id;
            $new_cobro_historial->remota_id = $remota->ultimoCobro()->remota_id;
            $new_cobro_historial->fecha_pago =  now()->format('Y-m-d');
            $new_cobro_historial->monto = $cobro->cantidadPendienteDelUltimoCobroPendiente();
            $new_cobro_historial->concepto =  "Pago exonerado: " . $remota->ultimoCobro()->concepto;
            $new_cobro_historial->utilidad = $cobro->utilidadActual();
            $new_cobro_historial->save();


            $newCobro = Cobranza::create([
                'cliente_id' => $remota->ultimoCobro()->cliente_id,
                'concepto' => 'Pago de mensualidad',
                'remota_id' => $remota->ultimoCobro()->remota_id,
                'monto' => $remota->costo,
                'fecha' =>  Carbon::createFromFormat('d/m/Y', $remota->proxima_fecha_cobro)->format('Y-m-d')
            ]);

            $remota->dia_corte = Carbon::createFromFormat('d/m/Y', $remota->proxima_fecha_cobro)->format('Y-m-d');

            $remota->save();

            $cobro->save();



            DB::commit();


            return redirect()->route($this->redirect)->with(
                [
                    'type' => 'success',
                    'message' => 'Pago exonerado correctamente'
                ]
            );
        } catch (Exception $e) {
            DB::rollBack();
            // dd($e->getMessage());
            return redirect()->route($this->redirect)->with(
                [
                    'type' => 'error',
                    'message' => 'Error al exonerar el pago',
                ]
            );
        }        // dd($cobro->cantidadPendienteDelUltimoCobroPendiente());

    }



    //===============================================Render
    public function render()
    {

        // Cobros de mensualidades de remotas
        $remotas_por_pagar =  Cobranza::JoinRemotas($this->search, $this->status_cobros, $this->status_remota, $this->orderBy)
            ->where('cobros.fecha', '<', now()->addDays(5)->format('Y-m-d'))
            ->paginate($this->perPage);


        $payment_methods = PaymentMethod::where('tipo_metodo_pago', 'cliente')->get();


        if (session()->has('message')) $this->alert(session('type'), session('message'));

        return view('livewire.cobranza.cobros-mensualidades-component', compact('remotas_por_pagar', 'payment_methods'));
    }
}
