<?php

namespace App\Http\Controllers\ParentPortal;

use App\Http\Controllers\Admin\PageController;
use App\Http\Controllers\ParentPortal\Concerns\ResolvesParentScope;
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 ResolvesParentScope;

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

        $summary = collect();
        $records = collect();
        $percentage = null;

        if ($studentId && $students->contains('id', $studentId)) {
            $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('COUNT(*) as total_sessions'),
                ])
                ->join('attendances', 'attendance_records.attendance_id', '=', 'attendances.id')
                ->where('attendance_records.student_id', $studentId)
                ->when($termId, fn ($q) => $q->where('attendances.term_id', $termId))
                ->first();

            $records = AttendanceRecord::query()
                ->with(['attendance.schoolClass'])
                ->where('student_id', $studentId)
                ->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.*')
                ->limit(30)
                ->get();

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

        return $this->page('parent.attendance.index', [
            'crumbTitle' => 'Attendance',
            'crumbSub' => 'Child attendance view',
            'students' => $students,
            'studentId' => $studentId,
            'activeChild' => $students->firstWhere('id', $studentId),
            'terms' => Term::query()->orderByDesc('starts_on')->get(),
            'termId' => $termId,
            'summary' => $summary,
            'percentage' => $percentage,
            'records' => $records,
        ]);
    }
}
