<?php
/**
 * @package         Conditions
 * @version         23.1.9739
 * 
 * @author          Peter van Westen <info@regularlabs.com>
 * @link            http://regularlabs.com
 * @copyright       Copyright © 2023 Regular Labs All Rights Reserved
 * @license         http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */

namespace RegularLabs\Component\Conditions\Administrator\Condition\Date;

defined('_JEXEC') or die;

use RegularLabs\Component\Conditions\Administrator\Condition\Condition;
use RegularLabs\Component\Conditions\Administrator\Helper\Date as DateHelper;
use RegularLabs\Library\Date as RL_Date;

class Time extends Condition
{
    public function pass()
    {
        $now = DateHelper::getTimeStamp();

        $comparison = $this->params->comparison ?? 'between';

        if ($comparison == 'before')
        {
            return $now < $this->getDateTime($this->params->date ?? '');
        }

        if ($comparison == 'after')
        {
            return $now > $this->getDateTime($this->params->date ?? '');
        }

        $from = $this->getDateTime($this->params->from);
        $to   = $this->getDateTime($this->params->to);

        if ($from > $to)
        {
            // from is after to (spans midnight)
            // current time should be:
            // - after from
            // - OR before to
            if ($now >= $from || $now < $to)
            {
                return true;
            }

            return false;
        }

        // to is after from (simple time span)
        // current time should be:
        // - after from
        // - AND before to
        if ($now >= $from && $now < $to)
        {
            return true;
        }

        return false;
    }

    private function getDateTime($value)
    {
        $date = DateHelper::getString('', 'Y-m-d');
        $time = RL_Date::fixTime($value);

        return strtotime($date . ' ' . $time);
    }
}
