<?php
require_once __DIR__ . '/../MPHX/common.php';

$user = check_user();
$task_prefix = 'ELEML TOD_' . $user['user'] . '_';
?>

<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/all.min.css">
<link rel="stylesheet" href="css/style.css">

<style>
    .cron-container {
        padding: 20px;
    }
    .cron-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }
    .btn-primary {
        background: #20a53a;
        border: none;
        padding: 10px 24px;
        font-size: 14px;
        font-weight: 500;
        border-radius: 4px;
        transition: background 0.2s;
        color: #fff;
    }
    .btn-primary:hover {
        background: #1a8f32;
    }
    .btn-secondary {
        background: #f1f1f1;
        border: 1px solid #dcdfe6;
        padding: 10px 24px;
        font-size: 14px;
        font-weight: 500;
        border-radius: 4px;
        color: #606266;
    }
    .btn-secondary:hover {
        background: #e8e8e8;
    }
    .btn-success {
        background: #20a53a;
        border: none;
        padding: 6px 16px;
        font-size: 12px;
        font-weight: 500;
        border-radius: 4px;
        color: #fff;
    }
    .btn-danger {
        background: #f56c6c;
        border: none;
        padding: 6px 16px;
        font-size: 12px;
        font-weight: 500;
        border-radius: 4px;
        color: #fff;
    }
    .btn-info {
        background: #409eff;
        border: none;
        padding: 6px 16px;
        font-size: 12px;
        font-weight: 500;
        border-radius: 4px;
        color: #fff;
    }
    .btn-test {
        background: #e6a23c;
        border: none;
        padding: 8px 16px;
        font-size: 13px;
        border-radius: 4px;
        color: #fff;
    }
    .cron-list {
        background: #fff;
        border-radius: 4px;
        overflow: hidden;
        border: 1px solid #ebeef5;
    }
    .cron-item {
        padding: 16px 20px;
        border-bottom: 1px solid #ebeef5;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .cron-item:last-child {
        border-bottom: none;
    }
    .cron-item:hover {
        background: #f5f7fa;
    }
    .cron-info {
        flex: 1;
    }
    .cron-info h4 {
        margin: 0 0 6px 0;
        color: #303133;
        font-size: 14px;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    .cron-info .task-type {
        display: inline-block;
        padding: 2px 8px;
        border-radius: 3px;
        font-size: 11px;
        font-weight: 500;
    }
    .cron-info .task-type.get {
        background: #e1f3d8;
        color: #67c23a;
    }
    .cron-info .task-type.post {
        background: #fdf6ec;
        color: #e6a23c;
    }
    .cron-info .status-badge {
        display: inline-block;
        padding: 2px 8px;
        border-radius: 3px;
        font-size: 11px;
        font-weight: 500;
    }
    .cron-info .status-badge.enabled {
        background: #e1f3d8;
        color: #67c23a;
    }
    .cron-info .status-badge.disabled {
        background: #fde2e2;
        color: #f56c6c;
    }
    .cron-info .details {
        color: #909399;
        font-size: 12px;
        margin-top: 6px;
    }
    .cron-info .details span {
        margin-right: 20px;
    }
    .cron-actions {
        display: flex;
        gap: 8px;
    }
    .empty-state {
        text-align: center;
        padding: 80px 20px;
        color: #909399;
    }
    .empty-state i {
        font-size: 64px;
        margin-bottom: 20px;
        color: #dcdfe6;
    }
    .empty-state h3 {
        margin: 0 0 10px 0;
        font-size: 16px;
        color: #606266;
        font-weight: normal;
    }
    .empty-state p {
        margin: 0;
        font-size: 13px;
    }
    /* Modal styles */
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        z-index: 1000;
        align-items: flex-start;
        justify-content: center;
        padding-top: 50px;
        overflow-y: auto;
    }
    .modal.show {
        display: flex;
    }
    .modal-content {
        background: #fff;
        border-radius: 4px;
        width: 700px;
        max-width: 95%;
        box-shadow: 0 2px 12px rgba(0,0,0,0.1);
        margin-bottom: 50px;
    }
    .modal-header {
        padding: 16px 20px;
        border-bottom: 1px solid #ebeef5;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .modal-header h3 {
        margin: 0;
        color: #303133;
        font-size: 16px;
        font-weight: 500;
    }
    .modal-close {
        background: none;
        border: none;
        font-size: 20px;
        cursor: pointer;
        color: #909399;
        line-height: 1;
    }
    .modal-close:hover {
        color: #606266;
    }
    .modal-body {
        padding: 20px;
    }
    .form-row {
        display: flex;
        align-items: flex-start;
        margin-bottom: 18px;
    }
    .form-row label {
        width: 90px;
        text-align: right;
        padding-right: 12px;
        color: #606266;
        font-size: 13px;
        line-height: 36px;
        flex-shrink: 0;
    }
    .form-row label .required {
        color: #f56c6c;
        margin-right: 2px;
    }
    .form-row .form-control-wrap {
        flex: 1;
        display: flex;
        align-items: center;
        gap: 10px;
        flex-wrap: wrap;
    }
    .form-row input,
    .form-row select,
    .form-row textarea {
        padding: 8px 12px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        font-size: 13px;
        box-sizing: border-box;
        transition: border-color 0.2s;
    }
    .form-row input:focus,
    .form-row select:focus,
    .form-row textarea:focus {
        outline: none;
        border-color: #20a53a;
    }
    .form-row input.full,
    .form-row select.full,
    .form-row textarea.full {
        width: 100%;
    }
    .form-row input.small {
        width: 60px;
        text-align: center;
    }
    .form-row select.medium {
        min-width: 120px;
    }
    .form-row .help-icon {
        color: #e6a23c;
        cursor: help;
    }
    .form-row .cycle-text {
        color: #909399;
        font-size: 12px;
        margin-top: 6px;
        width: 100%;
    }
    .form-row .checkbox-wrap {
        display: flex;
        align-items: center;
        gap: 6px;
        color: #606266;
        font-size: 13px;
    }
    .form-row .checkbox-wrap input[type="checkbox"] {
        width: 16px;
        height: 16px;
        accent-color: #20a53a;
    }
    /* Params table */
    .params-section {
        margin-top: 10px;
    }
    .params-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 13px;
    }
    .params-table th {
        background: #fafafa;
        padding: 10px 12px;
        text-align: left;
        font-weight: 500;
        color: #606266;
        border-bottom: 1px solid #ebeef5;
    }
    .params-table td {
        padding: 8px 12px;
        border-bottom: 1px solid #ebeef5;
    }
    .params-table input {
        width: 100%;
        padding: 6px 10px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        font-size: 13px;
    }
    .params-table .btn-remove {
        color: #f56c6c;
        cursor: pointer;
        font-size: 12px;
    }
    .params-table .btn-remove:hover {
        text-decoration: underline;
    }
    .btn-add-param {
        background: #20a53a;
        color: #fff;
        border: none;
        padding: 6px 12px;
        border-radius: 4px;
        font-size: 12px;
        cursor: pointer;
        margin-top: 10px;
    }
    .modal-footer {
        padding: 12px 20px;
        border-top: 1px solid #ebeef5;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }
    .alert {
        padding: 12px 16px;
        border-radius: 4px;
        margin-bottom: 16px;
        font-size: 13px;
    }
    .alert-success {
        background: #f0f9eb;
        color: #67c23a;
        border: 1px solid #c2e7b0;
    }
    .alert-danger {
        background: #fef0f0;
        color: #f56c6c;
        border: 1px solid #fbc4c4;
    }
    .loading {
        text-align: center;
        padding: 40px;
    }
    .loading i {
        font-size: 32px;
        color: #20a53a;
        margin-bottom: 12px;
    }
</style>

<div class="content-area cron-container">
    <div id="alertContainer"></div>
    
    <div class="cron-header">
        <div>
            <h3 style="margin: 0 0 6px 0; color: #303133; font-size: 18px; font-weight: 500;"><?php echo L('title', 'cron'); ?></h3>
            <p style="margin: 0; color: #909399; font-size: 13px;"><?php echo L('task_list', 'cron'); ?></p>
        </div>
        <button type="button" class="btn btn-primary" data-action="show-add-cron">
            <i class="fas fa-plus"></i> <?php echo L('add_task', 'cron'); ?>
        </button>
    </div>
    
    <div class="cron-list" id="cronList">
        <div class="loading">
            <i class="fas fa-spinner fa-spin"></i>
            <p style="color: #909399; margin: 0;"><?php echo L('loading', 'common'); ?>...</p>
        </div>
    </div>
</div>

<div class="modal" id="addModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3><?php echo L('add_task', 'cron'); ?></h3>
            <button type="button" class="modal-close" data-action="close-modal">&times;</button>
        </div>
        <div class="modal-body">
            <div class="form-row">
                <label><?php echo L('operation_type', 'logs'); ?></label>
                <div class="form-control-wrap">
                    <select id="taskType" class="medium" onchange="onTaskTypeChange()">
                        <option value="URL-GET">访问URL-GET</option>
                        <option value="URL-POST">访问URL-POST</option>
                    </select>
                    <span class="help-icon" title="GET: 简单访问URL&#10;POST: 带参数访问URL"><i class="fas fa-question-circle"></i></span>
                </div>
            </div>
            
            <div class="form-row">
                <label><span class="required">*</span> <?php echo L('task_name', 'cron'); ?></label>
                <div class="form-control-wrap">
                    <input type="text" id="taskName" class="full" placeholder="访问URL-[ http:// ]">
                </div>
            </div>
            
            <div class="form-row">
                <label><?php echo L('execution_cycle', 'cron'); ?></label>
                <div class="form-control-wrap">
                    <select id="cycleType" class="medium" onchange="onCycleTypeChange()">
                        <option value="day">每天</option>
                        <option value="day-n">每N天</option>
                        <option value="hour">每小时</option>
                        <option value="hour-n">每N小时</option>
                        <option value="minute-n">每N分钟</option>
                        <option value="week">每星期</option>
                    </select>
                    <span id="cycleDay" style="display:none;">
                        <input type="number" id="cycleDayVal" class="small" value="1" min="1" max="31"> 天
                    </span>
                    <span id="cycleHour">
                        <input type="number" id="cycleHourVal" class="small" value="1" min="0" max="23"> 小时
                    </span>
                    <span id="cycleMinute">
                        <input type="number" id="cycleMinuteVal" class="small" value="30" min="0" max="59"> 分钟
                    </span>
                    <span id="cycleWeek" style="display:none;">
                        <select id="cycleWeekVal" class="medium">
                            <option value="1">星期一</option>
                            <option value="2">星期二</option>
                            <option value="3">星期三</option>
                            <option value="4">星期四</option>
                            <option value="5">星期五</option>
                            <option value="6">星期六</option>
                            <option value="0">星期日</option>
                        </select>
                    </span>
                    <span class="checkbox-wrap">
                        <input type="checkbox" id="processLock" checked> 开启进程锁
                    </span>
                    <div class="cycle-text" id="cycleText">每天的 01:30 执行一次</div>
                </div>
            </div>
            
            <div class="form-row">
                <label><span class="required">*</span> URL地址</label>
                <div class="form-control-wrap">
                    <input type="text" id="taskUrl" class="full" placeholder="http://" style="flex:1;">
                    <button type="button" class="btn-test" onclick="testUrl()">测试URL</button>
                </div>
            </div>
            
            <div class="form-row">
                <label>User-Agent</label>
                <div class="form-control-wrap">
                    <textarea id="taskUserAgent" class="full" rows="2" placeholder="请输入User-Agent"></textarea>
                </div>
            </div>
            
            <div class="form-row" id="paramsSection" style="display:none;">
                <label>参数配置</label>
                <div class="form-control-wrap params-section">
                    <table class="params-table">
                        <thead>
                            <tr>
                                <th style="width:40%;">参数名</th>
                                <th style="width:40%;">参数值</th>
                                <th style="width:20%;">操作</th>
                            </tr>
                        </thead>
                        <tbody id="paramsBody">
                            <tr>
                                <td><input type="text" class="param-name" placeholder=""></td>
                                <td><input type="text" class="param-value" placeholder=""></td>
                                <td><span class="btn-remove" onclick="removeParam(this)">删除</span></td>
                            </tr>
                        </tbody>
                    </table>
                    <button type="button" class="btn-add-param" onclick="addParam()">
                        <i class="fas fa-plus"></i> 添加参数
                    </button>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-action="close-modal">取消</button>
            <button type="button" class="btn btn-primary" data-action="add-cron-task">确定</button>
        </div>
    </div>
</div>

<script src="/static/js/jquery.min.js"></script>
<script>
var TASK_PREFIX = '<?php echo $task_prefix; ?>';

function showAlert(message, type) {
    var alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    var alertHtml = '<div class="alert ' + alertClass + '">' + message + '</div>';
    $('#alertContainer').html(alertHtml);
    setTimeout(function() { $('#alertContainer').html(''); }, 3000);
}

function onTaskTypeChange() {
    var type = $('#taskType').val();
    var url = $('#taskUrl').val().trim() || 'http://';
    $('#taskName').val('访问URL-' + type.split('-')[1] + '[ ' + url + ' ]');
    if (type === 'URL-POST') {
        $('#paramsSection').show();
    } else {
        $('#paramsSection').hide();
    }
}

function onCycleTypeChange() {
    var type = $('#cycleType').val();
    $('#cycleDay, #cycleHour, #cycleMinute, #cycleWeek').hide();
    
    switch(type) {
        case 'day':
            $('#cycleHour, #cycleMinute').show();
            break;
        case 'day-n':
            $('#cycleDay, #cycleHour, #cycleMinute').show();
            break;
        case 'hour':
            $('#cycleMinute').show();
            break;
        case 'hour-n':
            $('#cycleHour, #cycleMinute').show();
            break;
        case 'minute-n':
            $('#cycleMinute').show();
            break;
        case 'week':
            $('#cycleWeek, #cycleHour, #cycleMinute').show();
            break;
    }
    updateCycleText();
}

function updateCycleText() {
    var type = $('#cycleType').val();
    var h = parseInt($('#cycleHourVal').val()) || 0;
    var m = parseInt($('#cycleMinuteVal').val()) || 0;
    var d = parseInt($('#cycleDayVal').val()) || 1;
    var w = $('#cycleWeekVal option:selected').text();
    var text = '';
    
    switch(type) {
        case 'day':
            text = '每天的 ' + String(h).padStart(2,'0') + ':' + String(m).padStart(2,'0') + ' 执行一次';
            break;
        case 'day-n':
            text = '每隔 ' + d + ' 天的 ' + String(h).padStart(2,'0') + ':' + String(m).padStart(2,'0') + ' 执行一次';
            break;
        case 'hour':
            text = '每小时的第 ' + m + ' 分钟执行一次';
            break;
        case 'hour-n':
            text = '每隔 ' + h + ' 小时的第 ' + m + ' 分钟执行一次';
            break;
        case 'minute-n':
            text = '每隔 ' + m + ' 分钟执行一次';
            break;
        case 'week':
            text = '每' + w + '的 ' + String(h).padStart(2,'0') + ':' + String(m).padStart(2,'0') + ' 执行一次';
            break;
    }
    $('#cycleText').text(text);
}

$('#cycleHourVal, #cycleMinuteVal, #cycleDayVal, #cycleWeekVal').on('change input', updateCycleText);
$('#taskUrl').on('input', function() {
    var type = $('#taskType').val();
    var url = $(this).val().trim() || 'http://';
    $('#taskName').val('访问URL-' + type.split('-')[1] + '[ ' + url + ' ]');
});

function addParam() {
    var row = '<tr><td><input type="text" class="param-name" placeholder=""></td><td><input type="text" class="param-value" placeholder=""></td><td><span class="btn-remove" onclick="removeParam(this)">删除</span></td></tr>';
    $('#paramsBody').append(row);
}

function removeParam(el) {
    $(el).closest('tr').remove();
}

function testUrl() {
    var url = $('#taskUrl').val().trim();
    if (!url || url === 'http://') {
        showAlert('请输入URL地址', 'error');
        return;
    }
    
    // 显示测试中的提示
    var $btn = $('.btn-test');
    var originalText = $btn.text();
    $btn.text('检测中...').prop('disabled', true);
    
    // 移除之前的提示
    $('#urlTestResult').remove();
    
    $.ajax({
        type: 'POST',
        url: 'api/api_router.php',
        data: {
            action: 'test_url',
            url: url
        },
        dataType: 'json',
        success: function(res) {
            $btn.text(originalText).prop('disabled', false);
            
            // 在按钮旁边显示结果
            var resultClass = res.status === true || res.code === 'success' ? 'success' : 'error';
            var resultText = res.status === true || res.code === 'success' ? '✓ 可以访问' : '✗ 无法访问';
            var resultColor = res.status === true || res.code === 'success' ? '#52c41a' : '#ff4d4f';
            
            var resultHtml = '<span id="urlTestResult" style="margin-left: 10px; color: ' + resultColor + '; font-size: 13px; font-weight: 500;">' + resultText + '</span>';
            $btn.after(resultHtml);
            
            // 3秒后自动清除提示
            setTimeout(function() {
                $('#urlTestResult').fadeOut(300, function() {
                    $(this).remove();
                });
            }, 3000);
        },
        error: function() {
            $btn.text(originalText).prop('disabled', false);
            
            var resultHtml = '<span id="urlTestResult" style="margin-left: 10px; color: #ff4d4f; font-size: 13px; font-weight: 500;">✗ 检测失败</span>';
            $btn.after(resultHtml);
            
            setTimeout(function() {
                $('#urlTestResult').fadeOut(300, function() {
                    $(this).remove();
                });
            }, 3000);
        }
    });
}

function getParams() {
    var params = [];
    $('#paramsBody tr').each(function() {
        var name = $(this).find('.param-name').val().trim();
        var value = $(this).find('.param-value').val().trim();
        if (name) {
            params.push({ name: name, value: value });
        }
    });
    return params;
}

function buildCronExpression() {
    var type = $('#cycleType').val();
    var h = parseInt($('#cycleHourVal').val()) || 0;
    var m = parseInt($('#cycleMinuteVal').val()) || 0;
    var d = parseInt($('#cycleDayVal').val()) || 1;
    var w = $('#cycleWeekVal').val();
    
    switch(type) {
        case 'day': return m + ' ' + h + ' * * *';
        case 'day-n': return m + ' ' + h + ' */' + d + ' * *';
        case 'hour': return m + ' * * * *';
        case 'hour-n': return m + ' */' + h + ' * * *';
        case 'minute-n': return '*/' + m + ' * * * *';
        case 'week': return m + ' ' + h + ' * * ' + w;
    }
    return '0 1 * * *';
}

function loadTasks() {
    $('#cronList').html('<div class="loading"><i class="fas fa-spinner fa-spin"></i><p style="color:#909399;margin:0;">加载中...</p></div>');
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: { egn: 'getcrontasks', prefix: TASK_PREFIX },
        dataType: 'json',
        success: function(data) {
            if (data.code === 'success') {
                renderTasks(data.tasks);
            } else {
                $('#cronList').html('<div class="empty-state"><i class="fas fa-exclamation-circle"></i><h3>加载失败</h3><p>' + data.code + '</p></div>');
            }
        },
        error: function() {
            $('#cronList').html('<div class="empty-state"><i class="fas fa-exclamation-circle"></i><h3>加载失败</h3><p>请刷新页面重试</p></div>');
        }
    });
}

function renderTasks(tasks) {
    if (!tasks || tasks.length === 0) {
        $('#cronList').html('<div class="empty-state"><i class="fas fa-clock"></i><h3>暂无定时任务</h3><p>您还没有创建任何定时任务</p></div>');
        return;
    }
    
    var html = '';
    tasks.forEach(function(task) {
        var statusText = task.status === 'enabled' ? '已启用' : '已禁用';
        var statusClass = task.status;
        var taskType = 'GET';
        var taskTypeClass = 'get';
        if (task.task_type === 'URL-POST' || (task.command && task.command.indexOf('POST') !== -1)) {
            taskType = 'POST';
            taskTypeClass = 'post';
        }
        
        html += '<div class="cron-item">';
        html += '<div class="cron-info">';
        html += '<h4><span class="task-type ' + taskTypeClass + '">' + taskType + '</span>' + escapeHtml(task.display_name || task.name) + '<span class="status-badge ' + statusClass + '">' + statusText + '</span></h4>';
        html += '<div class="details">';
        html += '<span><i class="fas fa-link"></i> ' + escapeHtml(task.url || task.command || '-') + '</span>';
        html += '<span><i class="fas fa-clock"></i> ' + (task.cycle_text || task.cron_expression || '-') + '</span>';
        html += '<span><i class="fas fa-play"></i> 执行 ' + (task.run_count || 0) + ' 次</span>';
        html += '</div>';
        html += '</div>';
        html += '<div class="cron-actions">';
        if (task.status === 'enabled') {
            html += '<button type="button" class="btn btn-danger cron-action" data-action="toggle" data-id="' + task.id + '"><i class="fas fa-pause"></i> 禁用</button>';
        } else {
            html += '<button type="button" class="btn btn-success cron-action" data-action="toggle" data-id="' + task.id + '"><i class="fas fa-play"></i> 启用</button>';
        }
        html += '<button type="button" class="btn btn-danger cron-action" data-action="delete" data-id="' + task.id + '"><i class="fas fa-trash"></i> 删除</button>';
        html += '</div>';
        html += '</div>';
    });
    
    $('#cronList').html(html);
}

function escapeHtml(str) {
    if (!str) return '';
    return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

function showAddModal() {
    // Reset form
    $('#taskType').val('URL-GET');
    $('#taskName').val('访问URL-GET[ http:// ]');
    $('#cycleType').val('day');
    $('#cycleHourVal').val(1);
    $('#cycleMinuteVal').val(30);
    $('#cycleDayVal').val(1);
    $('#taskUrl').val('');
    $('#taskUserAgent').val('');
    $('#paramsBody').html('<tr><td><input type="text" class="param-name" placeholder=""></td><td><input type="text" class="param-value" placeholder=""></td><td><span class="btn-remove" onclick="removeParam(this)">删除</span></td></tr>');
    $('#paramsSection').hide();
    $('#processLock').prop('checked', true);
    onCycleTypeChange();
    $('#addModal').addClass('show');
}

function closeModal() {
    $('#addModal').removeClass('show');
}

function addTask() {
    var taskType = $('#taskType').val();
    var name = $('#taskName').val().trim();
    var url = $('#taskUrl').val().trim();
    var userAgent = $('#taskUserAgent').val().trim();
    var cronExpr = buildCronExpression();
    var processLock = $('#processLock').is(':checked') ? 1 : 0;
    var params = taskType === 'URL-POST' ? getParams() : [];
    
    if (!url || url === 'http://') {
        showAlert('请输入URL地址', 'error');
        return;
    }
    
    // Build the command for BT panel
    var command = '';
    if (taskType === 'URL-GET') {
        command = 'curl -s';
        if (userAgent) command += " -A '" + userAgent.replace(/'/g, "\\'") + "'";
        command += " '" + url + "'";
    } else {
        command = 'curl -s -X POST';
        if (userAgent) command += " -A '" + userAgent.replace(/'/g, "\\'") + "'";
        if (params.length > 0) {
            var paramStr = params.map(function(p) { return encodeURIComponent(p.name) + '=' + encodeURIComponent(p.value); }).join('&');
            command += " -d '" + paramStr + "'";
        }
        command += " '" + url + "'";
    }
    
    closeModal();
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: {
            egn: 'addcrontask',
            name: TASK_PREFIX + name,
            command: command,
            cron_expression: cronExpr,
            task_type: taskType,
            url: url,
            user_agent: userAgent,
            params: JSON.stringify(params),
            process_lock: processLock,
            cycle_text: $('#cycleText').text()
        },
        dataType: 'json',
        success: function(data) {
            if (data.code === 'success') {
                showAlert('定时任务添加成功', 'success');
                loadTasks();
            } else {
                showAlert(data.code || '添加失败', 'error');
            }
        },
        error: function() {
            showAlert('添加失败，请重试', 'error');
        }
    });
}

function toggleTask(id) {
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: { egn: 'togglecrontask', id: id },
        dataType: 'json',
        success: function(data) {
            if (data.code === 'success') {
                showAlert('任务状态已更新', 'success');
                loadTasks();
            } else {
                showAlert(data.code || '操作失败', 'error');
            }
        },
        error: function() {
            showAlert('操作失败，请重试', 'error');
        }
    });
}

function deleteTask(id) {
    if (!confirm('确定要删除此定时任务吗？')) return;
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: { egn: 'deletecrontask', id: id },
        dataType: 'json',
        success: function(data) {
            if (data.code === 'success') {
                showAlert('定时任务删除成功', 'success');
                loadTasks();
            } else {
                showAlert(data.code || '删除失败', 'error');
            }
        },
        error: function() {
            showAlert('删除失败，请重试', 'error');
        }
    });
}

$(document).on('click', '.cron-action', function() {
    var action = $(this).data('action');
    var id = $(this).data('id');
    if (!action || !id) return;
    if (action === 'toggle') toggleTask(id);
    else if (action === 'delete') deleteTask(id);
});

$(document).on('click', '[data-action]', function(e) {
    var action = $(this).attr('data-action');
    if (!action) return;
    if (action === 'toggle' || action === 'delete') return; // handled above
    e.preventDefault();
    switch(action) {
        case 'show-add-cron': showAddModal(); break;
        case 'close-modal': closeModal(); break;
        case 'add-cron-task': addTask(); break;
    }
});

$(document).ready(function() {
    onCycleTypeChange();
    loadTasks();
});
</script>
