<?php

namespace App\Http\Requests\Mentorship;

use Illuminate\Foundation\Http\FormRequest;

class PaymentRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        $paymentMethod = $this->input('payment_method', 'mobile');

        $rules = [
            'application_id' => [
                'required',
                'exists:mentorship_applications,id',
            ],
            'payment_method' => ['nullable', 'string', 'in:mobile,card'],
            'amount' => ['nullable', 'numeric', 'min:1'],
            'currency' => ['nullable', 'string', 'size:3'],
        ];

        if ($paymentMethod === 'card') {
            $rules['card_number'] = ['required', 'string'];
            $rules['card_expiry'] = ['required', 'regex:/^(0[1-9]|1[0-2])\/\d{2}$/'];
            $rules['card_cvv']    = ['required', 'digits_between:3,4'];
        } else {
            $rules['phone_number'] = [
                'required',
                'string',
                'max:50',
                'regex:/^[0-9]{10,15}$/',
            ];
        }

        return $rules;
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'application_id.required' => 'Application ID is required.',
            'application_id.exists' => 'The specified application does not exist.',
            'phone_number.required' => 'Please enter your phone number for payment.',
            'phone_number.regex' => 'Please enter a valid phone number (10-15 digits).',
            'amount.numeric' => 'The amount must be a number.',
            'amount.min' => 'The amount must be at least 1.',
            'currency.size' => 'The currency must be a 3-letter code.',
        ];
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        // Normalize phone number
        if ($this->has('phone_number')) {
            $phone = preg_replace('/[^0-9]/', '', $this->input('phone_number'));
            $this->merge(['phone_number' => $phone]);
        }
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            // Verify application exists and requires payment
            if ($this->has('application_id')) {
                $application = \App\Models\Mentorship\Application::find($this->input('application_id'));
                
                if (!$application) {
                    return;
                }

                if (!$application->payment_required) {
                    $validator->errors()->add('application_id', 'This application does not require payment.');
                }

                if ($application->payment_status === 'paid') {
                    $validator->errors()->add('application_id', 'This application has already been paid.');
                }

                if (!in_array($application->status, ['pending', 'payment_pending', 'approved'])) {
                    $validator->errors()->add('application_id', 'This application is not in a payable status.');
                }
            }
        });
    }
}
