<?php

declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Bootstrap dan session
|--------------------------------------------------------------------------
*/

$bootstrapFile = __DIR__ . '/bootstrap.php';

if (is_file($bootstrapFile)) {
    require_once $bootstrapFile;
}

if (session_status() === PHP_SESSION_NONE) {
    session_name('USERSESSID');
    session_start();
}

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars(
            (string) $value,
            ENT_QUOTES,
            'UTF-8'
        );
    }
}

/*
|--------------------------------------------------------------------------
| Informasi halaman
|--------------------------------------------------------------------------
*/

$siteName = isset($siteName)
    ? (string) $siteName
    : 'Platform Online';

$pageTitle = 'Promo & Event';
$activeMenu = 'promo';

$isLoggedIn = !empty($_SESSION['user_id']);

$username = isset($_SESSION['username'])
    ? (string) $_SESSION['username']
    : 'Member';

/*
|--------------------------------------------------------------------------
| Koneksi database PDO
|--------------------------------------------------------------------------
*/

$databaseFile = __DIR__ . '/config/database.php';

if (!isset($pdo) || !($pdo instanceof PDO)) {
    if (!is_file($databaseFile)) {
        http_response_code(500);

        exit(
            'File koneksi database tidak ditemukan: ' .
            e($databaseFile)
        );
    }

    require_once $databaseFile;
}

if (!isset($pdo) || !($pdo instanceof PDO)) {
    http_response_code(500);

    exit(
        'Koneksi PDO $pdo tidak tersedia dari config/database.php.'
    );
}

$pdo->setAttribute(
    PDO::ATTR_ERRMODE,
    PDO::ERRMODE_EXCEPTION
);

$pdo->setAttribute(
    PDO::ATTR_DEFAULT_FETCH_MODE,
    PDO::FETCH_ASSOC
);

/*
|--------------------------------------------------------------------------
| Helper URL lokal aman
|--------------------------------------------------------------------------
*/

function promoSafeUrl($url)
{
    $url = trim((string) $url);

    if ($url === '') {
        return '#';
    }

    if (
        preg_match('/^https?:\/\//i', $url) ||
        preg_match('/^(mailto:|tel:)/i', $url)
    ) {
        return $url;
    }

    if (
        strpos($url, '//') === 0 ||
        preg_match('/[\r\n]/', $url)
    ) {
        return '#';
    }

    return ltrim($url, '/');
}

/*
|--------------------------------------------------------------------------
| Ambil promo aktif
|--------------------------------------------------------------------------
*/

$promoRows = [];
$promoError = '';

try {
    $audience = $isLoggedIn
        ? 'MEMBER'
        : 'GUEST';

    $promoStatement = $pdo->prepare(
        'SELECT
            id,
            title,
            slug,
            category,
            badge_text,
            short_description,
            description,
            image_url,
            mobile_image_url,
            button_label,
            button_url,
            terms_url,
            requires_login,
            audience,
            is_featured,
            sort_order,
            start_at,
            end_at
         FROM promos
         WHERE is_active = 1
           AND (
                audience = :audience_all
                OR audience = :audience_current
           )
           AND (
                start_at IS NULL
                OR start_at <= NOW()
           )
           AND (
                end_at IS NULL
                OR end_at >= NOW()
           )
         ORDER BY
            is_featured DESC,
            sort_order ASC,
            id DESC'
    );

    $promoStatement->execute([
        ':audience_all' => 'ALL',
        ':audience_current' => $audience,
    ]);

    $promoRows = $promoStatement->fetchAll();
} catch (Throwable $exception) {
    $promoRows = [];
    $promoError = $exception->getMessage();

    error_log(
        'PROMO PAGE ERROR: ' .
        $promoError
    );
}

/*
|--------------------------------------------------------------------------
| Normalisasi data untuk tampilan
|--------------------------------------------------------------------------
*/

$normalizedPromos = [];
$promoCategories = [];

foreach ($promoRows as $promoRow) {
    $category = strtoupper(
        trim(
            (string) (
                $promoRow['category'] ??
                'LAINNYA'
            )
        )
    );

    if ($category === '') {
        $category = 'LAINNYA';
    }

  $buttonUrl = promoSafeUrl(
    $promoRow['button_url'] ?? ''
);

$buttonLabel = trim(
    (string) (
        $promoRow['button_label'] ??
        'LIHAT PROMO'
    )
);

$buttonPath = parse_url(
    $buttonUrl,
    PHP_URL_PATH
);

$buttonFile = strtolower(
    basename(
        (string) $buttonPath
    )
);

/*
|--------------------------------------------------------------------------
| Pengguna sudah login tidak boleh diarahkan ke login/register
|--------------------------------------------------------------------------
*/

if (
    $isLoggedIn &&
    in_array(
        $buttonFile,
        [
            'login.php',
            'register.php',
        ],
        true
    )
) {
    $buttonUrl = 'account.php';
    $buttonLabel = 'BUKA AKUN';
}

/*
|--------------------------------------------------------------------------
| Promo khusus member mengarahkan guest ke login
|--------------------------------------------------------------------------
*/

if (
    !$isLoggedIn &&
    !empty($promoRow['requires_login'])
) {
    $buttonUrl =
        'login.php?next=' .
        rawurlencode($buttonUrl);

    $buttonLabel = 'LOGIN UNTUK CLAIM';
}

    $normalizedPromos[] = [
        'id' => (int) ($promoRow['id'] ?? 0),
        'title' => (string) (
            $promoRow['title'] ??
            'Promo'
        ),
        'slug' => (string) (
            $promoRow['slug'] ??
            ''
        ),
        'category' => $category,
        'badge_text' => (string) (
            $promoRow['badge_text'] ??
            'PROMO'
        ),
        'short_description' => (string) (
            $promoRow['short_description'] ??
            ''
        ),
        'description' => (string) (
            $promoRow['description'] ??
            ''
        ),
        'image_url' => (string) (
            $promoRow['image_url'] ??
            'assets/images/promo/promo-default.svg'
        ),
        'mobile_image_url' => (string) (
            $promoRow['mobile_image_url'] ??
            ''
        ),
        'button_label' => $buttonLabel,
        'button_url' => $buttonUrl,
        'terms_url' => promoSafeUrl(
            $promoRow['terms_url'] ?? ''
        ),
        'requires_login' => !empty(
            $promoRow['requires_login']
        ),
        'audience' => (string) (
            $promoRow['audience'] ??
            'ALL'
        ),
        'is_featured' => !empty(
            $promoRow['is_featured']
        ),
        'sort_order' => (int) (
            $promoRow['sort_order'] ??
            999
        ),
        'start_at' => $promoRow['start_at'] ?? null,
        'end_at' => $promoRow['end_at'] ?? null,
    ];

    $promoCategories[$category] = true;
}

$promoCategories = array_keys(
    $promoCategories
);

sort($promoCategories);

$featuredPromo = null;

foreach ($normalizedPromos as $promoItem) {
    if ($promoItem['is_featured']) {
        $featuredPromo = $promoItem;
        break;
    }
}

if (
    $featuredPromo === null &&
    !empty($normalizedPromos)
) {
    $featuredPromo = $normalizedPromos[0];
}

/*
|--------------------------------------------------------------------------
| Header
|--------------------------------------------------------------------------
*/

require __DIR__ . '/includes/header.php';

?>

<style>
/*
|--------------------------------------------------------------------------
| Halaman promo casino
|--------------------------------------------------------------------------
*/

.promo-page {
    position: relative;

    width: 100%;
    min-height: calc(100vh - 70px);

    padding: 12px 9px 25px;

    overflow: hidden;

    background:
        radial-gradient(
            circle at 50% -5%,
            rgba(0, 139, 255, 0.28),
            transparent 280px
        ),
        radial-gradient(
            circle at 108% 38%,
            rgba(255, 179, 0, 0.11),
            transparent 190px
        ),
        linear-gradient(
            180deg,
            #031431 0%,
            #020a1c 55%,
            #010610 100%
        );
}

.promo-page::before,
.promo-page::after {
    position: absolute;

    width: 190px;
    height: 190px;

    content: "";

    border-radius: 50%;

    filter: blur(38px);

    pointer-events: none;
}

.promo-page::before {
    top: 115px;
    left: -160px;

    background:
        rgba(0, 126, 255, 0.20);
}

.promo-page::after {
    right: -165px;
    bottom: 170px;

    background:
        rgba(255, 178, 0, 0.12);
}

.promo-shell {
    position: relative;
    z-index: 2;

    width: 100%;
    max-width: 540px;

    margin: 0 auto;
}

/*
|--------------------------------------------------------------------------
| Header promo
|--------------------------------------------------------------------------
*/

.promo-heading {
    display: grid;

    justify-items: center;

    margin-bottom: 11px;

    text-align: center;
}

.promo-heading-crown {
    margin-bottom: -4px;

    color: #ffd451;

    font-size: 28px;
    line-height: 1;

    text-shadow:
        0 1px 0 #fff5ac,
        0 3px 0 #713600,
        0 0 10px rgba(255, 194, 39, 0.65);
}

.promo-heading h1 {
    margin: 0;

    color: #ffd450;

    background:
        linear-gradient(
            180deg,
            #fff9ba 0%,
            #ffd451 36%,
            #e58b00 72%,
            #fff09a 100%
        );

    background-clip: text;
    -webkit-background-clip: text;

    font-size: clamp(24px, 7vw, 34px);
    font-weight: 1000;

    letter-spacing: -0.035em;

    -webkit-text-fill-color: transparent;

    filter:
        drop-shadow(0 2px 0 #713600)
        drop-shadow(0 5px 6px rgba(0, 0, 0, 0.72));
}

.promo-heading p {
    max-width: 430px;

    margin: 6px 0 0;

    color: #96aac5;

    font-size: 9px;
    line-height: 1.5;
}

.promo-login-state {
    display: inline-flex;

    min-height: 24px;

    align-items: center;

    margin-top: 8px;
    padding: 0 9px;

    gap: 5px;

    border:
        1px solid rgba(70, 222, 150, 0.25);

    border-radius: 999px;

    color: #a9dec4;

    background:
        rgba(4, 48, 32, 0.56);

    font-size: 7px;
    font-weight: 850;
}

.promo-login-state i {
    width: 5px;
    height: 5px;

    border-radius: 50%;

    background: #50e39a;

    box-shadow:
        0 0 6px rgba(80, 227, 154, 0.70);
}

/*
|--------------------------------------------------------------------------
| Featured promo
|--------------------------------------------------------------------------
*/

.promo-featured {
    position: relative;

    margin-bottom: 11px;

    overflow: hidden;

    border:
        1px solid rgba(255, 198, 48, 0.44);

    border-radius: 15px;

    background: #06142c;

    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.09),
        0 0 10px rgba(255, 182, 20, 0.15),
        0 8px 22px rgba(0, 0, 0, 0.34);
}

.promo-featured-picture {
    display: block;

    width: 100%;
    aspect-ratio: 16 / 8.5;

    overflow: hidden;

    background:
        linear-gradient(
            145deg,
            #082a5a,
            #04132d
        );
}

.promo-featured-picture img {
    display: block;

    width: 100%;
    height: 100%;

    object-fit: cover;
    object-position: center;
}

.promo-featured-overlay {
    position: absolute;
    inset: 0;

    display: flex;

    align-items: flex-end;

    padding: 14px;

    background:
        linear-gradient(
            180deg,
            transparent 30%,
            rgba(1, 7, 18, 0.35) 53%,
            rgba(1, 7, 18, 0.96) 100%
        );
}

.promo-featured-copy {
    width: 100%;
}

.promo-badge {
    display: inline-flex;

    min-height: 22px;

    align-items: center;

    padding: 0 8px;

    border:
        1px solid rgba(255, 234, 144, 0.70);

    border-radius: 999px;

    color: #341c00;

    background:
        linear-gradient(
            180deg,
            #fff29b,
            #ffc62e
        );

    font-size: 7px;
    font-weight: 1000;

    box-shadow:
        0 0 8px rgba(255, 191, 31, 0.35);
}

.promo-featured-copy h2 {
    margin: 7px 0 0;

    color: #ffffff;

    font-size: clamp(18px, 5.5vw, 27px);
    font-weight: 1000;

    line-height: 1.05;

    text-shadow:
        0 2px 2px rgba(0, 0, 0, 0.90),
        0 0 8px rgba(0, 132, 255, 0.35);
}

.promo-featured-copy p {
    max-width: 440px;

    margin: 6px 0 0;

    color: #d4deea;

    font-size: 8px;
    line-height: 1.45;

    text-shadow:
        0 1px 2px rgba(0, 0, 0, 0.90);
}

.promo-featured-actions {
    display: flex;

    margin-top: 9px;

    gap: 6px;
}

.promo-button {
    display: inline-flex;

    min-height: 34px;

    align-items: center;
    justify-content: center;

    padding: 0 12px;

    border:
        1px solid #ffe17f;

    border-radius: 8px;

    color: #301700;

    background:
        linear-gradient(
            180deg,
            #fff08c,
            #ffc32d 50%,
            #d87700
        );

    font-size: 8px;
    font-weight: 1000;

    text-decoration: none;

    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.62),
        0 3px 0 #572900,
        0 0 8px rgba(255, 183, 20, 0.28);
}

.promo-button--ghost {
    border-color:
        rgba(0, 172, 255, 0.45);

    color: #ffffff;

    background:
        linear-gradient(
            180deg,
            rgba(11, 63, 117, 0.92),
            rgba(3, 26, 59, 0.98)
        );

    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.09),
        0 3px 0 rgba(0, 0, 0, 0.55);
}

/*
|--------------------------------------------------------------------------
| Filter kategori
|--------------------------------------------------------------------------
*/

.promo-filter-wrap {
    margin-bottom: 10px;
}

.promo-filter-label {
    display: flex;

    align-items: center;
    justify-content: space-between;

    margin-bottom: 7px;
}

.promo-filter-label strong {
    color: #ffffff;

    font-size: 11px;
}

.promo-filter-label small {
    color: #758ba7;

    font-size: 7px;
}

.promo-filter-scroll {
    display: flex;

    overflow-x: auto;

    padding-bottom: 3px;

    gap: 6px;

    scrollbar-width: none;
}

.promo-filter-scroll::-webkit-scrollbar {
    display: none;
}

.promo-filter-button {
    flex: 0 0 auto;

    min-height: 29px;

    padding: 0 11px;

    border:
        1px solid rgba(0, 157, 255, 0.28);

    border-radius: 999px;

    color: #8fa7c3;

    background:
        linear-gradient(
            180deg,
            #08284f,
            #03142d
        );

    font-size: 7px;
    font-weight: 900;

    cursor: pointer;
}

.promo-filter-button.is-active {
    border-color:
        rgba(255, 211, 78, 0.72);

    color: #271400;

    background:
        linear-gradient(
            180deg,
            #ffe687,
            #ffb719
        );

    box-shadow:
        0 0 8px rgba(255, 183, 23, 0.28);
}

/*
|--------------------------------------------------------------------------
| Grid promo
|--------------------------------------------------------------------------
*/

.promo-grid {
    display: grid;

    grid-template-columns:
        repeat(2, minmax(0, 1fr));

    gap: 8px;
}

.promo-card {
    position: relative;

    display: grid;

    min-width: 0;

    overflow: hidden;

    border:
        1px solid rgba(0, 157, 255, 0.27);

    border-radius: 12px;

    background:
        linear-gradient(
            180deg,
            rgba(7, 30, 65, 0.98),
            rgba(2, 12, 29, 0.99)
        );

    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.07),
        0 4px 12px rgba(0, 0, 0, 0.25);

    transition:
        transform 160ms ease,
        border-color 160ms ease,
        box-shadow 160ms ease;
}

.promo-card:hover {
    transform: translateY(-2px);

    border-color:
        rgba(255, 194, 37, 0.55);

    box-shadow:
        0 7px 15px rgba(0, 0, 0, 0.34),
        0 0 9px rgba(255, 185, 23, 0.14);
}

.promo-card-picture {
    display: block;

    width: 100%;
    aspect-ratio: 16 / 9;

    overflow: hidden;

    background:
        linear-gradient(
            145deg,
            #082a5a,
            #04132d
        );
}

.promo-card-picture img {
    display: block;

    width: 100%;
    height: 100%;

    object-fit: cover;
    object-position: center;

    transition:
        transform 220ms ease;
}

.promo-card:hover
.promo-card-picture img {
    transform: scale(1.04);
}

.promo-card-body {
    display: grid;

    min-width: 0;

    padding: 8px;

    gap: 5px;
}

.promo-card-meta {
    display: flex;

    align-items: center;
    justify-content: space-between;

    gap: 5px;
}

.promo-card-category {
    overflow: hidden;

    color: #61cbff;

    font-size: 6px;
    font-weight: 1000;

    letter-spacing: 0.06em;

    text-overflow: ellipsis;
    white-space: nowrap;
}

.promo-card-badge {
    flex: 0 0 auto;

    padding: 2px 5px;

    border-radius: 999px;

    color: #3a2100;
    background: #ffd34e;

    font-size: 5px;
    font-weight: 1000;
}

.promo-card h3 {
    display: -webkit-box;

    min-height: 26px;

    margin: 0;

    overflow: hidden;

    color: #ffffff;

    font-size: 11px;
    font-weight: 1000;

    line-height: 1.15;

    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
}

.promo-card p {
    display: -webkit-box;

    min-height: 30px;

    margin: 0;

    overflow: hidden;

    color: #91a5bf;

    font-size: 7px;
    line-height: 1.45;

    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
}

.promo-card-actions {
    display: grid;

    margin-top: 2px;

    grid-template-columns:
        minmax(0, 1fr)
        auto;

    gap: 5px;
}

.promo-card-button {
    display: flex;

    min-height: 29px;

    align-items: center;
    justify-content: center;

    padding: 0 7px;

    border:
        1px solid rgba(255, 205, 70, 0.48);

    border-radius: 7px;

    color: #271400;

    background:
        linear-gradient(
            180deg,
            #ffe37e,
            #f3aa14
        );

    font-size: 6px;
    font-weight: 1000;

    text-decoration: none;
}

.promo-detail-button {
    min-width: 31px;
    min-height: 29px;

    padding: 0;

    border:
        1px solid rgba(0, 170, 255, 0.40);

    border-radius: 7px;

    color: #7ed7ff;
    background: #042144;

    font-size: 13px;

    cursor: pointer;
}

/*
|--------------------------------------------------------------------------
| Empty dan error
|--------------------------------------------------------------------------
*/

.promo-empty {
    grid-column: 1 / -1;

    padding: 22px 12px;

    border:
        1px dashed rgba(255, 194, 39, 0.30);

    border-radius: 12px;

    color: #91a5bf;
    background: rgba(4, 18, 42, 0.74);

    font-size: 9px;
    line-height: 1.5;

    text-align: center;
}

.promo-error {
    margin-bottom: 10px;
    padding: 9px;

    border:
        1px solid rgba(255, 77, 77, 0.38);

    border-radius: 10px;

    color: #ffd6d6;
    background: rgba(102, 12, 17, 0.48);

    font-size: 8px;
    line-height: 1.45;
}

/*
|--------------------------------------------------------------------------
| Modal detail promo
|--------------------------------------------------------------------------
*/

.promo-modal {
    position: fixed;
    z-index: 2000;

    inset: 0;

    display: none;

    align-items: flex-end;
    justify-content: center;

    padding: 12px;

    background:
        rgba(0, 4, 13, 0.80);

    backdrop-filter:
        blur(8px);
}

.promo-modal.is-open {
    display: flex;
}

.promo-modal-dialog {
    position: relative;

    width: 100%;
    max-width: 540px;
    max-height: 88vh;

    overflow-y: auto;

    border:
        1px solid rgba(255, 197, 43, 0.42);

    border-radius: 16px;

    background:
        radial-gradient(
            circle at 50% 0,
            rgba(255, 178, 0, 0.11),
            transparent 170px
        ),
        linear-gradient(
            180deg,
            #08234b,
            #020b1d
        );

    box-shadow:
        0 0 18px rgba(0, 129, 255, 0.24),
        0 18px 36px rgba(0, 0, 0, 0.55);
}

.promo-modal-image {
    display: block;

    width: 100%;
    aspect-ratio: 16 / 8.5;

    object-fit: cover;

    border-radius:
        15px
        15px
        0
        0;
}

.promo-modal-content {
    padding: 13px;
}

.promo-modal-content h2 {
    margin: 7px 0 0;

    color: #ffffff;

    font-size: 18px;
}

.promo-modal-description {
    margin-top: 8px;

    color: #adbed1;

    font-size: 9px;
    line-height: 1.65;

    white-space: pre-line;
}

.promo-modal-actions {
    display: flex;

    margin-top: 12px;

    gap: 7px;
}

.promo-modal-actions .promo-button {
    flex: 1;
}

.promo-modal-close {
    position: absolute;
    z-index: 3;

    top: 8px;
    right: 8px;

    display: grid;

    width: 31px;
    height: 31px;

    place-items: center;

    border:
        1px solid rgba(255, 255, 255, 0.22);

    border-radius: 50%;

    color: #ffffff;
    background: rgba(0, 0, 0, 0.70);

    font-size: 16px;

    cursor: pointer;
}

body.promo-modal-open {
    overflow: hidden;
}

/*
|--------------------------------------------------------------------------
| Responsive
|--------------------------------------------------------------------------
*/

@media (max-width: 390px) {
    .promo-page {
        padding-right: 7px;
        padding-left: 7px;
    }

    .promo-featured-overlay {
        padding: 11px;
    }

    .promo-featured-copy h2 {
        font-size: 18px;
    }

    .promo-card-body {
        padding: 7px;
    }
}

@media (max-width: 340px) {
    .promo-grid {
        grid-template-columns: 1fr;
    }

    .promo-card h3,
    .promo-card p {
        min-height: 0;
    }
}
</style>

<section class="promo-page">
    <div class="promo-shell">

        <header class="promo-heading">
            <span
                class="promo-heading-crown"
                aria-hidden="true"
            >
                ♛
            </span>

            <h1>
                PROMO & EVENT
            </h1>

            <p>
                Temukan bonus, event, cashback, dan penawaran
                terbaru yang tersedia untuk Anda.
            </p>

            <span class="promo-login-state">
                <i></i>

                <?php if ($isLoggedIn): ?>
                    Halo <?= e($username); ?>, promo member aktif
                <?php else: ?>
                    Promo dapat dilihat tanpa login
                <?php endif; ?>
            </span>
        </header>

        <?php if ($promoError !== ''): ?>

            <div class="promo-error">
                Data promo belum dapat dimuat.
                Pastikan tabel <strong>promos</strong> sudah dibuat.
            </div>

        <?php endif; ?>

        <?php if ($featuredPromo): ?>

            <article class="promo-featured">

                <picture class="promo-featured-picture">

                    <?php if (
                        $featuredPromo['mobile_image_url'] !== ''
                    ): ?>
                        <source
                            media="(max-width: 480px)"
                            srcset="<?= e($featuredPromo['mobile_image_url']); ?>"
                        >
                    <?php endif; ?>

                    <img
                        src="<?= e($featuredPromo['image_url']); ?>"
                        alt="<?= e($featuredPromo['title']); ?>"
                        loading="eager"
                        decoding="async"
                        onerror="
                            this.onerror = null;
                            this.src =
                                'assets/images/promo/promo-default.svg';
                        "
                    >
                </picture>

                <div class="promo-featured-overlay">
                    <div class="promo-featured-copy">

                        <span class="promo-badge">
                            <?= e($featuredPromo['badge_text']); ?>
                        </span>

                        <h2>
                            <?= e($featuredPromo['title']); ?>
                        </h2>

                        <p>
                            <?= e($featuredPromo['short_description']); ?>
                        </p>

                        <div class="promo-featured-actions">
                            <a
                                class="promo-button"
                                href="<?= e($featuredPromo['button_url']); ?>"
                            >
                                <?= e($featuredPromo['button_label']); ?>
                            </a>

                            <button
                                class="promo-button promo-button--ghost"
                                type="button"
                                data-promo-open="<?= (int) $featuredPromo['id']; ?>"
                            >
                                DETAIL
                            </button>
                        </div>

                    </div>
                </div>

            </article>

        <?php endif; ?>

        <section class="promo-filter-wrap">

            <div class="promo-filter-label">
                <strong>
                    Semua Penawaran
                </strong>

                <small>
                    <?= count($normalizedPromos); ?> promo aktif
                </small>
            </div>

            <div class="promo-filter-scroll">

                <button
                    class="promo-filter-button is-active"
                    type="button"
                    data-promo-filter="ALL"
                >
                    SEMUA
                </button>

                <?php foreach ($promoCategories as $category): ?>

                    <button
                        class="promo-filter-button"
                        type="button"
                        data-promo-filter="<?= e($category); ?>"
                    >
                        <?= e($category); ?>
                    </button>

                <?php endforeach; ?>

            </div>

        </section>

        <section
            class="promo-grid"
            id="promoGrid"
        >

            <?php if (empty($normalizedPromos)): ?>

                <div class="promo-empty">
                    Belum ada promo aktif saat ini.
                    Tambahkan data melalui tabel
                    <strong>promos</strong> di database.
                </div>

            <?php else: ?>

                <?php foreach ($normalizedPromos as $promo): ?>

                    <article
                        class="promo-card"
                        data-promo-category="<?= e($promo['category']); ?>"
                    >

                        <picture class="promo-card-picture">

                            <?php if (
                                $promo['mobile_image_url'] !== ''
                            ): ?>
                                <source
                                    media="(max-width: 480px)"
                                    srcset="<?= e($promo['mobile_image_url']); ?>"
                                >
                            <?php endif; ?>

                            <img
                                src="<?= e($promo['image_url']); ?>"
                                alt="<?= e($promo['title']); ?>"
                                loading="lazy"
                                decoding="async"
                                onerror="
                                    this.onerror = null;
                                    this.src =
                                        'assets/images/promo/promo-default.svg';
                                "
                            >
                        </picture>

                        <div class="promo-card-body">

                            <div class="promo-card-meta">
                                <span class="promo-card-category">
                                    <?= e($promo['category']); ?>
                                </span>

                                <span class="promo-card-badge">
                                    <?= e($promo['badge_text']); ?>
                                </span>
                            </div>

                            <h3>
                                <?= e($promo['title']); ?>
                            </h3>

                            <p>
                                <?= e($promo['short_description']); ?>
                            </p>

                            <div class="promo-card-actions">

                                <a
                                    class="promo-card-button"
                                    href="<?= e($promo['button_url']); ?>"
                                >
                                    <?= e($promo['button_label']); ?>
                                </a>

                                <button
                                    class="promo-detail-button"
                                    type="button"
                                    data-promo-open="<?= (int) $promo['id']; ?>"
                                    aria-label="Lihat detail <?= e($promo['title']); ?>"
                                >
                                    ›
                                </button>

                            </div>

                        </div>

                    </article>

                <?php endforeach; ?>

            <?php endif; ?>

        </section>

    </div>
</section>

<!-- MODAL DETAIL PROMO -->
<div
    class="promo-modal"
    id="promoModal"
    aria-hidden="true"
>
    <article
        class="promo-modal-dialog"
        role="dialog"
        aria-modal="true"
        aria-labelledby="promoModalTitle"
    >
        <button
            class="promo-modal-close"
            id="promoModalClose"
            type="button"
            aria-label="Tutup detail promo"
        >
            ×
        </button>

        <img
            class="promo-modal-image"
            id="promoModalImage"
            src="assets/images/promo/promo-default.svg"
            alt=""
        >

        <div class="promo-modal-content">

            <span
                class="promo-badge"
                id="promoModalBadge"
            >
                PROMO
            </span>

            <h2 id="promoModalTitle">
                Detail Promo
            </h2>

            <div
                class="promo-modal-description"
                id="promoModalDescription"
            ></div>

            <div class="promo-modal-actions">

                <a
                    class="promo-button"
                    id="promoModalAction"
                    href="#"
                >
                    LIHAT PROMO
                </a>

                <a
                    class="promo-button promo-button--ghost"
                    id="promoModalTerms"
                    href="#"
                >
                    SYARAT
                </a>

            </div>

        </div>
    </article>
</div>

<script>
(function () {
    'use strict';

    var promoData = <?= json_encode(
        $normalizedPromos,
        JSON_UNESCAPED_UNICODE |
        JSON_UNESCAPED_SLASHES |
        JSON_HEX_TAG |
        JSON_HEX_AMP |
        JSON_HEX_APOS |
        JSON_HEX_QUOT
    ); ?>;

    var promoMap = {};

    promoData.forEach(function (promo) {
        promoMap[String(promo.id)] = promo;
    });

    /*
    |--------------------------------------------------------------------------
    | Filter kategori
    |--------------------------------------------------------------------------
    */

    var filterButtons = document.querySelectorAll(
        '[data-promo-filter]'
    );

    var promoCards = document.querySelectorAll(
        '[data-promo-category]'
    );

    Array.prototype.forEach.call(
        filterButtons,
        function (button) {
            button.addEventListener(
                'click',
                function () {
                    var category =
                        button.getAttribute(
                            'data-promo-filter'
                        ) || 'ALL';

                    Array.prototype.forEach.call(
                        filterButtons,
                        function (item) {
                            item.classList.remove(
                                'is-active'
                            );
                        }
                    );

                    button.classList.add(
                        'is-active'
                    );

                    Array.prototype.forEach.call(
                        promoCards,
                        function (card) {
                            var cardCategory =
                                card.getAttribute(
                                    'data-promo-category'
                                );

                            var shouldShow =
                                category === 'ALL' ||
                                category === cardCategory;

                            card.style.display =
                                shouldShow
                                    ? ''
                                    : 'none';
                        }
                    );
                }
            );
        }
    );

    /*
    |--------------------------------------------------------------------------
    | Modal detail
    |--------------------------------------------------------------------------
    */

    var modal =
        document.getElementById('promoModal');

    var closeButton =
        document.getElementById('promoModalClose');

    var modalImage =
        document.getElementById('promoModalImage');

    var modalBadge =
        document.getElementById('promoModalBadge');

    var modalTitle =
        document.getElementById('promoModalTitle');

    var modalDescription =
        document.getElementById(
            'promoModalDescription'
        );

    var modalAction =
        document.getElementById('promoModalAction');

    var modalTerms =
        document.getElementById('promoModalTerms');

    function closePromoModal() {
        if (!modal) {
            return;
        }

        modal.classList.remove('is-open');
        modal.setAttribute('aria-hidden', 'true');

        document.body.classList.remove(
            'promo-modal-open'
        );
    }

    function openPromoModal(id) {
        var promo = promoMap[String(id)];

        if (!promo || !modal) {
            return;
        }

        modalImage.src =
            promo.image_url ||
            'assets/images/promo/promo-default.svg';

        modalImage.alt = promo.title || 'Promo';

        modalBadge.textContent =
            promo.badge_text || 'PROMO';

        modalTitle.textContent =
            promo.title || 'Detail Promo';

        modalDescription.textContent =
            promo.description ||
            promo.short_description ||
            '';

        modalAction.textContent =
            promo.button_label ||
            'LIHAT PROMO';

        modalAction.href =
            promo.button_url || '#';

        if (
            promo.terms_url &&
            promo.terms_url !== '#'
        ) {
            modalTerms.style.display = '';
            modalTerms.href = promo.terms_url;
        } else {
            modalTerms.style.display = 'none';
            modalTerms.href = '#';
        }

        modal.classList.add('is-open');
        modal.setAttribute('aria-hidden', 'false');

        document.body.classList.add(
            'promo-modal-open'
        );
    }

    var openButtons = document.querySelectorAll(
        '[data-promo-open]'
    );

    Array.prototype.forEach.call(
        openButtons,
        function (button) {
            button.addEventListener(
                'click',
                function () {
                    openPromoModal(
                        button.getAttribute(
                            'data-promo-open'
                        )
                    );
                }
            );
        }
    );

    if (closeButton) {
        closeButton.addEventListener(
            'click',
            closePromoModal
        );
    }

    if (modal) {
        modal.addEventListener(
            'click',
            function (event) {
                if (event.target === modal) {
                    closePromoModal();
                }
            }
        );
    }

    document.addEventListener(
        'keydown',
        function (event) {
            if (event.key === 'Escape') {
                closePromoModal();
            }
        }
    );
})();
</script>

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