<?php

namespace App\Http\Controllers;

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

    public function index(): View
    {
        $types = FeeType::orderBy('name')->get();

        return view('fees.types.index', compact('types'));
    }

    public function create(): View
    {
        return view('fees.types.create', ['type' => new FeeType()]);
    }

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

        return redirect()->route('fee-types.index')->with('success', 'Fee type created.');
    }

    public function edit(FeeType $feeType): View
    {
        return view('fees.types.edit', ['type' => $feeType]);
    }

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

        return redirect()->route('fee-types.index')->with('success', 'Fee type updated.');
    }

    public function destroy(FeeType $feeType): RedirectResponse
    {
        $feeType->delete();

        return redirect()->route('fee-types.index')->with('success', 'Fee type deleted.');
    }

    private function validateData(Request $request): array
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:100'],
            'code' => ['nullable', 'string', 'max:30'],
            'frequency' => ['required', 'in:'.implode(',', FeeType::FREQUENCIES)],
            'default_amount' => ['nullable', 'numeric', 'min:0'],
            'discountable' => ['nullable', 'boolean'],
            'is_active' => ['nullable', 'boolean'],
        ]);
        $data['discountable'] = (bool) ($data['discountable'] ?? false);
        $data['is_active'] = (bool) ($data['is_active'] ?? false);
        $data['default_amount'] = $data['default_amount'] ?? 0;

        return $data;
    }
}
