<?php
/**
 * AJOUAMAI IMMO-BUSINESS — Universal Router for PHP Built-in Web Server
 * 
 * Routes all requests for development (php -S localhost:8000 router.php)
 * Production environment uses Apache .htaccess rules.
 */

$rawUri  = $_SERVER['REQUEST_URI'] ?? '/';
$parsed  = parse_url($rawUri);
$uriPath = $parsed['path'] ?? '/';

$hindRoot = __DIR__;
$path     = '/' . ltrim($uriPath, '/');

// ── 1. Static Files (CSS, JS, WebP, JPG, PNG, SVG, WOFF, Fonts, JSON, PDF) ──
$diskPath = $hindRoot . str_replace('/', DIRECTORY_SEPARATOR, $path);
if (is_file($diskPath)) {
    $ext = strtolower(pathinfo($diskPath, PATHINFO_EXTENSION));
    if ($ext !== 'php') {
        $mimeMap = [
            'css'   => 'text/css; charset=utf-8',
            'js'    => 'application/javascript; charset=utf-8',
            'json'  => 'application/json',
            'png'   => 'image/png',      'jpg'   => 'image/jpeg',
            'jpeg'  => 'image/jpeg',     'gif'   => 'image/gif',
            'webp'  => 'image/webp',     'svg'   => 'image/svg+xml',
            'ico'   => 'image/x-icon',   'woff'  => 'font/woff',
            'woff2' => 'font/woff2',     'ttf'   => 'font/ttf',
            'eot'   => 'application/vnd.ms-fontobject',
            'pdf'   => 'application/pdf', 'xml'   => 'application/xml',
            'map'   => 'application/json',
        ];
        header('Content-Type: ' . ($mimeMap[$ext] ?? mime_content_type($diskPath) ?: 'application/octet-stream'));
        header('Content-Length: ' . filesize($diskPath));
        readfile($diskPath);
        exit;
    }
}

// ── 2. Legacy Aliases & Redirects ──
$legacyMap = [
    '/pages/buy'      => '/pages/properties',
    '/pages/buy.php'  => '/pages/properties',
    '/pages/rent'     => '/pages/properties',
    '/pages/rent.php' => '/pages/properties',
    '/pages/news'     => '/pages/articles',
    '/pages/news.php' => '/pages/articles',
];
if (isset($legacyMap[$path])) {
    header('Location: ' . $legacyMap[$path], true, 301);
    exit;
}

// ── 3. Canonical Admin Directory Redirect ──
if ($path === '/admin') {
    header('Location: /admin/', true, 301);
    exit;
}

// ── 4. Dedicated Admin Routing ──
if (strpos($path, '/admin/') === 0) {
    $adminSub = substr($path, 7); // e.g. "", "login", "properties", "index.php"
    $adminSubClean = preg_replace('#\.php$#i', '', rtrim($adminSub, '/'));

    if (empty($adminSubClean) || $adminSubClean === 'index') {
        require $hindRoot . '/admin/index.php';
        exit;
    }

    $targetAdminFile = $hindRoot . '/admin/' . $adminSubClean . '.php';
    if (file_exists($targetAdminFile)) {
        require $targetAdminFile;
        exit;
    }
}

// ── 5. Pretty Property Slugs: /pages/property/SLUG or /property/SLUG ──
if (preg_match('#^/(?:pages/)?property/([^/?]+)/?$#i', $path, $m)) {
    $_GET['slug'] = urldecode($m[1]);
    $_SERVER['QUERY_STRING'] = 'slug=' . urlencode($m[1]);
    require $hindRoot . '/pages/property.php';
    exit;
}

// ── 6. Pretty Article Slugs: /pages/article/SLUG or /article/SLUG ──
if (preg_match('#^/(?:pages/)?article/([^/?]+)/?$#i', $path, $m)) {
    $_GET['slug'] = urldecode($m[1]);
    $_SERVER['QUERY_STRING'] = 'slug=' . urlencode($m[1]);
    require $hindRoot . '/pages/article.php';
    exit;
}

// ── 7. Root Route / -> index.php ──
if ($path === '/' || $path === '') {
    require $hindRoot . DIRECTORY_SEPARATOR . 'index.php';
    exit;
}

// ── 8. Extensionless & Direct PHP File Resolution ──
$cleanPath = preg_replace('#\.php$#i', '', $path);
$targetPhp  = $hindRoot . str_replace('/', DIRECTORY_SEPARATOR, $cleanPath . '.php');
if (file_exists($targetPhp) && is_file($targetPhp)) {
    require $targetPhp;
    exit;
}

// ── 9. Directory Index Resolution ──
$dirIndex = rtrim($diskPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'index.php';
if (is_dir($diskPath) && file_exists($dirIndex)) {
    require $dirIndex;
    exit;
}

// ── 10. 404 Not Found Fallback ──
http_response_code(404);
$err404 = $hindRoot . DIRECTORY_SEPARATOR . 'pages' . DIRECTORY_SEPARATOR . '404.php';
if (file_exists($err404)) {
    require $err404;
} else {
    echo '<h1 style="font-family:sans-serif;text-align:center;margin-top:15vh">404 — Page non trouvée</h1>';
}
exit;
