<?php

namespace App\Livewire\Deudores;

use App\Models\Deudor;
use Livewire\Component;
use Livewire\WithPagination;

class DeudorManager extends Component
{
    use WithPagination;

    public string $search = '';
    public bool $showModal = false;
    public bool $showDeleteModal = false;
    public bool $editing = false;
    public ?int $deudorId = null;

    // Campos
    public string $tipo_documento = 'CC';
    public string $numero_documento = '';
    public string $nombre_completo = '';
    public string $email = '';
    public string $telefono = '';
    public string $direccion_notificacion = '';
    public string $ciudad = '';
    public bool $tiene_bienes = false;
    public string $notas_bienes = '';

    // Delete
    public ?int $deleteId = null;
    public string $deleteName = '';
    public string $numero_juicio    = '';
    public string $banco             = '';
    public string $ciudad_residencia = '';
    public string $departamento      = '';

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

    public function openCreate(): void
    {
        $this->resetForm();
        $this->editing = false;
        $this->showModal = true;
    }

    public function openEdit(int $id): void
    {
        $d = Deudor::findOrFail($id);
        $this->deudorId = $d->id;
        $this->tipo_documento = $d->tipo_documento;
        $this->numero_documento = $d->numero_documento;
        $this->nombre_completo = $d->nombre_completo;
        $this->email = $d->email ?? '';
        $this->telefono = $d->telefono ?? '';
        $this->direccion_notificacion = $d->direccion_notificacion ?? '';
        $this->ciudad = $d->ciudad ?? '';
        $this->tiene_bienes = $d->tiene_bienes;
        $this->notas_bienes      = $d->notas_bienes ?? '';
        $this->banco              = $d->banco ?? '';
        $this->ciudad_residencia  = $d->ciudad_residencia ?? '';
        $this->departamento       = $d->departamento ?? '';
        $this->numero_juicio      = $d->numero_juicio ?? '';
        $this->editing = true;
        $this->showModal = true;
    }

    public function save(): void
    {
        $rules = [
            'tipo_documento' => 'required|in:CC,NIT,CE,PP',
            'numero_documento' => 'required|string|max:30|unique:deudores,numero_documento' . ($this->editing ? ',' . $this->deudorId : ''),
            'nombre_completo' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'telefono' => 'nullable|string|max:20',
            'direccion_notificacion' => 'nullable|string|max:500',
            'ciudad' => 'nullable|string|max:100',
            'tiene_bienes' => 'boolean',
            'notas_bienes' => 'nullable|string|max:1000',
            'banco'            => 'nullable|string|max:100',
            'ciudad_residencia'=> 'nullable|string|max:100',
            'departamento'     => 'nullable|string|max:100',
            'numero_juicio'    => 'nullable|string|max:80',
        ];

        $validated = $this->validate($rules);

        if ($this->editing) {
            Deudor::findOrFail($this->deudorId)->update($validated);
            session()->flash('message', 'Deudor actualizado correctamente.');
        } else {
            Deudor::create($validated);
            session()->flash('message', 'Deudor registrado correctamente.');
        }

        $this->showModal = false;
        $this->resetForm();
    }

    public function confirmDelete(int $id): void
    {
        $d = Deudor::findOrFail($id);
        $this->deleteId = $id;
        $this->deleteName = $d->nombre_completo;
        $this->showDeleteModal = true;
    }

    public function deleteDeudor(): void
    {
        Deudor::findOrFail($this->deleteId)->delete();
        $this->showDeleteModal = false;
        session()->flash('message', 'Deudor eliminado correctamente.');
    }

    public function cancelDelete(): void { $this->showDeleteModal = false; }
    public function closeModal(): void { $this->showModal = false; $this->resetForm(); }

    private function resetForm(): void
    {
        $this->deudorId = null;
        $this->tipo_documento = 'CC';
        $this->numero_documento = '';
        $this->nombre_completo = '';
        $this->email = '';
        $this->telefono = '';
        $this->direccion_notificacion = '';
        $this->ciudad = '';
        $this->tiene_bienes = false;
        $this->notas_bienes      = '';
        $this->banco              = '';
        $this->ciudad_residencia  = '';
        $this->departamento       = '';
        $this->numero_juicio      = '';
        $this->resetValidation();
    }

    protected $messages = [
        'numero_documento.unique' => 'Este deudor ya existe (mismo documento). Búsquelo en la lista y asígnelo directamente al proceso.',
    ];

    public function render()
    {
        $query = Deudor::query();

        if ($this->search) {
            $query->where(function ($q) {
                $q->where('nombre_completo', 'like', '%' . $this->search . '%')
                  ->orWhere('numero_documento', 'like', '%' . $this->search . '%')
                  ->orWhere('email', 'like', '%' . $this->search . '%');
            });
        }

        return view('livewire.deudores.deudor-manager', [
            'deudores' => $query->orderBy('nombre_completo')->paginate(10),
        ]);
    }
}
