<?php
// index.php - Consolidated Multi-Site Entry
require 'bootstrap.php';
$db = Database::getInstance();

// 1. Detect Domain
$dm = new DomainManager();
$domain = $dm->detectDomain();
$domainId = $domain['id'];

// 2. Route Request
$router = new Router($domainId);
$uri = $_SERVER['REQUEST_URI'];
$route = $router->route($uri);

// 3. Prepare Data for Template
$data = [];
$view = '';

if ($route['type'] === '404') {
    http_response_code(404);
    $view = '404.php'; // Should exist in template
    $data['title'] = "Page Not Found";
    $data['content'] = "<p>Sorry, existing page not found.</p>";
} elseif ($route['type'] === 'home_default') {
    $view = 'home.php';
    $data['title'] = "Welcome to " . htmlspecialchars($domain['host']);
    $data['is_home'] = true;
    
    // Fetch Recent Articles
    $stmt = $db->query("SELECT * FROM articles WHERE domain_id = ? ORDER BY published_at DESC LIMIT 3", [$domainId]);
    $data['recent_articles'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Mock default content
    $data['content'] = ''; // Empty content as layout handles sections
} elseif ($route['type'] === 'blog') {
    $view = 'blog.php';
    $data['title'] = "Blog & Insights";
    $data['is_blog'] = true;
    
    // Fetch all articles
    $stmt = $db->query("SELECT * FROM articles WHERE domain_id = ? ORDER BY published_at DESC", [$domainId]);
    $data['articles'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
} elseif ($route['type'] === 'page') {
    $view = 'page.php';
    $data = $route['data'];
} elseif ($route['type'] === 'article') {
    $view = 'article.php';
    $data = $route['data'];
    $data['is_article'] = true;
}

// 4. Render Template
$templatePath = $dm->getTemplatePath();
$templateDir = dirname($templatePath);

// Make vars available to template
extract($data);

// Output Buffering to wrap in layout
if (file_exists($templatePath)) {
    include $templatePath;
} else {
    echo "<h1>Template System Error</h1><p>Template file not found: $templatePath</p>";
}
