<?php
/**
 * orkestrait.ai - Multi-Tenant Front Controller
 * Routes incoming requests to appropriate tenant sites or orkestrait landing
 */

// Load configuration
require_once __DIR__ . '/config.php';
require_once INCLUDES_PATH . '/db.php';
require_once INCLUDES_PATH . '/tenant.php';

// Get the incoming host
$host = $_SERVER['HTTP_HOST'] ?? '';

// Resolve tenant from domain
$tenant = resolveTenant($host);

if ($tenant === null) {
    // No tenant found - check if this is orkestrait.ai itself
    if (isOrkestRAItDomain($host)) {
        // Show orkestrait landing page
        include __DIR__ . '/index_orkestrait.html';
        exit;
    } else {
        // Unknown domain - 404
        http_response_code(404);
        echo '<!DOCTYPE html><html><head><title>404 Not Found</title></head><body>';
        echo '<h1>404 Not Found</h1>';
        echo '<p>The requested domain is not configured on this server.</p>';
        echo '</body></html>';
        exit;
    }
}

// We have a tenant - load their site
require_once INCLUDES_PATH . '/template_engine.php';

// Get tenant configuration
$tenant_config = getTenantConfig($tenant['customer_id']);

// Get tenant database connection
$tenant_db = getTenantDB($tenant['customer_id'], $tenant_config);

// Determine which page to render based on URI
$request_uri = $_SERVER['REQUEST_URI'] ?? '/';
$path = parse_url($request_uri, PHP_URL_PATH);

// For now, we only handle the homepage
// Future: add routing for /chat/, /model/{id}, /friends, etc.
if ($path === '/' || $path === '') {
    $page = 'index';
} else {
    // For now, 404 on other paths
    http_response_code(404);
    echo '<!DOCTYPE html><html><head><title>404 Not Found</title></head><body>';
    echo '<h1>404 Not Found</h1>';
    echo '<p>Page not found.</p>';
    echo '</body></html>';
    exit;
}

// Render the tenant page
renderTenantPage($tenant, $tenant_config, $tenant_db, $page);
