<?php
/**
 * Dynamic SEO Page Renderer
 * Renders pages with SEO settings from database
 */

require_once 'config/config.php';
require_once 'config/database.php';
require_once 'includes/functions.php';
require_once 'includes/SEO.php';

// Handle redirects
handleSEORedirects();

// Get page slug from URL
$slug = $_GET['page'] ?? 'home';
$slug = preg_replace('/[^a-z0-9\-_\/]/', '', strtolower($slug));

// Try to find page in database
$page = dbFetch(
    "SELECT * FROM seo_pages WHERE page_url = :url AND status = 'active'",
    ['url' => '/' . $slug]
);

// If not found, show 404
if (!$page && $slug !== 'home') {
    http_response_code(404);
    $pageTitle = 'Page Not Found';
    $content = '<div style="text-align:center;padding:100px 20px;"><h1>404</h1><p>Page not found</p><a href="/">Go Home</a></div>';
} else {
    $pageTitle = $page['page_title'] ?? 'Home';
    $content = '';
}

// Get site settings
$siteName = getSetting('site_name', APP_NAME);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <?= seo()->renderMetaTags($pageTitle) ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="<?= ASSETS_URL ?>/css/style.css">
    <?= seo()->renderSchema() ?>
    <?= seo()->renderAnalytics() ?>
</head>
<body>
    <nav style="background:#111827;padding:1rem 2rem;display:flex;justify-content:space-between;align-items:center;">
        <a href="/" style="color:#00d09c;font-size:1.5rem;font-weight:700;text-decoration:none;"><?= htmlspecialchars($siteName) ?></a>
        <div>
            <a href="user/login.php" style="color:#fff;margin-right:1rem;text-decoration:none;">Login</a>
            <a href="user/register.php" style="background:#00d09c;color:#000;padding:0.5rem 1rem;border-radius:6px;text-decoration:none;">Register</a>
        </div>
    </nav>
    
    <main>
        <?php if ($page && !empty($page['h1_tag'])): ?>
        <h1><?= htmlspecialchars($page['h1_tag']) ?></h1>
        <?php endif; ?>
        
        <?= $content ?>
    </main>
    
    <footer style="background:#111827;padding:2rem;text-align:center;color:#6b7280;margin-top:2rem;">
        <p>&copy; <?= date('Y') ?> <?= htmlspecialchars($siteName) ?>. All rights reserved.</p>
    </footer>
</body>
</html>
