<?php

declare(strict_types=1);

require_once __DIR__ . '/Auth.php';
require_once __DIR__ . '/../models/SiteSetting.php';

function dijikalaAsset(string $relativePath): string
{
    return htmlspecialchars(assetPath('/assets/dijikala/' . ltrim($relativePath, '/')));
}

/**
 * @return list<string>
 */
function dijikalaDistinctCategories(): array
{
    try {
        require_once __DIR__ . '/../models/Product.php';

        return (new Product())->distinctCategories();
    } catch (Throwable $e) {
        return [];
    }
}

/**
 * @param array{
 *   description?: string,
 *   canonical?: string,
 *   keywords?: string,
 *   og_image?: string,
 *   json_ld?: array|null,
 *   noindex?: bool
 * } $seo
 */
function renderDijikalaShellStart(string $title, array $seo = [], string $searchPrefill = ''): void
{
    Auth::startSession();

    $sessionUser = Auth::user();
    $cats = dijikalaDistinctCategories();
    $homePhp = htmlspecialchars(appPath('/public/home.php'));
    $productsPhp = htmlspecialchars(appPath('/public/products.php'));
    $cartPhp = htmlspecialchars(appPath('/public/cart.php'));
    $trackPhp = htmlspecialchars(appPath('/public/order-tracking.php'));
    $loginPhp = htmlspecialchars(appPath('/public/login.php'));
    $registerPhp = htmlspecialchars(appPath('/public/register.php'));
    $profilePhp = htmlspecialchars(appPath('/public/profile.php'));
    $logoutPhp = htmlspecialchars(appPath('/public/logout.php'));
    $comparePhp = htmlspecialchars(appPath('/public/compare.php'));
    $searchEscaped = htmlspecialchars($searchPrefill);

    $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((string)($globalSeo['seo_canonical_base'] ?: APP_URL), '/');
    $canonical = $seo['canonical'] ?? ($canonicalBase . ($_SERVER['REQUEST_URI'] ?? '/'));
    $ogImage = $seo['og_image'] ?? ($globalSeo['seo_og_image'] ?? '');
    if ($ogImage !== '' && isset($ogImage[0]) && $ogImage[0] === '/') {
        $ogImageAbs = rtrim(APP_URL, '/') . $ogImage;
    } else {
        $defaultLogo = appPath('.\images\logo.jpg');
        $ogImageAbs = $ogImage !== '' ? $ogImage : (rtrim(APP_URL, '/') . $defaultLogo);
    }
    $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.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <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((string)$desc) ?>">
    <meta property="og:type" content="website">
    <meta property="og:url" content="<?= htmlspecialchars($canonical) ?>">
    <meta property="og:image" content="<?= htmlspecialchars((string)$ogImageAbs) ?>">
    <?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;500;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?= dijikalaAsset('css/fonts/fonts.css') ?>">
    <link rel="stylesheet" href="<?= dijikalaAsset('css/style.css') ?>">
</head>
<body>
<header>
    <div class="container">
        <div class="t-header">
            <div class="t-header-right">
                <div class="t-header-logo">
                    <a href="<?= $homePhp ?>" class="brand-pill"><?= htmlspecialchars(APP_NAME) ?></a>
                </div>
                <div class="t-header-search">
                    <div class="t-header-search-box">
                        <form action="<?= htmlspecialchars(appPath('/public/products.php')) ?>" method="get">
                            <input type="text" name="q" class="input-t-header-search" placeholder="جستجو در محصولات..."
                                   value="<?= $searchEscaped ?>">
                        </form>
                    </div>
                </div>
            </div>
            <div class="t-header-left">
                <div class="t-header-account">
                    <?php if ($sessionUser): ?>
                        <a href="<?= $profilePhp ?>">حساب کاربری</a>
                    <?php else: ?>
                        <a href="<?= $loginPhp ?>">ورود به حساب کاربری</a>
                    <?php endif; ?>
                </div>
                <div class="t-header-basket">
                    <a href="<?= $cartPhp ?>" aria-label="سبد خرید"></a>
                </div>
            </div>
        </div>
    </div>

    <nav>
        <div class="container">
            <div class="nav">
                <div class="nav-level-1">
                    <ul class="nav-level-1-ul">
                        <li class="nav-level-1-li"><a href="<?= $homePhp ?>">خانه</a></li>
                        <li class="nav-level-1-li has-sub nav-level-1-li-1">
                            <div class="categoreis">دسته‌بندی کالاها</div>
                            <div class="sub-menu-categoreis">
                                <div class="sub-menu-right-list">
                                    <?php foreach ($cats as $idx => $catName): ?>
                                        <?php
                                            $catLink = htmlspecialchars(appPath('/public/products.php')) . '?category=' . rawurlencode($catName);
                                        ?>
                                        <a class="sub-menu-right-list-a<?= $idx === 0 ? ' sub-menu-right-list-a-1 active' : '' ?>"
                                           href="<?= $catLink ?>"><?= htmlspecialchars($catName) ?></a>
                                    <?php endforeach; ?>
                                    <?php if (!$cats): ?>
                                        <a class="sub-menu-right-list-a sub-menu-right-list-a-1 active" href="<?= $productsPhp ?>">همه محصولات</a>
                                    <?php endif; ?>
                                </div>
                                <div class="sub-menu-left-section">
                                    <div class="section" style="display:block">
                                        <div class="section-header"><a href="<?= $productsPhp ?>">مشاهده همه محصولات</a></div>
                                        <ul class="sub-menu-categoreis-ul">
                                            <?php foreach (array_slice($cats, 0, 12) as $catName): ?>
                                                <?php $catLinkInner = htmlspecialchars(appPath('/public/products.php')) . '?category=' . rawurlencode($catName); ?>
                                                <li class="sub-menu-categoreis-li sub-menu-categoreis-li-main">
                                                    <a href="<?= $catLinkInner ?>"><?= htmlspecialchars($catName) ?></a>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </li>
                        <li class="nav-level-1-li"><a href="<?= $cartPhp ?>">سبد خرید</a></li>
                        <li class="nav-level-1-li"><a href="<?= $trackPhp ?>">پیگیری سفارش</a></li>
                        <li class="nav-level-1-li"><a href="<?= $comparePhp ?>">مقایسه</a></li>
                        <li class="nav-level-1-li"><a href="<?= $registerPhp ?>">ثبت‌نام</a></li>
                    </ul>
                </div>
                <div class="nav-location">
                    <span class="send-location"><?= htmlspecialchars(APP_NAME) ?></span>
                </div>
            </div>
        </div>
    </nav>
</header>
<div class="overlay"></div>

<main id="main">
    <div class="content">
    <?php
}

/**
 * @param 'home'|'shop'|'minimal' $scriptPack
 */
function renderDijikalaShellEnd(string $pageKey = '', string $scriptPack = 'minimal'): void
{
    $settingModel = new SiteSetting();
    $ga = $settingModel->getMany(['seo_ga_measurement_id']);
    $gaId = trim((string)($ga['seo_ga_measurement_id'] ?? ''));
    ?>
    </div><!-- .content -->
</main>

<footer class="c-footer">
    <div class="container">
        <div class="c-footer__feature-innerbox">
            <span class="c-footer__badge"><span class="c-footer__feature-item c-footer__feature-item--1">ارسال سریع</span></span>
            <span class="c-footer__badge"><span class="c-footer__feature-item c-footer__feature-item--3">پشتیبانی آنلاین</span></span>
            <span class="c-footer__badge"><span class="c-footer__feature-item c-footer__feature-item--4">پرداخت امن</span></span>
            <span class="c-footer__badge"><span class="c-footer__feature-item c-footer__feature-item--5">پیگیری سفارش</span></span>
        </div>
        <div class="c-footer__middlebar">
            <div class="c-footer__links">
                <div class="c-footer__links--col">
                    <div class="o-headline-links"><div><span>دسترسی سریع</span></div></div>
                    <ul class="c-footer__links-ul">
                        <li><a href="<?= htmlspecialchars(appPath('/public/products.php')) ?>">فروشگاه</a></li>
                        <li><a href="<?= htmlspecialchars(appPath('/public/cart.php')) ?>">سبد خرید</a></li>
                        <li><a href="<?= htmlspecialchars(appPath('/public/order-tracking.php')) ?>">پیگیری سفارش</a></li>
                    </ul>
                </div>
                <div class="c-footer__links--col">
                    <div class="o-headline-links"><div><span>حساب کاربری</span></div></div>
                    <ul class="c-footer__links-ul">
                        <li><a href="<?= htmlspecialchars(appPath('/public/login.php')) ?>">ورود</a></li>
                        <li><a href="<?= htmlspecialchars(appPath('/public/register.php')) ?>">ثبت‌نام</a></li>
                        <li><a href="<?= htmlspecialchars(appPath('/public/sitemap.php')) ?>">نقشه سایت</a></li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="c-footer__address">
            <p class="c-footer__seo--content" style="padding:12px 0;">
                فروشگاه اینترنتی <?= htmlspecialchars(APP_NAME) ?> — خرید آنلاین کالا با پشتیبانی و پیگیری شفاف سفارش.
            </p>
        </div>
    </div>
</footer>
<a href="#" class="goToTop"></a>

<script src="<?= dijikalaAsset('js/js.js') ?>" defer></script>
<?php if ($scriptPack === 'home'): ?>
    <script src="<?= dijikalaAsset('js/slideshow.js') ?>" defer></script>
    <script src="<?= dijikalaAsset('js/slider-pro.js') ?>" defer></script>
    <script src="<?= dijikalaAsset('js/slider-scroll.js') ?>" defer></script>
    <script src="<?= dijikalaAsset('js/countDowntimer.js') ?>" defer></script>
<?php endif; ?>
<?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>
</body>
</html>
    <?php
}

/**
 * @param array<string, mixed> $product
 */
function dijikalaProductUrl(array $product): string
{
    if (!empty($product['slug'])) {
        return htmlspecialchars(appPath('/public/product.php')) . '?slug=' . rawurlencode((string)$product['slug']);
    }

    return htmlspecialchars(appPath('/public/product.php')) . '?id=' . (int)$product['id'];
}

/**
 * @param array<string, mixed> $product
 */
function dijikalaProductThumbUrl(array $product): string
{
    $raw = trim((string)($product['image_url'] ?? ''));
    if ($raw === '') {
        return dijikalaAsset('img/sman.png');
    }

    return htmlspecialchars(appPath('/' . ltrim($raw, '/')));
}
