<?php

namespace App\Livewire\Audit;

use App\Domain\Audit\Models\AuditLog;
use App\Livewire\Concerns\WithSorting;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('سجل التدقيق')]
class AuditLogList extends Component
{
    use WithPagination, WithSorting;

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

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

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

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

    public int $expandedRow = 0;

    public function mount(): void
    {
        $this->authorize('audit.list');
        $this->dateFrom = now()->subDays(7)->format('Y-m-d');
        $this->dateTo = now()->format('Y-m-d');
    }

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

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

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

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

    public function toggleExpand(int $id): void
    {
        $this->expandedRow = $this->expandedRow === $id ? 0 : $id;
    }

    public function render()
    {
        $query = AuditLog::query()
            ->with('user')
            ->when($this->search, function ($q) {
                $search = $this->search;
                $q->where(function ($q2) use ($search) {
                    $q2->where('auditable_type', 'ilike', "%{$search}%")
                       ->orWhereHas('user', fn ($uq) => $uq->where('name', 'ilike', "%{$search}%")
                           ->orWhere('name_ar', 'ilike', "%{$search}%"));
                });
            })
            ->when($this->actionFilter, fn ($q) => $q->where('action', $this->actionFilter))
            ->when($this->dateFrom, fn ($q) => $q->whereDate('created_at', '>=', $this->dateFrom))
            ->when($this->dateTo, fn ($q) => $q->whereDate('created_at', '<=', $this->dateTo))
            ->orderBy($this->sortBy, $this->sortDir);

        return view('livewire.audit.audit-log-list', [
            'logs' => $query->paginate(25),
        ]);
    }
}
