<?php

namespace App\Livewire\Reports;

use App\Models\AttendanceRecord;
use App\Models\User;
use App\Services\ReportExportService;
use App\Traits\WithToastNotifications;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class ClassRecapIndex extends Component
{
    use AuthorizesRequests, WithToastNotifications;

    public string $selectedClass = '';
    public string $selectedMonth = '';

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

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

        $this->selectedClass = $firstClass ?? 'XII RPL 1';
    }

    public function exportExcel(ReportExportService $exportService)
    {
        $this->authorize('viewAny', AttendanceRecord::class);

        if (!$this->selectedClass) {
            $this->notifyError('Silakan pilih kelas terlebih dahulu.');
            return;
        }

        return $exportService->exportClassMatrixExcel($this->selectedClass, $this->selectedMonth);
    }

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

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

        $carbonMonth = Carbon::parse($this->selectedMonth . '-01');
        $daysInMonth = $carbonMonth->daysInMonth;

        $students = collect();
        $matrix = [];
        $classSummary = [
            'total_students' => 0,
            'hadir' => 0,
            'pulang_cepat' => 0,
            'terlambat' => 0,
            'izin' => 0,
            'sakit' => 0,
            'alpha' => 0,
            'avg_attendance_pct' => 0,
        ];

        if ($this->selectedClass) {
            $students = User::where('class_name', $this->selectedClass)
                ->orderBy('name', 'asc')
                ->get();

            $dateParts = explode('-', $this->selectedMonth);
            $query = AttendanceRecord::whereIn('user_id', $students->pluck('id'));
            if (count($dateParts) == 2) {
                $query->whereYear('date', $dateParts[0])->whereMonth('date', $dateParts[1]);
            }
            $records = $query->get()->groupBy(fn($r) => $r->user_id . '_' . Carbon::parse($r->date)->day);

            $totalPctSum = 0;
            $studentCountWithData = 0;

            foreach ($students as $student) {
                $hadir = 0; $pulang_cepat = 0; $terlambat = 0; $izin = 0; $sakit = 0; $alpha = 0;
                $daily = [];

                for ($d = 1; $d <= $daysInMonth; $d++) {
                    $key = $student->id . '_' . $d;
                    $record = $records->get($key)?->first();

                    $status = null;
                    if ($record) {
                        $status = $record->status;
                        switch ($record->status) {
                            case 'Hadir': $hadir++; $classSummary['hadir']++; break;
                            case 'Pulang Cepat': $pulang_cepat++; $classSummary['pulang_cepat']++; break;
                            case 'Terlambat': $terlambat++; $classSummary['terlambat']++; break;
                            case 'Izin': $izin++; $classSummary['izin']++; break;
                            case 'Sakit': $sakit++; $classSummary['sakit']++; break;
                            case 'Alpha': $alpha++; $classSummary['alpha']++; break;
                        }
                    }
                    $daily[$d] = $status;
                }

                $totalRecorded = $hadir + $pulang_cepat + $terlambat + $izin + $sakit + $alpha;
                $pct = $totalRecorded > 0 ? round((($hadir + $pulang_cepat + $terlambat) / $totalRecorded) * 100, 1) : 0;

                if ($totalRecorded > 0) {
                    $totalPctSum += $pct;
                    $studentCountWithData++;
                }

                $matrix[$student->id] = [
                    'student' => $student,
                    'daily' => $daily,
                    'hadir' => $hadir,
                    'pulang_cepat' => $pulang_cepat,
                    'terlambat' => $terlambat,
                    'izin' => $izin,
                    'sakit' => $sakit,
                    'alpha' => $alpha,
                    'pct' => $pct,
                ];
            }

            $classSummary['total_students'] = $students->count();
            $classSummary['avg_attendance_pct'] = $studentCountWithData > 0 ? round($totalPctSum / $studentCountWithData, 1) : 0;
        }

        return view('livewire.reports.class-recap-index', [
            'classes' => $classes,
            'daysInMonth' => $daysInMonth,
            'matrix' => $matrix,
            'classSummary' => $classSummary,
            'monthLabel' => $carbonMonth->translatedFormat('F Y'),
        ])->layout('components.layouts.app');
    }
}
