<?php
// Include database configuration
require_once './includes/config.php';

// Function to check if the user's IP is whitelisted
function isIPAllowed($pdo) {
    $userIP = $_SERVER['REMOTE_ADDR']; // Dynamically capture the user's IP
    error_log("Checking IP: " . $userIP); // Debugging: Log the IP address

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM allowed_ips WHERE ip_address = :ip");
    $stmt->execute(['ip' => $userIP]);
    $count = $stmt->fetchColumn();

    error_log("IP Whitelist Check Result: " . ($count > 0 ? "Allowed" : "Denied")); // Debugging: Log the result
    return $count > 0;
}

// Check IP whitelist before proceeding with any other logic
if (!isIPAllowed($pdo)) {
    error_log("Unauthorized access attempt from IP: " . $_SERVER['REMOTE_ADDR']);
    header("HTTP/1.1 403 Forbidden");
    exit("Access Denied: Your IP is not whitelisted.");
}
?>