<?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;

class DatetimeRule extends TimeRule
{
    protected string $format = 'Y-m-d H:i';

    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) {
            $props->publish_up = $this->createDate($props->publish_up);
        }

        if ($props->publish_down) {
            $props->publish_down = $this->createDate($props->publish_down);
        }

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

        return $props;
    }

    public function createDate($date): ?\DateTime
    {
        $date = \DateTime::createFromFormat($this->format, $date);

        if (!$date) {
            return null;
        }

        return $date->setTimezone($this->tz);
    }
}
