<?php

namespace App\Http\Controllers\Student;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class AttendanceController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);
        $userId = $request->user()?->id;
        $studentId = $userId && $schoolId
            ? DB::table('students')->where('school_id', $schoolId)->where('user_id', $userId)->value('id')
            : null;

        $records = ($schoolId && $studentId)
            ? DB::table('attendance_records')
                ->join('attendance_sessions', 'attendance_sessions.id', '=', 'attendance_records.attendance_session_id')
                ->leftJoin('classrooms', 'classrooms.id', '=', 'attendance_sessions.classroom_id')
                ->where('attendance_records.school_id', $schoolId)
                ->where('attendance_records.student_id', $studentId)
                ->select([
                    'attendance_records.status',
                    'attendance_records.note',
                    'attendance_sessions.date',
                    'attendance_sessions.type',
                    'classrooms.name as classroom_name',
                ])
                ->orderByDesc('attendance_sessions.date')
                ->limit(60)
                ->get()
                ->map(fn ($r): array => [
                    'date' => $this->jalaliDate($r->date),
                    'status' => $r->status,
                    'type' => $r->type,
                    'classroom' => $r->classroom_name ?: '—',
                    'note' => $r->note,
                ])
                ->values()
            : collect()->values();

        $summary = [
            'present' => $records->where('status', 'present')->count(),
            'absent' => $records->where('status', 'absent')->count(),
            'late' => $records->where('status', 'late')->count(),
            'excused' => $records->where('status', 'excused')->count(),
        ];

        return Inertia::render('Student/Attendance', [
            'records' => $records,
            'summary' => $summary,
        ]);
    }
}
