<?php
session_start();



/* ---------------- SECURITY LOGIC ---------------- */

$ip = $_SERVER['REMOTE_ADDR'];
$blockedDir = __DIR__ . "/blocked";
$blockedFile = $blockedDir . "/blocked_ips.json";

$fingerprintFile = __DIR__ . "/blocked/blocked_fingerprints.json";

if (!file_exists($fingerprintFile)) {
    file_put_contents($fingerprintFile, json_encode([]));
}

$blockedFingerprints = json_decode(file_get_contents($fingerprintFile), true);
if (!is_array($blockedFingerprints)) {
    $blockedFingerprints = [];
}


/* Create blocked folder if missing */
if (!is_dir($blockedDir)) {
    mkdir($blockedDir, 0777, true);
}

/* Create block file if missing */
if (!file_exists($blockedFile)) {
    file_put_contents($blockedFile, json_encode([]));
}

/* Load blocked IPs */
$blockedIPs = json_decode(file_get_contents($blockedFile), true);
if (!is_array($blockedIPs)) {
    $blockedIPs = [];
}

/* If already blocked */
if (in_array($ip, $blockedIPs)) {
    header("Location: blocked/blocked.php");
    exit;
}

/* Generate new math question every page load */
/* Generate math question ONLY if not already set */
if (!isset($_SESSION['math_answer']) || $_SERVER['REQUEST_METHOD'] !== 'POST') {

    $a = random_int(2, 15);
    $b = random_int(2, 15);

$operators = ['+', '-'];
$operator = $operators[array_rand($operators)];

if ($operator === '-') {
    if ($a < $b) {
        // swap values so result is never negative
        $temp = $a;
        $a = $b;
        $b = $temp;
    }
}

switch ($operator) {
    case '+':
        $answer = $a + $b;
        break;
    case '-':
        $answer = $a - $b;
        break;
}

    $_SESSION['math_answer'] = $answer;
    $_SESSION['math_question'] = "$a $operator $b";
    $_SESSION['form_time'] = time();
}

/* Handle form submission */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $honeypot1 = $_POST['website'] ?? '';
    
    $honeypot2 = $_POST['email_confirm'] ?? '';
    $honeypot3 = $_POST['fullname'] ?? '';
    $mathInput = $_POST['math'] ?? '';

    $fingerprint = $_POST['device_fingerprint'] ?? '';
    $fingerprintHash = hash('sha256', $fingerprint);

    /* Honeypot triggered = permanent ban */
    if (!empty($honeypot1) || !empty($honeypot2) || !empty($honeypot3)) {
        $blockedIPs[] = $ip;
$blockedFingerprints[] = $fingerprintHash;

file_put_contents($blockedFile, json_encode($blockedIPs, JSON_PRETTY_PRINT));
file_put_contents($fingerprintFile, json_encode($blockedFingerprints, JSON_PRETTY_PRINT));
        file_put_contents($blockedFile, json_encode($blockedIPs, JSON_PRETTY_PRINT));
        header("Location: blocked/blocked.php");
        exit;
    }

    /* Too fast = bot */
    if (time() - $_SESSION['form_time'] < 2) {
       $blockedIPs[] = $ip;
       file_put_contents($blockedFile, json_encode($blockedIPs, JSON_PRETTY_PRINT));
       header("Location: blocked/blocked.php");
       exit;
   }

    /* Wrong math */
    if ($mathInput != $_SESSION['math_answer']) {
        header("Location: recaptcha.php?error=1");
        exit;
    }


if (in_array($fingerprintHash, $blockedFingerprints)) {
    header("Location: blocked/blocked.php");
    exit;
}


/* Passed verification */
$token = bin2hex(random_bytes(32));

$_SESSION['human_verified'] = true;
$_SESSION['verify_token'] = $token;

$tokenMapFile = __DIR__ . "/verified_tokens.json";

if (!file_exists($tokenMapFile)) {
    file_put_contents($tokenMapFile, json_encode([]));
}

$tokens = json_decode(file_get_contents($tokenMapFile), true);
$tokens[$token] = [
    "fingerprint" => $fingerprintHash,
    "ip" => $ip,
    "created" => time()
];

file_put_contents($tokenMapFile, json_encode($tokens, JSON_PRETTY_PRINT));

setcookie("verify_token", $token, [
    "expires" => time() + (60 * 60 * 24 * 30),
    "path" => "/",
    "httponly" => true,
    "secure" => false,
    "samesite" => "Strict"
]);

/* Secure cookie */
setcookie(
    "verify_token",
    $token,
    [
        "expires" => time() + (60 * 60 * 24 * 30), // 30 days
        "path" => "/",
        "httponly" => true,
        "secure" => false, // set true if HTTPS
        "samesite" => "Strict"
    ]
);

header("Location: ../../index.php");
exit;
}
?>