<?php

namespace App\Http\Controllers;

use App\Models\GradeScale;
use App\Support\BranchContext;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\View\View;

class GradeScaleController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:exams.view', only: ['index']),
            new Middleware('can:exams.update', only: ['store', 'destroy']),
        ];
    }

    public function index(): View
    {
        $grades = GradeScale::orderByDesc('min_percentage')->get();

        return view('exams.grades.index', compact('grades'));
    }

    public function store(Request $request, BranchContext $context): RedirectResponse
    {
        $data = $request->validate([
            'grade' => ['required', 'string', 'max:5'],
            'min_percentage' => ['required', 'numeric', 'min:0', 'max:100'],
            'max_percentage' => ['required', 'numeric', 'gte:min_percentage', 'max:100'],
            'gpa' => ['required', 'numeric', 'min:0', 'max:5'],
            'remark' => ['nullable', 'string', 'max:100'],
        ]);
        $branchId = $context->currentId() ?? auth()->user()->branch_id ?? \App\Models\Branch::min('id');

        GradeScale::updateOrCreate(
            ['branch_id' => $branchId, 'grade' => $data['grade']],
            $data + ['branch_id' => $branchId]
        );

        return back()->with('success', 'Grade band saved.');
    }

    public function destroy(GradeScale $gradeScale): RedirectResponse
    {
        $gradeScale->delete();

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