<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Route;

class LoanRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        $route = Route::getCurrentRoute()->getName();
        $rules = [
            'fk_site' => ['required', 'integer', 'exists:sy_sites,id'],
            'fk_office' => ['required', 'integer', 'exists:sy_offices,id']
        ];

        $routeRules = [
            'loan.index' => [],
            'loan.store' => [],
            'loan.destroy' => [
                'id' => ['required', 'integer', 'exists:sy_loans,id']
            ],
            'loan.show' => [
                'id' => ['required', 'integer', 'exists:sy_loans,id']
            ],
            'loan.show-renew' => [
                'id' => ['required', 'integer', 'exists:sy_loans,id']
            ],
            'loan.renew' => [
                'id' => ['required', 'integer', 'exists:sy_loans,id'],
                'fk_loan_type' => ['required', 'integer', 'exists:sy_loan_types,id'],
                'loanamount' => ['required', 'numeric', 'min:500'],
                'weeklypayment' => ['required', 'numeric', 'min:50'],
                'duration' => ['required', 'integer', 'min:1'],
                'loandate' => ['date', 'date'],
                'loanenddate' => ['date', 'date'],
                'realamount' => ['required', 'numeric', 'min:0'],
                'renewpayment' => ['required', 'numeric', 'min:0'],
                'paperworkpayment' => ['required', 'numeric', 'min:0'],
                'otherpayment' => ['required', 'numeric', 'min:0'],
                'interesrate' => ['sometimes', 'nullable', 'numeric', 'min:0'],
            ],
            'loan.reestructure' => [
                'id' => ['required', 'integer', 'exists:sy_loans,id'],
                'fk_loan_type' => ['required', 'integer', 'exists:sy_loan_types,id'],
                'loanamount' => ['required', 'numeric', 'min:500'],
                'weeklypayment' => ['required', 'numeric', 'min:50'],
                'duration' => ['required', 'integer', 'min:1'],
                'loandate' => ['date', 'date'],
                'loanenddate' => ['date', 'date'],
                'realamount' => ['required', 'numeric', 'min:0'],
                'renewpayment' => ['required', 'numeric', 'min:0'],
                'paperworkpayment' => ['required', 'numeric', 'min:0'],
                'otherpayment' => ['required', 'numeric', 'min:0'],
                'interesrate' => ['sometimes', 'nullable', 'numeric', 'min:0'],
            ]
        ];

        return array_merge($rules, $routeRules[$route]);
    }
}
