<?php

namespace App\Livewire\Documents;

use App\Domain\Document\DocumentSettings;
use App\Domain\Document\Enums\DocumentStatus;
use App\Domain\Document\Models\Document;
use App\Domain\Document\Services\DocumentService;
use App\Domain\Shared\Models\SystemSetting;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('مراجعة مستند')]
class DocumentApproval extends Component
{
    /**
     * Locked because this is the record the whole screen acts on: approve()
     * and reject() write to whatever sits here, and in Livewire v4 an unlocked
     * public property — a model's attributes included — is settable from the
     * page. The branch check itself is not here: `documents` carries branch_id
     * and Document uses the strict BranchScope, so route-model binding runs
     * through the scope and a document from another branch 404s before mount()
     * is ever reached.
     */
    #[Locked]
    public Document $document;

    public string $expiresAt = '';
    public string $rejectionReason = '';

    public function mount(Document $document): void
    {
        $this->authorize('documents.approve');
        $this->document = $document;
    }

    public function approve(DocumentService $service): void
    {
        $expiryRequired = $this->document->document_type->requiresExpiry()
            && SystemSetting::get(DocumentSettings::MEDICAL_CERTIFICATE_EXPIRY_REQUIRED, true);

        $rules = [];
        if ($expiryRequired) {
            $rules['expiresAt'] = 'required|date|after:today';
        } else {
            $rules['expiresAt'] = 'nullable|date|after:today';
        }

        $this->validate($rules);

        $service->approve(
            $this->document,
            $this->expiresAt ?: null,
            auth()->user()
        );

        session()->flash('success', __('تم اعتماد المستند بنجاح'));
        $this->redirectRoute('documents.approvals', navigate: true);
    }

    public function reject(DocumentService $service): void
    {
        $this->validate([
            'rejectionReason' => 'required|string|min:5|max:500',
        ]);

        $service->reject(
            $this->document,
            $this->rejectionReason,
            auth()->user()
        );

        session()->flash('success', __('تم رفض المستند'));
        $this->redirectRoute('documents.approvals', navigate: true);
    }

    public function render()
    {
        return view('livewire.documents.document-approval', [
            'expiryRequired' => $this->document->document_type->requiresExpiry()
                && SystemSetting::get(DocumentSettings::MEDICAL_CERTIFICATE_EXPIRY_REQUIRED, true),
        ]);
    }
}
