<?php
define('SECURE_ACCESS', true);

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

requireLogin();

$slug = trim($_GET['slug'] ?? '');

if (empty($slug)) {
    header("Location: dashboard");
    exit();
}

$page = null;
try {
    $stmt = $pdo->prepare("SELECT * FROM cms_pages WHERE slug = ?");
    $stmt->execute([$slug]);
    $page = $stmt->fetch();
} catch (PDOException $e) {
    // Database error
}

if (!$page) {
    // 404 Render
    $pageTitle = "Page Not Found";
    require_once __DIR__ . '/../includes/header.php';
    ?>
    <div class="container-fluid px-md-5 py-5 text-center">
        <div class="row justify-content-center py-5">
            <div class="col-12 col-md-6 py-5">
                <i class="bi bi-file-earmark-x text-secondary" style="font-size: 5rem;"></i>
                <h1 class="fw-bold mt-3 text-dark">404 - Page Not Found</h1>
                <p class="text-secondary mb-4">The dynamic page you requested does not exist or has been removed.</p>
                <a href="dashboard" class="btn btn-primary px-4 fw-bold">Return to Dashboard</a>
            </div>
        </div>
    </div>
    <?php
    require_once __DIR__ . '/../includes/footer.php';
    exit();
}

$pageTitle = $page['title'];
require_once __DIR__ . '/../includes/header.php';
?>

<div class="container-fluid px-md-5 py-5">
    <div class="row justify-content-center">
        <div class="col-12 col-lg-10">
            <div class="card border-0 shadow-sm p-4 p-md-5 rounded-3 bg-white">
                <!-- Title & Last Updated -->
                <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-2 mb-3">
                    <h1 class="fw-bold text-dark mb-0"><?php echo htmlspecialchars($page['title']); ?></h1>
                    <span class="text-secondary small font-monospace">Last updated: <?php echo date('F d, Y', strtotime($page['updated_at'])); ?></span>
                </div>
                <hr class="my-4">
                
                <!-- HTML Content Rendered directly from DB -->
                <div class="cms-rendered-content text-secondary leading-relaxed" style="font-size: 0.95rem; line-height: 1.75;">
                    <?php echo $page['content']; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
require_once __DIR__ . '/../includes/footer.php';
?>
