<?php

declare(strict_types=1);

namespace App\Http\Requests\Wallet;

use Illuminate\Foundation\Http\FormRequest;

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

    public function rules(): array
    {
        return [
            'bank_name' => ['nullable', 'string', 'max:100'],
            'card_number' => ['nullable', 'string', 'regex:/^\d{16}$/'],
            'shaba' => ['required', 'string', 'regex:/^IR\d{24}$/'],
            'account_holder_name' => ['required', 'string', 'max:120'],
            'is_default' => ['nullable', 'boolean'],
        ];
    }

    public function messages(): array
    {
        return [
            'shaba.regex' => 'شماره شبا باید با IR و ۲۴ رقم باشد.',
            'card_number.regex' => 'شماره کارت باید ۱۶ رقم باشد.',
        ];
    }

    protected function prepareForValidation(): void
    {
        if ($this->has('shaba')) {
            $shaba = strtoupper(preg_replace('/\s+/', '', (string) $this->input('shaba')) ?? '');
            $this->merge(['shaba' => $shaba]);
        }

        if ($this->has('card_number')) {
            $card = preg_replace('/\D+/', '', (string) $this->input('card_number')) ?? '';
            $this->merge(['card_number' => $card !== '' ? $card : null]);
        }
    }
}
