<?php
/* ============================================================
   ENGINE — MESIN TEMPLATE
   ============================================================
   JANGAN DIUTAK-ATIK kalau tidak paham PHP.
   File ini yang nge-render data.php jadi HTML.
   ============================================================ */


/* ---------- Auto cache-buster (?v=<timestamp>) ---------- */
function asset($path) {
    $file = __DIR__ . '/' . ltrim($path, '/');
    if (file_exists($file)) {
        return $path . '?v=' . filemtime($file);
    }
    return $path;
}


/* ---------- Builder banner utama ---------- */
function build_banner_main($b, $canonical) {
    $href     = htmlspecialchars($b['href']   ?? $canonical, ENT_QUOTES);
    $target   = htmlspecialchars($b['target'] ?? '_blank',   ENT_QUOTES);
    $alt      = htmlspecialchars($b['alt'], ENT_QUOTES);
    $title    = htmlspecialchars($b['title'] ?? $b['alt'], ENT_QUOTES);
    $img      = htmlspecialchars($b['img'], ENT_QUOTES);
    $isFirst  = !empty($b['priority']);
    $loading  = $isFirst ? 'eager' : 'lazy';
    $priority = $isFirst ? ' fetchpriority="high"' : '';

    return <<<HTML
            <div class="vertical-wrapper">
                <div class="">
                    <div class="slide-item">
                        <a href="{$href}" target="{$target}" rel="">
                            <img class="banner-img" src="{$img}" alt="{$alt}" title="{$title}" loading="{$loading}"{$priority} width="1920" height="588" />
                        </a>
                    </div>
                </div>
            </div>

HTML;
}


/* ---------- Builder banner sub-grup ---------- */
function build_banner_sub_group($group, $canonical, $chevron) {
    $items = '';
    foreach ($group as $b) {
        $href   = htmlspecialchars($b['href']   ?? $canonical, ENT_QUOTES);
        $target = htmlspecialchars($b['target'] ?? '_self',    ENT_QUOTES);
        $alt    = htmlspecialchars($b['alt'], ENT_QUOTES);
        $title  = htmlspecialchars($b['title'] ?? $b['alt'], ENT_QUOTES);
        $img    = htmlspecialchars($b['img'], ENT_QUOTES);

        $items .= <<<HTML
                    <div class="slide-item">
                        <a href="{$href}" target="{$target}">
                            <img class="banner-img" src="{$img}" alt="{$alt}" title="{$title}" loading="lazy" width="1920" height="588" />
                        </a>
                    </div>

HTML;
    }

    return <<<HTML
            <div class="vertical-wrapper">
                <div class="banner-group-vertical">
{$items}                </div>
                <div class="nav-btn sub-up">
                    <img alt="chevron up" class="arrow-right rotate-up " loading="lazy" src="{$chevron}" />
                </div>
                <div class="nav-btn sub-down">
                    <img alt="chevron down" class="arrow-right rotate-down " loading="lazy" src="{$chevron}" />
                </div>
            </div>

HTML;
}


/* ---------- Bangun JSON-LD Schema (SEO rich snippet) ---------- */
function build_schema_jsonld($d) {
    $canonical    = $d['CANONICAL']           ?? '';
    $brand        = $d['BRAND']               ?? '';
    $description  = $d['DESKRIPSI']           ?? '';
    $productName  = $d['SCHEMA_PRODUCT_NAME'] ?? $brand;
    $sku          = $d['SCHEMA_SKU']          ?? '';
    $image        = $d['SCHEMA_IMAGE']        ?? $d['BANNER-GOOGLE'] ?? '';
    $rating       = (float)($d['SCHEMA_RATING']       ?? 4.8);
    $reviewCount  = (int)  ($d['SCHEMA_REVIEW_COUNT'] ?? 1000);
    $reviewValue  = (int)  ($d['SCHEMA_REVIEW_VALUE'] ?? 4);
    $reviewer     = $d['SCHEMA_REVIEWER']     ?? $brand;
    $price        = (float)($d['SCHEMA_PRICE']        ?? 5000);
    $currency     = $d['SCHEMA_CURRENCY']     ?? 'IDR';
    $country      = $d['SCHEMA_COUNTRY']      ?? 'ID';
    $validUntil   = $d['SCHEMA_VALID_UNTIL']  ?? '2088-12-15';

    // Image jadi URL absolut
    if ($image && strpos($image, 'http') !== 0) {
        $image = rtrim($canonical, '/') . '/' . ltrim($image, '/');
    }

    // Keywords (5 pertama) → positiveNotes
    $keywords = array_filter(array_map('trim', explode(',', $d['KEYWORDS'] ?? '')));
    $keywords = array_slice($keywords, 0, 5);
    $positiveItems = [];
    foreach ($keywords as $i => $kw) {
        $positiveItems[] = [
            '@type'    => 'ListItem',
            'position' => $i + 1,
            'name'     => $kw,
        ];
    }

    // Schema 1: WebSite
    $website = [
        '@context'    => 'http://schema.org',
        '@type'       => 'WebSite',
        'url'         => $canonical,
        'name'        => $brand,
        'description' => $description,
    ];

    // Schema 2: Product
    $product = [
        '@context'    => 'https://schema.org/',
        '@type'       => 'Product',
        'name'        => $productName,
        'url'         => $canonical,
        'image'       => [$image],
        'description' => $description,
        'sku'         => $sku,
        'brand'       => [
            '@type' => 'Brand',
            'name'  => $brand,
        ],
        'positiveNotes' => [
            '@type'           => 'ItemList',
            'itemListElement' => $positiveItems,
        ],
        'aggregateRating' => [
            '@type'       => 'AggregateRating',
            'ratingValue' => $rating,
            'reviewCount' => $reviewCount,
        ],
        'review' => [
            '@type'        => 'Review',
            'reviewRating' => [
                '@type'       => 'Rating',
                'ratingValue' => $reviewValue,
                'bestRating'  => 5,
            ],
            'author' => [
                '@type' => 'Person',
                'name'  => $reviewer,
            ],
        ],
        'offers' => [[
            '@type' => 'Offer',
            'sku'   => $sku,
            'shippingDetails' => [
                '@type'        => 'OfferShippingDetails',
                'shippingRate' => [
                    '@type'    => 'MonetaryAmount',
                    'value'    => 5.00,
                    'currency' => $currency,
                ],
                'shippingDestination' => [
                    '@type'          => 'DefinedRegion',
                    'addressCountry' => $country,
                ],
                'deliveryTime' => [
                    '@type'        => 'ShippingDeliveryTime',
                    'handlingTime' => [
                        '@type'    => 'QuantitativeValue',
                        'minValue' => 0,
                        'maxValue' => 1,
                        'unitCode' => 'DAY',
                    ],
                    'transitTime' => [
                        '@type'    => 'QuantitativeValue',
                        'minValue' => 1,
                        'maxValue' => 5,
                        'unitCode' => 'DAY',
                    ],
                ],
            ],
            'hasMerchantReturnPolicy' => [
                '@type'                => 'MerchantReturnPolicy',
                'applicableCountry'    => $country,
                'returnPolicyCategory' => 'https://schema.org/MerchantReturnFiniteReturnWindow',
                'merchantReturnDays'   => 60,
                'returnMethod'         => 'https://schema.org/ReturnByMail',
                'returnFees'           => 'https://schema.org/FreeReturn',
            ],
            'availability'    => 'https://schema.org/InStock',
            'price'           => $price,
            'priceCurrency'   => $currency,
            'priceValidUntil' => $validUntil,
            'url'             => $canonical,
        ]],
    ];

    $opts = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT;
    return "<script type=\"application/ld+json\">\n"
         . json_encode($website, $opts)
         . "\n</script>\n<script type=\"application/ld+json\">\n"
         . json_encode($product, $opts)
         . "\n</script>";
}

$data['SCHEMA_JSON'] = build_schema_jsonld($data);


/* ---------- Build POPUP WELCOME ---------- */
function build_popup($d) {
    if (empty($d['POPUP_ENABLED'])) return '';

    $logo    = htmlspecialchars($d['LOGO'] ?? '', ENT_QUOTES);
    $logoW   = (int)($d['LOGO_WIDTH']  ?? 150);
    $logoH   = (int)($d['LOGO_HEIGHT'] ??  75);
    $banner  = htmlspecialchars($d['POPUP_BANNER'] ?? '', ENT_QUOTES);
    $title   = htmlspecialchars($d['TITLE'] ?? '', ENT_QUOTES);
    $brand   = htmlspecialchars($d['BRAND'] ?? '', ENT_QUOTES);
    $url     = htmlspecialchars($d['AMP'] ?? '#', ENT_QUOTES);
    $year    = date('Y');

    return <<<HTML
    <div id="popupCenter" class="popup-welcome" role="dialog" aria-modal="true">
        <div class="popup-card">
            <div class="popup-logo">
                <img src="{$logo}" alt="{$brand}" width="{$logoW}" height="{$logoH}" />
            </div>
            <div class="popup-banner">
                <img src="{$banner}" alt="{$brand}" width="600" height="600" />
            </div>
            <div class="popup-title">{$title}</div>
            <div class="popup-actions">
                <a href="{$url}" class="popup-btn popup-btn-login">MASUK</a>
                <a href="{$url}" class="popup-btn popup-btn-register">DAFTAR</a>
            </div>
            <div class="popup-footer">&copy; {$year} {$brand}. All rights reserved.</div>
        </div>
    </div>
HTML;
}

$data['POPUP'] = build_popup($data);


/* ---------- Bottom fixed nav (mobile only) — reuse $footer_nav ---------- */
function build_bottom_nav($nav, $canonical) {
    if (empty($nav)) return '';
    $html = '<div class="mobile-bottom-nav">';
    foreach ($nav as $i => $item) {
        $href   = htmlspecialchars($item['href']   ?? $canonical, ENT_QUOTES);
        $target = htmlspecialchars($item['target'] ?? '_self', ENT_QUOTES);
        $label  = htmlspecialchars($item['label'], ENT_QUOTES);
        $icon   = htmlspecialchars($item['icon'],  ENT_QUOTES);
        $active = !empty($item['active']) ? ' active' : '';
        $isMid  = (count($nav) === 5 && $i === 2);
        $cls    = trim($active . ($isMid ? ' center' : ''));
        $clsAttr = $cls ? " class=\"{$cls}\"" : '';
        $tgtAttr = $target === '_self' ? '' : " target=\"{$target}\"";
        $html .= "<a href=\"{$href}\"{$tgtAttr}{$clsAttr}><img src=\"{$icon}\" alt=\"{$label}\" width=\"30\" height=\"30\"><span>{$label}</span></a>";
    }
    $html .= '</div>';
    return $html;
}
$data['MOBILE_BOTTOM_NAV'] = build_bottom_nav($footer_nav ?? [], $data['DOMAIN'] ?? $data['CANONICAL']);


/* ---------- Mobile banner section (terpisah dari slick) ---------- */
function build_mobile_banners($mains, $url, $brand) {
    if (empty($mains)) return '';
    $html = '<div class="mobile-banner-section">';
    foreach ($mains as $b) {
        $href = htmlspecialchars($b['href'] ?? $url, ENT_QUOTES);
        $alt  = htmlspecialchars($b['alt'] ?? $brand, ENT_QUOTES);
        $img  = htmlspecialchars($b['img'], ENT_QUOTES);
        $html .= "<a href=\"{$href}\" class=\"mobile-banner-item\"><img src=\"{$img}\" alt=\"{$alt}\" loading=\"lazy\"></a>";
    }
    $html .= '</div>';
    return $html;
}
$data['MOBILE_BANNERS'] = build_mobile_banners($banners_main ?? [], $data['DOMAIN'] ?? $data['CANONICAL'], $data['BRAND']);


/* ---------- Mobile category scroll bar (HOT GAMES, SLOTS, ...) ---------- */
function build_mobile_category_bar($url) {
    $cats = [
        ['Hot Games',   '/assets/images/Images/v-normad-alpha/blue-magenta/desktop/menu/hot-games.svg'],
        ['Slots',       '/assets/images/Images/v-normad-alpha/blue-magenta/desktop/menu/slots.svg'],
        ['Live Casino', '/assets/images/Images/v-normad-alpha/blue-magenta/desktop/menu/casino.svg'],
        ['Olahraga',    '/assets/images/Images/v-normad-alpha/blue-magenta/desktop/menu/sports.svg'],
        ['Poker',       '/assets/images/Images/v-normad-alpha/blue-magenta/desktop/menu/poker.svg'],
        ['Togel',       '/assets/images/Images/v-normad-alpha/blue-magenta/desktop/menu/others.svg'],
        ['Crash Game',  '/assets/images/Images/v-normad-alpha/blue-magenta/desktop/menu/crash-game.svg'],
        ['Arcade',      '/assets/images/Images/v-normad-alpha/blue-magenta/desktop/menu/arcade.svg'],
        ['E-Sports',    '/assets/images/Images/v-normad-alpha/blue-magenta/desktop/menu/e-sports.svg'],
        ['Sabung Ayam', '/assets/images/Images/v-normad-alpha/blue-magenta/desktop/menu/cockfight.svg'],
    ];
    $u = htmlspecialchars($url, ENT_QUOTES);
    $html = '<div class="mobile-category-bar">';
    foreach ($cats as $c) {
        $name = htmlspecialchars($c[0], ENT_QUOTES);
        $icon = htmlspecialchars($c[1], ENT_QUOTES);
        $html .= "<a href=\"{$u}\"><img src=\"{$icon}\" alt=\"{$name}\" width=\"30\" height=\"30\"><span>{$name}</span></a>";
    }
    $html .= '</div>';
    return $html;
}
$data['MOBILE_CATEGORY_BAR'] = build_mobile_category_bar($data['DOMAIN'] ?? $data['CANONICAL']);


/* ---------- Inject CSS variables warna tema ---------- */
$data['THEME_VARS'] = '<style id="theme-vars">:root{'
    . '--c-primary:'       . ($data['COLOR_PRIMARY']       ?? '#0a1849') . ';'
    . '--c-primary-light:' . ($data['COLOR_PRIMARY_LIGHT'] ?? '#1e3a8a') . ';'
    . '--c-primary-dark:'  . ($data['COLOR_PRIMARY_DARK']  ?? '#030a2e') . ';'
    . '--c-accent:'        . ($data['COLOR_ACCENT']        ?? '#ffd700') . ';'
    . '--c-accent-light:'  . ($data['COLOR_ACCENT_LIGHT']  ?? '#ffe066') . ';'
    . '--c-accent-dark:'   . ($data['COLOR_ACCENT_DARK']   ?? '#b8a000') . ';'
    . '}</style>';


/* ---------- Render artikel ---------- */
function render_artikel($text) {
    $text = trim($text);
    if ($text === '') return '';

    // Mode HTML — kalau sudah ada tag, pakai apa adanya
    if (strpos($text, '<') !== false) {
        return $text;
    }

    // Mode plain text — pisah per baris kosong jadi paragraf
    $paragraphs = preg_split('/\n\s*\n/', $text);
    $html = '';
    foreach ($paragraphs as $p) {
        $p = trim($p);
        if ($p === '') continue;
        // single newline jadi <br> dalam paragraf
        $p = nl2br(htmlspecialchars($p, ENT_QUOTES));
        $html .= '<p>' . $p . '</p>' . "\n";
    }
    return $html;
}

$data['ARTICLE'] = render_artikel($artikel ?? '');


/* ---------- Auto-versioning untuk path file lokal ---------- */
foreach ($data as $key => $value) {
    if (is_string($value) && preg_match('#^/assets/.+\.(css|js|png|jpg|jpeg|webp|svg|gif|ico|woff2?)$#i', $value)) {
        $data[$key] = asset($value);
    }
}


/* ---------- Render banner slider jadi HTML ---------- */
$_canonical = $data['CANONICAL'];
$_chevron   = '/assets/images/Images/icons/chevron-right.svg';

$_banner_html = '';
foreach ($banners_main as $b) $_banner_html .= build_banner_main($b, $_canonical);
foreach ($banners_sub  as $g) $_banner_html .= build_banner_sub_group($g, $_canonical, $_chevron);

$data['BANNER_SLIDES'] = $_banner_html;
