<?php
require_once __DIR__ . "/../includes/admin_auth.php"; // Must be first
require_once '../includes/db.php';

// ==========================
// FILTER
// ==========================
$type = $_GET['type'] ?? '';

$where = "WHERE 1=1";

if (!empty($type)) {
    $where .= " AND type = '" . $conn->real_escape_string($type) . "'";
}

// ==========================
// FETCH LOGS
// ==========================
$result = $conn->query("
    SELECT * FROM security_logs
    $where
    ORDER BY id DESC
");

ob_start();
?>

<div class="main-content">

    <h2 class="page-title">System Logs</h2>

    <!-- FILTER -->
    <div class="panel">

        <form method="GET" class="filter-form">

            <select name="type">
                <option value="">All Types</option>
                <option value="admin_login" <?= $type == 'admin_login' ? 'selected' : '' ?>>Admin Login</option>
                <option value="user_action" <?= $type == 'user_action' ? 'selected' : '' ?>>User Action</option>
                <option value="security" <?= $type == 'security' ? 'selected' : '' ?>>Security</option>
            </select>

            <button type="submit" class="btn-small">Filter</button>

        </form>

    </div>

    <!-- TABLE -->
    <div class="panel">

        <table class="table">

            <thead>
                <tr>
                    <th>ID</th>
                    <th>Type</th>
                    <th>Message</th>
                    <th>Date</th>
                </tr>
            </thead>

            <tbody>

                <?php if ($result && $result->num_rows > 0): ?>
                    <?php while ($log = $result->fetch_assoc()): ?>

                        <tr>

                            <td><?= $log['id'] ?></td>

                            <td>
                                <span class="badge <?= $log['type'] ?>">
                                    <?= ucfirst(str_replace('_', ' ', $log['type'])) ?>
                                </span>
                            </td>

                            <td><?= htmlspecialchars($log['message']) ?></td>

                            <td><?= date("d M Y, H:i", strtotime($log['created_at'])) ?></td>

                        </tr>

                    <?php endwhile; ?>
                <?php else: ?>

                    <tr>
                        <td colspan="4">No logs found.</td>
                    </tr>

                <?php endif; ?>

            </tbody>

        </table>

    </div>

</div>

<?php
$content = ob_get_clean();
$page_title = "System Logs";
include '../components/admin_layout.php';
?>