<?php
/**
 * admin/system-events.php - System Events & Scheduled Tasks Monitor
 */

require_once __DIR__ . '/includes/base.php';

if (!hasAdminPermission('view_logs')) {
    setFlashMessage('Access denied.', 'error');
    header('Location: ' . APP_URL . '/admin/index.php');
    exit();
}

$breadcrumbs = [['title' => 'System Events', 'url' => '']];

renderAdminHeader('System Events', $breadcrumbs);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold"><i class="bi bi-calendar-event me-2"></i>System Events</h2>
        <p class="text-muted mb-0">Monitor scheduled tasks and system events</p>
    </div>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addTaskModal">
        <i class="bi bi-plus-circle me-2"></i>Schedule Task
    </button>
</div>

<!-- Tabs -->
<ul class="nav nav-tabs mb-4">
    <li class="nav-item">
        <a class="nav-link active" data-bs-toggle="tab" href="#scheduled">Scheduled Tasks</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-bs-toggle="tab" href="#system_logs">System Logs</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-bs-toggle="tab" href="#alerts">System Alerts</a>
    </li>
</ul>

<div class="tab-content">
    <!-- Scheduled Tasks -->
    <div class="tab-pane fade show active" id="scheduled">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <table class="table" id="tasksTable">
                    <thead>
                        <tr>
                            <th>Task Name</th>
                            <th>Schedule</th>
                            <th>Last Run</th>
                            <th>Next Run</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr><td colspan="6" class="text-center py-5"><div class="spinner-border"></div></td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- System Logs -->
    <div class="tab-pane fade" id="system_logs">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <table class="table" id="logsTable">
                    <thead>
                        <tr>
                            <th>Timestamp</th>
                            <th>Level</th>
                            <th>Category</th>
                            <th>Message</th>
                            <th>Details</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr><td colspan="5" class="text-center py-5"><div class="spinner-border"></div></td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- System Alerts -->
    <div class="tab-pane fade" id="alerts">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div id="alertsContainer">
                    <div class="text-center py-5"><div class="spinner-border"></div></div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Task Modal -->
<div class="modal fade" id="addTaskModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Schedule New Task</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="taskForm">
                <input type="hidden" name="task_id" id="task_id">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Task Name *</label>
                            <input type="text" class="form-control" name="task_name" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Task Type *</label>
                            <select class="form-select" name="task_type" required>
                                <option value="backup">Database Backup</option>
                                <option value="cleanup">Cleanup Old Data</option>
                                <option value="email">Send Emails</option>
                                <option value="report">Generate Report</option>
                                <option value="maintenance">Maintenance Task</option>
                                <option value="custom">Custom Script</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Schedule (Cron Expression) *</label>
                        <input type="text" class="form-control" name="schedule" required placeholder="*/5 * * * *">
                        <small class="text-muted">
                            Examples: */5 * * * * (every 5 min) | 0 2 * * * (daily at 2am) | 0 0 * * 0 (weekly)
                        </small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Command/Script *</label>
                        <input type="text" class="form-control" name="command" required placeholder="php /path/to/script.php">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="description" rows="2"></textarea>
                    </div>
                    
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" name="is_active" id="task_active" checked>
                        <label class="form-check-label" for="task_active">Active</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Schedule Task</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    loadTasks();
    loadLogs();
    loadAlerts();
});

function loadTasks() {
    $.get(APP_URL + '/api/admin.php?action=get_scheduled_tasks', function(response) {
        if (response.success && response.data.length > 0) {
            let html = '';
            response.data.forEach(task => {
                html += `
                    <tr>
                        <td><strong>${task.task_name}</strong><br><small class="text-muted">${task.task_type}</small></td>
                        <td><code>${task.schedule}</code></td>
                        <td>${task.last_run || 'Never'}</td>
                        <td>${task.next_run || 'Calculating...'}</td>
                        <td><span class="badge bg-${task.is_active ? 'success' : 'secondary'}">${task.is_active ? 'Active' : 'Inactive'}</span></td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary" onclick="runTask(${task.id})"><i class="bi bi-play-fill"></i></button>
                            <button class="btn btn-sm btn-outline-secondary" onclick="editTask(${task.id})"><i class="bi bi-pencil"></i></button>
                            <button class="btn btn-sm btn-outline-danger" onclick="deleteTask(${task.id})"><i class="bi bi-trash"></i></button>
                        </td>
                    </tr>
                `;
            });
            $('#tasksTable tbody').html(html);
        } else {
            $('#tasksTable tbody').html('<tr><td colspan="6" class="text-center">No scheduled tasks</td></tr>');
        }
    });
}

function loadLogs() {
    $.get(APP_URL + '/api/admin.php?action=get_system_logs', function(response) {
        if (response.success && response.data.length > 0) {
            let html = '';
            response.data.forEach(log => {
                const levelClass = log.level === 'error' ? 'danger' : (log.level === 'warning' ? 'warning' : 'info');
                html += `
                    <tr>
                        <td><small>${log.created_at}</small></td>
                        <td><span class="badge bg-${levelClass}">${log.level}</span></td>
                        <td>${log.category}</td>
                        <td>${log.message}</td>
                        <td><button class="btn btn-sm btn-outline-primary" onclick="viewLogDetails(${log.id})"><i class="bi bi-eye"></i></button></td>
                    </tr>
                `;
            });
            $('#logsTable tbody').html(html);
        } else {
            $('#logsTable tbody').html('<tr><td colspan="5" class="text-center">No system logs</td></tr>');
        }
    });
}

function loadAlerts() {
    $.get(APP_URL + '/api/admin.php?action=get_system_alerts', function(response) {
        if (response.success && response.data.length > 0) {
            let html = '';
            response.data.forEach(alert => {
                const alertClass = alert.severity === 'critical' ? 'danger' : (alert.severity === 'warning' ? 'warning' : 'info');
                html += `
                    <div class="alert alert-${alertClass} alert-dismissible fade show">
                        <h6><i class="bi bi-exclamation-triangle me-2"></i>${alert.alert_type}</h6>
                        <p class="mb-1">${alert.message}</p>
                        <small class="text-muted">${alert.created_at}</small>
                        ${!alert.is_acknowledged ? 
                            '<button class="btn btn-sm btn-outline-' + alertClass + ' mt-2" onclick="acknowledgeAlert(' + alert.id + ')">Acknowledge</button>' 
                            : '<span class="badge bg-success">Acknowledged</span>'}
                    </div>
                `;
            });
            $('#alertsContainer').html(html);
        } else {
            $('#alertsContainer').html('<div class="text-center py-5"><i class="bi bi-check-circle text-success" style="font-size: 3rem;"></i><p class="text-muted mt-3">No active alerts</p></div>');
        }
    });
}

$('#taskForm').submit(function(e) {
    e.preventDefault();
    const formData = $(this).serializeArray();
    formData.push({name: 'action', value: $('#task_id').val() ? 'update_scheduled_task' : 'create_scheduled_task'});
    
    $.post(APP_URL + '/api/admin.php', $.param(formData), function(response) {
        if (response.success) {
            showToast(response.message, 'success');
            $('#addTaskModal').modal('hide');
            $('#taskForm')[0].reset();
            loadTasks();
        } else {
            showToast(response.message, 'error');
        }
    });
});

function runTask(taskId) {
    Swal.fire({
        title: 'Run Task Now?',
        text: 'This will execute the task immediately',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Run Now'
    }).then((result) => {
        if (result.isConfirmed) {
            showLoading();
            $.post(APP_URL + '/api/admin.php', {action: 'run_scheduled_task', task_id: taskId}, function(response) {
                hideLoading();
                showToast(response.message, response.success ? 'success' : 'error');
                loadTasks();
            });
        }
    });
}

function deleteTask(taskId) {
    Swal.fire({
        title: 'Delete Task?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        confirmButtonText: 'Delete'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post(APP_URL + '/api/admin.php', {action: 'delete_scheduled_task', task_id: taskId}, function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    loadTasks();
                }
            });
        }
    });
}

function acknowledgeAlert(alertId) {
    $.post(APP_URL + '/api/admin.php', {action: 'acknowledge_alert', alert_id: alertId}, function(response) {
        if (response.success) {
            showToast('Alert acknowledged', 'success');
            loadAlerts();
        }
    });
}
</script>

<?php renderAdminFooter(); ?>