<?php

namespace EasySales\Integrari\Core;

use EasySales\Integrari\Helper\Data;
use Magento\Framework\HTTP\ClientInterface;

class EasySales
{
    const MODULE_NAME = 'EasySales_Integrari';
    const MICROSERVICE_URL = "https://magento2-microservice.easysales.ro/api";
    const DECIMAL_PRECISION = 4;

    /**
     * @var ClientInterface
     */
    private $client;

    /**
     * @var Data
     */
    private $helperData;

    /**
     * @var mixed
     */
    public $websiteToken;

    /**
     * @var array
     */
    private $routes;



    /**
     * EasySales constructor.
     * @param ClientInterface $client
     * @param Data $helperData
     */
    public function __construct(ClientInterface $client, Data $helperData)
    {
        $this->client = $client;
        $this->helperData = $helperData;
        $this->websiteToken = $helperData->getGeneralConfig('website_token');

        $this->routes = [
            'sendCategory' => '/v1/website/categories/save',
            'sendProduct' => '/v1/website/products/save',
            'sendOrder' => '/v1/website/orders/save',
            'sendCharacteristic' => '/v1/website/characteristics/save',
        ];
    }

    /**
     * @param $storeId
     * @return void
     */
    public function setWebsiteTokenByStoreId($storeId){
        $this->websiteToken = $this->helperData->getGeneralConfig('website_token', 'general', $storeId);
    }

    /**
     * @param $method
     * @param $params
     */
    public function execute($method, $params)
    {
        $params['website_token'] = $this->websiteToken;

        $this->sendRequest($this->route($method), json_encode($params), ['Content-Type: application/json'], 'POST');

        // $this->client->post($this->route($method), $params);
    }

    /**
     * @param $method
     * @return string
     */
    private function route($method)
    {
        $route = $this->routes[$method];
        return sprintf("%s%s", self::MICROSERVICE_URL, $route);
    }

    /**
     *  Send a cURL request to the specified URL
     * @param $url
     * @param $data
     * @param $headers
     * @param $method
     * @return bool|string
     */
    public function sendRequest($url, $data = null, $headers = null, $method = 'POST') {
        $curl = curl_init();

        // Set the URL and options for the cURL session
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);

        // If sending data, set the appropriate cURL options
        if ($data !== null) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }

        // If headers are provided, set the appropriate cURL options
        if ($headers !== null) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }

        // Execute the cURL session and return the result
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }
}
