<?php

namespace Benhauer\Salesmanago\Controller\Adminhtml\Config;

use \Benhauer\Salesmanago\Exception\SalesManagoException;
use \Benhauer\Salesmanago\Exception\UserAccessException;

use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Provider\UserProvider;

class CronExportData extends \Benhauer\Salesmanago\Controller\Adminhtml\Config\ExportData
{

    /**
     * from: 2019-10-01 00:00:01
     * to: 2019-10-16 23:59:59
    */
    public function setAdvancedExport($from = null, $to = null, $advancedExport = true)
    {
        $this->advancedExport = $advancedExport;

        if ($this->advancedExport
            && !empty($from)
            && !empty($to)
        ) {
            $this->exportDateRange = [
                'from' => $from,
                'to'   => $to
            ];
        }

        return $this;
    }

    public function setEvents()
    {
        try {
            $userAccount = $this->factoryOrganizer->getInst(
                FactoryOrganizer::USER_ACCOUNT_C,
                UserProvider::initSettingsUser(
                    $this->model
                ),
                $this->model
            );

            $collectSize = $this->getCountOrders();
            $collection = $this->getOrdersCollection();

            $loops = intval(ceil($collectSize / self::EXP_PACKAGE_SIZE));
            $collection->setPageSize(self::EXP_PACKAGE_SIZE);

            for ($i = 0; $i < $loops; $i++) {
                $collection->setCurPage($i);
                $orders = $collection->setOrder('entity_id', 'DESC');
                $package = $this->exportModel->prepareOrdersToExport($orders);
                $userAccount->exportContactExtEvents($package);
            }
            return __("Success").' '.$collectSize. ' events was exported';
        } catch (UserAccessException $e) {
            $this->logger->critical($e->getUserMessage());
            $this->messageManager->addError($e->getUserMessage());
        } catch (SalesManagoException $e) {
            $this->logger->critical($e->getSalesManagoMessage());
            $this->messageManager->addError($e->getUserMessage());
        } catch (\Exception $e) {
            $this->logger->critical($e->getMessage());
            $this->messageManager->addError($e->getMessage());
        }
    }

    /**
     * Filter Order collection depends on $this->exportDateRange, $this->storeId
     * @return \Magento\Sales\Model\ResourceModel\Order\Collection $orderFactory
     */
    protected function getOrdersCollection()
    {
        try {
            $orderFactory = $this->orderFactory->create();

            if (isset($this->exportDateRange)) {
                $orderFactory->addFieldToFilter(
                    'created_at',
                    [
                        'from' => $this->exportDateRange['from'],
                        'to' => $this->exportDateRange['to'],
                        'date' => true
                    ]
                );
            }

            $orderFactory->addFieldToSelect(['*']);

            return $orderFactory;

        } catch (\Exception $e) {
            $this->logger->critical($e->getMessage());
            $this->messageManager->addError($e->getMessage());
        }
    }
}