<?php

namespace App\Http\Requests\Admin\Finances;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

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

    public function rules(): array
    {
        $rules = [
            'academic_term_id' => ['required', 'integer', Rule::exists('academic_terms', 'id')],
            'amount_due' => ['required', 'numeric', 'min:0'],
            'due_date' => ['required', 'date'],
        ];

        if ($this->isMethod('post')) {
            $rules['student_ids'] = ['required', 'array', 'min:1'];
            $rules['student_ids.*'] = [
                'integer',
                Rule::exists('students', 'id'),
                Rule::unique('tuition_invoices', 'student_id')
                    ->where('academic_term_id', $this->input('academic_term_id')),
            ];
        } else {
            $invoice = $this->route('tuition_invoice');

            $rules['student_id'] = [
                'required',
                'integer',
                Rule::exists('students', 'id'),
                Rule::unique('tuition_invoices', 'student_id')
                    ->where('academic_term_id', $this->input('academic_term_id'))
                    ->ignore($invoice?->id),
            ];
        }

        return $rules;
    }

    public function messages(): array
    {
        return [
            'student_ids.*.unique' => 'Salah satu mahasiswa yang dipilih sudah memiliki tagihan untuk periode akademik tersebut.',
            'student_id.unique' => 'Mahasiswa ini sudah memiliki tagihan untuk periode akademik tersebut.',
        ];
    }
}
