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

if(!isset($_SESSION['admin_id'])){
    die("Unauthorized");
}

$message = "";

/* ===============================
   UNBLOCK ACTION
================================ */
if(isset($_GET['unblock'])){

    $ip = trim($_GET['unblock']);

    $stmt = $log_conn->prepare("DELETE FROM blocked_ips WHERE ip_address=?");
    $stmt->bind_param("s", $ip);
    $stmt->execute();
    $stmt->close();

    include "includes/activity_logger.php";
    logActivity($log_conn, $_SESSION['admin_id'], 
        "Unblocked IP: ".$ip
    );

    $message = "IP unblocked successfully!";
}

/* ===============================
   FETCH BLOCKED IPS
================================ */
$result = $log_conn->query("
    SELECT ip_address, blocked_at 
    FROM blocked_ips 
    ORDER BY blocked_at DESC
");
?>

<h1>Blocked IP Management</h1>

<div class="card">

<?php if($message): ?>
<p style="color:green;font-weight:600;"><?= $message ?></p>
<?php endif; ?>

<?php if($result->num_rows == 0): ?>

<p style="color:#555;">No blocked IP addresses found.</p>

<?php else: ?>

<div class="table-wrapper">
<table class="responsive-table">
<thead>
<tr>
    <th>IP Address</th>
    <th>Blocked At</th>
    <th>Action</th>
</tr>
</thead>
<tbody>

<?php while($row = $result->fetch_assoc()): ?>
<tr>
    <td><?= htmlspecialchars($row['ip_address']) ?></td>
    <td><?= date("d M Y, h:i A", strtotime($row['blocked_at'])) ?></td>
    <td>
        <a href="?unblock=<?= urlencode($row['ip_address']) ?>" 
           class="btn"
           style="background:#d9534f;color:#fff;"
           onclick="return confirm('Are you sure you want to unblock this IP?');">
           Unblock
        </a>
    </td>
</tr>
<?php endwhile; ?>

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

<?php endif; ?>

</div>

<style>
.table-wrapper{overflow-x:auto;}
.responsive-table{
    width:100%;
    border-collapse:collapse;
}
.responsive-table th,
.responsive-table td{
    padding:12px;
    border-bottom:1px solid #eee;
    text-align:left;
}
</style>

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