<?php

namespace App\Http\Controllers;

use App\Models\AcademicSession;
use App\Models\FeeStructure;
use App\Models\FeeType;
use App\Models\SchoolClass;
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 FeeStructureController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:fees.view', only: ['index']),
            new Middleware('can:fees.update', only: ['store']),
        ];
    }

    public function index(Request $request): View
    {
        $session = $request->integer('session_id') ?: optional(AcademicSession::current())->id;
        $classId = $request->integer('class_id') ?: null;

        $feeTypes = FeeType::active()->orderBy('name')->get();
        $amounts = collect();

        if ($session && $classId) {
            $amounts = FeeStructure::where('academic_session_id', $session)
                ->where('class_id', $classId)
                ->pluck('amount', 'fee_type_id');
        }

        return view('fees.structure.index', [
            'sessions' => AcademicSession::orderByDesc('id')->get(),
            'classes' => SchoolClass::active()->orderBy('level')->get(),
            'feeTypes' => $feeTypes,
            'amounts' => $amounts,
            'sessionId' => $session,
            'classId' => $classId,
        ]);
    }

    public function store(Request $request, BranchContext $context): RedirectResponse
    {
        $data = $request->validate([
            'session_id' => ['required', 'exists:academic_sessions,id'],
            'class_id' => ['required', 'exists:classes,id'],
            'amounts' => ['array'],
            'amounts.*' => ['nullable', 'numeric', 'min:0'],
        ]);

        $branchId = $context->currentId() ?? auth()->user()->branch_id;

        foreach ($data['amounts'] as $feeTypeId => $amount) {
            FeeStructure::updateOrCreate(
                ['academic_session_id' => $data['session_id'], 'class_id' => $data['class_id'], 'fee_type_id' => $feeTypeId],
                ['branch_id' => $branchId, 'amount' => $amount ?? 0]
            );
        }

        return back()->with('success', 'Fee structure saved.');
    }
}
