<?php
session_start();
include "includes/layout.php";
include __DIR__ . '/../database/search_log_config.php';

/* ================= FILTER VALUES ================= */
$search = $_GET['search'] ?? '';
$from   = $_GET['from'] ?? '';
$to     = $_GET['to'] ?? '';

$page  = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 20;
$start = ($page - 1) * $limit;

/* ================= BUILD WHERE ================= */
$where = "WHERE 1=1";

if($search){
    $searchSafe = $log_conn->real_escape_string($search);
    $where .= " AND (
        u.admin_name LIKE '%$searchSafe%' OR
        a.activity LIKE '%$searchSafe%' OR
        a.ip_address LIKE '%$searchSafe%'
    )";
}

if($from){
    $where .= " AND DATE(a.created_at) >= '$from'";
}

if($to){
    $where .= " AND DATE(a.created_at) <= '$to'";
}

/* ================= FETCH DATA ================= */
$logs = $log_conn->query("
SELECT a.*, u.admin_name
FROM admin_activity_logs a
LEFT JOIN admin_users u ON a.admin_id = u.id
$where
ORDER BY a.created_at DESC
LIMIT $start, $limit
");
?>

<h1>Admin Activity Logs</h1>

<div class="card">

<form method="GET" style="display:flex;flex-wrap:wrap;gap:12px;margin-bottom:20px;">

<input type="text"
id="liveSearch"
name="search"
placeholder="Search logs..."
value="<?= htmlspecialchars($search) ?>"
style="padding:10px;border:1px solid #ddd;border-radius:8px;min-width:200px;">

<input type="date" name="from"
value="<?= $from ?>"
style="padding:10px;border:1px solid #ddd;border-radius:8px;">

<input type="date" name="to"
value="<?= $to ?>"
style="padding:10px;border:1px solid #ddd;border-radius:8px;">

<button class="btn">Filter</button>

<a href="export_logs.php?search=<?= urlencode($search) ?>&from=<?= $from ?>&to=<?= $to ?>"
class="btn" style="background:#28a745;">Export</a>

<a href="delete_logs.php"
onclick="return confirm('Delete all logs?');"
class="btn" style="background:#dc3545;">Delete All</a>

</form>

<!-- AJAX REPLACE AREA -->
<div id="logResults">

<?php if($logs && $logs->num_rows > 0): ?>

<div style="overflow-x:auto;">
<table style="width:100%;border-collapse:collapse;">

<thead>
<tr style="background:#f5f5f5;">
<th style="padding:12px;">Admin</th>
<th style="padding:12px;">Activity</th>
<th style="padding:12px;">IP</th>
<th style="padding:12px;">Date & Time</th>
<th style="padding:12px;">Action</th>
</tr>
</thead>

<tbody>

<?php while($row = $logs->fetch_assoc()): ?>
<tr style="border-bottom:1px solid #eee;">
<td style="padding:12px;"><?= htmlspecialchars($row['admin_name']) ?></td>
<td style="padding:12px;"><?= htmlspecialchars($row['activity']) ?></td>
<td style="padding:12px;"><?= htmlspecialchars($row['ip_address']) ?></td>
<td style="padding:12px;"><?= $row['created_at'] ?></td>
<td style="padding:12px;">
<a href="delete_single_log.php?id=<?= $row['id'] ?>"
onclick="return confirm('Delete this log?');"
style="color:red;text-decoration:none;">
Delete
</a>
</td>
</tr>
<?php endwhile; ?>

</tbody>
</table>
</div>

<?php else: ?>
<p>No logs found.</p>
<?php endif; ?>

</div> <!-- END logResults -->

</div>

<script>
document.addEventListener("DOMContentLoaded", function(){

    const searchInput = document.getElementById("liveSearch");
    const logContainer = document.getElementById("logResults");

    if(!searchInput || !logContainer){
        return;
    }

    let typingTimer;

    searchInput.addEventListener("keyup", function(){

        clearTimeout(typingTimer);

        typingTimer = setTimeout(function(){

            let query = searchInput.value.trim();

            fetch("ajax_activity_logs.php?search=" + encodeURIComponent(query))
            .then(response => response.text())
            .then(data => {
                logContainer.innerHTML = data;
            });

        }, 400);

    });

});
</script>

<?php
$log_conn->close();
include "includes/footer.php";
?>