<?php

namespace App\Http\Requests;

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

class RLoanRequest 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 = [
            'requestloan.index' => [],
            'requestloan.store' => [
                'fk_loan_type' => ['required', 'integer', 'exists:sy_loan_types,id'],
                'loandate' => ['required', 'date'],
                'loanenddate' => ['required', 'date'],
                'loans' => ['required', 'array', 'min:1']
            ],
            'requestloan.update' => [
                'id' => ['required', 'integer', 'exists:sy_loan_requests,id'],
                'fk_loan_type' => ['required', 'integer', 'exists:sy_loan_types,id'],
                'fk_group' => ['nullable', 'integer', 'exists:sy_groups,id'],
                'fk_promoter' => ['nullable', 'integer', 'exists:ct_collaborators,id'],
                'fk_request_client' => ['nullable', 'integer', 'exists:sy_clients,id'],
                'fk_client' => ['nullable', 'integer', 'exists:sy_clients,id'],
                'duration' => ['required', 'integer', 'min:1'],
                'loandate' => ['required', 'date'],
                'loanenddate' => ['required', 'date'],
                'weeklypayment' => ['required', 'numeric', 'min:0'],
                'realamount' => ['required', 'numeric', 'min:0'],
                'fk_executive' => ['nullable', 'integer', 'exists:ct_collaborators,id'],
                'fk_supervisor' => ['nullable', 'integer', 'exists:ct_collaborators,id'],
                'fk_collaborator' => ['nullable', 'integer', 'exists:sy_collaborators,id'],
                'firstpay' => ['required', 'boolean'],
                'renewpayment' => ['nullable', 'numeric', 'min:0'],
                'paperworkpayment' => ['nullable', 'numeric', 'min:0'],
                'otherpayment' => ['nullable', 'numeric', 'min:0'],
                'interesrate' => ['sometimes'],
            ],
            'requestloan.destroy' => [
                'id' => ['required', 'integer', 'exists:sy_loan_requests,id']
            ],
            'requestloan.show' => [
                'id' => ['required', 'integer', 'exists:sy_loan_requests,id']
            ],
            'requestloan.approveReject' => [
                'id' => ['required', 'integer', 'exists:sy_loan_requests,id'],
                'approved' => ['boolean'],
            ]
        ];

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