<?php

namespace traits;

trait economic_endpoint_t
{
    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'];

    }

    /**
     * Filters for e-conomic requests
     * @param array $filters
     * @return string The filters for the request (e.g. 'customerNumber$eq:12345678')
     * @example ['customer.customerNumber' => '12345678']
     */
    public static function filters(array $filters): string
    {
        $filter_string = '';
        foreach ( $filters as $key => $value ) {
            // If the filter string is not empty, and the key has a value, add an $and
            if (!empty($filter_string) && !empty($value)) {
                $filter_string .= '$and:';
            }
            // Check if there's a "$" in the key, and if not, add it as $eq (equals) by default
            if (!str_contains($value, '$') && !empty($value)) {
                $value = '$eq:' . $value;
            }
            $filter_string .= $key . $value;
        }
        return $filter_string;
    }

    /**
     * Pagination for e-conomic requests
     * @param array $pagination
     * @return string The pagination for the request (e.g. '&maxPageSize=100&skipPages=0')
     * @example ['maxPageSize' => 100, 'skipPages' => 0]
     */
    public static function pagination(array $pagination): string
    {
        $pagination_string = '';
        foreach ( $pagination as $key => $value ) {
            $pagination_string .= '&' . $key . '=' . $value;
        }
        return $pagination_string;
    }

    /**
     * Send a request to the Economic API
     * @param string $url
     * @param string $method
     * @param string $data
     * @param bool $authToken2
     * @return string
     */
    public 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);
        }
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($curl);
        // Check for errors
        if (curl_errno($curl)) {
            echo 'Curl error: ' . curl_error($curl);
            return curl_error($curl);
        }
        curl_close($curl);
        return $response;
    }

    public function send_file_download_request($url, $method, $data = '', bool $authToken2 = false, $outputFile = null)
    {
        // Initialize cURL session
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->api_url . $url,
            CURLOPT_RETURNTRANSFER => true, // Get the response as a string
            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'
            ),
        ));

        // Execute the request
        $response = curl_exec($curl);

        // Handle errors
        if (curl_errno($curl)) {
            echo 'Curl error: ' . curl_error($curl);
            return curl_error($curl);
        }

        // Close the cURL session
        curl_close($curl);

        // If a file path is provided, save the response to the file
        if ($outputFile) {
            // Write file contents
            file_put_contents($outputFile, $response);
            return "File saved to: " . $outputFile;
        }

        // Otherwise, return the raw content (e.g., for inline use)
        return $response;
    }
}