<?php
/**
 * Dynamic page loader - ensures pages always load current header/footer and content
 * This file is included by all dynamically created pages in /pages/ folder
 */
if (session_status() !== PHP_SESSION_ACTIVE) session_start();

// Get the requested page slug from the URL or from the calling page
$requestedSlug = basename($_SERVER['PHP_SELF'], '.php');

// Load pages from JSON
$pagesFile = __DIR__ . '/data/pages.json';
$pages = [];
if (file_exists($pagesFile)) {
    $p = @json_decode(file_get_contents($pagesFile), true);
    if (is_array($p)) $pages = $p;
}

// Find the requested page
$pageData = null;
$pageTitle = 'Page Not Found';
$pageContent = '<p>The page you requested could not be found.</p>';

foreach ($pages as $pg) {
    if (($pg['slug'] ?? '') === $requestedSlug) {
        $pageData = $pg;
        $pageTitle = $pg['title'] ?? 'Page';
        $pageContent = $pg['html'] ?? '';
        break;
    }
}

// Load site config for page title and logo
$siteConfig = ['title' => "Esa's Fashion", 'logo' => ''];
$configFile = __DIR__ . '/data/site_config.json';
if (file_exists($configFile)) {
    $c = @json_decode(file_get_contents($configFile), true);
    if (is_array($c)) $siteConfig = array_merge($siteConfig, $c);
}

// Load categories (for any page that might need it)
$categories = [];
$categoriesFile = __DIR__ . '/data/categories.json';
if (file_exists($categoriesFile)) {
    $cats = @json_decode(file_get_contents($categoriesFile), true);
    if (is_array($cats)) $categories = $cats;
}

// Set base path for links - pages are in /pages/ subdirectory
define('BASE_URL', '../');

// Pre-calculate logo cache-buster since header.php won't have direct access
$logoCacheBuster = '';
$siteTitle = "Esa's Fashion";
$siteLogo = "pics_ecom/logo.png";
if (!empty($siteConfig['title'])) $siteTitle = $siteConfig['title'];
if (!empty($siteConfig['logo'])) $siteLogo = $siteConfig['logo'];

// Logo path needs to be relative to parent directory since we're in /pages/
$logoPath = __DIR__ . '/' . $siteLogo;
if (file_exists($logoPath)) {
    $logoCacheBuster = filemtime($logoPath);
} else {
    $logoCacheBuster = time();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title><?php echo htmlspecialchars($pageTitle); ?> - <?php echo htmlspecialchars($siteConfig['title']); ?></title>
  <link rel="stylesheet" href="../styles.css">
</head>
<body>
<?php 
// Include header from parent directory - it will use relative paths correctly
include __DIR__ . '/header.php'; 
?>
<main class="container">
<?php echo $pageContent; ?>
</main>
<?php 
// Include footer from parent directory
include __DIR__ . '/footer.php'; 
?>
</body>
</html>
