<?php
/**
 * This is a common store component which will be used across all
 * Module-store-controllers
 *
 * PHP version 5.6
 *
 * @category  Magento_Store
 * @package   Store
 * @author    Travis <travis@imprintnext.com>
 * @copyright 2021-2022 Imprintnext
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 * @link      http://inkxe-v10.inkxe.io/xetool/admin
 */
namespace ComponentStoreSpace\Controllers;

use App\Components\Controllers\Component;

/**
 * Store Component
 *
 * @category Magento_Store
 * @package  Store
 * @author   Travis <travis@imprintnext.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     https://imprintnext.com/
 */
class StoreComponent extends Component
{
    function __construct(){
        parent::__construct();
        $this->headers = array(
            'Authorization: Bearer '.ACCESSTOKEN,
            'Accept: application/json',
            'Content-Type: application/json'
        );
    }
    /**
     * Magento REST API call helper function
     *
     * @param $httpMethod  REST API call method (GET, POST, PUT, DELETE)
     * @param $path  Magento API end point
     * @param $params  Magento API parameters if any
     *
     * @author steve@imprintnext.com
     * @date   17 may 2022
     * @return Magento REST API call response in array
     */
    public function call($httpMethod, $module, $path, $params = array(), $version = 'V1'){
        $apiPath = API_PATH.'/'.$module."/".$path;
        switch ($httpMethod) {
            case "GET":
            $result = $this->get($apiPath, $params);
            break;
            case "POST":
            $result = $this->post($apiPath, $params);
            break;
            case "PUT":
            $result = $this->put($apiPath, $params);
            break;
            case "DELETE":
            $result = $this->delete($apiPath, $params);
            break;
            default:
            $result =  "Error";
        }
        return $result;
    }
    
    /**
     * Performs a get request to the instantiated class.
     * 
     * 
     * @param $path string $path a string Magento Rest Api End Point.
     * @param $params array of arguments.
     * @return results in json format.
     */
    private function get($apiPath, $params = array()){
        if(!empty($params)){
            $pathValue = "filters=1&";
            foreach($params as $key => $value){
                if($key == 'range'){
                   $pathValue .= "range=".$value['range']."&";
                }
                if(!is_array($value)){
                    $pathValue .= $key .'='. $value."&" ;
                }
            }
            $pathValue = rtrim($pathValue, '&');
            $apiPath .= "?".$pathValue;
            $apiPath = str_replace(" ","%20",$apiPath);
        }
        try {
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $apiPath,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLOPT_HTTPHEADER => $this->headers,
            ));        
            $response = curl_exec($curl);
            $err = curl_error($curl);
            curl_close($curl);
            $response = json_clean_decode($response);
        }catch (\Exception $e) {
            // Store exception in logs
            create_log(
                'store', 'error',
                [
                    'message' => $e->getMessage(),
                    'extra' => [
                        'module' => 'Rest Api GET Method Issue'
                    ]
                ]
            );
            $response = 'Error in Rest Api';
        }
        return $response;
    }

    /**
     * Performs a get request to the instantiated class.
     * 
     * @param $path string $path a string Magento Rest Api End Point.
     * @param $params array of arguments.
     * @return results in json format.
     */
    private function post($apiPath, $params = array()){
        $jsonParam = json_encode($params);
        try {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $apiPath);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $this->headers);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_VERBOSE, 1);
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonParam);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            $response = curl_exec($curl);
            $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
            $body = substr($response, $header_size);
            curl_close ($curl);
        }catch (\Exception $e) {
            // Store exception in logs
            create_log(
                'store', 'error',
                [
                    'message' => $e->getMessage(),
                    'extra' => [
                        'module' => 'Rest Api POST Method Issue'
                    ]
                ]
            );
            $response = 'Error In Rest Api';
        }
        return json_decode($response,true);
    }
}
