<?php

namespace App\Http\Controllers;

use App\Models\FeeChallan;
use App\Models\FeePayment;
use App\Services\FeeService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class FeePaymentController extends Controller implements HasMiddleware
{
    public function __construct(private FeeService $fees)
    {
    }

    public static function middleware(): array
    {
        return [new Middleware('can:fees.collect')];
    }

    public function store(Request $request, FeeChallan $challan): RedirectResponse
    {
        if (in_array($challan->status, ['paid', 'waived'], true)) {
            return back()->with('error', 'This challan is already settled.');
        }

        $data = $request->validate([
            'amount' => ['required', 'numeric', 'min:0.01', 'max:'.max($challan->balance, 0.01)],
            'payment_date' => ['required', 'date'],
            'payment_method_id' => ['nullable', 'exists:payment_methods,id'],
            'method' => ['nullable', 'in:'.implode(',', array_keys(FeePayment::METHODS))],
            'reference' => ['nullable', 'string', 'max:100'],
            'notes' => ['nullable', 'string', 'max:200'],
        ]);

        // Derive the legacy method string (channel) from the chosen payment method.
        if (! empty($data['payment_method_id'])) {
            $data['method'] = \App\Models\PaymentMethod::find($data['payment_method_id'])?->channel ?? 'cash';
        }
        $data['method'] ??= 'cash';

        $this->fees->recordPayment($challan, $data);

        return back()->with('success', 'Payment of '.number_format($data['amount']).' recorded.');
    }

    public function destroy(FeeChallan $challan, FeePayment $payment): RedirectResponse
    {
        abort_unless($payment->fee_challan_id === $challan->id, 404);
        $payment->delete();
        $challan->recalculateStatus();

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