<?php

namespace App\Services\ThirdPartyApiServices\VATApi;

use App\Models\CSRNow\Country;
use App\Services\ThirdPartyApiServices\BaseApiCall;
use Illuminate\Support\Facades\Session;

class VATService extends BaseApiCall
{
    protected array $data = [];
    protected array $config = [];
    protected string $mode;

    public function __construct()
    {
        $this->config = config('amplivo.eu_vat_api');
        $this->mode = $this->config['mode'];
        $this->setCredential($this->config['access_key']);
        if ($this->mode == 'live') {
            $this->setApiUrl($this->config['live_endpoint']);
        } elseif ($this->mode == 'test') {
            $this->setApiUrl($this->config['test_endpoint']);
        }
    }

    /**
     * @param $data
     * @param string $query
     * @param string $param
     * @return array|mixed|void
     */
    public function validate($data, string $query = 'vat_number', string $param = 'validate')
    {
        $this->setQueryData($query, $data);
        return $this->callToApi($param);
    }

    /**
     * @param $data
     * @param string $query
     * @param string $param
     * @return array|mixed|void
     */
    public function getCountriesByIP($data, string $query = 'ip_address', string $param = 'rate')
    {
        $this->setQueryData($query, $data);
        return $this->callToApi($param);
    }

    /**
     * @return array
     */
    public function calculateRate($request)
    {
        $vatNumber = $request->input('vat_number');
        $countryInput = $request->input('country');
        $sessionData = Session::get('product.data');
        $country = null;
        $getRateByCountryCode = null;
        if ($countryInput) {
            $country = Country::findOrFail($countryInput)->country_code;
            $getRateByCountryCode = $this->getRateByCountryCode($country);
        }

        // if country is not empty and vat number is not empty
        if (!empty($country) && !empty($vatNumber)) {
            $isEU = $this->getEUCountries();
            if (array_key_exists($country, $isEU)) {
                if ($country === 'EE') {
                    $percent = 20;
                } elseif ($country === 'GB') {
                    $percent = 0;
                } else {
                    $percent = 'Reverse-Charge';
                }
            } else {
                // Business, non-European Union, non-Estonia
                $percent = 0;
            }
        } // if country is not empty and EE (Estonia) vat rate is 20%
        elseif (!empty($country) && $country === 'EE') {
            $percent = 20;
        } // if country is not empty and GB (United Kingdom) vat rate is 0%
        elseif (!empty($country) && $country === 'GB') {
            $percent = 0;
        } // if country is not empty and returns false vat rate is 0%
        elseif (!empty($country) && $getRateByCountryCode['success'] === false) {
            $percent = 0;
        } // if country is not empty get vat rate from api for other countries
        else {
            if (empty($country)) {
                $percent = 0;
            } else {
                $percent = $getRateByCountryCode['standard_rate'];
            }
        }
        $vatAmount = ($sessionData['price'] * ($percent !== 'Reverse-Charge' ? $percent : 0) / 100);
        $netAmount = ($sessionData['price'] + $vatAmount);
        $grossAmount = (int)$sessionData['price'];


        return [
            'vat_percentage' => $percent,
            'vat_amount' => $vatAmount,
            'net_amount' => $netAmount,
            'gross_amount' => $grossAmount,

            'po_vat_percentage' => $percent,
            'po_vat_amount' => $vatAmount,
            'po_net_amount' => $netAmount,
            'po_gross_amount' => $grossAmount,
        ];
    }

    /**
     * @param $data
     * @param string $query
     * @param string $param
     * @return array|mixed|void
     */
    public function getRateByCountryCode($data, string $query = 'country_code', string $param = 'rate')
    {
        $this->setQueryData($query, $data);
        return $this->callToApi($param);
    }

    /**
     * @param string $data
     * @param string $query
     * @param string $param
     * @return array
     */
    public function getEUCountries(string $data = '', string $query = '', string $param = 'rate_list')
    {
        $countries = [];
        $this->setQueryData($query, $data);
        $response = $this->callToApi($param);
        if (!empty($response['rates'])) {
            foreach ($response['rates'] as $key => $rate) {
                $countries[$key] = $rate['country_code'];
                $countries[$key] = $rate['country_name'];
            }
        }
        return $countries;
    }
}
