<?php

define("IN_SITE", true);
require_once __DIR__ . "/../libs/db.php";
require_once __DIR__ . "/../config.php";
require_once __DIR__ . "/../libs/lang.php";
require_once __DIR__ . "/../libs/helper.php";
$CMSNT = new DB();
if($_SERVER["REQUEST_METHOD"] == "GET") {
    if($CMSNT->site("cronjob_debug") == 1) {
        if(!($cron_server = $CMSNT->get_row(" SELECT * FROM `cron_server` WHERE `status` = 1 "))) {
            exit(json_encode(["status" => "error", "msg" => __("Địa chỉ IP không được cấp phép")]));
        }
    } elseif(!($cron_server = $CMSNT->get_row(" SELECT * FROM `cron_server` WHERE `ip` = '" . myip() . "' AND `status` = 1 "))) {
        exit(json_encode(["status" => "error", "msg" => __("Địa chỉ IP " . myip() . " không được cấp phép")]));
    }
    $CMSNT->update("cron_server", ["last_run" => time()], " `id` = '" . $cron_server["id"] . "' ");
    $list_cron = [];
    $current_time = time();
    $sql = "SELECT * FROM `cron_jobs` \n            WHERE `status` = 'active' \n            AND `server_id` = '" . $cron_server["id"] . "' \n            AND (" . $current_time . " - `last_run`) >= `timeloop`\n            ORDER BY RAND() ";
    foreach ($CMSNT->get_list($sql) as $cron) {
        $currentTime = time();
        $last = $currentTime - (int) $cron["last_run"];
        if((int) $cron["timeloop"] + (int) $cron["timeout"] + 3 < $last) {
            $CMSNT->update("cron_jobs", ["last_run" => $currentTime], " `id` = '" . (int) $cron["id"] . "' ");
        }
        $list_cron[] = ["id" => (int) $cron["id"], "link_cron" => $cron["link_cron"], "method" => $cron["method"], "timeloop" => (int) $cron["timeloop"], "last_run" => (int) $cron["last_run"], "timeout" => (int) $cron_server["timeout"]];
    }
    exit(json_encode(["status" => "success", "msg" => __("Lấy dữ liệu CRON thành công"), "data" => $list_cron]));
}

?>