<?php
/**
 * Public Front-End Entry Point
 */
session_start();
require_once('../site/libs/classes/DbPathsArray.php');
require_once('../site/libs/classes/App_DB.php');

$db = new App_DB(DBU::$dba_user);

// 1. Load CMS Settings
$settings_res = $db->getRecordSet("SELECT * FROM cms_settings");
$cms_settings = [];
foreach ($settings_res as $row) {
    $cms_settings[$row['setting_key']] = $row['setting_value'];
}

// 2. Identify Active Theme
$active_theme = $cms_settings['active_theme'] ?? 'default';
$theme_path = "themes/" . $active_theme . "/";

// 3. Routing (Basic for now)
$slug = $_GET['page'] ?? 'home';

// 4. Fetch Page Content
$page = $db->getRecordFilled("SELECT * FROM cms_pages WHERE slug = :slug AND status = 'published'", ['slug' => $slug]);

if (!$page && $slug === 'home') {
    $page = [
        'title' => 'Welcome to Madrasa',
        'content' => '<h1>Welcome</h1><p>This is the default home page content. Please create a page with slug "home" in the CMS to change this.</p>',
        'meta_title' => 'Home | Madrasa',
        'meta_description' => 'Welcome to our Madrasa website'
    ];
} elseif (!$page) {
    http_response_code(404);
    die("Page not found.");
}

// 5. Build Theme Data
$site_title = $cms_settings['site_title'] ?? 'Madrasa Website';

// 6. Include Theme Layout
if (file_exists($theme_path . "layout/main.php")) {
    include($theme_path . "layout/main.php");
} else {
    // Fallback if theme is broken
    echo "<h1>" . htmlspecialchars($page['title']) . "</h1>";
    echo $page['content'];
}
?>