<?php

namespace FiloBlu\ActiveCampaign\Controller\Adminhtml\Connection;

use Exception;
use FiloBlu\ActiveCampaign\Helper\Data;
use FiloBlu\ActiveCampaign\Model\Resource\ActiveCampaign;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
use Throwable;

/**
 * Class Sync
 * @package FiloBlu\ActiveCampaign\Controller\Adminhtml\Connection
 */
class Sync extends Action
{

    /**
     * @var JsonFactory
     */
    protected $resultJsonFactory;
    /**
     * @var Data
     */
    protected $helperData;
    /**
     * @var ActiveCampaign
     */
    protected $activeCampaign;

    /**
     * @param Context $context
     * @param JsonFactory $resultJsonFactory
     * @param Data $helperData
     * @param ActiveCampaign $activeCampaign
     */
    public function __construct(
        Context $context,
        JsonFactory $resultJsonFactory,
        Data $helperData,
        ActiveCampaign $activeCampaign
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->helperData = $helperData;
        $this->activeCampaign = $activeCampaign;
        parent::__construct($context);
    }

    /**
     * Collect relations data
     *
     * @return Json
     * @throws Exception
     */
    public function execute()
    {
        try {
            $connectionName = $this->helperData->getConnectionName();
            $externalId = $this->helperData->getConnectionExternalId();
            $url = $this->helperData->getConnectionUrl();
            $logo = $this->helperData->getConnectionLogo();

            if (empty($externalId) || empty($connectionName) || empty($url) || empty($logo)) {
                return $this->resultJsonFactory->create()->setData(
                    ['success' => false, 'message' => 'Please insert connection name, external id, url, logo']
                );
            }

            $request = [
                'connection' => [
                    'service'    => 'Magento Commerce',
                    'externalid' => $externalId,
                    'name'       => $connectionName,
                    'logoUrl'    => $logo,
                    'linkUrl'    => $url
                ]
            ];

            $response = $this->activeCampaign->createConnection($request);
            $connectionResponse = $this->helperData->serializer->unserialize($response->getBody()->getContents());

            $connectionId = $connectionResponse['connection']['id'];

            if (empty($connectionId)) {
                return $this->resultJsonFactory->create()->setData(
                    ['success' => false, 'message' => 'There was an error syncing']
                );
            }
            //write value in config
            $this->helperData->writeConnectionId($connectionId);
            return $this->resultJsonFactory->create()->setData(
                ['success' => true, 'message' => 'Connection synced', 'connection_id' => $connectionId]
            );
        } catch (Exception $exception) {
            return $this->resultJsonFactory->create()->setData(
                ['success' => false, 'message' => $exception->getMessage()]
            );
        } catch (Throwable $throwable) {
            return $this->resultJsonFactory->create()->setData(
                ['success' => false, 'message' => $throwable->getMessage()]
            );
        }
    }

    /**
     * @return bool
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('FiloBlu_ActiveCampaign::config');
    }
}