<?php

namespace KupShop\OrderDiscountBundle\Triggers;

use KupShop\KupShopBundle\Query\JsonOperator;
use KupShop\OrderingBundle\Entity\Purchase\PurchaseState;
use Query\Operator;

require_once $GLOBALS['cfg']['Path']['shared_version'].'admin/class/smarty_plugins/function.insert_calendar.php';
require_once $GLOBALS['cfg']['Path']['shared_version'].'admin/class/smarty_plugins/modifier.format_datetime.php';

class DateTimeTrigger extends AbstractTrigger
{
    protected static $type = 'datetime';
    protected static $position = 10;
    protected $adminTemplate = 'triggers/datetime.tpl';

    public function getDiscountFilterSpec(PurchaseState $purchaseState)
    {
        $now = (new \DateTime())->format('Y-m-d H:i:s');

        $dateFrom = JsonOperator::value('odt.data', 'dateFrom', true);
        $dateTo = JsonOperator::value('odt.data', 'dateTo', true);

        return Operator::andX(
            Operator::equals(['odt.type' => static::getType()]),
            Operator::not(
                Operator::andX(
                    "'{$now}' >= {$dateFrom} OR {$dateFrom} IS NULL",
                    "'{$now}' <= {$dateTo} OR {$dateTo} IS NULL"
                )
            )
        );
    }

    public function handleData($data)
    {
        $data['dateFrom'] = $this->prepareDateTime($data['dateFrom']);
        if (empty($data['dateFrom'])) {
            unset($data['dateFrom']);
        }

        $data['dateTo'] = $this->prepareDateTime($data['dateTo']);
        if (empty($data['dateTo'])) {
            unset($data['dateTo']);
        }

        return $data;
    }

    /**
     * @return bool
     *
     * @throws \Exception
     */
    public function checkValidity(&$data)
    {
        $handleData = $this->handleData($data);
        if (!empty($handleData)) {
            if (empty($data['dateFrom']) == empty($handleData['dateFrom'])) {
                $dateFrom = null;
                if (!empty($handleData['dateFrom'])) {
                    $dateFrom = \DateTime::createFromFormat('Y-m-d H:i:s', $handleData['dateFrom']);
                }
                if (empty($data['dateTo']) == empty($handleData['dateTo'])) {
                    if (empty($handleData['dateTo'])) {
                        return true;
                    }

                    $dateTo = \DateTime::createFromFormat('Y-m-d H:i:s', $handleData['dateTo']);
                    if ($dateFrom < $dateTo) {
                        return true;
                    }
                }
            }
        }

        throw new \Exception($this->getName().' ['.$this->getType().'] - data is not valid.');
    }

    public function prepareDateTime($datetime)
    {
        if (empty($datetime)) {
            return '';
        }

        if (!$datetime instanceof \DateTime) {
            $format = \Settings::getDateFormat().' '.\Settings::getTimeFormat();

            $datetime = \DateTime::createFromFormat($format, $datetime);
            if ($datetime == false) {
                return '';
            }
        }

        return $datetime->format('Y-m-d H:i:s');
    }
}
