<?php

use classes\economic;

class economic_m
{
    public economic $economic;
    /**
     * https://secure.e-conomic.com/secure/api1/requestaccess.aspx?appPublicToken=WeG89W2Y63wLjy1lnqfpsHlfa1mBiyNKByqtGmBOoOw&redirectUrl=truckwash.dk
     */
    private string $api_url = 'https://restapi.e-conomic.com';
    private string $appAccessGrant;
    private string $app_token;
    private string $appAccessGrant2;

    public function __construct()
    {
        global $ECONOMIC_API;
        $this->app_token = $ECONOMIC_API['app_secret_token'];
        $this->appAccessGrant = $ECONOMIC_API['app_access_grant'];
        $this->appAccessGrant2 = $ECONOMIC_API['app_access_grant2'];
        $this->economic = new economic();
    }

    /**
     * Allowed search filters
     * @return array
     */
    public function allowed_search_filters_customers(): array
    {
        return [
            'address', 'balance', 'barred', 'city', 'corporateIdentificationNumber', 'country', 'creditLimit', 'currency', 'customerGroup.customerGroupNumber', 'customerNumber', 'ean', 'email', 'lastUpdated', 'mobilePhone', 'name', 'publicEntryNumber', 'telephoneAndFaxNumber', 'vatNumber', 'website', 'zip'
        ];
    }

    /**
     * Send a request to the Economic API
     * @param string $url
     * @param string $method
     * @param string $data
     * @param bool $authToken2
     * @return string
     */
    protected function send_request($url, $method, $data = '', bool $authToken2 = false): string
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->api_url . $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => array(
                'X-AppSecretToken: ' . $this->app_token,
                'X-AgreementGrantToken: ' . ($authToken2 ? $this->appAccessGrant2 : $this->appAccessGrant),
                'Content-Type: application/json'
            ),
        ));

        if ($method === 'POST') {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }

        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
}