<?php
namespace App\Livewire\Tickets;

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

class TicketTable extends Component
{
    use WithPagination;

    public string $search       = '';
    public string $filterStatus = '';
    public string $filterPriority= '';
    public string $filterAgent  = '';
    public string $filterMine   = '';
    public int    $perPage      = 20;

    protected $queryString = ['search','filterStatus','filterPriority','filterAgent','filterMine'];

    public function updatingSearch()        { $this->resetPage(); }
    public function updatingFilterStatus()  { $this->resetPage(); }
    public function updatingFilterPriority(){ $this->resetPage(); }
    public function updatingFilterAgent()   { $this->resetPage(); }

    public function render()
    {
        $user = auth()->user();
        $isAgent = $user->hasAnyRole(['admin','superadmin','jefe_soporte','agente']);

        $tickets = Ticket::with(['status','priority','category','requester','assignee'])
            ->when($this->search, fn($q) => $q->where(function($q) {
                $q->where('title', 'like', "%{$this->search}%")
                  ->orWhere('number', 'like', "%{$this->search}%")
                  ->orWhereHas('requester', fn($r) => $r->where('name','like',"%{$this->search}%"));
            }))
            ->when($this->filterStatus,   fn($q) => $q->where('status_id', $this->filterStatus))
            ->when($this->filterPriority, fn($q) => $q->where('priority_id', $this->filterPriority))
            ->when($this->filterAgent,    fn($q) => $q->where('assignee_id', $this->filterAgent))
            ->when($this->filterMine === '1' && $isAgent, fn($q) => $q->where('assignee_id', $user->id))
            ->when(!$isAgent, fn($q) => $q->where('requester_id', $user->id))
            ->orderByRaw("FIELD(priority_id, 4,3,2,1)") // crítica primero
            ->orderBy('created_at', 'desc')
            ->paginate($this->perPage);

        return view('livewire.tickets.ticket-table', compact('tickets'));
    }
}
