<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in and has admin rights
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 1) {
    header('Location: login.php');
    exit();
}

// Include the AuditLogger class
require_once 'includes/AuditLogger.php';

// Get user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, role_id, full_name FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $role_id = $row_user_details['role_id'];
    $full_name = $row_user_details['full_name'];
} else {
    // Handle the case if user details not found
    header('Location: login.php');
    exit();
}

// Pagination settings
$records_per_page = 20;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $records_per_page;

// Filter settings
$action_filter = isset($_GET['action']) ? $conn->real_escape_string($_GET['action']) : '';
$user_filter = isset($_GET['user']) ? intval($_GET['user']) : 0;
$date_from = isset($_GET['date_from']) ? $conn->real_escape_string($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? $conn->real_escape_string($_GET['date_to']) : '';

// Build the query with filters
$query = "SELECT al.*, u.username, u.full_name 
          FROM admin_logs al
          LEFT JOIN users u ON al.user_id = u.user_id
          WHERE 1=1";

$count_query = "SELECT COUNT(*) as total FROM admin_logs al WHERE 1=1";

if (!empty($action_filter)) {
    $query .= " AND al.action LIKE '%$action_filter%'";
    $count_query .= " AND al.action LIKE '%$action_filter%'";
}

if ($user_filter > 0) {
    $query .= " AND al.user_id = $user_filter";
    $count_query .= " AND al.user_id = $user_filter";
}

if (!empty($date_from)) {
    $query .= " AND DATE(al.created_at) >= '$date_from'";
    $count_query .= " AND DATE(al.created_at) >= '$date_from'";
}

if (!empty($date_to)) {
    $query .= " AND DATE(al.created_at) <= '$date_to'";
    $count_query .= " AND DATE(al.created_at) <= '$date_to'";
}

// Add sorting and pagination
$query .= " ORDER BY al.created_at DESC LIMIT $offset, $records_per_page";

// Get total records for pagination
$count_result = $conn->query($count_query);
$total_records = $count_result->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);

// Get all users for filter dropdown
$users_query = "SELECT user_id, username, full_name FROM users ORDER BY username ASC";
$users_result = $conn->query($users_query);
$users = [];
while ($user = $users_result->fetch_assoc()) {
    $users[] = $user;
}

// Get unique action types for filter dropdown
$actions_query = "SELECT DISTINCT action FROM admin_logs ORDER BY action ASC";
$actions_result = $conn->query($actions_query);
$actions = [];
while ($action = $actions_result->fetch_assoc()) {
    $actions[] = $action['action'];
}

// Execute the main query
$result = $conn->query($query);
$logs = [];
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $logs[] = $row;
    }
}

// Include layout headers
include 'layouts/main.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Audit Logs')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <style>
        .log-details {
            white-space: pre-wrap;
            word-break: break-word;
        }
        .filter-section {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .pagination-container {
            margin-top: 20px;
        }
        .action-badge {
            font-size: 0.75rem;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'System Management', 'title' => 'Audit Logs')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h5 class="card-title mb-0 flex-grow-1">System Audit Logs</h5>
                                    <div>
                                        <button class="btn btn-primary" id="exportBtn">
                                            <i class="ri-file-download-line align-bottom me-1"></i> Export
                                        </button>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <!-- Filter Section -->
                                    <div class="filter-section">
                                        <form method="GET" action="">
                                            <div class="row">
                                                <div class="col-md-3">
                                                    <div class="mb-3">
                                                        <label for="action" class="form-label">Action Type</label>
                                                        <select class="form-select" id="action" name="action">
                                                            <option value="">All Actions</option>
                                                            <?php foreach ($actions as $action): ?>
                                                                <option value="<?php echo htmlspecialchars($action); ?>" <?php echo ($action_filter == $action) ? 'selected' : ''; ?>>
                                                                    <?php echo htmlspecialchars($action); ?>
                                                                </option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="col-md-3">
                                                    <div class="mb-3">
                                                        <label for="user" class="form-label">User</label>
                                                        <select class="form-select" id="user" name="user">
                                                            <option value="0">All Users</option>
                                                            <?php foreach ($users as $user): ?>
                                                                <option value="<?php echo $user['user_id']; ?>" <?php echo ($user_filter == $user['user_id']) ? 'selected' : ''; ?>>
                                                                    <?php echo htmlspecialchars($user['username'] . ' (' . $user['full_name'] . ')'); ?>
                                                                </option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="col-md-3">
                                                    <div class="mb-3">
                                                        <label for="date_from" class="form-label">Date From</label>
                                                        <input type="text" class="form-control datepicker" id="date_from" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>" placeholder="YYYY-MM-DD">
                                                    </div>
                                                </div>
                                                <div class="col-md-3">
                                                    <div class="mb-3">
                                                        <label for="date_to" class="form-label">Date To</label>
                                                        <input type="text" class="form-control datepicker" id="date_to" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>" placeholder="YYYY-MM-DD">
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-12 text-end">
                                                    <a href="audit_logs.php" class="btn btn-secondary">Reset Filters</a>
                                                    <button type="submit" class="btn btn-primary">Apply Filters</button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>

                                    <!-- Logs Table -->
                                    <div class="table-responsive">
                                        <table id="logs-table" class="table table-striped table-hover align-middle">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Date & Time</th>
                                                    <th>User</th>
                                                    <th>Action</th>
                                                    <th>IP Address</th>
                                                    <th>Details</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($logs)): ?>
                                                    <tr>
                                                        <td colspan="5" class="text-center">No audit logs found</td>
                                                    </tr>
                                                <?php else: ?>
                                                    <?php foreach ($logs as $log): ?>
                                                        <tr>
                                                            <td><?php echo date('Y-m-d H:i:s', strtotime($log['created_at'])); ?></td>
                                                            <td>
                                                                <?php echo htmlspecialchars($log['username'] ?? 'Unknown'); ?>
                                                            </td>
                                                            <td>
                                                                <?php 
                                                                $badge_class = 'bg-info';
                                                                
                                                                if (strpos($log['action'], 'create') !== false) {
                                                                    $badge_class = 'bg-success';
                                                                } elseif (strpos($log['action'], 'update') !== false) {
                                                                    $badge_class = 'bg-warning';
                                                                } elseif (strpos($log['action'], 'delete') !== false) {
                                                                    $badge_class = 'bg-danger';
                                                                } elseif (strpos($log['action'], 'security') !== false) {
                                                                    $badge_class = 'bg-dark';
                                                                } elseif (strpos($log['action'], 'config') !== false) {
                                                                    $badge_class = 'bg-primary';
                                                                }
                                                                ?>
                                                                <span class="badge <?php echo $badge_class; ?> action-badge">
                                                                    <?php echo htmlspecialchars($log['action']); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($log['ip_address']); ?></td>
                                                            <td>
                                                                <button class="btn btn-sm btn-soft-info" type="button" data-bs-toggle="collapse" data-bs-target="#details-<?php echo $log['id']; ?>" aria-expanded="false">
                                                                    View Details
                                                                </button>
                                                                <div class="collapse mt-2" id="details-<?php echo $log['id']; ?>">
                                                                    <div class="card card-body">
                                                                        <pre class="log-details mb-0"><?php echo htmlspecialchars($log['details']); ?></pre>
                                                                    </div>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>

                                    <!-- Pagination -->
                                    <?php if ($total_pages > 1): ?>
                                        <div class="pagination-container d-flex justify-content-end">
                                            <ul class="pagination mb-0">
                                                <?php if ($page > 1): ?>
                                                    <li class="page-item">
                                                        <a class="page-link" href="?page=1<?php echo (!empty($action_filter)) ? '&action=' . urlencode($action_filter) : ''; ?><?php echo ($user_filter > 0) ? '&user=' . $user_filter : ''; ?><?php echo (!empty($date_from)) ? '&date_from=' . urlencode($date_from) : ''; ?><?php echo (!empty($date_to)) ? '&date_to=' . urlencode($date_to) : ''; ?>">First</a>
                                                    </li>
                                                    <li class="page-item">
                                                        <a class="page-link" href="?page=<?php echo $page - 1; ?><?php echo (!empty($action_filter)) ? '&action=' . urlencode($action_filter) : ''; ?><?php echo ($user_filter > 0) ? '&user=' . $user_filter : ''; ?><?php echo (!empty($date_from)) ? '&date_from=' . urlencode($date_from) : ''; ?><?php echo (!empty($date_to)) ? '&date_to=' . urlencode($date_to) : ''; ?>">Previous</a>
                                                    </li>
                                                <?php endif; ?>

                                                <?php
                                                // Calculate range of page numbers to display
                                                $start_page = max(1, $page - 2);
                                                $end_page = min($total_pages, $page + 2);

                                                for ($i = $start_page; $i <= $end_page; $i++):
                                                ?>
                                                    <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                                                        <a class="page-link" href="?page=<?php echo $i; ?><?php echo (!empty($action_filter)) ? '&action=' . urlencode($action_filter) : ''; ?><?php echo ($user_filter > 0) ? '&user=' . $user_filter : ''; ?><?php echo (!empty($date_from)) ? '&date_from=' . urlencode($date_from) : ''; ?><?php echo (!empty($date_to)) ? '&date_to=' . urlencode($date_to) : ''; ?>"><?php echo $i; ?></a>
                                                    </li>
                                                <?php endfor; ?>

                                                <?php if ($page < $total_pages): ?>
                                                    <li class="page-item">
                                                        <a class="page-link" href="?page=<?php echo $page + 1; ?><?php echo (!empty($action_filter)) ? '&action=' . urlencode($action_filter) : ''; ?><?php echo ($user_filter > 0) ? '&user=' . $user_filter : ''; ?><?php echo (!empty($date_from)) ? '&date_from=' . urlencode($date_from) : ''; ?><?php echo (!empty($date_to)) ? '&date_to=' . urlencode($date_to) : ''; ?>">Next</a>
                                                    </li>
                                                    <li class="page-item">
                                                        <a class="page-link" href="?page=<?php echo $total_pages; ?><?php echo (!empty($action_filter)) ? '&action=' . urlencode($action_filter) : ''; ?><?php echo ($user_filter > 0) ? '&user=' . $user_filter : ''; ?><?php echo (!empty($date_from)) ? '&date_from=' . urlencode($date_from) : ''; ?><?php echo (!empty($date_to)) ? '&date_to=' . urlencode($date_to) : ''; ?>">Last</a>
                                                    </li>
                                                <?php endif; ?>
                                            </ul>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="assets/libs/xlsx/xlsx.full.min.js"></script>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize date pickers
            flatpickr(".datepicker", {
                dateFormat: "Y-m-d"
            });

            // Export functionality
            document.getElementById('exportBtn').addEventListener('click', function() {
                // Get the table element
                const table = document.getElementById('logs-table');
                
                // Get the table headers
                const headers = [];
                for (const cell of table.querySelectorAll('thead th')) {
                    headers.push(cell.innerText);
                }
                
                // Get the table rows
                const rows = [];
                for (const row of table.querySelectorAll('tbody tr')) {
                    const rowData = [];
                    // Get cells except for the last one (which has the collapse button)
                    for (let i = 0; i < row.cells.length - 1; i++) {
                        rowData.push(row.cells[i].innerText);
                    }
                    
                    // Get the details text from the collapsed content
                    const detailsElement = row.querySelector('.log-details');
                    if (detailsElement) {
                        rowData.push(detailsElement.innerText);
                    } else {
                        rowData.push('');
                    }
                    
                    rows.push(rowData);
                }
                
                // Create a workbook
                const wb = XLSX.utils.book_new();
                // Add the data as a worksheet
                const ws = XLSX.utils.aoa_to_sheet([headers, ...rows]);
                XLSX.utils.book_append_sheet(wb, ws, "Audit Logs");
                
                // Generate filename with current date
                const now = new Date();
                const filename = `audit_logs_${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}.xlsx`;
                
                // Save the file
                XLSX.writeFile(wb, filename);
            });
        });
    </script>
</body>
</html>