<?php

namespace App\Livewire\Clientes;

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

class ClienteManager extends Component
{
    use WithPagination;

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

    // Campos
    public string $nombre = '';
    public string $nit = '';
    public string $contacto_nombre = '';
    public string $contacto_email = '';
    public string $contacto_telefono = '';
    public string $plataforma_externa = '';
    public int $sla_dias_radicacion = 5;
    public bool $activo = true;

    // Delete
    public ?int $deleteId = null;
    public string $deleteName = '';

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

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

    public function openEdit(int $id): void
    {
        $c = ClienteCorporativo::findOrFail($id);
        $this->clienteId = $c->id;
        $this->nombre = $c->nombre;
        $this->nit = $c->nit;
        $this->contacto_nombre = $c->contacto_nombre ?? '';
        $this->contacto_email = $c->contacto_email ?? '';
        $this->contacto_telefono = $c->contacto_telefono ?? '';
        $this->plataforma_externa = $c->plataforma_externa ?? '';
        $this->sla_dias_radicacion = $c->sla_dias_radicacion ?? 5;
        $this->activo = $c->activo;
        $this->editing = true;
        $this->showModal = true;
    }

    public function save(): void
    {
        $rules = [
            'nombre' => 'required|string|max:255',
            'nit' => 'required|string|max:50|unique:clientes_corporativos,nit' . ($this->editing ? ',' . $this->clienteId : ''),
            'contacto_nombre' => 'nullable|string|max:255',
            'contacto_email' => 'nullable|email|max:255',
            'contacto_telefono' => 'nullable|string|max:20',
            'plataforma_externa' => 'nullable|string|max:100',
            'sla_dias_radicacion' => 'nullable|integer|min:1|max:60',
            'activo' => 'boolean',
        ];

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

        if ($this->editing) {
            $c = ClienteCorporativo::findOrFail($this->clienteId);
            $c->update($validated);
            session()->flash('message', 'Cliente actualizado correctamente.');
        } else {
            ClienteCorporativo::create($validated);
            session()->flash('message', 'Cliente creado correctamente.');
        }

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

    public function confirmDelete(int $id): void
    {
        $c = ClienteCorporativo::findOrFail($id);
        $this->deleteId = $id;
        $this->deleteName = $c->nombre;
        $this->showDeleteModal = true;
    }

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

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

    private function resetForm(): void
    {
        $this->clienteId = null;
        $this->nombre = '';
        $this->nit = '';
        $this->contacto_nombre = '';
        $this->contacto_email = '';
        $this->contacto_telefono = '';
        $this->plataforma_externa = '';
        $this->sla_dias_radicacion = 5;
        $this->activo = true;
        $this->resetValidation();
    }

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

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

        return view('livewire.clientes.cliente-manager', [
            'clientes' => $query->orderBy('nombre')->paginate(10),
        ]);
    }
}
