<?php
// Entry point
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Find the backend directory
$backend_dir = null; // CPANEL_BACKEND_PATH

if (!$backend_dir) {
    $possible_paths = [
        __DIR__ . '/../',                          // Standard local / split upload
        __DIR__ . '/../wts-back/',                 // Parallel wts-back
        __DIR__ . '/../../wts-back/',              // Parent's parallel wts-back
        __DIR__ . '/wts-back/',                    // Nested wts-back
        __DIR__ . '/../../',                       // Two levels up
        __DIR__ . '/'                              // Same directory
    ];

    foreach ($possible_paths as $path) {
        if (file_exists($path . 'app/bootstrap.php')) {
            $backend_dir = realpath($path);
            break;
        }
    }
}

if (!$backend_dir) {
    header("HTTP/1.1 500 Internal Server Error");
    echo "<h2>❌ Application Error</h2>";
    echo "<p>Could not locate the application backend directory (specifically <code>app/bootstrap.php</code>).</p>";
    echo "<p>Please ensure you have uploaded the backend files (the <code>app</code>, <code>routes</code>, and <code>vendor</code> folders) to your server.</p>";
    exit;
}

// Normalize path separator and ensure trailing slash
$backend_dir = str_replace('\\', '/', $backend_dir);
$backend_dir = rtrim($backend_dir, '/') . '/';

// Simple autoloader
spl_autoload_register(function ($class) use ($backend_dir) {
    $prefix = 'App\\';
    $base_dir = $backend_dir . 'app/';
    
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }
    
    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
    
    if (file_exists($file)) {
        require $file;
    }
});

require_once $backend_dir . 'app/bootstrap.php';

$router = new App\Core\Router();
require_once $backend_dir . 'routes/web.php';

$router->dispatch($_SERVER['REQUEST_URI'], $_SERVER['REQUEST_METHOD']);

