<?php

namespace FiloBlu\ActiveCampaign\Model\Entity\Export;

use FiloBlu\ActiveCampaign\Api\Data\JobsInterface;
use FiloBlu\ActiveCampaign\Api\Data\JobsInterfaceFactory;
use FiloBlu\ActiveCampaign\Api\JobsRepositoryInterface;
use FiloBlu\ActiveCampaign\Helper\Data;
use FiloBlu\ActiveCampaign\Model\Config\Source\DirectionType;
use FiloBlu\ActiveCampaign\Model\Config\Source\EntityType;
use FiloBlu\ActiveCampaign\Model\Config\Source\JobStatus;
use FiloBlu\ActiveCampaign\Model\Resource\ActiveCampaign;
use Magento\Framework\App\ResourceConnection;
use Magento\Quote\Api\CartRepositoryInterface;

/**
 * Class Quote
 * @package FiloBlu\ActiveCampaign\Model\Entity\Export
 */
class Quote extends AbstractEntityExport {

    /**
     * @var ResourceConnection
     */
    protected $resourceConnection;
    /**
     * @var Data
     */
    protected $helperData;
    /**
     * @var JobsRepositoryInterface
     */
    protected $jobsRepository;
    /**
     * @var string
     */
    protected $entity = EntityType::ENTITY_QUOTE;
    /**
     * @var string
     */
    protected $direction = DirectionType::DIRECTION_EXPORT;
    /**
     * @var CartRepositoryInterface
     */
    protected $cartRepository;

    /**
     * Quote constructor.
     * @param ResourceConnection $resourceConnection
     * @param Data $helperData
     * @param JobsRepositoryInterface $jobsRepository
     * @param JobsInterfaceFactory $jobsFactory
     * @param ActiveCampaign $activeCampaign
     * @param CartRepositoryInterface $cartRepository
     */
    public function __construct(
        ResourceConnection $resourceConnection,
        Data $helperData,
        JobsRepositoryInterface $jobsRepository,
        JobsInterfaceFactory $jobsFactory,
        ActiveCampaign $activeCampaign,
        CartRepositoryInterface $cartRepository
    )
    {
        parent::__construct($resourceConnection, $helperData, $jobsRepository, $jobsFactory, $activeCampaign);
        $this->cartRepository = $cartRepository;
    }

    /**
     * @return array|mixed
     */
    public function getAllIncrementalIds()
    {
        $connection = $this->resourceConnection->getConnection();
        $tableName = $this->resourceConnection->getTableName('quote');
        $tableNameJobs = $this->resourceConnection->getTableName(JobsInterface::DB_TABLE);

        if (empty($sw = $this->helperData->getEnabledStoreViews())) {
            return [];
        }

        $sql = "SELECT `ce`.`entity_id` as `entity_id`
                    FROM {$tableName} AS `ce`
                    LEFT JOIN {$tableNameJobs} AS `mj`
                    ON
                        `mj`.`entity_id` = `ce`.`entity_id`
                    AND
                        mj.entity = ?
                    AND
                         mj.direction = ?
                    WHERE
                        `mj`.`status` IS NULL
                    AND
                        `ce`.`is_active` = 1
                    AND
                        ce.items_count > 0
                    AND
                        ce.customer_email IS NOT NULL
                    AND
                        TIMESTAMPDIFF(SECOND,ce.updated_at,NOW()) > ?
                    AND
                        FIND_IN_SET(ce.store_id, ?) > 0";

        //TODO CHECK QUERY WITH MAX TIME

        return $connection->fetchCol($sql,[$this->entity, $this->direction, $this->helperData->getAbandonedCartTime(), $sw]);
    }

    /**
     * @param array $job
     * @return mixed|void
     * @throws \Exception
     */
    public function executeProcess(array $job): bool
    {
        if(!$this->helperData->isQuoteEnabled()) {
            $this->jobsRepository->setStatus($this->options,$job['entity_id'],JobStatus::JOB_STATUS_SKIPPED,'The quote job is not active');
            return false;
        }
        $quoteData = $this->getQuoteData($job);
        if(count($quoteData)>0){
            $this->executeSalesRestProcess($quoteData, $job);
            return true;
        }
        return false;
    }

    /**
     * @param $job
     * @return array[]
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getQuoteData($job): array
    {
        $data = [];
        $quote = $this->cartRepository->get($job['entity_id']);
        if(!$quote->getIsActive()) {
            $this->jobsRepository->setStatus($this->options,$job['entity_id'],JobStatus::JOB_STATUS_SKIPPED,'The quote is not active');
            return [];
        }
        $result = [
            'ecomOrder' => [
                'externalcheckoutid' => $quote->getEntityId(),
                'source' => 1,
                'email' => $quote->getCustomerEmail(),
                'externalCreatedDate' => $quote->getCreatedAt(),
                'externalUpdatedDate' => $quote->getUpdatedAt(),
                'abandonedDate' => $quote->getUpdatedAt(),
                'totalPrice' => $this->helperData->formatPrice($quote->getGrandTotal()),
                'currency' => $quote->getQuoteCurrencyCode(),
                'connectionid' => $this->helperData->getConnectionId(),
                'customerid' => $quote->getCustomerId()
            ]
        ];
        foreach ($quote->getAllItems() as $item) {
            $product = $item->getProduct();
            $storeUrl = $this->helperData->getMediaUrl($quote->getStoreId());
            $productUrl = $this->helperData->getProductUrl($product,$quote->getStoreId());

            $thumbnail = '';
            if(!empty($product->getThumbnail())) {
                $thumbnail = ($product->getThumbnail() === 'no_selection') ? '' : $storeUrl . 'catalog/product' . $product->getThumbnail();
            }
            $itemPrice = $item->getPriceInclTax();

            if($this->helperData->quoteExportOnlySimple()) {
                if(in_array($product->getTypeId(), ['configurable','bundle'])){
                    continue;
                }

                //If export only simple get info from parent
                if (!empty($item->getParentItemId()) && $item->getParentItem()->getProductType()=="configurable") {
                    $itemPrice = $item->getParentItem()->getPriceInclTax();
                    if(empty($thumbnail)) {
                        $parentProduct = $this->helperData->getProduct($item->getParentItem()->getProductId());
                        if(!empty($parentProduct->getThumbnail())) {
                            $thumbnail = ($parentProduct->getThumbnail() === 'no_selection') ? '' : $storeUrl . 'catalog/product' . $parentProduct->getThumbnail();
                        }
                    }
                }
            }
            $data[] = [
                'name' => $item->getName(),
                'price' => $this->helperData->formatPrice($itemPrice),
                'quantity' => $item->getQty(),
                'external_id' => $item->getProductId(),
                'sku' => $item->getSku(),
                'description' => $product->getDescription(),
                'productUrl' => $productUrl,
                'imageUrl' => $thumbnail
            ];
        }

        $result['ecomOrder']['orderProducts'] = $data;
        return $result;
    }

}
