<?php

namespace FiloBlu\ActiveCampaign\Controller\Adminhtml\Field;

use Exception;
use FiloBlu\ActiveCampaign\Api\Data\FieldsInterfaceFactory;
use FiloBlu\ActiveCampaign\Api\FieldsRepositoryInterface;
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;
    /**
     * @var FieldsInterfaceFactory
     */
    protected $fieldsFactory;
    /**
     * @var FieldsRepositoryInterface
     */
    protected $fieldsRepository;

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

    /**
     * Collect relations data
     *
     * @return Json
     * @throws Exception
     */
    public function execute()
    {
        try {
            $fieldResponse = $this->activeCampaign->getFields();
            $fields = $fieldResponse['fields'];

            if (count($fields) == 0) {
                return $this->resultJsonFactory->create()->setData(['success' => true, 'message' => '0 fields synced']);
            }
            $this->fieldsRepository->deleteAll();
            foreach ($fields as $field) {
                $f = $this->fieldsFactory->create();
                $f->setAcId($field['id'])->setName($field['title']);
                $this->fieldsRepository->save($f);
            }

            return $this->resultJsonFactory->create()->setData(
                ['success' => true, 'message' => count($fields) . ' fields synced']
            );
        } 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');
    }
}