<?php

namespace App\Livewire\CasosPrejuridicos;

use App\Models\CasoPrejuridico;
use App\Models\ClienteCorporativo;
use Livewire\Component;
use Livewire\WithPagination;

class CasoPrejuridicoManager extends Component
{
    use WithPagination;

    public string $search = '';
    public string $entidadFiltro = '';
    public string $etapaFiltro = '';

    protected $queryString = [
        'search' => ['except' => ''],
        'entidadFiltro' => ['except' => ''],
        'etapaFiltro' => ['except' => ''],
    ];

    public function updatingSearch(): void { $this->resetPage(); }
    public function updatingEntidadFiltro(): void { $this->resetPage(); }
    public function updatingEtapaFiltro(): void { $this->resetPage(); }

    public function limpiar(): void
    {
        $this->search = '';
        $this->entidadFiltro = '';
        $this->etapaFiltro = '';
        $this->resetPage();
    }

    public function render()
    {
        $query = CasoPrejuridico::query()
            ->with(['deudor', 'clienteCorporativo', 'responsable'])
            ->whereNull('deleted_at');

        if ($this->search !== '') {
            $term = '%' . $this->search . '%';
            $query->where(function ($q) use ($term) {
                $q->where('radicado', 'like', $term)
                  ->orWhereHas('deudor', function ($qd) use ($term) {
                      $qd->where('nombre_completo', 'like', $term)
                         ->orWhere('numero_documento', 'like', $term);
                  });
            });
        }

        if ($this->entidadFiltro !== '') {
            $query->where('cliente_corporativo_id', $this->entidadFiltro);
        }

        if ($this->etapaFiltro !== '') {
            $query->where('etapa', $this->etapaFiltro);
        }

        $casos = $query->orderByDesc('created_at')->paginate(15);

        $totalCasos = CasoPrejuridico::whereNull('deleted_at')->count();
        $totalDeuda = CasoPrejuridico::whereNull('deleted_at')->sum('total_deuda');

        $entidades = ClienteCorporativo::orderBy('nombre')->get();
        $etapas = CasoPrejuridico::ETAPAS;

        return view('livewire.casos-prejuridicos.caso-prejuridico-manager', [
            'casos' => $casos,
            'totalCasos' => $totalCasos,
            'totalDeuda' => $totalDeuda,
            'entidades' => $entidades,
            'etapas' => $etapas,
        ]);
    }
}
