<?php

namespace App\Livewire\Documents;

use App\Domain\Document\Enums\DocumentStatus;
use App\Domain\Document\Enums\DocumentType;
use App\Domain\Document\Models\Document;
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 DocumentApprovalList extends Component
{
    use WithPagination, WithSorting;

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

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

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

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

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

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

    public function render()
    {
        $this->authorize('documents.approve');

        $query = Document::with(['documentable', 'uploader'])
            ->orderBy($this->sortBy, $this->sortDir);

        if ($this->status) {
            $query->where('status', $this->status);
        }

        if ($this->documentType) {
            $query->where('document_type', $this->documentType);
        }

        if ($this->search) {
            $search = $this->search;
            $query->where(function ($q) use ($search) {
                $q->where('original_filename', 'ilike', "%{$search}%")
                    ->orWhereHasMorph('documentable', '*', function ($mq) use ($search) {
                        $mq->where('name_ar', 'ilike', "%{$search}%")
                            ->orWhere('name', 'ilike', "%{$search}%");
                    });
            });
        }

        return view('livewire.documents.document-approval-list', [
            'documents' => $query->paginate(20),
            'statuses' => DocumentStatus::cases(),
            'documentTypes' => DocumentType::cases(),
        ]);
    }
}
