<?php

$correct_password = "GabrielIsDeBeste123";

$ip = $_SERVER['REMOTE_ADDR'];
$banDir = __DIR__ . "/bans";

if (!is_dir($banDir)) {
    mkdir($banDir);
}

$banFile = $banDir . "/" . md5($ip) . ".json";

$data = [
    "attempts" => 0,
    "ban_until" => 0
];

if (file_exists($banFile)) {
    $data = json_decode(file_get_contents($banFile), true);
}

if (time() < $data["ban_until"]) {
    http_response_code(403);
    exit("IP geblokkeerd tot " . date("Y-m-d H:i:s", $data["ban_until"]));
}

// Basic Auth check
if (!isset($_SERVER['PHP_AUTH_PW']) ||
    $_SERVER['PHP_AUTH_PW'] !== $correct_password) {

    $data["attempts"]++;

    if ($data["attempts"] >= 10) {
        $data["ban_until"] = time() + 86400; // 24 uur
    }

    file_put_contents($banFile, json_encode($data));

    header('WWW-Authenticate: Basic realm="Foto Viewer"');
    header('HTTP/1.0 401 Unauthorized');
    exit('Wachtwoord vereist');
}

// reset bij succes
if (file_exists($banFile)) {
    unlink($banFile);
}

$images = array_values(array_filter(scandir('.'), function($file) {
    return preg_match('/\.(jpg|jpeg|png|gif|webp)$/i', $file);
}));

?>