<?php

namespace App\Http\Controllers;

use App\Models\Exam;
use App\Models\ExamPaper;
use App\Models\SchoolClass;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class ExamPaperController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [new Middleware('can:exams.update')];
    }

    /** Generate papers for every allocated subject of a class. */
    public function generate(Request $request, Exam $exam): RedirectResponse
    {
        $data = $request->validate([
            'class_id' => ['required', 'exists:classes,id'],
            'total_marks' => ['required', 'numeric', 'min:1'],
            'passing_marks' => ['required', 'numeric', 'min:0'],
        ]);

        $class = SchoolClass::with('subjects')->findOrFail($data['class_id']);

        foreach ($class->subjects as $subject) {
            ExamPaper::firstOrCreate(
                ['exam_id' => $exam->id, 'class_id' => $class->id, 'subject_id' => $subject->id],
                ['branch_id' => $exam->branch_id, 'total_marks' => $data['total_marks'], 'passing_marks' => $data['passing_marks']]
            );
        }

        return back()->with('success', "Papers generated for {$class->name}.");
    }

    public function destroy(ExamPaper $paper): RedirectResponse
    {
        $paper->delete();

        return back()->with('success', 'Paper removed.');
    }
}
