<?php

namespace App\Http\Controllers\School;

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);

        $session = $schoolId
            ? DB::table('attendance_sessions')
                ->leftJoin('classrooms', 'classrooms.id', '=', 'attendance_sessions.classroom_id')
                ->leftJoin('subjects', 'subjects.id', '=', 'attendance_sessions.subject_id')
                ->where('attendance_sessions.school_id', $schoolId)
                ->select([
                    'attendance_sessions.id',
                    'attendance_sessions.date',
                    'attendance_sessions.date_jalali',
                    'attendance_sessions.status',
                    'classrooms.name as classroom_name',
                    'subjects.name as subject_name',
                ])
                ->latest('attendance_sessions.date')
                ->first()
            : null;

        $records = $session
            ? DB::table('attendance_records')
                ->join('students', 'students.id', '=', 'attendance_records.student_id')
                ->where('attendance_records.attendance_session_id', $session->id)
                ->select([
                    'students.first_name',
                    'students.last_name',
                    'attendance_records.status',
                    'attendance_records.delay_minutes',
                    'attendance_records.note',
                    'attendance_records.updated_at',
                ])
                ->orderBy('students.last_name')
                ->get()
            : collect();

        return Inertia::render('Attendance/ClassSheet', [
            'session' => $session ? [
                'title' => trim(($session->classroom_name ?: 'کلاس').' - '.($session->subject_name ?: 'درس')),
                'date' => $session->date_jalali ?: $this->jalaliDate($session->date),
                'status' => $session->status,
            ] : null,
            'records' => $records->map(fn ($record): array => [
                'student' => trim($record->first_name.' '.$record->last_name),
                'status' => $this->attendanceStatusLabel($record->status),
                'process' => $record->status === 'absent' ? 'در انتظار تایید SMS' : ($record->note ?: 'ثبت شده'),
                'time' => $record->updated_at ? $this->jalaliDate($record->updated_at, true) : '—',
            ])->values(),
        ]);
    }

    private function attendanceStatusLabel(string $status): string
    {
        return match ($status) {
            'present' => 'حاضر',
            'absent' => 'غایب',
            'late' => 'تاخیر',
            'excused' => 'موجه',
            default => $status,
        };
    }
}
