<!DOCTYPE html>
<html lang="en">
<head>
    <?php require $_SERVER['DOCUMENT_ROOT'].'/hethong/head2.php';?>
    <title>Quản Lý Cronjobs | <?=$lxtdev['ten_web'];?></title>
    <?php require $_SERVER['DOCUMENT_ROOT'].'/hethong/nav.php';?>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <style>
        /* Tối ưu hóa khối thẻ form và datatable cao cấp */
        .premium-cron-card {
            border: 1px solid rgba(0, 0, 0, 0.05) !important;
            border-radius: 16px !important;
            background: #ffffff;
            box-shadow: 0 12px 30px rgba(0, 0, 0, 0.02) !important;
        }
        [data-bs-theme="dark"] .premium-cron-card {
            background: #1e1e2d;
            border: 1px solid rgba(255, 255, 255, 0.05) !important;
        }

        .form-label-custom {
            font-size: 0.95rem !important;
            font-weight: 700 !important;
            color: #181c32 !important;
            margin-bottom: 8px;
        }
        [data-bs-theme="dark"] .form-label-custom {
            color: #cdcdde !important;
        }

        .custom-cron-table thead tr {
            background: rgba(48, 133, 214, 0.04) !important;
            border-bottom: 2px solid rgba(48, 133, 214, 0.1) !important;
        }
        [data-bs-theme="dark"] .custom-cron-table thead tr {
            background: rgba(255, 255, 255, 0.02) !important;
            border-bottom: 2px solid rgba(255, 255, 255, 0.05) !important;
        }

        .custom-cron-table th, .custom-cron-table td {
            padding: 14px 10px !important;
            vertical-align: middle !important;
        }

        .badge-index {
            background: #f4f6f9;
            color: #5e6278;
            padding: 4px 8px;
            border-radius: 6px;
            font-weight: 700;
        }
        [data-bs-theme="dark"] .badge-index {
            background: #2b2b40;
            color: #92929f;
        }

        .cron-url-text {
            max-width: 220px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            display: inline-block;
        }
    </style>

    <script>
    function mincron() {
        var server_cron = document.getElementById("server_cron").value;
        $.ajax({
            type: "POST",
            url: "/ajax/cronjob/mincron",
            data: { server_cron: server_cron },
            success: function(result) {
                var mincr = JSON.parse(result);
                var selectHtml = '';
                
                for (var i = 0; i < mincr.length; i++) {
                    selectHtml += '<div class="mb-6 animate__animated animate__fadeIn">';
                    selectHtml += '<label class="form-label-custom required">Chu kỳ lặp (Số giây cách nhau):</label>';
                    selectHtml += '<div class="input-group">';
                    selectHtml += '<span class="input-group-text"><i class="fa-solid fa-stopwatch"></i></span>';
                    selectHtml += '<input type="number" name="interval_seconds" id="interval_seconds" class="form-control form-control-lg form-control-solid" placeholder="Tối thiểu giữa các lần chạy: ' + mincr[i].min + ' giây" min="' + mincr[i].min + '" />';
                    selectHtml += '</div>';
                    selectHtml += '</div>';
                }
                document.getElementById("min_cron").innerHTML = selectHtml;

                var tongTienHtml = '';
                for (var i = 0; i < mincr.length; i++) {
                    tongTienHtml += '<div class="mb-6 animate__animated animate__fadeIn">';
                    tongTienHtml += '<label class="form-label-custom">Tổng chi phí dự tính:</label>';
                    tongTienHtml += '<div class="input-group">';
                    tongTienHtml += '<span class="input-group-text"><i class="fa-solid fa-wallet text-success"></i></span>';
                    tongTienHtml += '<input type="text" name="tong_tien" class="form-control form-control-lg form-control-solid text-success fw-bold" value="' + mincr[i].gia + ' / 1 tháng" readonly />';
                    tongTienHtml += '</div>';
                    tongTienHtml += '</div>';
                }
                document.getElementById("tong_tien_div").innerHTML = tongTienHtml;
            },
            error: function() {
                alert("Đã xảy ra lỗi khi gửi yêu cầu đồng bộ cấu hình Server Cron.");
            }
        });
    }
    </script>
</head>

<?php
if(isset($_GET['edit'])) {
    $id_cron = $_GET['edit'];
    $check_code = $ketnoi->query("SELECT * FROM `list_cron` WHERE `id` = '$id_cron' AND `username`='$username'");
    if($check_code->num_rows != 0){
        $toz_cron = $ketnoi->query("SELECT * FROM `list_cron` WHERE `id` = '$id_cron' ")->fetch_array();
    } else {
        header('Location: /cron-jobs');
        exit();
    }
}
?>

<body id="kt_app_body" data-kt-app-layout="light-sidebar" data-kt-app-header-fixed="true"
    data-kt-app-sidebar-enabled="true" data-kt-app-sidebar-fixed="true" data-kt-app-sidebar-hoverable="true"
    data-kt-app-sidebar-push-header="true" data-kt-app-sidebar-push-toolbar="true"
    data-kt-app-sidebar-push-footer="true" data-kt-app-toolbar-enabled="true" class="app-default">
    
    <script>var defaultThemeMode = "light"; var themeMode; if (document.documentElement) { if (document.documentElement.hasAttribute("data-bs-theme-mode")) { themeMode = document.documentElement.getAttribute("data-bs-theme-mode"); } else { if (localStorage.getItem("data-bs-theme") !== null) { themeMode = localStorage.getItem("data-bs-theme"); } else { themeMode = defaultThemeMode; } } if (themeMode === "system") { themeMode = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; } document.documentElement.setAttribute("data-bs-theme", themeMode); }</script>
    
    <div class="d-flex flex-column flex-root app-root" id="kt_app_root">
        <div class="app-page flex-column flex-column-fluid" id="kt_app_page">
            
            <div class="app-wrapper flex-column flex-row-fluid" id="kt_app_wrapper">
                <?php require $_SERVER['DOCUMENT_ROOT'].'/hethong/sider.php';?>
            </div>
            
            <div class="app-main flex-column flex-row-fluid" id="kt_app_main">
                <div class="d-flex flex-column flex-column-fluid">
                    
                    <div id="kt_app_toolbar" class="app-toolbar py-3 py-lg-6">
                        <div id="kt_app_toolbar_container" class="app-container container-fluid d-flex flex-stack">
                            <div class="page-title d-flex flex-column justify-content-center flex-wrap me-3">
                                <h1 class="page-heading d-flex text-dark fw-bold fs-3 flex-column justify-content-center my-0">
                                    <i class="fa-solid fa-clock-rotate-left text-primary fs-4 mb-1"></i> Quản Lý Hệ Thống Cronjobs
                                </h1>
                                <ul class="breadcrumb breadcrumb-separatorless fw-semibold fs-7 my-0 pt-1">
                                    <li class="breadcrumb-item text-muted"><a href="/" class="text-muted text-hover-primary">Home</a></li>
                                    <li class="breadcrumb-item"><span class="bullet bg-gray-400 w-5px h-2px"></span></li>
                                    <li class="breadcrumb-item text-muted">Hệ Thống Tự Động</li>
                                </ul>
                            </div>
                            <div class="d-flex align-items-center gap-2 gap-lg-3">
                                <a href="#" class="btn btn-sm fw-bold btn-light-success px-4 py-3" data-bs-toggle="modal" data-bs-target="#kt_modal_create_app">
                                    <i class="fa-solid fa-wallet me-1"></i> <?=tien($user['money']);?>đ
                                </a>
                            </div>
                        </div>
                    </div>

                    <div class="content d-flex flex-column flex-column-fluid" id="kt_content">
                        <div class="container-xxl" id="kt_content_container">
                            
                            <?php if(empty($id_cron)){ ?>
                            <div id="buy-cron" class="card premium-cron-card mb-6">
                                <div class="card-header border-0 pt-6 bg-transparent">
                                    <div class="card-title">
                                        <span class="fw-black text-dark fs-4"><i class="fa-solid fa-plus-circle text-primary me-2"></i>Khởi tạo tiến trình Cron mới</span>
                                    </div>
                                </div>
                                <div class="card-body p-6 p-lg-10">
                                    <div class="row">
                                        <div class="col-xl-12 mb-6">
                                            <label class="form-label-custom required">Đường dẫn liên kết (URL Cron):</label>
                                            <input type="text" name="url" id="url" class="form-control form-control-lg form-control-solid" placeholder="Nhập địa chỉ URL cần kích hoạt (Ví dụ: https://domain.com/cron/auto.php)" />
                                        </div>
                                        
                                        <div class="col-xl-12 mb-6">
                                            <label class="form-label-custom required">Chọn cụm Máy chủ (Server Cron):</label>
                                            <select name="server_cron" id="server_cron" data-control="select2" class="form-select form-select-solid form-select-lg fw-bold" onchange="mincron()">
                                                <option value="">-- Vui lòng lựa chọn cụm máy chủ xử lý --</option>
                                                <?php
                                                $result = mysqli_query($ketnoi,"SELECT * FROM `list_server_cron` WHERE `status` = 'ON' ORDER BY id");
                                                while($row1 = mysqli_fetch_assoc($result)) { ?>
                                                    <option value='<?=$row1['name_cron'];?>'>Cụm Server: <?=$row1['name_cron'];?> (Hạn mức tối thiểu: <?=$row1['min_time'];?> giây)</option>
                                                <?php } ?>
                                            </select>
                                        </div>
                                        
                                        <div class="col-xl-12" id="min_cron"></div>
                                        <div class="col-xl-12" id="tong_tien_div"></div>
                                    </div>
                                </div>
                                <div class="card-footer d-flex justify-content-end py-6 px-9 bg-transparent border-top border-gray-100">
                                    <button type="reset" class="btn btn-light fw-bold me-2">Làm mới Form</button>
                                    <button class="btn btn-primary fw-bold px-6" id="kt_account_profile_details_submit" type="button" onclick="thanhtoan()">
                                        <span id="button1" class="indicator-label"><i class="fa-solid fa-credit-card me-1"></i> Thanh Toán & Tạo Ngay</span>
                                        <span id="button2" class="indicator-progress" style="display: none;">Đang xử lý tạo dữ liệu...
                                            <span class="spinner-border spinner-border-sm align-middle ms-2"></span>
                                        </span>
                                    </button>
                                </div>
                            </div>
                            <?php } else { ?>
                            
                            <div class="card premium-cron-card mb-6">
                                <div class="card-header border-0 pt-6 bg-transparent">
                                    <div class="card-title">
                                        <span class="fw-black text-dark fs-4 text-warning"><i class="fa-solid fa-pen-to-square text-warning me-2"></i>Hiệu chỉnh tiến trình Cron: #<?=$toz_cron['id'];?></span>
                                    </div>
                                </div>
                                <div class="card-body p-6 p-lg-10">
                                    <div class="row">
                                        <div class="col-xl-12 mb-6">
                                            <label class="form-label-custom required">Liên kết đang chạy (URL):</label>
                                            <input type="text" name="edit_url" id="edit_url" class="form-control form-control-lg form-control-solid" value="<?=$toz_cron['url'];?>" />
                                        </div>
                                        
                                        <div class="col-xl-12 mb-6">
                                            <label class="form-label-custom required">Tốc độ lặp (Số giây):</label>
                                            <input type="number" min="5" name="edit_interval_seconds" id="edit_interval_seconds" class="form-control form-control-lg form-control-solid" value="<?=$toz_cron['interval_seconds'];?>" />
                                        </div>
                                        
                                        <div class="col-xl-12 mb-6">
                                            <label class="form-label-custom">Đang chạy trên Máy chủ:</label>
                                            <input type="text" class="form-control form-control-lg form-control-solid" value="Hệ thống Máy chủ xử lý: <?=$toz_cron['server_cron'];?>" readonly />
                                        </div>
                                        
                                        <div class="col-xl-12 mb-6">
                                            <label class="form-label-custom required">Trạng thái hoạt động:</label>
                                            <select name="status" id="status" data-control="select2" class="form-select form-select-solid form-select-lg fw-bold">
                                                <?php if ($toz_cron['status'] == "hethan") { ?>
                                                    <option value="hethan">Hết hạn định kỳ</option>
                                                <?php } else { ?>
                                                    <option value="<?= $toz_cron['status']; ?>"><?= $toz_cron['status']; ?></option>
                                                    <?php $st2 = ($toz_cron['status'] == "ON") ? "OFF" : "ON"; ?>
                                                    <option value="<?= $st2; ?>"><?= $st2; ?></option>
                                                <?php } ?>
                                            </select>
                                        </div>
                                        
                                        <div class="col-xl-12 mb-2">
                                            <label class="form-label-custom required">Yêu cầu gia hạn thêm chu kỳ:</label>
                                            <select name="gia_han" id="gia_han" data-control="select2" class="form-select form-select-solid form-select-lg fw-bold">
                                                <option value="0">Không gia hạn (Giữ nguyên chu kỳ hiện tại)</option>
                                                <option value="1">Gia hạn thêm 1 tháng</option>
                                                <option value="2">Gia hạn thêm 2 tháng</option>
                                                <option value="3">Gia hạn thêm 3 tháng</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-footer d-flex justify-content-end py-6 px-9 bg-transparent border-top border-gray-100">
                                    <a href="/cron-jobs" class="btn btn-light fw-bold me-2">Hủy Bỏ</a>
                                    <button class="btn btn-warning fw-bold px-6" id="kt_account_profile_details_submit" type="button" onclick="luungay()">
                                        <span id="button1" class="indicator-label"><i class="fa-solid fa-floppy-disk me-1"></i> Lưu Thay Đổi</span>
                                        <span id="button2" class="indicator-progress" style="display: none;">Đang ghi nhận dữ liệu...
                                            <span class="spinner-border spinner-border-sm align-middle ms-2"></span>
                                        </span>
                                    </button>
                                </div>
                            </div>
                            <?php } ?>

                            <div class="card premium-cron-card mt-6">
                                <div class="card-header border-0 pt-6 bg-transparent">
                                    <div class="card-title">
                                        <div class="d-flex flex-column">
                                            <span class="fw-black text-dark fs-4 mb-1">Danh sách giám sát hệ thống Cron của bạn</span>
                                            <span class="text-muted fw-semibold fs-7"><i class="fa-regular fa-clock me-1"></i> Cập nhật chu kỳ: <?=$time;?></span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="card-body py-4">
                                    <div class="table-responsive">
                                        <table class="table custom-cron-table table-row-dashed align-middle gs-0 gy-4">
                                            <thead>
                                                <tr class="fw-bolder text-muted text-uppercase fs-8">
                                                    <th class="w-60px text-center">Mã ID</th>
                                                    <th class="min-w-150px">Đường dẫn Cron URL</th>
                                                    <th class="min-w-80px text-center">Tốc Độ</th>
                                                    <th class="min-w-100px text-center">Server</th>
                                                    <th class="min-w-140px text-center">Ngày Tạo</th>
                                                    <th class="min-w-140px text-center">Hết Hạn</th>
                                                    <th class="min-w-180px text-center">Lần Chạy Gần Nhất (Phản Hồi)</th>
                                                    <th class="min-w-100px text-center">Trạng Thái</th>
                                                    <th class="min-w-130px text-end pe-3">Thao Tác</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                $i = 1;
                                                $result = mysqli_query($ketnoi, "SELECT * FROM `list_cron` WHERE `username` = '$username' ORDER BY `id` DESC");
                                                while($row = mysqli_fetch_assoc($result)) { ?>
                                                <tr>
                                                    <td class="text-center">
                                                        <span class="badge-index"><?=$row['id'];?></span>
                                                    </td>
                                                    
                                                    <td>
                                                        <a href="<?=$row['url'];?>" target="_blank" class="text-dark fw-bold text-hover-primary fs-7 d-inline-flex align-items-center gap-1" data-bs-toggle="tooltip" title="<?=$row['url'];?>">
                                                            <i class="fa-solid fa-link text-muted fs-8"></i>
                                                            <span class="cron-url-text"><?=$row['url'];?></span>
                                                        </a>
                                                    </td>
                                                    
                                                    <td class="text-center text-gray-800 fw-bold fs-7">
                                                        <?=$row['interval_seconds'];?> giây
                                                    </td>
                                                    
                                                    <td class="text-center">
                                                        <span class="badge badge-light-secondary fw-semibold fs-7 text-gray-700">
                                                            Server <?=$row['server_cron'];?>
                                                        </span>
                                                    </td>
                                                    
                                                    <td class="text-center text-gray-600 fs-7 fw-semibold">
                                                        <?=ngay($row['ngay_mua']);?>
                                                    </td>
                                                    
                                                    <td class="text-center text-danger fs-7 fw-semibold">
                                                        <?=ngay($row['ngay_het']);?>
                                                    </td>
                                                    
                                                    <td class="text-center fs-7 text-gray-700">
                                                        <span class="badge badge-light-info fw-bold me-1">Code: <?=$row['response'];?></span> 
                                                        <span class="fw-semibold text-gray-600"><?=ngay($row['last_cron']);?></span>
                                                    </td>
                                                    
                                                    <td class="text-center fw-bold">
                                                        <?=status($row['status']); ?>
                                                    </td>
                                                    
                                                    <td class="text-end pe-3">
                                                        <div class="d-flex justify-content-end gap-1">
                                                            <button onclick="toggleStatus(<?=$row['id'];?>, 'on')" class="btn btn-icon btn-light-success btn-sm" data-bs-toggle="tooltip" title="Bật tiến trình">
                                                                <i class="fa-solid fa-play fs-6"></i>
                                                            </button>
                                                            <button onclick="toggleStatus(<?=$row['id'];?>, 'off')" class="btn btn-icon btn-light-danger btn-sm" data-bs-toggle="tooltip" title="Tạm dừng tiến trình">
                                                                <i class="fa-solid fa-pause fs-6"></i>
                                                            </button>
                                                            <a href="?edit=<?=$row['id'];?>" class="btn btn-icon btn-light-warning btn-sm" data-bs-toggle="tooltip" title="Thay đổi thông số">
                                                                <i class="fa-solid fa-pen-to-square fs-6"></i>
                                                            </a>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php } ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
                
                <?php require $_SERVER['DOCUMENT_ROOT'].'/hethong/foot.php';?>
            </div>
        </div>
    </div>

    <script>
    function toggleStatus(id, action) {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", `/ajax/cronjob/status_cron?id=${id}&action=${action}`);
        xhr.onload = function () {
            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText);
                if (response.success) {
                    Swal.fire({
                        icon: "success",
                        text: `Cập nhật trạng thái thành công: ${action.toUpperCase()}`,
                    }).then(() => {
                        window.location.href = "";
                    });
                } else {
                    Swal.fire({
                        icon: "error",
                        text: response.message,
                    });
                }
            } else {
                Swal.fire({
                    icon: "error",
                    text: "Error: " + xhr.statusText,
                });
            }
        };
        xhr.onerror = function () {
            Swal.fire({
                icon: "error",
                text: "Error: " + xhr.statusText,
            });
        };
        xhr.send();
    }

    function luungay() {
        const button1 = document.getElementById("button1");
        const button2 = document.getElementById("button2");

        button1.style.display = "none";
        button2.style.display = "inline-block";
        button2.disabled = true;

        const username = "<?=$username;?>";
        const id_cron = "<?=$toz_cron['id'];?>";
        const edit_url = document.getElementById("edit_url").value;
        const edit_interval_seconds = document.getElementById("edit_interval_seconds").value;
        const status = document.getElementById("status").value;
        const gia_han = document.getElementById("gia_han").value;

        const xhr = new XMLHttpRequest();
        xhr.open("POST", "/ajax/cronjob/edit-cron");
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onload = function() {
            button1.style.display = "inline-block";
            button2.style.display = "none";
            button2.disabled = false;

            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText);
                if (response.success) {
                    Swal.fire({
                        icon: "success",
                        text: "Cập nhật thông số CronJob thành công!",
                    }).then(() => {
                        window.location.href = "/cron-jobs";
                    });
                } else {
                    Swal.fire({
                        icon: "error",
                        text: response.message,
                    });
                }
            } else {
                Swal.fire({
                    icon: "error",
                    text: "Error: " + xhr.statusText,
                });
            }
        };
        xhr.send(
            "username=" + encodeURIComponent(username) +
            "&id_cron=" + encodeURIComponent(id_cron) +
            "&edit_url=" + encodeURIComponent(edit_url) +
            "&edit_interval_seconds=" + encodeURIComponent(edit_interval_seconds) +
            "&status=" + encodeURIComponent(status) +
            "&gia_han=" + encodeURIComponent(gia_han)
        );
    }

    function thanhtoan() {
        const button1 = document.getElementById("button1");
        const button2 = document.getElementById("button2");

        button1.style.display = "none";
        button2.style.display = "inline-block";
        button2.disabled = true;

        const username = "<?=$username?>";
        const url = document.getElementById("url").value;
        const interval_seconds = document.getElementById("interval_seconds").value;
        const server_cron = document.getElementById("server_cron").value;

        Swal.fire({
            title: 'Xác nhận tạo Cron',
            text: "Xác nhận các thông tin cài đặt tác vụ tự động đã chính xác?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Xác nhận thuê',
            cancelButtonText: 'Kiểm tra lại'
        }).then((result) => {
            if (result.isConfirmed) {
                const xhr = new XMLHttpRequest();
                xhr.open("POST", "/ajax/cronjob/cronjob");
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.onload = function() {
                    button1.style.display = "inline-block";
                    button2.style.display = "none";
                    button2.disabled = false;

                    if (xhr.status === 200) {
                        const response = JSON.parse(xhr.responseText);
                        if (response.success) {
                            Swal.fire({
                                icon: "success",
                                text: "Đăng ký thuê cron thành công! Tiến trình sẽ tự động kích hoạt sau ít phút.",
                            }).then(function() {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                icon: "error",
                                text: response.message,
 Berry                          });
                        }
                    } else {
                        Swal.fire({
                            icon: "error",
                            text: "Error: " + xhr.statusText,
                        });
                    }
                };
                xhr.send(
                    "username=" + encodeURIComponent(username) +
                    "&url=" + encodeURIComponent(url) +
                    "&interval_seconds=" + encodeURIComponent(interval_seconds) +
                    "&server_cron=" + encodeURIComponent(server_cron)
                );
            } else {
                button1.style.display = "inline-block";
                button2.style.display = "none";
                button2.disabled = false;
            }
        });
    }
    </script>
</body>
</html>
