<?php
require_once '../includes/constants.php';
require_once '../includes/session.php';
require_once '../includes/functions.php';

if (!isset($_SESSION['admin_id']) || !in_array($_SESSION['admin_role'], ['manager','superadmin'])) {
    die("Access denied");
}
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Admin Logs'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<?php
$filterAdmin = $_GET['admin'] ?? null;
$filterType = $_GET['type'] ?? null;

$query = "SELECT l.*, a.username FROM admin_action_logs l 
          JOIN admin_users a ON l.admin_id = a.id WHERE 1";
$params = [];

if ($filterAdmin) {
    $query .= " AND a.username = ?";
    $params[] = $filterAdmin;
}
if ($filterType) {
    $query .= " AND l.action_type = ?";
    $params[] = $filterType;
}

$query .= " ORDER BY l.created_at DESC LIMIT 100";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Export CSV
if (isset($_GET['export'])) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename=admin_logs.csv');
    echo "Admin,Action,Details,IP,Time\n";
    foreach ($logs as $log) {
        echo "\"{$log['username']}\",\"{$log['action_type']}\",\"{$log['action_detail']}\",\"{$log['ip_address']}\",\"{$log['created_at']}\"\n";
    }
    exit;
}

// UI
echo "<h2>📜 Admin Logs</h2>
<form method='get'>
    <input name='admin' placeholder='Filter by admin' value='" . htmlspecialchars($filterAdmin) . "'>
    <input name='type' placeholder='Filter by action type' value='" . htmlspecialchars($filterType) . "'>
    <button type='submit'>Filter</button>
    <button onclick=\"window.location='?admin=" . urlencode($filterAdmin) . "&type=" . urlencode($filterType) . "&export=1';return false;\">Export CSV</button>
</form>";

echo "<table><tr>
    <th>Admin</th><th>Action</th><th>Details</th><th>IP</th><th>Time</th>
</tr>";
foreach ($logs as $log) {
    echo "<tr>
        <td>" . htmlspecialchars($log['username']) . "</td>
        <td>" . htmlspecialchars($log['action_type']) . "</td>
        <td><textarea readonly style='width:300px;height:40px'>" . htmlspecialchars($log['action_detail']) . "</textarea></td>
        <td>" . htmlspecialchars($log['ip_address']) . "</td>
        <td>{$log['created_at']}</td>
    </tr>";
}
echo "</table>";
?>
</div>
</body>
</html>