<?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\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('مراجعة مستند')]
class DocumentApproval extends Component
{
    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),
        ]);
    }
}
