<?php

use Jaybizzle\CrawlerDetect\CrawlerDetect;

require_once './config/config.php';

$CrawlerDetect = new CrawlerDetect;

// Check the user agent of the current 'visitor'
if ($CrawlerDetect->isCrawler()) {
    // true if crawler user agent detected
    http_response_code(403);
    die();
}

if (!isset($_GET['key']) || isset($_GET['key']) && $_GET['key'] != KEY) {
    http_response_code(403);
    die();
}

// Open a database connection
$db = new SQLiteDB(BASE_PATH . '/data/db/blacklist.db');

// Create the 'blacklist' table if it doesn't exist
$db->exec("CREATE TABLE IF NOT EXISTS blacklist (
    ip_address TEXT PRIMARY KEY,
    blocked_at TEXT
)");

// Handle IP blocking if provided in URL
if (isset($_GET['ip_address'])) {
    $ip_to_block = $_GET['ip_address'];
    $stmt = $db->prepare("INSERT OR IGNORE INTO blacklist (ip_address, blocked_at) VALUES (:ip, :time)");
    $stmt->bindValue(':ip', $ip_to_block, SQLITE3_TEXT);
    $stmt->bindValue(':time', date('Y-m-d H:i:s'), SQLITE3_TEXT);
    $stmt->execute();
    header("Location: blacklist.php?key=" . KEY);
    exit();
}

// Handle IP unblocking
if (isset($_POST['unblock'])) {
    $ip_to_unblock = $_POST['unblock'];
    $stmt = $db->prepare("DELETE FROM blacklist WHERE ip_address = :ip");
    $stmt->bindValue(':ip', $ip_to_unblock, SQLITE3_TEXT);
    $stmt->execute();
    header("Location: blacklist.php?key=" . KEY);
    exit();
}

// Handle manual IP blocking
if (isset($_POST['block_ip'])) {
    $ip_to_block = $_POST['block_ip'];
    $stmt = $db->prepare("INSERT OR IGNORE INTO blacklist (ip_address, blocked_at) VALUES (:ip, :time)");
    $stmt->bindValue(':ip', $ip_to_block, SQLITE3_TEXT);
    $stmt->bindValue(':time', date('Y-m-d H:i:s'), SQLITE3_TEXT);
    $stmt->execute();
    header("Location: blacklist.php?key=" . KEY);
    exit();
}

// Pagination setup
$perPage = 15;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $perPage;

// Fetch blocked IPs with pagination
$result = $db->query("SELECT COUNT(*) as count FROM blacklist");
$row = $result->fetchArray();
$totalRecords = $row['count'];
$totalPages = ceil($totalRecords / $perPage);

$stmt = $db->prepare("SELECT * FROM blacklist ORDER BY blocked_at DESC LIMIT :limit OFFSET :offset");
$stmt->bindValue(':limit', $perPage, SQLITE3_INTEGER);
$stmt->bindValue(':offset', $start, SQLITE3_INTEGER);
$result = $stmt->execute();
$blocked_ips = [];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    $blocked_ips[] = $row;
}

$currentDateTime = date('Y-m-d H:i:s');

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IP Blacklist Management</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="#">Admin Panel</a>
            <div class="navbar-nav">
                <a class="nav-link" href="visitors.php?key=<?php echo KEY; ?>">Visitors</a>
                <a class="nav-link active" href="blacklist.php?key=<?php echo KEY; ?>">Blacklist</a>
                <a class="nav-link" href="status.php?key=<?php echo KEY; ?>">Status</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <h1 class="mb-4">IP Blacklist Management</h1>

        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5>Block New IP</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="input-group">
                                <input type="text" id="block_ip" name="block_ip" class="form-control"
                                    placeholder="Enter IP address to block" required>
                                <button type="submit" class="btn btn-danger">Block IP</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h6 class="card-subtitle mb-2 text-muted">Current date and time</h6>
                        <p class="card-text"><?php echo $currentDateTime; ?></p>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h6 class="card-subtitle mb-2 text-muted">Blocked IPs</h6>
                        <p class="card-text">Total blocked IPs: <?php echo $totalRecords; ?></p>
                    </div>
                </div>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead class="table-dark">
                            <tr>
                                <th>IP Address</th>
                                <th>Blocked At</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($blocked_ips as $ip): ?>
                                <tr>
                                    <td><strong><?php echo htmlspecialchars($ip['ip_address']); ?></strong></td>
                                    <td><?php echo htmlspecialchars($ip['blocked_at']); ?></td>
                                    <td>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="unblock" value="<?php echo htmlspecialchars($ip['ip_address']); ?>">
                                            <button type="submit" class="btn btn-success btn-sm"
                                                onclick="return confirm('Are you sure you want to unblock this IP?')">
                                                Unblock
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($totalPages > 1): ?>
                    <nav aria-label="Page navigation">
                        <ul class="pagination justify-content-center">
                            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                </li>
                            <?php endfor; ?>
                        </ul>
                    </nav>
                <?php endif; ?>
        </div>

        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>