<?php

namespace App\Http\Controllers;

use App\Models\Subject;
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 SubjectController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:academics.view', only: ['index']),
            new Middleware('can:academics.create', only: ['create', 'store']),
            new Middleware('can:academics.update', only: ['edit', 'update']),
            new Middleware('can:academics.delete', only: ['destroy']),
        ];
    }

    public function index(): View
    {
        $subjects = Subject::withCount('classes')->orderBy('name')->get();

        return view('academics.subjects.index', compact('subjects'));
    }

    public function create(): View
    {
        return view('academics.subjects.create', ['subject' => new Subject()]);
    }

    public function store(Request $request, BranchContext $context): RedirectResponse
    {
        $data = $this->validateData($request);
        $data['branch_id'] = $context->currentId() ?? auth()->user()->branch_id;
        Subject::create($data);

        return redirect()->route('subjects.index')->with('success', 'Subject created.');
    }

    public function edit(Subject $subject): View
    {
        return view('academics.subjects.edit', compact('subject'));
    }

    public function update(Request $request, Subject $subject): RedirectResponse
    {
        $subject->update($this->validateData($request, $subject));

        return redirect()->route('subjects.index')->with('success', 'Subject updated.');
    }

    public function destroy(Subject $subject): RedirectResponse
    {
        $subject->delete();

        return redirect()->route('subjects.index')->with('success', 'Subject deleted.');
    }

    private function validateData(Request $request, ?Subject $subject = null): array
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'code' => ['nullable', 'string', 'max:30'],
            'is_elective' => ['nullable', 'boolean'],
            'is_active' => ['nullable', 'boolean'],
        ]);
        $data['is_elective'] = (bool) ($data['is_elective'] ?? false);
        $data['is_active'] = (bool) ($data['is_active'] ?? false);

        return $data;
    }
}
