<?php

namespace App\Livewire\Reports;

use App\Models\WarningLetter;
use App\Services\WarningLetterService;
use App\Traits\WithToastNotifications;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class WarningLetterIndex extends Component
{
    use AuthorizesRequests, WithToastNotifications;

    public string $selectedMonth = '';
    public string $search = '';

    // Modal state for issuing letter
    public bool $showIssueModal = false;
    public ?int $selectedUserId = null;
    public string $selectedStudentName = '';
    public string $letter_type = 'sp1';
    public string $notes = '';

    public function mount(): void
    {
        $this->selectedMonth = now()->format('Y-m');
    }

    public function openIssueModal(int $userId, string $studentName, string $recommendedType): void
    {
        $this->authorize('create', WarningLetter::class);

        $this->selectedUserId = $userId;
        $this->selectedStudentName = $studentName;
        $this->letter_type = $recommendedType;
        $this->notes = '';
        $this->showIssueModal = true;
    }

    public function issueLetter(WarningLetterService $service): void
    {
        $this->authorize('create', WarningLetter::class);

        if (!$this->selectedUserId) return;

        $letter = $service->issueWarningLetter($this->selectedUserId, $this->letter_type, $this->notes, $this->selectedMonth);
        $this->notifySuccess("{$letter->letter_type_label} berhasil diterbitkan dengan nomor {$letter->letter_number}.");

        $this->showIssueModal = false;
        $this->selectedUserId = null;
    }

    public function render(WarningLetterService $service)
    {
        $this->authorize('viewAny', WarningLetter::class);

        $studentsAtRisk = $service->getStudentsAtRisk($this->selectedMonth);

        $issuedLetters = WarningLetter::with(['user', 'creator'])
            ->where('month', $this->selectedMonth)
            ->when($this->search !== '', function ($q) {
                $q->whereHas('user', fn($u) => $u->where('name', 'like', "%{$this->search}%")->orWhere('nip_nis', 'like', "%{$this->search}%"));
            })
            ->orderBy('created_at', 'desc')
            ->get();

        return view('livewire.reports.warning-letter-index', [
            'studentsAtRisk' => $studentsAtRisk,
            'issuedLetters' => $issuedLetters,
        ])->layout('components.layouts.app');
    }
}
