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

$user = check_user();
$is_admin = is_admin_login();
?>

<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>
    /* 确保整个页面所有元素始终可见 */
    html, body, div, span, button, input, select, label, table, thead, tbody, tr, td, th, h2, p, i {
        opacity: 1 !important;
        visibility: visible !important;
    }

    .logs-container {
        padding: 24px;
        max-width: 1000px;
        margin: 0 auto;
    }
    .panel-header {
        margin-bottom: 24px;
        text-align: center;
    }
    .panel-header h2 {
        color: #188038;
        font-size: 20px;
        font-weight: 600;
        margin: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
    }
    .panel-header p {
        color: #5f6368;
        font-size: 13px;
        margin: 8px 0 0 0;
    }
    .filter-section {
        background: #fff;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        border: 1px solid #e8eaed;
        margin-bottom: 20px;
    }
    .filter-row {
        display: flex;
        gap: 16px;
        margin-bottom: 16px;
    }
    .filter-item {
        flex: 1;
    }
    .filter-item label {
        display: block;
        margin-bottom: 6px;
        color: #202124;
        font-weight: 500;
        font-size: 14px;
    }
    .filter-item input,
    .filter-item select {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid #e8eaed;
        border-radius: 6px;
        font-size: 14px;
        box-sizing: border-box;
    }
    .filter-actions {
        display: flex;
        gap: 10px;
        margin-top: 16px;
    }
    .btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        padding: 8px 16px;
        cursor: pointer;
        transition: background 0.2s;
        border: none;
        text-decoration: none;
    }
    .btn-primary {
        background: #188038;
        color: #fff;
    }
    .btn-primary:hover {
        background: #137333;
    }
    .btn-secondary {
        background: #f8f9fa;
        color: #202124;
        border: 1px solid #e8eaed;
    }
    .btn-secondary:hover {
        background: #e8eaed;
    }
    .logs-table {
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        border: 1px solid #e8eaed;
        overflow: hidden;
    }
    .logs-table table {
        width: 100%;
        border-collapse: collapse;
    }
    .logs-table th,
    .logs-table td {
        padding: 12px 16px;
        text-align: left;
        border-bottom: 1px solid #e8eaed;
    }
    .logs-table th {
        background: #f8f9fa;
        font-weight: 500;
        color: #202124;
        font-size: 14px;
    }
    .logs-table td {
        color: #5f6368;
        font-size: 14px;
    }
    .logs-table tr:hover {
        background: #f8f9fa;
    }
    .logs-table tr:last-child td {
        border-bottom: none;
    }
    .log-type {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
    }
    .log-type.info {
        background: #e3f2fd;
        color: #1976d2;
    }
    .log-type.success {
        background: #e8f5e8;
        color: #2e7d32;
    }
    .log-type.warning {
        background: #fff3e0;
        color: #ef6c00;
    }
    .log-type.error {
        background: #ffebee;
        color: #c62828;
    }
    .pagination {
        display: flex;
        justify-content: center;
        gap: 8px;
        margin-top: 20px;
    }
    .pagination button {
        padding: 6px 12px;
        border: 1px solid #e8eaed;
        background: #fff;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
    }
    .pagination button:hover {
        background: #f8f9fa;
    }
    .pagination button.active {
        background: #188038;
        color: #fff;
        border-color: #188038;
    }
    .pagination button:disabled {
        background: #f5f7fa;
        color: #ccc;
        cursor: not-allowed;
    }
    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #5f6368;
    }
    .empty-state i {
        font-size: 48px;
        margin-bottom: 16px;
        color: #dadce0;
    }
    @media (max-width: 768px) {
        .logs-container {
            padding: 16px;
        }
        .filter-row {
            flex-direction: column;
        }
        .filter-actions {
            flex-direction: column;
        }
        .logs-table {
            overflow-x: auto;
        }
        .logs-table table {
            min-width: 600px;
        }
    }
</style>

<div class="logs-container">
    <div class="panel-header">
        <h2><i class="fas fa-history"></i> <?php echo L('title', 'logs'); ?></h2>
        <p><?php echo L('filter', 'logs'); ?></p>
    </div>
    
    <div class="filter-section">
        <div class="filter-row">
            <div class="filter-item">
                <label for="startDate"><?php echo L('start_date', 'logs'); ?></label>
                <input type="date" id="startDate" class="form-control">
            </div>
            <div class="filter-item">
                <label for="endDate"><?php echo L('end_date', 'logs'); ?></label>
                <input type="date" id="endDate" class="form-control">
            </div>
            <div class="filter-item">
                <label for="logType"><?php echo L('operation_type', 'logs'); ?></label>
                <select id="logType" class="form-control">
                    <option value=""><?php echo L('all', 'common'); ?></option>
                    <?php
                    $admin_actions = [
                        'API设置', '添加宝塔', '编辑宝塔', '删除宝塔', '发布公告', '编辑公告', '删除公告',
                        '支付设置', '邮箱设置', '管理设置', '监控设置', '检查更新', '后台登录', '后台登出'
                    ];
                    
                    $user_actions = [
                        'PHP版本切换', 'SQL权限设置', 'SSL证书', '修改默认文档', '关闭SSL', '创建文件', '创建文件夹',
                        '删除', '删除主机', '删除文件', '删除禁止访问', '加密访问', '域名修改', '子目录伪静态',
                        '流量限制', '添加主机', '添加域名', '添加禁止访问', '用户登出', '用户登录', '目录密码访问设置',
                        '禁止访问设置', '移动文件', '网站设置', '设置伪静态', '设置密码访问', '设置运行目录', '防盗链设置'
                    ];
                    
                    if ($is_admin) {
                        foreach ($admin_actions as $action) {
                            echo "<option value=\"$action\">$action</option>";
                        }
                    } else {
                        foreach ($user_actions as $action) {
                            echo "<option value=\"$action\">$action</option>";
                        }
                    }
                    ?>
                </select>
            </div>
        </div>
        <div class="filter-actions">
            <button class="btn btn-primary" data-action="load-logs" data-page="1">
                <i class="fas fa-search"></i> <?php echo L('query', 'logs'); ?>
            </button>
            <button class="btn btn-secondary" data-action="reset-filters">
                <i class="fas fa-redo"></i> <?php echo L('reset', 'logs'); ?>
            </button>
            <button class="btn btn-danger" data-action="clear-logs" style="background: #dc3545; color: #fff; border: none;">
                <i class="fas fa-trash"></i> <?php echo L('delete', 'common'); ?> <?php echo L('logs', 'menu'); ?>
            </button>
        </div>
    </div>
    
    <div class="logs-table" id="logsTable">
        <table>
            <thead>
                <tr>
                    <th><?php echo L('operation_time', 'logs'); ?></th>
                    <th><?php echo L('operation_type', 'logs'); ?></th>
                    <th><?php echo L('operation_content', 'logs'); ?></th>
                    <th><?php echo L('ip_address', 'logs'); ?></th>
                </tr>
            </thead>
            <tbody id="logsBody">
                <tr>
                    <td colspan="4" class="empty-state">
                        <i class="fas fa-spinner fa-spin"></i>
                        <p><?php echo L('loading', 'common'); ?>...</p>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    
    <div class="pagination" id="pagination"></div>
</div>

<script src="/static/js/jquery.min.js"></script>
<script>
var currentPage = 1;
var pageSize = 20;

function loadLogs(page) {
    if (page) {
        currentPage = page;
    }
    
    var startDate = $('#startDate').val();
    var endDate = $('#endDate').val();
    var logType = $('#logType').val();
    
    $('#logsBody').html('<tr><td colspan="4" class="empty-state"><i class="fas fa-spinner fa-spin"></i><p><?php echo L('loading', 'common'); ?>...</p></td></tr>');
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: {
            egn: 'getlogs',
            page: currentPage,
            pageSize: pageSize,
            startDate: startDate,
            endDate: endDate,
            logType: logType
        },
        dataType: 'json',
        success: function(data) {
            if (data.code === 'success') {
                renderLogs(data);
            } else {
                $('#logsBody').html('<tr><td colspan="4" class="empty-state"><i class="fas fa-exclamation-circle"></i><p>' + (data.msg || data.code) + '</p></td></tr>');
                $('#pagination').html('');
            }
        },
        error: function(xhr, status, error) {
            console.log('AJAX Error:', status, error);
            console.log('Response:', xhr.responseText);
            $('#logsBody').html('<tr><td colspan="4" class="empty-state"><i class="fas fa-exclamation-circle"></i><p>加载失败，请重试</p></td></tr>');
            $('#pagination').html('');
        }
    });
}

function renderLogs(data) {
    var logsBody = $('#logsBody');
    var pagination = $('#pagination');
    
    if (!data.logs || data.logs.length === 0) {
        logsBody.html('<tr><td colspan="4" class="empty-state"><i class="fas fa-clock"></i><p>暂无操作日志</p></td></tr>');
        pagination.html('');
        return;
    }
    
    var logsHtml = '';
    data.logs.forEach(function(log) {
        var typeClass = 'info';
        if (log.content && log.content.includes('成功')) typeClass = 'success';
        if (log.content && log.content.includes('失败')) typeClass = 'error';
        
        logsHtml += '<tr>';
        logsHtml += '<td>' + (log.date || '-') + '</td>';
        logsHtml += '<td><span class="log-type ' + typeClass + '">' + (log.type || '-') + '</span></td>';
        logsHtml += '<td>' + (log.content || '-') + '</td>';
        logsHtml += '<td>' + (log.ip || '-') + '</td>';
        logsHtml += '</tr>';
    });
    
    logsBody.html(logsHtml);
    
    // 生成分页
    var totalPages = data.totalPages || 1;
    if (totalPages <= 1) {
        pagination.html('');
        return;
    }
    
    var paginationHtml = '';
    
    paginationHtml += '<button class="logs-page" data-page="1" ' + (currentPage === 1 ? 'disabled' : '') + '><i class="fas fa-angle-double-left"></i></button>';
    paginationHtml += '<button class="logs-page" data-page="' + (currentPage - 1) + '" ' + (currentPage === 1 ? 'disabled' : '') + '><i class="fas fa-angle-left"></i></button>';
    
    for (var i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            paginationHtml += '<button class="logs-page ' + (i === currentPage ? 'active' : '') + '" data-page="' + i + '">' + i + '</button>';
        }
    }
    
    paginationHtml += '<button class="logs-page" data-page="' + (currentPage + 1) + '" ' + (currentPage === totalPages ? 'disabled' : '') + '><i class="fas fa-angle-right"></i></button>';
    paginationHtml += '<button class="logs-page" data-page="' + totalPages + '" ' + (currentPage === totalPages ? 'disabled' : '') + '><i class="fas fa-angle-double-right"></i></button>';
    
    pagination.html(paginationHtml);
}

function resetFilters() {
    $('#startDate').val('');
    $('#endDate').val('');
    $('#logType').val('');
    currentPage = 1;
    loadLogs();
}

// 事件代理：日志分页按钮
$(document).on('click', '.logs-page', function() {
    var page = $(this).data('page');
    if (page) loadLogs(parseInt(page));
});

// 事件代理：日志页面动作
$(document).on('click', '[data-action="load-logs"]', function(e){
    e.preventDefault();
    var page = $(this).attr('data-page');
    if (page) loadLogs(parseInt(page));
    else loadLogs(1);
});

$(document).on('click', '[data-action="reset-filters"]', function(e){ 
    e.preventDefault(); 
    resetFilters(); 
});

$(document).on('click', '[data-action="clear-logs"]', function(e){ 
    e.preventDefault();
    if (confirm('确定要清空所有操作日志吗？此操作不可恢复！')) {
        clearLogs();
    }
});

function clearLogs() {
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: {
            egn: 'clearlogs'
        },
        dataType: 'json',
        success: function(data) {
            if (data.code === 'success') {
                alert('操作日志已清空');
                currentPage = 1;
                loadLogs(1);
            } else {
                alert('清空失败：' + (data.msg || data.code));
            }
        },
        error: function(xhr, status, error) {
            console.log('AJAX Error:', status, error);
            alert('清空失败，请重试');
        }
    });
}

// 初始化加载日志
$(document).ready(function() {
    loadLogs(1);
});
</script>
