<?php

namespace App\Rules;

use App\Facades\Settings;
use Illuminate\Contracts\Validation\Rule;
use Mtc\MercuryDataModels\Country;

class ValidVehicleRegistrationNumber implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct(private ?bool $personalized = false, private ?bool $is_new = false)
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        // For personalized we skip validation
        if ($this->personalized) {
            return true;
        }

        // Skip validation if new AND no value provided
        if ($this->is_new && empty($value)) {
            return true;
        }

        $country = Country::query()
            ->where('code', Settings::get('app-details-country') ?? config('app.default_country'))
            ->firstOrFail();

        return empty($country->number_plate_regex) || preg_match($country->number_plate_regex, strtoupper($value));
    }


    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The number plate format is not valid.';
    }
}
