<?php
$filename = 'blocked_ips.txt';

// Ensure the file exists
if (!file_exists($filename)) {
    file_put_contents($filename, '');
}

$ips = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

// Add new IP
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['ip'])) {
        $newIp = trim($_POST['ip']);
        if (filter_var($newIp, FILTER_VALIDATE_IP) && !in_array($newIp, $ips)) {
            file_put_contents($filename, $newIp . PHP_EOL, FILE_APPEND);
            $ips[] = $newIp;
        }
    }

    // Remove IP
    if (isset($_POST['remove_ip'])) {
        $removeIp = $_POST['remove_ip'];
        $ips = array_filter($ips, fn($ip) => $ip !== $removeIp);
        file_put_contents($filename, implode(PHP_EOL, $ips) . PHP_EOL);
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>IP Block List</title>
    <style>
        body {
            font-family: sans-serif;
            background: #f4f4f4;
            padding: 20px;
        }
        .box {
            background: white;
            padding: 20px;
            max-width: 500px;
            margin: auto;
            border-radius: 10px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
        }
        input[type="text"] {
            width: calc(100% - 22px);
            padding: 10px;
            margin-top: 10px;
            border-radius: 5px;
            border: 1px solid #aaa;
        }
        button {
            margin-top: 10px;
            padding: 10px;
            width: 100%;
            background: #d9534f;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        ul {
            margin-top: 20px;
            list-style: none;
            padding: 0;
        }
        li {
            padding: 5px 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #eee;
        }
        .remove-button {
            background: #dc3545;
            border: none;
            color: white;
            padding: 5px 10px;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="box">
    <h2>Add Blocked IP</h2>
    <form method="POST">
        <input type="text" name="ip" placeholder="Enter IP address" required>
        <button type="submit">Block IP</button>
    </form>
    <h3>Blocked IPs</h3>
    <ul>
        <?php foreach ($ips as $ip): ?>
            <li>
                <?= htmlspecialchars($ip) ?>
                <form method="POST" style="margin: 0;">
                    <input type="hidden" name="remove_ip" value="<?= htmlspecialchars($ip) ?>">
                    <button class="remove-button" type="submit">Remove</button>
                </form>
            </li>
        <?php endforeach; ?>
    </ul>
</div>
</body>
</html>
