<?php

namespace App\Rules\VAT;

use App\Models\ApiSettings;
use App\Models\CSRNow\Country;
use App\Services\ThirdPartyApiServices\VATApi\VATService;
use Illuminate\Contracts\Validation\Rule;

class ValidVatNumber implements Rule
{
    protected $vatService;
    protected $response;
    protected $message;
    protected $vatApi;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->vatService = new VATService();
        $this->vatApi = ApiSettings::where('domain_holder', '=', ApiSettings::DOMAIN_HOLDER['eu_vat_api'])->first();
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if ($this->vatApi->status !== ApiSettings::ENABLE) {
            reportLog('Vat System is Currently Disabled by the Administration.');
            return $this->fail('Vat System is Currently Down. Please Contact Support.');
        }

        $this->response = $this->vatService->validate($value);

        if ($this->response) {
            if (!$this->response['success']) {
                reportLog($this->response['error']['info']);
                return $this->fail('Something went wrong. Please Contact Support.');
            }


            // vat number validity check fails
            if (!$this->response['valid']) {
                return $this->fail('VAT number is not valid.');
            }

            // if vat number format check fails
            if (!$this->response['format_valid']) {
                return $this->fail('VAT number format is not valid.');
            }

            // special character check
            if (!preg_match('/^[A-Za-z0-9 ]+$/', $value)) {
                return $this->fail('Special characters are not allowed.');
            }

            // Cross-match
            if (!is_null(request('country'))) {
                $country = Country::findOrFail(request('country'));
                if ($this->response['country_code'] != $country->country_code) {
                    return $this->fail('VAT Number did not matched with the selected country.');
                }
            } else {
                return $this->fail('Country field is required with VAT Number.');
            }
        } else {
            return $this->fail('Something went wrong, during vat number validation. Please contact administration.');
        }

        return true;
    }

    /**
     * @param $message
     * @return false
     */
    protected function fail($message)
    {
        $this->message = $message;
        return false;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->message;
    }
}
