<?php
header('Content-Type: application/json');
include 'database.php';
date_default_timezone_set('Asia/Dhaka');

$createBlockIpTable = "
    CREATE TABLE IF NOT EXISTS block_ips (
        id INT AUTO_INCREMENT PRIMARY KEY,
        ip_address VARCHAR(45) NOT NULL UNIQUE,
        blocked TINYINT(1) NOT NULL DEFAULT 1,
        created_at DATETIME DEFAULT NULL
    )
";
$conn->query($createBlockIpTable);

$ip = $_GET['ip'] ?? null;
$action = $_GET['action'] ?? null;

if (!filter_var($ip, FILTER_VALIDATE_IP)) {
    echo json_encode(['error' => 'Invalid IP Address'], JSON_PRETTY_PRINT);
    exit;
}

$allowedActions = ['blockIp', 'unblockIp'];
if (!in_array($action, $allowedActions)) {
    echo json_encode(['error' => 'Invalid action'], JSON_PRETTY_PRINT);
    exit;
}

if ($action === 'blockIp') {
    blockIp($conn, $ip);
    echo json_encode(['block' => true], JSON_PRETTY_PRINT);
} elseif ($action === 'unblockIp') {
    unblockIp($conn, $ip);
    echo json_encode(['unblock' => true], JSON_PRETTY_PRINT);
} else {
    echo json_encode(['error' => 'Invalid action'], JSON_PRETTY_PRINT);
}

mysqli_close($conn);

function blockIp($conn, $ip) {
    $currentDatetime = date('Y-m-d H:i:s');
    
    $queryCheck = "SELECT id FROM block_ips WHERE ip_address = ?";
    $stmtCheck = mysqli_prepare($conn, $queryCheck);
    mysqli_stmt_bind_param($stmtCheck, 's', $ip);
    mysqli_stmt_execute($stmtCheck);
    mysqli_stmt_store_result($stmtCheck);

    if (mysqli_stmt_num_rows($stmtCheck) > 0) {
        $queryUpdate = "UPDATE block_ips SET blocked = 1, created_at = ? WHERE ip_address = ?";
        $stmtUpdate = mysqli_prepare($conn, $queryUpdate);
        mysqli_stmt_bind_param($stmtUpdate, 'ss', $currentDatetime, $ip);
        mysqli_stmt_execute($stmtUpdate);
        mysqli_stmt_close($stmtUpdate);
    } else {
        $queryInsert = "INSERT INTO block_ips (ip_address, blocked, created_at) VALUES (?, 1, ?)";
        $stmtInsert = mysqli_prepare($conn, $queryInsert);
        mysqli_stmt_bind_param($stmtInsert, 'ss', $ip, $currentDatetime);
        mysqli_stmt_execute($stmtInsert);
        mysqli_stmt_close($stmtInsert);
    }

    mysqli_stmt_close($stmtCheck);
}

function unblockIp($conn, $ip) {
    $query = "UPDATE block_ips SET blocked = 0 WHERE ip_address = ?";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, 's', $ip);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
}
?>