<?php

namespace App\Http\Controllers\Student;

use App\Http\Controllers\Admin\PageController;
use App\Http\Controllers\Student\Concerns\ResolvesStudentScope;
use App\Models\AttendanceRecord;
use App\Models\Term;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class AttendanceController extends PageController
{
    use ResolvesStudentScope;

    public function index(Request $request): View
    {
        $student = $this->ensureStudent();
        $termId = $request->integer('term_id') ?: Term::query()->where('is_current', true)->value('id');

        $summary = AttendanceRecord::query()
            ->select([
                DB::raw("SUM(CASE WHEN attendance_records.status = 'present' THEN 1 ELSE 0 END) as present_count"),
                DB::raw("SUM(CASE WHEN attendance_records.status = 'absent' THEN 1 ELSE 0 END) as absent_count"),
                DB::raw("SUM(CASE WHEN attendance_records.status = 'late' THEN 1 ELSE 0 END) as late_count"),
                DB::raw("SUM(CASE WHEN attendance_records.status = 'excused' THEN 1 ELSE 0 END) as excused_count"),
                DB::raw("SUM(CASE WHEN attendance_records.status = 'sick' THEN 1 ELSE 0 END) as sick_count"),
                DB::raw('COUNT(*) as total_sessions'),
            ])
            ->join('attendances', 'attendance_records.attendance_id', '=', 'attendances.id')
            ->where('attendance_records.student_id', $student->id)
            ->when($termId, fn ($q) => $q->where('attendances.term_id', $termId))
            ->first();

        $records = AttendanceRecord::query()
            ->with(['attendance.schoolClass'])
            ->where('student_id', $student->id)
            ->whereHas('attendance', fn ($q) => $q->when($termId, fn ($t) => $t->where('term_id', $termId)))
            ->join('attendances', 'attendance_records.attendance_id', '=', 'attendances.id')
            ->orderByDesc('attendances.date')
            ->select('attendance_records.*')
            ->paginate(30);

        $percentage = ($summary && $summary->total_sessions > 0)
            ? round(($summary->present_count / $summary->total_sessions) * 100, 1)
            : null;

        return $this->page('student.attendance.index', [
            'crumbTitle' => 'Attendance',
            'crumbSub' => 'Your attendance record',
            'student' => $student,
            'terms' => Term::query()->orderByDesc('starts_on')->get(),
            'termId' => $termId,
            'summary' => $summary,
            'percentage' => $percentage,
            'records' => $records,
        ]);
    }
}
