<?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";
require_once __DIR__ . "/../libs/sendEmail.php";
$CMSNT = new DB();
if($CMSNT->site("check_time_cron_cron") < time() && time() - $CMSNT->site("check_time_cron_cron") < 3) {
    exit("Thao tác quá nhanh, vui lòng thử lại sau!");
}
$CMSNT->update("settings", ["value" => time()], " `name` = 'check_time_cron_cron' ");
foreach ($CMSNT->get_list("SELECT * FROM cron_jobs WHERE expires_at <= '" . gettime() . "' AND status != 'expired'") as $cron) {
    $getUser = $CMSNT->get_row(" SELECT * FROM `users` WHERE `id` = '" . $cron["user_id"] . "' ");
    $CMSNT->update("cron_jobs", ["status" => "expired", "updated_at" => gettime()], " `id` = '" . $cron["id"] . "' ");
    $replacements = ["{domain}" => $_SERVER["SERVER_NAME"], "{title}" => $CMSNT->site("title"), "{username}" => $getUser["username"], "{link_cron}" => $cron["link_cron"], "{server}" => getRowRealtime("cron_server", $cron["server_id"], "name"), "{link_renew}" => "<a target=\"_blank\" href=\"" . base_url("?action=cron-job-renew&id=" . $cron["trans_id"]) . "\">" . base_url("?action=cron-job-renew&id=" . $cron["trans_id"]) . "</a>", "{time}" => gettime()];
    $content = $CMSNT->site("email_temp_content_thong_bao_link_het_han");
    $subject = $CMSNT->site("email_temp_subject_thong_bao_link_het_han");
    foreach ($replacements as $key => $value) {
        $content = str_replace($key, $value, $content);
        $subject = str_replace($key, $value, $subject);
    }
    $bcc = $CMSNT->site("title");
    sendCSM($getUser["email"], $getUser["username"], $subject, $content, $bcc);
}
$servers = $CMSNT->get_list("SELECT * FROM `cron_server` WHERE `status` = 1 ");
foreach ($CMSNT->get_list("SELECT * FROM `cron_server` WHERE `status` = 1 ") as $server) {
    if(120 <= time() - $server["last_run"]) {
        $message = "⚠️ [CẢNH BÁO] Mất kết nối đến Máy chủ!\n\n            📅 Thời gian: " . date("Y-m-d H:i:s") . "\n            🖥️ Máy chủ: " . $server["name"] . "\n            ❌ Trạng thái: Không kết nối được trong " . timeAgo($server["last_run"]) . "\n            \n            Vui lòng kiểm tra và xử lý ngay lập tức.";
        sendMessAdmin($message);
    }
}
$urls = [];
$urls[] = base_url("cron-jobs");
foreach ($CMSNT->get_list(" SELECT * FROM posts WHERE `status` = 1 ") as $blog) {
    $urls[] = base_url("blog/" . $blog["slug"]);
}
$xml = new DOMDocument("1.0", "UTF-8");
$xml->formatOutput = true;
$urlset = $xml->createElement("urlset");
$urlset->setAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
foreach ($urls as $url) {
    $urlElement = $xml->createElement("url");
    $locElement = $xml->createElement("loc", htmlspecialchars($url));
    $urlElement->appendChild($locElement);
    $urlset->appendChild($urlElement);
}
$xml->appendChild($urlset);
$xml->save("../sitemap.xml");

?>