<?php

namespace App\Http\Controllers;

use App\Models\Fee;
use App\Models\Classes;
use Illuminate\Http\Request;

class FeeController extends Controller
{
    public function index()
    {
        $fees = Fee::with('class')->latest()->paginate(20);
        return view('admin.fees.index', compact('fees'));
    }

    public function create()
    {
        $classes = Classes::all();
        return view('admin.fees.create', compact('classes'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'category' => 'nullable|string',
            'amount' => 'required|numeric|min:0',
            'currency' => 'default:NGN',
            'session_year' => 'required|string',
            'term' => 'required|string',
            'class_id' => 'nullable|exists:classes,id',
            'is_compulsory' => 'boolean',
            'deadline' => 'nullable|date',
            'description' => 'nullable|string',
        ]);

        Fee::create($validated);

        return redirect()->route('admin.fees.index')->with('success', 'Fee created successfully!');
    }

    public function show(Fee $fee)
    {
        return view('admin.fees.show', compact('fee'));
    }

    public function edit(Fee $fee)
    {
        $classes = Classes::all();
        return view('admin.fees.edit', compact('fee', 'classes'));
    }

    public function update(Request $request, Fee $fee)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'category' => 'nullable|string',
            'amount' => 'required|numeric|min:0',
            'currency' => 'default:NGN',
            'session_year' => 'required|string',
            'term' => 'required|string',
            'class_id' => 'nullable|exists:classes,id',
            'is_compulsory' => 'boolean',
            'deadline' => 'nullable|date',
            'description' => 'nullable|string',
        ]);

        $fee->update($validated);

        return redirect()->route('admin.fees.index')->with('success', 'Fee updated successfully!');
    }

    public function destroy(Fee $fee)
    {
        $fee->delete();
        return redirect()->route('admin.fees.index')->with('success', 'Fee deleted successfully!');
    }
}