<?php

namespace App\Livewire;

use App\Models\Company;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class EmpresasTable extends Component
{
    use WithPagination;

    #[Url(as: 'q', except: '')]
    public string $busca = '';

    #[Url(except: '')]
    public string $status = '';

    #[Url(except: '')]
    public string $certificado = '';

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

    public function limpar(): void
    {
        $this->reset('busca', 'status', 'certificado');
        $this->resetPage();
    }

    public function render(): View
    {
        $empresas = Company::query()
            ->withCount('notasFiscais')
            ->when($this->busca, function ($q) {
                $termo = trim($this->busca);
                $digits = preg_replace('/\D/', '', $termo);

                $q->where(function ($sub) use ($termo, $digits) {
                    $sub->where('razao_social', 'like', "%{$termo}%")
                        ->orWhere('nome_fantasia', 'like', "%{$termo}%");

                    if ($digits !== '') {
                        $sub->orWhere('cnpj', 'like', "%{$digits}%");
                    }
                });
            })
            ->when($this->status === 'ativa', fn ($q) => $q->where('is_active', true))
            ->when($this->status === 'inativa', fn ($q) => $q->where('is_active', false))
            ->when($this->status === 'vencida', fn ($q) => $q->whereDate('assinatura_expira_em', '<', now()))
            ->when($this->certificado === 'com', fn ($q) => $q->whereNotNull('cert_path'))
            ->when($this->certificado === 'sem', fn ($q) => $q->whereNull('cert_path'))
            ->when($this->certificado === 'vencendo', fn ($q) => $q
                ->whereNotNull('cert_valid_to')
                ->whereBetween('cert_valid_to', [now(), now()->addDays(30)]))
            ->orderBy('razao_social')
            ->paginate(20);

        return view('livewire.empresas-table', ['empresas' => $empresas]);
    }
}
