<?php
/**
 * Main Public Entry Point
 * Routes requests to the appropriate marketing or app pages.
 */

// If running under PHP built-in server, serve static files directly
if (php_sapi_name() === 'cli-server') {
    $path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
    if (is_file(__DIR__ . $path)) {
        return false;
    }
}

// Fallback: If request targets a static asset but the webserver routed it to PHP (e.g., rewrite rules),
// try to serve the file from public/ or from the project root `assets/` directory to avoid 404s for images/favicon.
$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
if ($path) {
    $publicFile = __DIR__ . $path;
    $rootFile = __DIR__ . '/../' . ltrim($path, '/');

    // Special fallback for favicon.ico -> use logo if favicon is missing
    if ($path === '/favicon.ico') {
        $candidates = [
            $publicFile,
            __DIR__ . '/assets/images/logo.png',
            __DIR__ . '/assets/images/logo.jpg',
            __DIR__ . '/../assets/images/logo.png',
            __DIR__ . '/../assets/images/logo.jpg'
        ];
        foreach ($candidates as $f) {
            if (is_file($f) && is_readable($f)) {
                header('Content-Type: image/png');
                header('Cache-Control: public, max-age=86400');
                readfile($f);
                exit;
            }
        }
    }

    // Serve file from public/ if it exists
    if (is_file($publicFile) && is_readable($publicFile)) {
        $mime = mime_content_type($publicFile) ?: 'application/octet-stream';
        header('Content-Type: ' . $mime);
        header('Cache-Control: public, max-age=86400');
        readfile($publicFile);
        exit;
    }

    // Serve file from project root (e.g., /assets/...) if present
    if (is_file($rootFile) && is_readable($rootFile)) {
        $mime = mime_content_type($rootFile) ?: 'application/octet-stream';
        header('Content-Type: ' . $mime);
        header('Cache-Control: public, max-age=86400');
        readfile($rootFile);
        exit;
    }
}

// Router Logic
$request = $_SERVER['REQUEST_URI'];
$path = parse_url($request, PHP_URL_PATH);
$path = trim($path, '/');

// Handle empty path or index.php
if ($path === '' || $path === 'index.php' || $path === 'public' || $path === 'public/index.php') {
    require __DIR__ . '/../marketing/home.php';
    exit;
}

// Normalize path to remove 'public/' prefix if accessed that way
if (strpos($path, 'public/') === 0) {
    $path = substr($path, 7);
}

// Simple Routing Map
$routes = [
    'home' => '../marketing/home.php',
    'about' => '../marketing/about.php',
    'about.php' => '../marketing/about.php',
    'features' => '../marketing/features.php',
    'features.php' => '../marketing/features.php',
    'pricing' => '../marketing/pricing.php',
    'pricing.php' => '../marketing/pricing.php',
    'welcome' => '../marketing/welcome.php',
    'welcome.php' => '../marketing/welcome.php',
    'login' => '../app/Auth/login.php',
    'customer' => '../app/Customer/index.php',
    'logout' => '../app/Auth/logout.php',
    'request-demo' => '../marketing/request-demo.php',
    'request-demo.php' => '../marketing/request-demo.php',
    'dashboard' => '../app/Dashboard/index.php',
    'admin' => '../app/Admin/index.php',
    'admin/login' => '../app/Admin/login.php',
    'subscription-expired' => '../app/Auth/subscription_expired.php',
];

// Dynamic Routing for Dashboard/Admin Modules
if (strpos($path, 'dashboard/') === 0 || strpos($path, 'admin/') === 0) {
    $isAdmin = strpos($path, 'admin/') === 0;
    $prefix = $isAdmin ? 'admin/' : 'dashboard/';
    
    $parts = explode('/', substr($path, strlen($prefix)));
    $module = $parts[0] ?? 'index';
    $action = $parts[1] ?? '';
    
    if ($isAdmin) {
        // First check if it's a directory (e.g., admin/shops -> app/Admin/shops/index.php)
        $dirPath = __DIR__ . "/../app/Admin/$module";
        if (is_dir($dirPath)) {
            $targetFile = $action ? str_replace('.php', '', $action) : 'index';
            $target = "../app/Admin/$module/$targetFile.php";
        } else {
            // Otherwise, it's a direct file (e.g., admin/users -> app/Admin/users.php)
            $target = "../app/Admin/" . str_replace('.php', '', $module) . ".php";
        }
    } else {
        // Dashboard paths: app/Customers/index.php
        $module = ucfirst($module);
        if ($module) {
            $targetFile = $action ? str_replace('.php', '', $action) : 'index';
            $target = "../app/$module/$targetFile.php";
        }
    }
    
    if (isset($target) && file_exists(__DIR__ . '/' . $target)) {
        require __DIR__ . '/' . $target;
        exit;
    }
}

if (array_key_exists($path, $routes)) {
    require __DIR__ . '/' . $routes[$path];
} else {
    // 404
    http_response_code(404);
    echo "<h1>404 Not Found</h1><p>The page you are looking for is not here. Path: " . htmlspecialchars($path) . "</p>";
}
