<?php

namespace App\Http\Requests;

use Illuminate\Validation\Validator;
use Mtc\MercuryDataModels\DealBuilder\DealPaymentType;

class InitiateDealPayment extends DealBuilderRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email:rfc,dns', 'max:255'],
            'contact_number' => ['required', 'string', 'max:50'],
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            $deal = $this->deal();

            // Finance selection is required unless payment type is full payment
            if ($deal->payment_type !== DealPaymentType::FULL_PAYMENT) {
                $hasSelectedFinance = $deal->finance()->where('selected', true)->exists();

                if (!$hasSelectedFinance) {
                    $validator->errors()->add('finance', __('deal_builder.finance_selection_required'));
                }
            }
        });
    }
}
