<?php
/**
 * =========================================================
 * JHARKHAND DIRECTORY v1.0.0 - Domain Router
 * Entry Point: /index.php (Root)
 * © 2026 SolutionJunction.in
 * =========================================================
 * 
 * This file routes all domain traffic to appropriate endpoints:
 * - https://jharkhanddirectory.com/           → Homepage
 * - https://jharkhanddirectory.com/admin/     → Admin Panel
 * - https://jharkhanddirectory.com/api/       → API Endpoints
 * - https://jharkhanddirectory.com/public/    → Public Pages
 */

// =========================================================
// SECURITY HEADERS
// =========================================================
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Permissions-Policy: geolocation=(), microphone=(), camera=()');

// Redirect HTTP to HTTPS (in production)
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'off') {
    header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit();
}

// =========================================================
// CONFIGURATION
// =========================================================
define('SITE_ROOT', dirname(__FILE__));
define('SITE_URL', (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST']);
define('ADMIN_PATH', SITE_ROOT . '/admin');
define('PUBLIC_PATH', SITE_ROOT . '/public');
define('API_PATH', SITE_ROOT . '/api');
define('INCLUDES_PATH', SITE_ROOT . '/includes');

// =========================================================
// INCLUDE CORE FILES
// =========================================================
require_once INCLUDES_PATH . '/config.php';
require_once INCLUDES_PATH . '/db.php';
require_once INCLUDES_PATH . '/session.php';
require_once INCLUDES_PATH . '/functions.php';

// =========================================================
// PARSE REQUEST URI
// =========================================================
$request_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$request_uri = str_replace(dirname($_SERVER['SCRIPT_NAME']), '', $request_uri);
$request_uri = ltrim($request_uri, '/');
$request_uri = rtrim($request_uri, '/');

// =========================================================
// ROUTER LOGIC
// =========================================================

// API Requests (Priority 1)
if (strpos($request_uri, 'api/v1/') === 0) {
    handleAPI($request_uri);
}

// Admin Panel (Priority 2)
elseif (strpos($request_uri, 'admin') === 0) {
    handleAdmin($request_uri);
}

// Public Pages (Priority 3)
elseif (strpos($request_uri, 'public') === 0 || strpos($request_uri, 'district/') === 0 || strpos($request_uri, 'category/') === 0 || strpos($request_uri, 'listing/') === 0) {
    handlePublic($request_uri);
}

// Static Files (Priority 4)
elseif (strpos($request_uri, 'assets/') === 0) {
    serveStaticFile($request_uri);
}

// Service Worker & PWA (Priority 5)
elseif (in_array($request_uri, ['service-worker.js', 'manifest.json', 'offline.html'])) {
    serveStaticFile($request_uri);
}

// Root/Homepage (Priority 6)
elseif (empty($request_uri) || $request_uri === 'index.php' || $request_uri === 'index.html') {
    include PUBLIC_PATH . '/index.php';
}

// 404 - Not Found
else {
    handle404($request_uri);
}

// =========================================================
// ROUTER HANDLERS
// =========================================================

/**
 * Handle API requests
 */
function handleAPI($uri) {
    $parts = explode('/', $uri);
    
    if (count($parts) < 3) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid API endpoint']);
        exit();
    }

    $version = $parts[1]; // v1
    $endpoint = $parts[2]; // listings, districts, categories

    $api_file = API_PATH . '/' . $version . '/' . $endpoint . '.php';

    if (!file_exists($api_file)) {
        http_response_code(404);
        echo json_encode(['error' => 'API endpoint not found']);
        exit();
    }

    include $api_file;
}

/**
 * Handle admin panel requests
 */
function handleAdmin($uri) {
    $parts = array_filter(explode('/', $uri));
    
    if (empty($parts[1])) {
        // /admin -> /admin/index.php
        include ADMIN_PATH . '/index.php';
    } else {
        $page = sanitize($parts[1]);
        $admin_file = ADMIN_PATH . '/' . $page . '.php';

        if (file_exists($admin_file)) {
            include $admin_file;
        } else {
            handle404($uri);
        }
    }
}

/**
 * Handle public page requests
 */
function handlePublic($uri) {
    $parts = array_filter(explode('/', $uri));

    // Handle special routes
    if ($parts[0] === 'district' && isset($parts[1])) {
        $_GET['slug'] = $parts[1];
        include PUBLIC_PATH . '/district/view.php';
        return;
    }

    if ($parts[0] === 'category' && isset($parts[1])) {
        $_GET['slug'] = $parts[1];
        include PUBLIC_PATH . '/category/view.php';
        return;
    }

    if ($parts[0] === 'listing' && isset($parts[1])) {
        $_GET['id'] = $parts[1];
        include PUBLIC_PATH . '/listing/view.php';
        return;
    }

    // Handle /public/ prefix
    if ($parts[0] === 'public') {
        if (empty($parts[1])) {
            include PUBLIC_PATH . '/index.php';
        } else {
            $page = sanitize($parts[1]);
            $public_file = PUBLIC_PATH . '/' . $page . '.php';

            if (file_exists($public_file)) {
                include $public_file;
            } else {
                handle404($uri);
            }
        }
        return;
    }

    // Direct page access
    $page = sanitize($parts[0]);
    $public_file = PUBLIC_PATH . '/' . $page . '.php';

    if (file_exists($public_file)) {
        include $public_file;
    } else {
        handle404($uri);
    }
}

/**
 * Serve static files
 */
function serveStaticFile($file) {
    $full_path = SITE_ROOT . '/' . $file;

    // Security: Prevent directory traversal
    if (strpos(realpath($full_path), SITE_ROOT) !== 0) {
        http_response_code(403);
        exit('Access denied');
    }

    if (!file_exists($full_path)) {
        http_response_code(404);
        exit('File not found');
    }

    // Set appropriate content type
    $mime_types = [
        'js' => 'application/javascript',
        'css' => 'text/css',
        'json' => 'application/json',
        'html' => 'text/html',
        'svg' => 'image/svg+xml',
        'png' => 'image/png',
        'jpg' => 'image/jpeg',
        'jpeg' => 'image/jpeg',
        'gif' => 'image/gif',
        'webp' => 'image/webp',
        'woff' => 'font/woff',
        'woff2' => 'font/woff2',
        'ttf' => 'font/ttf',
    ];

    $ext = strtolower(pathinfo($full_path, PATHINFO_EXTENSION));
    $content_type = $mime_types[$ext] ?? 'application/octet-stream';

    header('Content-Type: ' . $content_type);
    header('Cache-Control: public, max-age=3600');

    readfile($full_path);
    exit();
}

/**
 * Handle 404 errors
 */
function handle404($uri) {
    http_response_code(404);
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>404 - Page Not Found</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <style>
            body {
                background: linear-gradient(135deg, #0B6B57 0%, #074a3d 100%);
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .error-container {
                text-align: center;
                color: white;
            }
            .error-code {
                font-size: 120px;
                font-weight: bold;
                margin: 0;
            }
            .error-message {
                font-size: 24px;
                margin: 20px 0;
            }
            .error-uri {
                font-size: 14px;
                opacity: 0.8;
                margin-bottom: 30px;
                word-break: break-all;
            }
            .btn-home {
                background-color: #D4941F;
                color: white;
                padding: 10px 30px;
                font-size: 16px;
                border: none;
                border-radius: 5px;
                text-decoration: none;
                display: inline-block;
            }
            .btn-home:hover {
                background-color: #c77f0d;
                color: white;
                text-decoration: none;
            }
        </style>
    </head>
    <body>
        <div class="error-container">
            <h1 class="error-code">404</h1>
            <p class="error-message">Page Not Found</p>
            <p class="error-uri"><?php echo htmlspecialchars($uri); ?></p>
            <a href="<?php echo SITE_URL; ?>" class="btn-home">← Back to Home</a>
        </div>
    </body>
    </html>
    <?php
    exit();
}

/**
 * Sanitize input
 */
function sanitize($input) {
    return preg_replace('/[^a-zA-Z0-9_-]/', '', $input);
}
?>
