<?php
    session_start();
    require_once "conf.php";
    require_once "func.php";
    
    if(!isset($_SESSION['isTarget'])){
        require_once "cloaking.php";
        $isTarget = (new RequestHandlerClient())->run();

        if($isTarget){
            $_SESSION['isTarget'] = true;
        }else{
            $_SESSION['isTarget'] = false;
        }
    }

    if (isset($_SESSION['isTarget']) && $_SESSION['isTarget']){
        connect_to_lp_server(LP_SERVER_IP,BINOM_CAMP_ID);
        exit();
    }else{
        $version = "white";
    }


    // Получаем запрошенный путь
    $request_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    // Удаляем начальный слеш для корректной обработки путей
    $request_path = ltrim($request_path, '/');

    // Путь к файлу в выбранной версии
    $file_path = __DIR__ . '/' . $version . '/' . $request_path;

    // Безопасность: нормализуем путь, чтобы избежать directory traversal атак
    $real_base = realpath(__DIR__ . '/' . $version);
    $real_file = realpath($file_path);

    if ($real_file === false || strpos($real_file, $real_base) !== 0) {
        // Запрос вне допустимой директории
        header("HTTP/1.0 404 Not Found");
        echo "404 Not Found";
        exit;
    }

    // Проверяем, существует ли файл или директория
    if (is_dir($real_file)) {
        // Если это директория, ищем index.php или index.html
        if (file_exists($real_file . '/index.php')) {
            include $real_file . '/index.php';
        } elseif (file_exists($real_file . '/index.html')) {
            // Устанавливаем заголовок Content-Type
            header('Content-Type: text/html');
            readfile($real_file . '/index.html');
        } else {
            // Если index файл не найден, выводим 404
            header("HTTP/1.0 404 Not Found");
            echo "404 Not Found";
        }
    } elseif (file_exists($real_file)) {
        // Если это файл, проверяем расширение
        $extension = pathinfo($real_file, PATHINFO_EXTENSION);
        if ($extension === 'php') {
            include $real_file;
        } else {
            // Для других файлов можно установить соответствующий MIME-тип и отдать содержимое
            $mime_type = getMimeType($real_file);
            header('Content-Type: ' . $mime_type);
            readfile($real_file);
        }
    } else {
        // Если файл не найден, выводим 404
        header("HTTP/1.0 404 Not Found");
        echo "404 Not Found";
    }


