<?php

namespace App\Http\Controllers\Api\Attendance;

use App\Http\Controllers\Controller;
use App\Http\Requests\Attendance\TeacherSubmitAttendanceRequest;
use App\Http\Resources\Attendance\TeacherAttendanceFormResource;
use App\Http\Resources\Attendance\TeacherGridResource;
use App\Services\Attendance\AttendanceQueryService;
use App\Services\Attendance\AttendanceService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Throwable;

class TeacherAttendanceApiController extends Controller
{
    public function __construct(
        protected AttendanceQueryService $queryService,
        protected AttendanceService $attendanceService
    ) {}

    public function grid(Request $request): TeacherGridResource
    {
        $semester = (string)($request->query('semester') ?: $this->attendanceService->currentSemester());
        $schoolYear = (string)($request->query('school_year') ?: $this->attendanceService->currentSchoolYear());
        $date = (string)($request->query('date') ?: now()->toDateString());
        $sectionCode = (int)$request->query('class_section_id', 0);

        return new TeacherGridResource(
            $this->queryService->teacherGrid($semester, $schoolYear, $date, $sectionCode)
        );
    }

    public function form(Request $request): JsonResponse|TeacherAttendanceFormResource
    {
        try {
            return new TeacherAttendanceFormResource(
                $this->queryService->teacherAttendanceFormData(
                    auth()->id(),
                    (int)$request->query('class_section_id', 0)
                )
            );
        } catch (Throwable $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }

    public function submit(TeacherSubmitAttendanceRequest $request): JsonResponse
    {
        try {
            return response()->json(
                $this->attendanceService->submitTeacherAttendance(auth()->user(), $request->validated())
            );
        } catch (Throwable $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }
}