<?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 AttendanceApprovalController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);

        $requests = $schoolId
            ? DB::table('attendance_approval_requests')
                ->join('attendance_sessions', 'attendance_sessions.id', '=', 'attendance_approval_requests.attendance_session_id')
                ->join('classrooms', 'classrooms.id', '=', 'attendance_sessions.classroom_id')
                ->leftJoin('subjects', 'subjects.id', '=', 'attendance_sessions.subject_id')
                ->where('attendance_approval_requests.school_id', $schoolId)
                ->where('attendance_approval_requests.status', 'pending')
                ->select([
                    'classrooms.name as classroom_name',
                    'subjects.name as subject_name',
                    'attendance_approval_requests.absent_count',
                    'attendance_approval_requests.sms_cost',
                    'attendance_approval_requests.created_at',
                ])
                ->latest('attendance_approval_requests.created_at')
                ->get()
            : collect();

        return Inertia::render('Attendance/ApprovalQueue', [
            'requests' => $requests->map(fn ($item): array => [
                'classroom' => $item->classroom_name,
                'subject' => $item->subject_name ?: '—',
                'absentCount' => (int) $item->absent_count,
                'smsCost' => (int) $item->sms_cost,
                'createdAt' => $this->jalaliDate($item->created_at, true),
            ])->values(),
        ]);
    }
}
