<?php

define('ROOT_PATH', dirname(__DIR__));
require_once ROOT_PATH . '/app/core/Autoloader.php';
\App\Core\Autoloader::register();

// Load the helper file explicitly for testing
require_once ROOT_PATH . '/app/helpers/env.php';
require_once ROOT_PATH . '/app/helpers/url.php';

// A simple test runner framework
function run_test(string $name, callable $test) {
    try {
        $test();
        echo "✅ PASS: $name\n";
    } catch (\Throwable $e) {
        echo "❌ FAIL: $name\n";
        echo "   Error: " . $e->getMessage() . " at " . $e->getFile() . ":" . $e->getLine() . "\n";
    }
}

// Ensure clean cache state
$originalServer = $_SERVER;

run_test('base_path() - localhost subdirectory with public', function () {
    $_SERVER['SCRIPT_NAME'] = '/inveetaire/public/index.php';
    $_SERVER['HTTP_HOST'] = 'localhost';
    
    // Clear static cache in base_path if it was set
    $ref = new ReflectionFunction('base_path');
    $static = $ref->getStaticVariables();
    if (array_key_exists('basePath', $static)) {
        // Since reflection can't directly clear static variables, we will test it by modifying a mock of $_SERVER
        // before any call. Because this is the first call in the script, static $basePath is currently null.
    }
    
    $bp = base_path();
    if ($bp !== '/inveetaire') {
        throw new Exception("Expected '/inveetaire', got '$bp'");
    }
});

// Since PHP static variables persist during execution, to test other script names we need to reflect/reset or test the logic directly or run it as sub-processes.
// Let's run subprocesses or write a script that tests the logic.
// Better: we can check the logic of base_path manually in code or make a test that checks it.
// To do this, let's write a helper in test to reset the static variable. But since we cannot reset a static variable in PHP, let's do a subprocess call to test each variation!
// Let's write the subprocess runner.

function run_subtest(string $scriptName, string $expectedBasePath, string $expectedUrl, string $path = '/login') {
    $cmd = 'C:/xampp/php/php.exe -r "' .
        'define(\'ROOT_PATH\', \'' . str_replace('\\', '/', ROOT_PATH) . '\'); ' .
        'require_once ROOT_PATH . \'/app/helpers/env.php\'; ' .
        'require_once ROOT_PATH . \'/app/helpers/url.php\'; ' .
        '$_SERVER[\'SCRIPT_NAME\'] = \'' . $scriptName . '\'; ' .
        '$_SERVER[\'HTTP_HOST\'] = \'localhost\'; ' .
        '$_SERVER[\'HTTPS\'] = \'off\'; ' .
        '$bp = base_path(); ' .
        '$u = url(\'' . $path . '\'); ' .
        'echo $bp . \'||\' . $u;"';
    
    $output = shell_exec($cmd);
    [$bp, $u] = explode('||', trim($output));
    
    if ($bp !== $expectedBasePath) {
        throw new Exception("For SCRIPT_NAME '$scriptName', expected base_path '$expectedBasePath', got '$bp'");
    }
    if ($u !== $expectedUrl) {
        throw new Exception("For SCRIPT_NAME '$scriptName', expected url '$expectedUrl', got '$u'");
    }
}

run_test('base_path & url - localhost subdirectory with public', function () {
    run_subtest('/inveetaire/public/index.php', '/inveetaire', 'http://localhost/inveetaire/login');
});

run_test('base_path & url - localhost root with public', function () {
    run_subtest('/public/index.php', '', 'http://localhost/login');
});

run_test('base_path & url - production root without public', function () {
    run_subtest('/index.php', '', 'http://localhost/login');
});

run_test('base_path & url - production subdirectory without public', function () {
    run_subtest('/wedding/index.php', '/wedding', 'http://localhost/wedding/login');
});

run_test('url() with external urls', function () {
    $url = url('https://example.com/invitation');
    if ($url !== 'https://example.com/invitation') {
        throw new Exception("Expected 'https://example.com/invitation', got '$url'");
    }
});

run_test('asset() helper', function () {
    $cmd = 'C:/xampp/php/php.exe -r "' .
        'define(\'ROOT_PATH\', \'' . str_replace('\\', '/', ROOT_PATH) . '\'); ' .
        'require_once ROOT_PATH . \'/app/helpers/env.php\'; ' .
        'require_once ROOT_PATH . \'/app/helpers/url.php\'; ' .
        '$_SERVER[\'SCRIPT_NAME\'] = \'/inveetaire/public/index.php\'; ' .
        '$_SERVER[\'HTTP_HOST\'] = \'localhost\'; ' .
        'echo asset(\'/assets/css/app.css\');"';
    $output = trim(shell_exec($cmd));
    if ($output !== '/inveetaire/assets/css/app.css') {
        throw new Exception("Expected '/inveetaire/assets/css/app.css', got '$output'");
    }
});

run_test('route() helper', function () {
    $cmd = 'C:/xampp/php/php.exe -r "' .
        'define(\'ROOT_PATH\', \'' . str_replace('\\', '/', ROOT_PATH) . '\'); ' .
        'require_once ROOT_PATH . \'/app/helpers/env.php\'; ' .
        'require_once ROOT_PATH . \'/app/helpers/url.php\'; ' .
        '$_SERVER[\'SCRIPT_NAME\'] = \'/inveetaire/public/index.php\'; ' .
        '$_SERVER[\'HTTP_HOST\'] = \'localhost\'; ' .
        '$_SERVER[\'HTTPS\'] = \'off\'; ' .
        'echo route(\'/{slug}/i/{guest_token}\', [\'slug\' => \'smith\', \'guest_token\' => \'abc\']);"';
    $output = trim(shell_exec($cmd));
    if ($output !== 'http://localhost/inveetaire/smith/i/abc') {
        throw new Exception("Expected 'http://localhost/inveetaire/smith/i/abc', got '$output'");
    }
});

// Restore state
$_SERVER = $originalServer;
