<?php

namespace App\Http\Livewire\SuperAdmin;

use App\Enums\CompanyStatus;
use App\Models\Company;
use App\Models\Plan;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class CompaniesTable extends Component
{
    use WithPagination;

    #[Url(as: 'q')]
    public string $search = '';

    #[Url]
    public string $status = '';

    #[Url]
    public ?int $planId = null;

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

    public function toggleSuspend(int $companyId): void
    {
        $company = Company::findOrFail($companyId);
        if ($company->status === CompanyStatus::Suspended) {
            $company->update([
                'status'         => CompanyStatus::Active,
                'suspended_at'   => null,
                'suspension_reason' => null,
            ]);
            session()->flash('success', "Empresa {$company->name} reactivada.");
        } else {
            $company->update([
                'status'         => CompanyStatus::Suspended,
                'suspended_at'   => now(),
                'suspension_reason' => 'Suspensión manual desde panel.',
            ]);
            session()->flash('warning', "Empresa {$company->name} suspendida.");
        }
    }

    public function render()
    {
        $companies = Company::query()
            ->with('plan:id,name')
            ->when($this->search, fn ($q) => $q->where(function ($q2) {
                $q2->where('name', 'like', '%'.$this->search.'%')
                   ->orWhere('email', 'like', '%'.$this->search.'%')
                   ->orWhere('document_number', 'like', '%'.$this->search.'%');
            }))
            ->when($this->status, fn ($q) => $q->where('status', $this->status))
            ->when($this->planId, fn ($q) => $q->where('plan_id', $this->planId))
            ->latest()
            ->paginate(15);

        return view('livewire.superadmin.companies-table', [
            'companies' => $companies,
            'plans'     => Plan::active()->ordered()->get(['id', 'name']),
            'statuses'  => CompanyStatus::cases(),
        ]);
    }
}
