<?php
declare(strict_types=1);

function publicPageMeta(string $pageKey): array
{
    $map = [
        'home' => ['خانه', 'variant-home'],
        'products' => ['فروشگاه محصولات', 'variant-products'],
        'product' => ['جزئیات محصول', 'variant-product'],
        'cart' => ['سبد خرید هوشمند', 'variant-cart'],
        'checkout' => ['تسویه حساب امن', 'variant-checkout'],
        'tracking' => ['پیگیری سفارش', 'variant-tracking'],
        'login' => ['ورود کاربر', 'variant-login'],
        'register' => ['ثبت نام کاربر', 'variant-register'],
        'profile' => ['پروفایل کاربری', 'variant-profile'],
        'payment' => ['نتیجه پرداخت', 'variant-payment'],
    ];

    return $map[$pageKey] ?? ['صفحه', 'variant-default'];
}

/**
 * @param array{
 *   description?: string,
 *   canonical?: string,
 *   keywords?: string,
 *   og_image?: string,
 *   json_ld?: array|null,
 *   noindex?: bool
 * } $seo
 */
function renderPublicShellStart(string $title, string $pageKey, array $seo = []): void
{
    require_once __DIR__ . '/Auth.php';
    require_once __DIR__ . '/../models/SiteSetting.php';

    Auth::startSession();
    $sessionUser = Auth::user();

    [$label, $variantClass] = publicPageMeta($pageKey);
    $homeUrl = htmlspecialchars(appPath('/public/home.php'));
    $productsUrl = htmlspecialchars(appPath('/public/products.php'));
    $cartUrl = htmlspecialchars(appPath('/public/cart.php'));
    $trackingUrl = htmlspecialchars(appPath('/public/order-tracking.php'));
    $loginUrl = htmlspecialchars(appPath('/public/login.php'));
    $profileUrl = htmlspecialchars(appPath('/public/profile.php'));
    $logoutUrl = htmlspecialchars(appPath('/public/logout.php'));

    $settingModel = new SiteSetting();
    $globalSeo = $settingModel->getMany([
        'seo_meta_description',
        'seo_keywords',
        'seo_canonical_base',
        'seo_og_image',
        'seo_ga_measurement_id',
    ]);
    $desc = $seo['description'] ?? ($globalSeo['seo_meta_description'] ?? '');
    $keywords = $seo['keywords'] ?? ($globalSeo['seo_keywords'] ?? '');
    $canonicalBase = rtrim($globalSeo['seo_canonical_base'] ?? APP_URL, '/');
    $canonical = $seo['canonical'] ?? ($canonicalBase . ($_SERVER['REQUEST_URI'] ?? '/'));
    $ogImage = $seo['og_image'] ?? ($globalSeo['seo_og_image'] ?? '');
    if ($ogImage !== '' && $ogImage[0] === '/') {
        $ogImageAbs = rtrim(APP_URL, '/') . $ogImage;
    } else {
        $ogImageAbs = $ogImage !== '' ? $ogImage : (rtrim(APP_URL, '/') . appPath('.\images\logo.jpg'));
    }
    $jsonLd = $seo['json_ld'] ?? null;
    $noindex = !empty($seo['noindex']);
    ?>
<!doctype html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= htmlspecialchars($title) ?></title>
    <?php if ($desc !== ''): ?>
        <meta name="description" content="<?= htmlspecialchars($desc) ?>">
    <?php endif; ?>
    <?php if ($keywords !== ''): ?>
        <meta name="keywords" content="<?= htmlspecialchars($keywords) ?>">
    <?php endif; ?>
    <link rel="canonical" href="<?= htmlspecialchars($canonical) ?>">
    <meta property="og:title" content="<?= htmlspecialchars($title) ?>">
    <meta property="og:description" content="<?= htmlspecialchars($desc) ?>">
    <meta property="og:type" content="website">
    <meta property="og:url" content="<?= htmlspecialchars($canonical) ?>">
    <meta property="og:image" content="<?= htmlspecialchars($ogImageAbs) ?>">
    <meta name="twitter:card" content="summary_large_image">
    <?php if ($noindex): ?>
        <meta name="robots" content="noindex,nofollow">
    <?php endif; ?>
    <?php if (is_array($jsonLd) && $jsonLd !== []): ?>
        <script type="application/ld+json"><?= json_encode($jsonLd, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?></script>
    <?php endif; ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?= htmlspecialchars(assetPath('/assets/css/style.css')) ?>">
</head>
<body class="public-page <?= htmlspecialchars($variantClass) ?>">
    <header class="advanced-header">
        <div class="container advanced-header-inner">
            <a class="advanced-brand" href="<?= $homeUrl ?>">زایلون صنعت</a>
            <strong class="advanced-page-tag"><?= htmlspecialchars($label) ?></strong>
            <nav class="advanced-nav">
                <a href="<?= $productsUrl ?>">محصولات</a>
                <a href="<?= $cartUrl ?>">سبد خرید</a>
                <a href="<?= $trackingUrl ?>">پیگیری</a>
                <?php if ($sessionUser): ?>
                    <a href="<?= $profileUrl ?>">حساب شما</a>
                    <a href="<?= $logoutUrl ?>">خروج</a>
                <?php else: ?>
                    <a href="<?= $loginUrl ?>">ورود</a>
                <?php endif; ?>
            </nav>
        </div>
    </header>
<?php
}

function renderPublicShellEnd(string $pageKey): void
{
    require_once __DIR__ . '/../models/SiteSetting.php';
    $homeUrl = htmlspecialchars(appPath('/public/home.php'));
    $ga = (new SiteSetting())->getMany(['seo_ga_measurement_id']);
    $gaId = trim((string)($ga['seo_ga_measurement_id'] ?? ''));
    ?>
    <a class="back-home-fab" href="<?= $homeUrl ?>" aria-label="بازگشت به صفحه اصلی">خانه</a>
    <footer class="advanced-footer">
        <div class="container advanced-footer-grid">
            <div>
                <h3>زایلون صنعت</h3>
                <p>تولید و فروش تجهیزات صنعتی با پشتیبانی و خدمات پس از فروش.</p>
            </div>
            <div>
                <h4>دسترسی سریع</h4>
                <a href="<?= htmlspecialchars(appPath('/public/products.php')) ?>">فروشگاه</a>
                <a href="<?= htmlspecialchars(appPath('/public/order-tracking.php')) ?>">پیگیری سفارش</a>
                <a href="<?= htmlspecialchars(appPath('/public/sitemap.php')) ?>">نقشه سایت</a>
            </div>
            <div>
                <h4>وضعیت صفحه</h4>
                <p><?= htmlspecialchars(publicPageMeta($pageKey)[0]) ?> با چیدمان اختصاصی</p>
            </div>
        </div>
    </footer>
    <?php if ($gaId !== ''): ?>
        <script async src="https://www.googletagmanager.com/gtag/js?id=<?= htmlspecialchars($gaId) ?>"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '<?= htmlspecialchars($gaId) ?>');
        </script>
    <?php endif; ?>
    <script>window.ZYLON_BASE_URL = "<?= htmlspecialchars(rtrim((parse_url(APP_URL, PHP_URL_PATH) ?: ''), '/')) ?>";</script>
    <script src="<?= htmlspecialchars(assetPath('/assets/js/main.js')) ?>" defer></script>
</body>
</html>
<?php
}
