<?php

namespace App\Livewire\Personnel;

use App\Models\SchoolSetting;
use App\Models\User;
use App\Traits\WithToastNotifications;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class StudentIdCardIndex extends Component
{
    use AuthorizesRequests, WithToastNotifications;

    public string $selectedClass = '';
    public string $search = '';

    public function mount(): void
    {
        $firstClass = User::whereNotNull('class_name')
            ->where('class_name', '!=', '')
            ->distinct()
            ->orderBy('class_name', 'asc')
            ->value('class_name');

        $this->selectedClass = $firstClass ?? '';
    }

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

        $classes = User::whereNotNull('class_name')
            ->where('class_name', '!=', '')
            ->select('class_name')
            ->distinct()
            ->orderBy('class_name', 'asc')
            ->pluck('class_name');

        $students = User::whereNotNull('class_name')
            ->when($this->selectedClass !== '', fn($q) => $q->where('class_name', $this->selectedClass))
            ->when($this->search !== '', fn($q) => $q->where('name', 'like', "%{$this->search}%")->orWhere('nip_nis', 'like', "%{$this->search}%"))
            ->orderBy('name', 'asc')
            ->get();

        $schoolSettings = SchoolSetting::getAllCached();

        return view('livewire.personnel.student-id-card-index', [
            'classes' => $classes,
            'students' => $students,
            'school' => $schoolSettings,
            'logoUrl' => SchoolSetting::getFileUrl('school_logo'),
        ])->layout('components.layouts.app');
    }
}
