<?php

namespace App\Http\Controllers\Admin\AcademicClasses;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\AcademicClasses\AttendanceStoreRequest;
use App\Models\CourseClass;
use App\Services\Admin\AcademicClasses\AttendanceService;
use App\Services\Admin\Manage\CourseClassService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class AttendanceController extends Controller
{
    public function __construct(
        private readonly AttendanceService $service,
        private readonly CourseClassService $courseClassService,
    ) {}

    public function index(): Response
    {
        return Inertia::render('admin/academic-classes/attendances/index', [
            'sessions' => $this->service->sessions(),
            'courseClasses' => $this->courseClassService->getAllForSelect(),
        ]);
    }

    public function session(CourseClass $courseClass, int $meetingNumber): Response
    {
        $courseClass->load('course');
        $data = $this->service->session($courseClass, $meetingNumber);

        return Inertia::render('admin/academic-classes/attendances/session', [
            'courseClass' => $courseClass,
            'meetingNumber' => $meetingNumber,
            'roster' => $data['roster'],
            'date' => $data['date'],
        ]);
    }

    public function store(AttendanceStoreRequest $request, CourseClass $courseClass, int $meetingNumber): RedirectResponse
    {
        $this->service->saveSession($courseClass->id, $meetingNumber, $request->validated('date'), $request->validated('records'));

        Inertia::flash('toast', ['type' => 'success', 'message' => 'Kehadiran berhasil disimpan.']);

        return to_route('admin.academic-classes.attendances.session', [$courseClass->id, $meetingNumber]);
    }

    public function destroy(CourseClass $courseClass, int $meetingNumber): RedirectResponse
    {
        $this->service->deleteSession($courseClass->id, $meetingNumber);

        Inertia::flash('toast', ['type' => 'success', 'message' => 'Sesi kehadiran berhasil dihapus.']);

        return to_route('admin.academic-classes.attendances.index');
    }
}
