<?php

namespace App\Http\Requests\Admin\Finances;

use App\Enums\PaymentMethod;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class TuitionPaymentRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can($this->isMethod('post') ? 'create-tuition-payments' : 'update-tuition-payments');
    }

    public function rules(): array
    {
        $invoice = $this->route('tuition_invoice');
        $payment = $this->route('payment');

        $otherPaidTotal = $invoice->payments()
            ->when($payment, fn ($query) => $query->where('id', '!=', $payment->id))
            ->sum('amount_paid');

        $remaining = max(0, round($invoice->amount_due - $otherPaidTotal, 2));

        return [
            'amount_paid' => ['required', 'numeric', 'min:0.01', "max:{$remaining}"],
            'paid_at' => ['required', 'date', 'before_or_equal:now'],
            'payment_method' => ['required', Rule::enum(PaymentMethod::class)],
            'notes' => ['nullable', 'string'],
            'proof' => ['nullable', 'file', 'max:10240', 'mimes:pdf,jpg,jpeg,png'],
        ];
    }

    public function messages(): array
    {
        return [
            'amount_paid.max' => 'Jumlah dibayar tidak boleh melebihi sisa tagihan.',
            'paid_at.before_or_equal' => 'Tanggal & waktu bayar tidak boleh melebihi waktu saat ini.',
        ];
    }
}
