<?php
/**
 * @package   Essentials YOOtheme Pro 2.2.16 build 0813.1608
 * @author    ZOOlanders https://www.zoolanders.com
 * @copyright Copyright (C) Joolanders, SL
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace ZOOlanders\YOOessentials\Condition\Rule\Datetime;

use function YOOtheme\app;
use ZOOlanders\YOOessentials\Condition\ConditionRule;

class TimeRule extends ConditionRule
{
    protected \DateTimeZone $tz;

    protected string $format = 'H:i';

    public function __construct(array $data)
    {
        $this->tz = new \DateTimeZone(app()->config->get('yooessentials.timezone') ?? 'UTC');

        parent::__construct($data);
    }

    public function now(): \DateTimeImmutable
    {
        return new \DateTimeImmutable('now', new \DateTimeZone('UTC'));
    }

    public function resolveProps(object $props, object $node): object
    {
        $props->now = $this->now()->setTimezone($this->tz);
        $props->publish_up = $props->publish_up ?? null;
        $props->publish_down = $props->publish_down ?? null;

        if ($props->publish_up) {
            [$hour, $min] = explode(':', $props->publish_up);
            $props->publish_up = $this->now()
                ->setTime($hour, $min)
                ->setTimezone($this->tz)
                // enforce today
                ->setDate(date('Y'), date('m'), date('d'));
        }

        if ($props->publish_down) {
            [$hour, $min] = explode(':', $props->publish_down);
            $props->publish_down = $this->now()
                ->setTime($hour, $min)
                ->setTimezone($this->tz)
                // enforce today
                ->setDate(date('Y'), date('m'), date('d'));
        }

        if (!$props->publish_up && !$props->publish_down) {
            throw new \RuntimeException('Not Valid Evaluation Arguments');
        }

        return $props;
    }

    public function resolve($props, $node): bool
    {
        if ($props->publish_up and (int) $props->publish_up->format('U') > (int) $props->now->format('U')) {
            return false;
        }

        if ($props->publish_down and (int) $props->publish_down->format('U') < (int) $props->now->format('U')) {
            return false;
        }

        return true;
    }
}
