<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SchoolClass;
use App\Models\Student;
use App\Models\StudentAttendance;
use Illuminate\Http\Request;

class AbsenSiswaController extends Controller
{
    public function index(Request $request)
    {
        $tanggal    = $request->input('tanggal', today()->format('Y-m-d'));
        $filterKelas = $request->input('kelas', '');

        $query = Student::orderBy('class')->orderBy('name');
        if ($filterKelas) {
            $query->where('class', $filterKelas);
        }

        $students = $query->get()->map(function ($s) use ($tanggal) {
            $s->absen = StudentAttendance::where('student_id', $s->id)
                ->whereDate('date', $tanggal)->first();
            return $s;
        });

        $semuaKelas = SchoolClass::orderBy('grade_level')->orderBy('name')->pluck('name');

        $rekap = [
            'hadir' => StudentAttendance::whereDate('date', $tanggal)->where('status', 'hadir')->count(),
            'sakit' => StudentAttendance::whereDate('date', $tanggal)->where('status', 'sakit')->count(),
            'izin'  => StudentAttendance::whereDate('date', $tanggal)->where('status', 'izin')->count(),
            'alfa'  => StudentAttendance::whereDate('date', $tanggal)->where('status', 'alfa')->count(),
            'belum' => Student::count() - StudentAttendance::whereDate('date', $tanggal)->count(),
        ];

        return view('admin.absen.siswa', compact('students', 'tanggal', 'filterKelas', 'semuaKelas', 'rekap'));
    }
}
