<?php

namespace BG\DesignHuddle\Helper;

use Magento\Store\Model\ScopeInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\HTTP\ZendClientFactory;
use Magento\Catalog\Model\Session;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    const CONFIG_MODULE_ENABLE = 'bgdesignhuddlesection/access/active';
    const CONFIG_DH_DOMAIN_URL = 'bgdesignhuddlesection/access/storeurl';
    const CONFIG_CLIENT_ID = 'bgdesignhuddlesection/access/clientid';
    const CONFIG_CLIENT_SECRET = 'bgdesignhuddlesection/access/clientsecret';
    const CONFIG_SELECTMODE = 'bgdesignhuddlesection/access/selectmode';

    const CONFIG_POSTURL = 'bgdesignhuddlesection/access/posturl';

    protected $_session;

    protected $_storeId;
    protected $_storeManager;
    protected $_httpClient;
    protected $_appState;
    protected $messageManager;

    private $file;
    private $dir;
    protected  Session $sessionObj;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        ZendClientFactory $httpClient,
        \Magento\Framework\Session\Generic $session,
        Session $sessionObj,
        \Magento\Framework\Filesystem\Io\File $file,
        \Magento\Framework\Filesystem\DirectoryList $dir,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\App\State $appState
    ) {
        $this->_session = $session;
        $this->sessionObj = $sessionObj;
        $this->_storeManager = $storeManager;
        $this->_httpClient = $httpClient;
        $this->file = $file;
        $this->dir = $dir;
        $this->messageManager = $messageManager;
        $this->_appState = $appState;
        parent::__construct($context);
    }

    /**
     * Set a specified store ID value
     *
     * @param int $store
     * @return $this
     */
    public function setStoreId($store)
    {
        $this->_storeId = $store;
        return $this;
    }

    public function getModuleEnable()
    {
        return $this->scopeConfig->getValue(
            self::CONFIG_MODULE_ENABLE,
            ScopeInterface::SCOPE_STORE
        );
    }

    public function getClientID()
    {
        return $this->scopeConfig->getValue(
            self::CONFIG_CLIENT_ID,
            ScopeInterface::SCOPE_STORE
        );
    }

    public function getClientSecret()
    {
        return $this->scopeConfig->getValue(
            self::CONFIG_CLIENT_SECRET,
            ScopeInterface::SCOPE_STORE
        );
    }

    public function getPostUrl()
    {
        return $this->scopeConfig->getValue(
            self::CONFIG_POSTURL,
            ScopeInterface::SCOPE_STORE
        );
    }

    public function getDomainStoreUrl()
    {
        return $this->scopeConfig->getValue(
            self::CONFIG_DH_DOMAIN_URL,
            ScopeInterface::SCOPE_STORE
        );
    }

    public function getDhAccessToken()
    {
        //$getSessionToken = $this->_session->getExampleArry('dh_access_token');

        $this->sessionObj->start();
        $getSessionToken = $this->sessionObj->getDhAccessToken();

        return ((!empty($getSessionToken)) ? $getSessionToken : null);
    }

    public function ajaxGenerateApiToken($accessToken)
    {
        $this->_session->setExampleArry(['dh_access_token' => $accessToken]);
        $this->sessionObj->start();
        $this->sessionObj->setDhAccessToken($accessToken);

        return true;

        /* $oauthToken = $this->generateApiToken();

        if (!empty($oauthToken)) {
            $oauthTokenArray = json_decode($oauthToken, true);

            if (json_last_error() !== JSON_ERROR_NONE || empty($oauthTokenArray['access_token'])) {
                //echo "Error! While calling oauth/token API.";
                 echo json_encode(['error' => 401, 'message' => 'Error! While calling oauth/token API']);
                //$this->messageManager->addErrorMessage(__("Error! While calling oauth/token API."));
            } else {
                $accessToken = $oauthTokenArray['access_token'];

                // if (!$this->sessionObj->getDhAccessToken()) {

                // }
                $this->_session->setExampleArry(['dh_access_token' => $accessToken]);
                $this->sessionObj->start();
                $this->sessionObj->setDhAccessToken($accessToken);

                return true;
            }
        }

        return false; */
    }

    public function generateApiToken()
    {
        $domainUrl      = $this->getDomainStoreUrl();
        $clientId       = $this->getClientID();
        $siteStatus    = $this->getSiteMode();

        //echo "domainUrl: ".$domainUrl;
        //echo "clientId: ".$clientId;
        //echo "siteStatus: ".$siteStatus;

        // $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/generateAPIToken.log');
        // $logger = new \Zend_Log();
        // $logger->addWriter($writer);


        // $logger->info('---------------------------------------- site status ---------');
        // $logger->info($siteStatus);

        // As Admin
        if ($siteStatus == 'live') {
            $clientSecret   = $this->getClientSecret();
            $OuthUrl        = $domainUrl . '/oauth/token';
            $postFields     = 'client_id=' . $clientId . '&client_secret=' . $clientSecret . '&grant_type=client_credentials';
        } else {
            // As Guest
            $OuthUrl        = $domainUrl . '/oauth/token/guest';
            $postFields     = 'client_id=' . $clientId . '&username=houseofflags&grant_type=password';
        }
        $curl           = curl_init();

        // $logger->info('---------------------------------------- OuthUrl ---------');
        // $logger->info($OuthUrl);

        curl_setopt_array($curl, array(
            CURLOPT_URL => $OuthUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $postFields,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/x-www-form-urlencoded'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);

        return $response;
    }

    public function getDhProjectId()
    {
        //$getSessionId = $this->_session->getExampleArry('dh_project_id');
        $this->sessionObj->start();
        $getSessionId = $this->sessionObj->getDhProjectId();

        //return ((!empty($getSessionId['dh_project_id'])) ? $getSessionId['dh_project_id'] : null);
        return ((!empty($getSessionId)) ? $getSessionId : null);
    }

    public function ajaxDhApiProjectData($prodSku = null)
    {
        $accessToken = $this->getDhAccessToken();

        // If not found session then create it once.
        if (empty($accessToken)) {
            $this->ajaxGenerateApiToken();

            $accessToken = $this->getDhAccessToken();
        }

        $projectData = $this->getDhApiPorjectData($accessToken, $prodSku);

        if (!empty($projectData)) {
            $projectDataArray = json_decode($projectData, true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                //echo "Error! While calling partners/api/projects API.";
                echo json_encode(['error' => 401, 'message' => 'Error! While calling partners/api/projects API']);
                //$this->messageManager->addErrorMessage(__("Error! While calling partners/api/projects API."));
            } elseif (empty($projectDataArray['success']) || !$projectDataArray['success'] || empty($projectDataArray['data']['project_id'])) {
                //echo "Error! partners/api/projects API returns false success response.";
                echo json_encode(['error' => 401, 'message' => 'Error! partners/api/projects API returns false success response']);
                //$this->messageManager->addErrorMessage(__("Error! partners/api/projects API returns false success response."));
            } else {
                $projectId = $projectDataArray['data']['project_id'];

                if (!$this->sessionObj->getDhProjectId()) {
                    //$this->_session->setExampleArry(['dh_project_id' => $projectId]);
                    $this->sessionObj->start();
                    $this->sessionObj->setDhProjectId($projectId);
                }

                echo json_encode(['project_id' => $projectId, 'access_token' => $accessToken]);
            }
        }

        echo false;
    }

    public function getDhApiPorjectData($accessToken, $prodSku = null)
    {
        $oMr  = \Magento\Framework\App\ObjectManager::getInstance();
        $product        = $oMr->get('Magento\Framework\Registry')->registry('current_product');

        $domainUrl      = $this->getDomainStoreUrl();
        $apiUrl         = $domainUrl . '/partners/api/projects';
        $authorization  = 'Bearer ' . $accessToken;
        $curl           = curl_init();

        // TODO: To set dynamic template_id.
        $postFields     = json_encode([
            'template_code' =>  $prodSku
        ]);

        curl_setopt_array($curl, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $postFields,
            CURLOPT_HTTPHEADER => array(
                'Authorization: ' . $authorization,
                'Content-Type: application/json'
            ),
        ]);

        $response = curl_exec($curl);

        curl_close($curl);

        return $response;
    }

    /* public function ajaxGenerateIframe()
    {
        $accessToken = $this->getDhAccessToken();

        if (empty($accessToken)) {
            // If not found session then create it once.
            $this->ajaxGenerateApiToken();

            $accessToken = $this->getDhAccessToken();
        }

        $projectId = $this->getDhProjectId();

        if (empty($projectId)) {
            // If not found session then create it once.
            $this->ajaxDhApiProjectData();

            $projectId = $this->getDhProjectId();
        }

        // Create Design Huddle iframe.
        $generateiFrame = $this->generateiFramePage($projectId, $accessToken);

        if (!empty($generateiFrame)) {
            echo $generateiFrame;
        }


        echo false;
    }*/

    /* public function generateiFramePage($projectId, $accessToken)
    {
        $domainUrl = $this->getDomainStoreUrl();
        $apiUrl    = $domainUrl . "/editor?project_id=" . $projectId . "&token=" . $accessToken;

        return "<iframe src='" . $apiUrl . "' width='0' height='0'></iframe>";
    }*/

    public function getSiteMode()
    {
        return $this->scopeConfig->getValue(
            self::CONFIG_SELECTMODE,
            ScopeInterface::SCOPE_STORE
        );
    }

    public function saveDesignHudFile($dfilepath, $projectId)
    {

        // $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/dhsave-log1.log');
        // $logger = new \Zend_Log();
        // $logger->addWriter($writer);
        // $logger->info('1');


        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $fileSystem = $objectManager->create('\Magento\Framework\Filesystem');
        $io = $objectManager->create('\Magento\Framework\Filesystem\Io\File');

        $mediaPath = $this->dir->getPath('media') . '/desginhuddle/images/';
        if (! file_exists($mediaPath)) {
            $this->file->mkdir($mediaPath, 0775);
        }

        $ci = curl_init();
        $url = $dfilepath;

        $nurl = strtok($url, '?');
        $basename = basename($nurl);
        $fp = fopen($mediaPath . "" . $projectId . ".png", "w");
        curl_setopt_array($ci, array(
            CURLOPT_URL => $url,
            CURLOPT_TIMEOUT => 3600,
            CURLOPT_FILE => $fp
        ));
        $contents = curl_exec($ci);
        curl_close($ci);
        fclose($fp);

        // $logger->info('done');
        return '1';
    }


    public function genrateJobId($projectId, $filetype)
    {

        $domainUrl = $this->getDomainStoreUrl();
        $CURLOPT_URL = $domainUrl . '/partners/api/projects/' . $projectId . '/export';
        //echo "CURLOPT_URL: ".$CURLOPT_URL;
        $genToken = json_decode($this->generateApiToken());
        $access_token = $genToken->access_token;
        //echo "access_token: ".$access_token;
        $Authorization = 'Bearer ' . $access_token;

        $filetype = 'pdf';
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $CURLOPT_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 => 'POST',
            CURLOPT_POSTFIELDS => '{
            "format": "' . $filetype . '"
            }',
            CURLOPT_HTTPHEADER => array(
                'Authorization: ' . $Authorization,
                'Content-Type: text/plain'
            ),
        ));

        $response = curl_exec($curl);


        curl_close($curl);
        $jobs = json_decode($response);

        /*echo "<pre>";
        print_r($jobs);
        echo "</pre>";*/

        if ($jobs->success == '1') {
            return $jobs->data->job_id;
        } else {
            return '';
        }
    }


    public function exportDesignHuddleFile($projectId, $filetype)
    {

        $jobids = $this->genrateJobId($projectId, $filetype);
        $domainUrl = $this->getDomainStoreUrl();
        // /partners/api/projects/cfjem28f4840020w5rz0/export/jobs/cfjepasxpheg0206qmy0
        // $CURLOPT_URL = $domainUrl.'/partners/api/projects/'.$projectId.'/export/jobs/'.$jobids;
        $CURLOPT_URL = $domainUrl . '/partners/api/projects/' . $projectId;
        $genToken = json_decode($this->generateApiToken());
        $access_token = $genToken->access_token;
        $Authorization = 'Bearer ' . $access_token;
        // echo $CURLOPT_URL.' '.$Authorization;exit;

        $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/DesignHuddleLog-NEW.log');
        $logger = new \Zend_Log();
        $logger->addWriter($writer);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $CURLOPT_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 => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Authorization: ' . $Authorization
            ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        $exportFileName = json_decode($response);

        /*echo "<pre>";
        print_r($exportFileName);
        echo "</pre>";
        die();*/
        $logger->info('Export File Name:');
        $logger->info(print_r($exportFileName, true));
        if ($exportFileName->success == '1') {

            return json_decode($response);
        } else {
            return '';
        }
    }

    public function exportDesignHuddleFileEmail($projectId, $filetype)
    {

        $jobids = $this->genrateJobId($projectId, $filetype);
        $domainUrl = $this->getDomainStoreUrl();
        // /partners/api/projects/cfjem28f4840020w5rz0/export/jobs/cfjepasxpheg0206qmy0
        $CURLOPT_URL = $domainUrl.'/partners/api/projects/'.$projectId.'/export/jobs/'.$jobids;
        // $CURLOPT_URL = $domainUrl . '/partners/api/projects/' . $projectId;
        $genToken = json_decode($this->generateApiToken());
        $access_token = $genToken->access_token;
        $Authorization = 'Bearer ' . $access_token;
        // echo $CURLOPT_URL.' '.$Authorization;exit;

        $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/DesignHuddleLog-NEW.log');
        $logger = new \Zend_Log();
        $logger->addWriter($writer);

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $CURLOPT_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 => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Authorization: ' . $Authorization
            ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        $exportFileName = json_decode($response);

        /*echo "<pre>";
        print_r($exportFileName);
        echo "</pre>";
        die();*/
	$logger->info('Project Id:'.$projectId);
        $logger->info('Export File Name in pdf:');
        $logger->info(print_r($exportFileName, true));
        if ($exportFileName->success == '1') {

            return json_decode($response);
        } else {
            return '';
        }
    }



    public function exportDesignHuddleFileData($projectId, $access_key)
    {

        // $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/DesignHuddleLog-NEW.log');
        // $logger = new \Zend_Log();
        // $logger->addWriter($writer);

        // $logger->info('1');
        // $logger->info($projectId);

        // $jobids = $this->genrateJobId($projectId,$filetype);
        $domainUrl = $this->getDomainStoreUrl();
        // /partners/api/projects/cfjem28f4840020w5rz0/export/jobs/cfjepasxpheg0206qmy0
        $CURLOPT_URL = $domainUrl . '/api/projects/' . $projectId . '?generate_latest_thumbnail=true';
        if (!empty($access_key)) {
            $access_token = $access_key;
        } else {
            $genToken = json_decode($this->generateApiToken());
            $access_token = $genToken->access_token;
        }

        $Authorization = 'Bearer ' . $access_token;

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $CURLOPT_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 => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Authorization: ' . $Authorization
            ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        $exportFileName = json_decode($response);

        // $logger->info($exportFileName);

        if ($exportFileName->success == '1') {
            // $logger->info('2');
            // $logger->info($response);
            return $response;
        } else {
            return '';
        }
    }
}
