<?php

require_once __DIR__ . '/../../admin/vendor/autoload.php';
require __DIR__ . '/common.php';
require_once \PROJECT_PATH . '/../storage/config.php';
use Ministra\Lib\AdminPanelEvents;
use Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\B4291b8d8fa2d898727b1f446db1e661e;
use Ministra\Lib\CronExpression;
$run_start_time = \time();
$five_minute_interval = $run_start_time - $run_start_time % 300;
echo 'Scheduled events time - ', \strftime('%Y-%m-%d %H:%M:%S', $five_minute_interval), \PHP_EOL;
$_SERVER['TARGET'] = 'ADM';
$schedule_events = \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\B4291b8d8fa2d898727b1f446db1e661e::getInstance()->from('`schedule_events`')->where(['state' => 1, 'date_begin<=' => 'now()'])->where(['date_end>last_run and date_end>' => 'now()', 'date_end' => 0], 'OR ')->get()->all();
$update_data = [];
$event = new \Ministra\Lib\AdminPanelEvents();
$cronTab = new \Ministra\Lib\CronExpression('* * * * *', new \Cron\FieldFactory());
$cronTab->setCurrentTime('now');
foreach ($schedule_events as $row) {
    if (!empty($row['schedule'])) {
        $cronTab->setExpression($row['schedule']);
        $next_run_interval = $cronTab->getNextRunDate(\null, \null, \true)->getTimestamp() - $five_minute_interval;
        echo "next_run_interval - {$next_run_interval}", \PHP_EOL;
        if (\abs($next_run_interval) > 30) {
            continue;
        }
        $event->setTtl((int) $row['ttl']);
        if (!empty($row['post_function']) && !empty($row['param1'])) {
            $event->setPostFunctionParam($row['post_function'], $row['param1']);
        } else {
            $event->setPostFunctionParam('', '');
        }
        if ($add_params = \json_decode($row['recipient'], \true)) {
            list($user_list_type, $param) = \each($add_params);
            $row['user_list_type'] = $user_list_type;
            if (\is_array($param)) {
                $row = \array_merge($row, $param);
            }
            $event->setPostData($row);
            echo $get_list_func_name = 'get_userlist_' . \str_replace('to_', '', $row['user_list_type']), \PHP_EOL;
            echo $set_event_func_name = 'set_event_' . \str_replace('to_', '', $row['event']), \PHP_EOL, \PHP_EOL;
            if ($event->{$get_list_func_name}()->cleanAndSetUsers()->{$set_event_func_name}()) {
                $update_data[] = $row['id'];
            }
        }
    }
}
if (!empty($update_data)) {
    $last_run = new \DateTime();
    $last_run->setTimestamp($run_start_time);
    \Ministra\Lib\bd5c9022e9a9029209e5fd05775ea272\B4291b8d8fa2d898727b1f446db1e661e::getInstance()->update('`schedule_events`', ['state = IF(periodic=1, state, 0), 
            last_run' => $last_run->format('Y-m-d H:i:s')], [" `id` IN ('" . \implode("', '", $update_data) . "') AND 1=" => 1]);
}
