<?php

namespace Tops\AmazonSellingPartnerAPI\Helpers;

use Tops\AmazonSellingPartnerAPI\Signature;

trait SellingPartnerApiRequest
{
    /**
     * Generate request data
     *
     * @param string $resource_path
     *
     * @param array $query_params
     *
     * @param array $http_body
     *
     * @param  object $config
     */
    protected function generateRequest($resource_path, $query_params, $http_body, $config, string $method, string $service_name="execute-api")
    {
        $headers['Content-Type'] = 'application/json';
        
        if ($service_name=="sts") {
            $headers['Accept'] = 'application/json';
        }
        
        if (!empty($config->getSessionToken())) {
            $headers['X-Amz-Security-Token'] = $config->getSessionToken();
        }
        
        $headers['x-amz-access-token'] = $config->getAccessToken();
        $headers['user-agent'] = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;NLNL)';
      
        // sort query params in acceding order
        if (!empty($query_params)) {
            ksort($query_params);
        }
       
        $amazonHeader = Signature::calculateSignature(
            $config,
            str_replace('https://', '', $config->getHost()),
            $method,
            $resource_path,
            http_build_query($query_params),
            $http_body,
            $service_name
        );

        $headers = array_merge(
            $headers,
            $amazonHeader
        );

        return $this->createCurlHeader($headers);
    }

    /**
     * Send request
     *
     * @param string $url
     *
     * @param array $query_params
     *
     * @param array $curl_headers
     */
    protected function sendRequest($url, $query_params, $http_body, $curl_headers, $method)
    {
        $url = empty($query_params) ? $url : $url . '?' . http_build_query($query_params);
        return $this->curlCall($url, $query_params, $http_body, $curl_headers, $method);
    }

    /**
     * Convert array of header to curl header
     *
     * @param array $headers
     *
     * @return array $header_array
     */
    private function createCurlHeader($headers)
    {
        $header_array = array();
        $opt_count = 0;
        foreach ($headers as $key => $header) {
            $opt_count++;
            $header_array[] = $key . ':' . $header;
        }
        return  $header_array;
    }

    private function curlCall($url, $get_array, $http_body, $header, $method)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLINFO_HEADER_OUT, false);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_COOKIESESSION, true);
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        switch ($method) {
            case 'POST':
                curl_setopt($ch, CURLOPT_POST, true);
                if (!empty($http_body)) {
                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($http_body));
                }
                break;
            case 'PUT':
                if (!empty($http_body)) {
                    if (isset($this->config->putType) && $this->config->putType=='json') {
                        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($http_body));
                    } else {
                        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($http_body));
                    }
                }
                break;
            case 'DELETE':
                if (!empty($http_body)) {
                    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($http_body));
                }
                break;
            case 'GET':
            default:
        }

        $result = curl_exec($ch);
                // dump(curl_getinfo($ch,CURLOPT_POSTFIELDS)); die;
        $result = json_decode($result, true);
        return $result;
    }
}
