<?php

namespace App\Http\Controllers;

use App\Models\Exam;
use App\Models\QuizAttempt;
use Illuminate\Http\Request;

class StudentExamController extends Controller
{
    public function join(Request $request, Exam $exam)
    {
        $user = $request->user();

        if (!$user->school_id || $user->school_id !== $exam->school_id) {
            return back()->withErrors(['exam' => __('app.student.exams.errors.not_in_school')]);
        }
        if ($exam->grade !== null && (string)$user->grade !== (string)$exam->grade) {
            return back()->withErrors(['exam' => __('app.student.exams.errors.grade_mismatch')]);
        }
        if (!$exam->is_active) {
            return back()->withErrors(['exam' => __('app.student.exams.errors.inactive')]);
        }


        // One attempt per (user, exam) – also enforced by unique index in DB
        $attempt = QuizAttempt::firstOrCreate(
            ['user_id' => $user->id, 'exam_id' => $exam->id],
            [
                'subject_id'   => $exam->subject_id,
                'max_items'    => $exam->num_questions, // map num_questions -> max_items
                'start_level'  => 5,
                'start_theta'  => 0,
                'started_at'   => now(),
            ]
        );

        // app/Http/Controllers/StudentExamController.php
// ...
        if ($attempt->finished_at) {
            // still do NOT show results to students for exam attempts
            return redirect()->route('exams.attempts.submitted', $attempt->id);
        }
        return redirect()->route('exams.attempts.show', $attempt->id);

    }
}
