<?php
declare(strict_types=1);

// Configuration Session Cookie (10 Tahun / Eternal)
$cookieLifetime = 86400 * 365 * 10;
session_set_cookie_params([
    'lifetime' => $cookieLifetime,
    'path'     => '/',
    'domain'   => '',
    'secure'   => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on',
    'httponly' => true,
    'samesite' => 'Lax'
]);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/config.php';

/**
 * 1. AMBIL DETAIL PENGATURAN SITUS (site_settings)
 */
$stmtSite = $pdo->query("SELECT * FROM site_settings LIMIT 1");
$siteSettings = $stmtSite->fetch() ?: [];

// CEK MODE MAINTENANCE
if (!empty($siteSettings['maintenance_mode']) && (int)$siteSettings['maintenance_mode'] === 1) {
    http_response_code(530);
    $mMsg = !empty($siteSettings['maintenance_message']) ? htmlspecialchars($siteSettings['maintenance_message']) : 'Kami sedang melakukan pemeliharaan sistem rutin. Silahkan kembali lagi nanti.';
    echo '<!DOCTYPE html><html lang="id"><head><meta charset="UTF-8"><title>Maintenance Mode</title><style>body{font-family:"Outfit",sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;background:#f2f3f5;color:#222;text-align:center;padding:20px;margin:0;} .card{background:#fff;padding:30px;border-radius:12px;max-width:400px;box-shadow:0 4px 12px rgba(0,0,0,0.05);} h2{color:#8a704c;margin-bottom:10px;}</style></head><body><div class="card"><h2>Sistem Dalam Pemeliharaan</h2><p>' . $mMsg . '</p></div></body></html>';
    exit;
}

/**
 * Memeriksa status login pengguna via Session atau Cookie Remember Me
 */
function checkUserSession(PDO $pdo): ?array {
    if (isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])) {
        $stmt = $pdo->prepare("SELECT id, username, email, phone_number, saldo, poin, user_type, referral_code, status FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $_SESSION['user_id']]);
        $user = $stmt->fetch();
        if ($user && $user['status'] === 'aktif') {
            return $user;
        }
    }

    if (!empty($_COOKIE['pusatchip_remember'])) {
        $cookieValue = $_COOKIE['pusatchip_remember'];
        $parts = explode(':', $cookieValue);
        if (count($parts) === 2) {
            [$selector, $validator] = $parts;
            $stmt = $pdo->prepare("
                SELECT t.user_id, t.token_hash, u.id, u.username, u.email, u.phone_number, u.saldo, u.poin, u.user_type, u.referral_code, u.status 
                FROM user_remember_tokens t 
                JOIN users u ON t.user_id = u.id 
                WHERE t.selector = :selector AND t.expires_at > NOW() 
                LIMIT 1
            ");
            $stmt->execute([':selector' => $selector]);
            $data = $stmt->fetch();

            if ($data && $data['status'] === 'aktif') {
                $calcHash = hash('sha256', $validator);
                if (hash_equals($data['token_hash'], $calcHash)) {
                    $_SESSION['user_id'] = (int)$data['id'];
                    $up = $pdo->prepare("UPDATE users SET last_login_at = NOW() WHERE id = :id");
                    $up->execute([':id' => $data['id']]);
                    return $data;
                }
            }
        }
        setcookie('pusatchip_remember', '', time() - 3600, '/', '', isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on', true);
    }

    return null;
}

// PERBAIKAN: MENDUKUNG TRANSAKSI GUEST (JIKA TDK LOGIN, $currentUser BERISI NULL)
$currentUser = checkUserSession($pdo);
$isGuest     = ($currentUser === null);

/**
 * Helper: Mencatat Log Transaksi Penggunaan Saldo ke file log-transaksi.txt
 */
function logSaldoTransaction(array $logDetails): void {
    try {
        $logFile = __DIR__ . '/log-transaksi.txt';
        $timestamp = date('Y-m-d H:i:s') . ' WIB';

        $divider = str_repeat('=', 75);
        $logText  = "{$divider}\n";
        $logText .= "[LOG TRANSAKSI SALDO] - {$timestamp}\n";
        $logText .= "{$divider}\n";
        $logText .= "TRX ID        : " . ($logDetails['trx_id'] ?? '-') . "\n";
        $logText .= "REF ID        : " . ($logDetails['ref_id'] ?? '-') . "\n";
        $logText .= "PEMBELI       : " . ($logDetails['user_info'] ?? 'GUEST') . "\n";
        $logText .= "PRODUK        : " . ($logDetails['product_name'] ?? '-') . " (Kode: " . ($logDetails['product_code'] ?? '-') . ")\n";
        $logText .= "TARGET NO     : " . ($logDetails['customer_no'] ?? '-') . "\n";
        $logText .= "HARGA JUAL    : Rp " . number_format((float)($logDetails['total_price'] ?? 0), 2, ',', '.') . "\n";
        $logText .= "HARGA VENDOR  : Rp " . number_format((float)($logDetails['harga_vendor'] ?? 0), 2, ',', '.') . "\n";
        $logText .= "VENDOR TUJUAN : " . strtoupper($logDetails['vendor'] ?? 'MANUAL') . "\n";
        $logText .= "STATUS LOG    : " . ($logDetails['status'] ?? 'PENDING') . "\n";
        $logText .= "CATATAN       : " . ($logDetails['message'] ?? '-') . "\n";
        
        if (!empty($logDetails['raw_response'])) {
            $raw = is_array($logDetails['raw_response']) ? json_encode($logDetails['raw_response'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) : $logDetails['raw_response'];
            $logText .= "RAW RESPONSE  :\n{$raw}\n";
        }
        $logText .= "{$divider}\n\n";

        @file_put_contents($logFile, $logText, FILE_APPEND | LOCK_EX);
    } catch (Exception $e) {
        // Abaikan error penulisan file log agar transaksi utama tidak gagal
    }
}

/**
 * Helper: Mengirimkan Notifikasi Transaksi ke Telegram Bot untuk Vendor "MANUAL"
 */
function sendTelegramManualNotification(PDO $pdo, array $trx, ?array $user, array $product, array $paymentMethod): void {
    try {
        $stmtVM = $pdo->prepare("SELECT chat_id, bot_token FROM vendor_manual WHERE status = 1 LIMIT 1");
        $stmtVM->execute();
        $vm = $stmtVM->fetch();

        if ($vm && !empty($vm['bot_token']) && !empty($vm['chat_id'])) {
            $usernameText = $user ? $user['username'] . " (ID: " . $user['id'] . " - " . strtoupper($user['user_type']) . ")" : "GUEST (Tanpa Akun - WA: " . ($trx['guest_phone'] ?? '-') . ")";
            
            $msg  = "Halo, ada transaksi baru\n\n";
            $msg .= "TRX ID: " . $trx['trx_id'] . "\n";
            $msg .= "REFID: " . ($trx['ref_id'] ?? $trx['trx_id']) . "\n";
            $msg .= "Pembeli: " . $usernameText . "\n";
            $msg .= "Produk: " . $product['nama_produk'] . "\n";
            $msg .= "Customer No: `" . $trx['customer_no'] . "`\n";
            $msg .= "Harga jual: Rp " . number_format((float)$trx['harga_jual'], 0, ',', '.') . "\n";
            $msg .= "Metode Bayar: " . $paymentMethod['nama_metode'] . "\n";
            $msg .= "Status Payment: " . strtoupper($trx['status_payment']) . "\n";
            $msg .= "Status Order: " . strtoupper($trx['status_order']) . "\n";
            $msg .= "Waktu: " . date('Y-m-d H:i:s') . " WIB";

            // INLINE KEYBOARD (TOMBOL KONFIRMASI DAN TOLAK)
            $inlineKeyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => 'Konfirmasi', 'callback_data' => 'confirm_' . $trx['trx_id']],
                        ['text' => 'Tolak', 'callback_data' => 'reject_' . $trx['trx_id']]
                    ]
                ]
            ];

            $url = "https://api.telegram.org/bot" . $vm['bot_token'] . "/sendMessage";
            $postData = [
                'chat_id'      => $vm['chat_id'],
                'text'         => $msg,
                'parse_mode'   => 'Markdown',
                'reply_markup' => json_encode($inlineKeyboard)
            ];

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 8);
            curl_exec($ch);
            curl_close($ch);
        }
    } catch (Exception $e) {
        // Abaikan error cURL agar transaksi tetap berjalan lancar
    }
}

/**
 * Helper: Memproses Transaksi ke Vendor SABASTORE via API
 */
function processSabastoreTransaction(PDO $pdo, array $trx, array $product): array {
    try {
        $stmt = $pdo->query("SELECT member_code, api_key, status FROM vendor_sabastore WHERE status = 1 LIMIT 1");
        $saba = $stmt->fetch();

        if (!$saba || empty($saba['member_code']) || empty($saba['api_key'])) {
            return ['status' => false, 'message' => 'Sistem penyedia Sabastore sedang mengalami pemeliharaan rutin.', 'raw_response' => 'Config Sabastore kosong/nonaktif'];
        }

        $memberCode  = $saba['member_code'];
        $apiKey      = $saba['api_key'];
        $productCode = !empty($product['kode_produk_vendor']) ? $product['kode_produk_vendor'] : $product['kode_produk'];
        $refId       = !empty($trx['ref_id']) ? $trx['ref_id'] : $trx['trx_id'];
        $customerNo  = $trx['customer_no'];

        // Formula Signature API Sabastore: SHA256(member_code + api_key + ref_id)
        $sign = hash('sha256', $memberCode . $apiKey . $refId);

        $payload = [
            'member_code'  => $memberCode,
            'product_code' => $productCode,
            'customer_no'  => $customerNo,
            'ref_id'       => $refId,
            'sign'         => $sign
        ];

        $ch = curl_init('https://api.sabastore.top/v1/transaksi');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        $response = curl_exec($ch);
        $curlErr  = curl_error($ch);
        curl_close($ch);

        if ($curlErr) {
            return ['status' => false, 'message' => 'Gagal terhubung ke penyedia layanan Sabastore.', 'raw_response' => $curlErr];
        }

        $resData = json_decode($response, true);
        if (isset($resData['status_code']) && (int)$resData['status_code'] === 200 && ($resData['status'] ?? '') === 'success') {
            return ['status' => true, 'data' => $resData['data'] ?? [], 'raw_response' => $response];
        } else {
            $msg = $resData['message'] ?? 'Terjadi kendala saat memproses pesanan otomatis di Sabastore.';
            return ['status' => false, 'message' => 'Pesanan gagal dipproses Sabastore: ' . htmlspecialchars($msg), 'raw_response' => $response];
        }
    } catch (Exception $e) {
        return ['status' => false, 'message' => 'Terjadi kesalahan sistem internal pemrosesan Sabastore.', 'raw_response' => $e->getMessage()];
    }
}

/**
 * Helper: Memproses Transaksi ke Vendor WARTOPCOIN via API
 */
function processWartopcoinTransaction(PDO $pdo, array $trx, array $product): array {
    try {
        $stmt = $pdo->query("SELECT member_code, api_key, status FROM vendor_wartopcoin WHERE status = 1 LIMIT 1");
        $wtc = $stmt->fetch();

        if (!$wtc || empty($wtc['member_code']) || empty($wtc['api_key'])) {
            return ['status' => false, 'message' => 'Sistem penyedia Wartopcoin sedang tidak tersedia atau dalam pemeliharaan.', 'raw_response' => 'Config Wartopcoin kosong/nonaktif'];
        }

        $memberCode  = $wtc['member_code'];
        $apiKey      = $wtc['api_key'];
        $productCode = !empty($product['kode_produk_vendor']) ? $product['kode_produk_vendor'] : $product['kode_produk'];
        $refId       = !empty($trx['ref_id']) ? $trx['ref_id'] : $trx['trx_id'];
        $customerNo  = $trx['customer_no'];

        // Formula Signature API Wartopcoin: sha256(member_code + apikey + ref_id)
        $signature = hash('sha256', $memberCode . $apiKey . $refId);

        $payload = [
            'member_code'  => $memberCode,
            'ref_id'       => $refId,
            'product_code' => $productCode,
            'customer_no'  => $customerNo,
            'signature'    => $signature
        ];

        $ch = curl_init('https://wartopcoin.com/api/transaksi');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        $response = curl_exec($ch);
        $curlErr  = curl_error($ch);
        curl_close($ch);

        if ($curlErr) {
            return ['status' => false, 'message' => 'Gagal terhubung ke penyedia layanan Wartopcoin: ' . $curlErr, 'raw_response' => $curlErr];
        }

        $resData = json_decode($response, true);
        if (isset($resData['status']) && $resData['status'] === 'success') {
            return ['status' => true, 'data' => $resData['data'] ?? [], 'raw_response' => $response];
        } else {
            $msg = $resData['message'] ?? 'Terjadi kesalahan saat memproses transaksi di Wartopcoin.';
            return ['status' => false, 'message' => 'Pesanan gagal dipproses Wartopcoin: ' . htmlspecialchars($msg), 'raw_response' => $response];
        }
    } catch (Exception $e) {
        return ['status' => false, 'message' => 'Terjadi kesalahan sistem internal pemrosesan Wartopcoin.', 'raw_response' => $e->getMessage()];
    }
}

/**
 * PENANGANAN SELURUH ENDPOINT AJAX SIKLUS (METODE POST)
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax'])) {
    header('Content-Type: application/json');
    $ajaxAction = trim($_POST['ajax']);

    // 1. AJAX: GET NOTIFICATIONS
    if ($ajaxAction === 'get_notifications') {
        if ($isGuest || !$currentUser) {
            echo json_encode(['status' => 'error', 'message' => 'Silahkan login terlebih dahulu.']);
            exit;
        }

        $stmtNotif = $pdo->prepare("
            SELECT id, judul, pesan, type, icon, url, is_read, created_at 
            FROM notifications 
            WHERE user_id = :user_id 
            ORDER BY id DESC 
            LIMIT 15
        ");
        $stmtNotif->execute([':user_id' => $currentUser['id']]);
        $notifications = $stmtNotif->fetchAll();

        $upNotif = $pdo->prepare("UPDATE notifications SET is_read = 1, read_at = NOW() WHERE user_id = :user_id AND is_read = 0");
        $upNotif->execute([':user_id' => $currentUser['id']]);

        echo json_encode(['status' => 'success', 'notifications' => $notifications]);
        exit;
    }

    // 2. AJAX: GET BRAND DETAIL
    if ($ajaxAction === 'get_brand_detail') {
        $brandSlug = trim($_POST['slug'] ?? '');
        $brandId   = (int)($_POST['brand_id'] ?? 0);

        if ($brandId > 0) {
            $stmtB = $pdo->prepare("SELECT b.*, c.nama_kategori FROM brands b LEFT JOIN categories c ON b.category_id = c.id WHERE b.id = :id AND b.status = 1 LIMIT 1");
            $stmtB->execute([':id' => $brandId]);
        } else {
            $stmtB = $pdo->prepare("SELECT b.*, c.nama_kategori FROM brands b LEFT JOIN categories c ON b.category_id = c.id WHERE b.slug = :slug AND b.status = 1 LIMIT 1");
            $stmtB->execute([':slug' => $brandSlug]);
        }

        $brand = $stmtB->fetch();

        if (!$brand) {
            echo json_encode(['status' => 'error', 'message' => 'Brand tidak ditemukan.']);
            exit;
        }

        $stmtT = $pdo->prepare("SELECT id, brand_id, nama_type, slug, img_url FROM types WHERE brand_id = :brand_id AND status = 1 ORDER BY urutan ASC, id ASC");
        $stmtT->execute([':brand_id' => $brand['id']]);
        $types = $stmtT->fetchAll();

        $stmtP = $pdo->prepare("SELECT id, brand_id, type_id, nama_produk, harga_modal, harga_umum, harga_reseller, img_url, kode_produk, kode_produk_vendor, vendor, deskripsi FROM products WHERE brand_id = :brand_id AND status = 1 ORDER BY harga_umum ASC");
        $stmtP->execute([':brand_id' => $brand['id']]);
        $products = $stmtP->fetchAll();

        $stmtPm = $pdo->prepare("
            SELECT id, nama_metode, slug, kategori, provider, kode_channel, img_url, biaya_admin, biaya_persen, minimal_nominal, maksimal_nominal, is_populer, urutan 
            FROM payment_methods 
            WHERE status = 1 AND digunakan_untuk IN ('transaksi', 'semua') 
            ORDER BY urutan ASC, nama_metode ASC
        ");
        $stmtPm->execute();
        $paymentMethods = $stmtPm->fetchAll();

        echo json_encode([
            'status'          => 'success',
            'brand'           => $brand,
            'types'           => $types,
            'products'        => $products,
            'payment_methods' => $paymentMethods,
            'user_type'       => $currentUser['user_type'] ?? 'umum',
            'is_guest'        => $isGuest
        ]);
        exit;
    }

    // 3. AJAX: CREATE ORDER (PROSES PEMBUATAN TRANSAKSI BARU)
    if ($ajaxAction === 'create_order') {
        $productId       = (int)($_POST['product_id'] ?? 0);
        $paymentMethodId = (int)($_POST['payment_method_id'] ?? 0);
        $userIdTarget    = trim($_POST['user_id_target'] ?? '');
        $zoneIdTarget    = trim($_POST['zone_id_target'] ?? '');
        $guestPhone      = trim($_POST['guest_phone'] ?? '');

        if ($productId <= 0 || $paymentMethodId <= 0 || empty($userIdTarget)) {
            echo json_encode(['status' => 'error', 'message' => 'Lengkapi seluruh data pesanan Anda!']);
            exit;
        }

        // PEMERIKSAAN WAJIB NOMOR WHATSAPP UNTUK GUEST
        if ($isGuest && empty($guestPhone)) {
            echo json_encode(['status' => 'error', 'message' => 'Pengguna Guest wajib memasukkan nomor WhatsApp aktif!']);
            exit;
        }

        $customerNo = !empty($zoneIdTarget) ? $userIdTarget . ' (' . $zoneIdTarget . ')' : $userIdTarget;

        try {
            $pdo->beginTransaction();

            $userData = null;
            if ($currentUser) {
                $stmtUser = $pdo->prepare("SELECT id, saldo, username, user_type FROM users WHERE id = :id LIMIT 1 FOR UPDATE");
                $stmtUser->execute([':id' => $currentUser['id']]);
                $userData = $stmtUser->fetch();
            }

            $stmtP = $pdo->prepare("SELECT * FROM products WHERE id = :id AND status = 1 LIMIT 1 FOR UPDATE");
            $stmtP->execute([':id' => $productId]);
            $product = $stmtP->fetch();

            if (!$product) {
                $pdo->rollBack();
                echo json_encode(['status' => 'error', 'message' => 'Produk yang dipilih tidak ditemukan atau nonaktif.']);
                exit;
            }

            // PERIKSA VENDOR YANG DIDUKUNG (MANUAL, SABASTORE, WARTOPCOIN)
            if ($product['vendor'] !== 'manual' && $product['vendor'] !== 'sabastore' && $product['vendor'] !== 'wartopcoin') {
                $pdo->rollBack();
                echo json_encode(['status' => 'error', 'message' => 'Layanan untuk produk ini sedang dalam pemeliharaan (maintenance). Silahkan pilih produk lain.']);
                exit;
            }

            $stmtPM = $pdo->prepare("SELECT * FROM payment_methods WHERE id = :id AND status = 1 LIMIT 1");
            $stmtPM->execute([':id' => $paymentMethodId]);
            $paymentMethod = $stmtPM->fetch();

            if (!$paymentMethod) {
                $pdo->rollBack();
                echo json_encode(['status' => 'error', 'message' => 'Metode pembayaran tidak valid.']);
                exit;
            }

            $isSaldoPayment = ($paymentMethod['kategori'] === 'saldo' || $paymentMethod['slug'] === 'saldo');

            if ($isGuest && $isSaldoPayment) {
                $pdo->rollBack();
                echo json_encode(['status' => 'error', 'message' => 'Pengguna Guest tidak dapat menggunakan pembayaran saldo. Silahkan login terlebih dahulu atau pilih metode pembayaran lain.']);
                exit;
            }

            $userType = $userData['user_type'] ?? 'umum';
            if ($userType === 'reseller') {
                $basePrice = (float)$product['harga_reseller'];
            } else {
                $basePrice = (float)$product['harga_umum'];
            }

            $feeAdmin   = (float)$paymentMethod['biaya_admin'];
            $feePersen  = (float)$paymentMethod['biaya_persen'];
            $totalPrice = $basePrice + $feeAdmin + ($basePrice * ($feePersen / 100));

            // AMBIL PREFIX DARI SITE_SETTINGS DATABASE
            $trxPrefix = !empty($siteSettings['trx_id_prefix']) ? $siteSettings['trx_id_prefix'] : 'TRX';
            $refPrefix = !empty($siteSettings['ref_id_prefix']) ? $siteSettings['ref_id_prefix'] : 'REF';

            // GENERATE TRX ID DAN REF ID MENGGUNAKAN PREFIX
            $trxId = $trxPrefix . date('YmdHis') . strtoupper(substr(bin2hex(random_bytes(3)), 0, 4));
            $refId = $refPrefix . date('YmdHis') . strtoupper(substr(bin2hex(random_bytes(3)), 0, 4));

            $statusPayment = 'pending';
            $statusOrder   = 'pending'; // Status Order WAJIB Tetap 'pending' Sesuai ENUM SQL

            if ($isSaldoPayment) {
                $userSaldoBefore = (float)$userData['saldo'];

                if ($userSaldoBefore < $totalPrice) {
                    $pdo->rollBack();
                    echo json_encode([
                        'status'  => 'error',
                        'message' => 'Saldo akun Anda tidak mencukupi! Sisa Saldo: Rp ' . number_format($userSaldoBefore, 0, ',', '.') . ', Total Bayar: Rp ' . number_format($totalPrice, 0, ',', '.')
                    ]);
                    exit;
                }

                $userSaldoAfter = $userSaldoBefore - $totalPrice;
                $updateSaldo = $pdo->prepare("UPDATE users SET saldo = :saldo WHERE id = :id");
                $updateSaldo->execute([':saldo' => $userSaldoAfter, ':id' => $currentUser['id']]);

                $insertMutation = $pdo->prepare("
                    INSERT INTO balance_mutations (user_id, tipe, kategori, ref_id, saldo_sebelum, nominal, saldo_sesudah, keterangan)
                    VALUES (:user_id, 'debit', 'transaksi', :ref_id, :saldo_sebelum, :nominal, :saldo_sesudah, :keterangan)
                ");
                $insertMutation->execute([
                    ':user_id'       => $currentUser['id'],
                    ':ref_id'        => $trxId,
                    ':saldo_sebelum' => $userSaldoBefore,
                    ':nominal'       => $totalPrice,
                    ':saldo_sesudah' => $userSaldoAfter,
                    ':keterangan'    => 'Pembelian ' . $product['nama_produk'] . ' (' . $customerNo . ')'
                ]);

                $statusPayment = 'sukses';
            }

            // SIMPAN DATA TRANSAKSI
            $insertTrx = $pdo->prepare("
                INSERT INTO transactions (user_id, payment_method_id, product_id, transaction_type, trx_id, ref_id, customer_no, guest_phone, harga_jual, harga_vendor, status_payment, status_order, ordered_at)
                VALUES (:user_id, :payment_method_id, :product_id, 'reguler', :trx_id, :ref_id, :customer_no, :guest_phone, :harga_jual, :harga_vendor, :status_payment, :status_order, NOW())
            ");
            $insertTrx->execute([
                ':user_id'           => $currentUser ? $currentUser['id'] : null,
                ':payment_method_id' => $paymentMethod['id'],
                ':product_id'        => $product['id'],
                ':trx_id'            => $trxId,
                ':ref_id'            => $refId,
                ':customer_no'       => $customerNo,
                ':guest_phone'       => $isGuest ? $guestPhone : null,
                ':harga_jual'        => $totalPrice,
                ':harga_vendor'      => $product['harga_modal'],
                ':status_payment'    => $statusPayment,
                ':status_order'      => $statusOrder
            ]);

            $trxData = [
                'trx_id'         => $trxId,
                'ref_id'         => $refId,
                'customer_no'    => $customerNo,
                'guest_phone'    => $isGuest ? $guestPhone : null,
                'harga_jual'     => $totalPrice,
                'status_payment' => $statusPayment,
                'status_order'   => $statusOrder
            ];

            // KONEKSI LANGSUNG VENDOR HANYA JIKA METODE PEMBAYARAN SALDO
            if ($isSaldoPayment) {
                $vendorResponse = null;
                $vendorMessage  = 'Transaksi berhasil dikirim ke vendor.';

                if ($product['vendor'] === 'wartopcoin') {
                    $wtcRes = processWartopcoinTransaction($pdo, $trxData, $product);
                    $vendorResponse = $wtcRes['raw_response'] ?? null;
                    if (!$wtcRes['status']) {
                        $pdo->rollBack();

                        // SIMPAN LOG KETIKA GAGAL TRANSAKSI VENDOR SALDO
                        logSaldoTransaction([
                            'trx_id'       => $trxId,
                            'ref_id'       => $refId,
                            'user_info'    => $currentUser ? ($currentUser['username'] . " (ID: {$currentUser['id']})") : 'GUEST',
                            'product_name' => $product['nama_produk'],
                            'product_code' => $product['kode_produk'],
                            'customer_no'  => $customerNo,
                            'total_price'  => $totalPrice,
                            'harga_vendor' => $product['harga_modal'],
                            'vendor'       => 'WARTOPCOIN',
                            'status'       => 'GAGAL',
                            'message'      => $wtcRes['message'],
                            'raw_response' => $vendorResponse
                        ]);

                        echo json_encode(['status' => 'error', 'message' => $wtcRes['message']]);
                        exit;
                    }
                } elseif ($product['vendor'] === 'sabastore') {
                    $sabaRes = processSabastoreTransaction($pdo, $trxData, $product);
                    $vendorResponse = $sabaRes['raw_response'] ?? null;
                    if (!$sabaRes['status']) {
                        $pdo->rollBack();

                        // SIMPAN LOG KETIKA GAGAL TRANSAKSI VENDOR SALDO
                        logSaldoTransaction([
                            'trx_id'       => $trxId,
                            'ref_id'       => $refId,
                            'user_info'    => $currentUser ? ($currentUser['username'] . " (ID: {$currentUser['id']})") : 'GUEST',
                            'product_name' => $product['nama_produk'],
                            'product_code' => $product['kode_produk'],
                            'customer_no'  => $customerNo,
                            'total_price'  => $totalPrice,
                            'harga_vendor' => $product['harga_modal'],
                            'vendor'       => 'SABASTORE',
                            'status'       => 'GAGAL',
                            'message'      => $sabaRes['message'],
                            'raw_response' => $vendorResponse
                        ]);

                        echo json_encode(['status' => 'error', 'message' => $sabaRes['message']]);
                        exit;
                    }
                } elseif ($product['vendor'] === 'manual') {
                    sendTelegramManualNotification($pdo, $trxData, $userData, $product, $paymentMethod);
                    $vendorMessage = 'Notifikasi Telegram Vendor Manual terkirim.';
                }

                // SIMPAN LOG KETIKA SUKSES TRANSAKSI VENDOR SALDO
                logSaldoTransaction([
                    'trx_id'       => $trxId,
                    'ref_id'       => $refId,
                    'user_info'    => $currentUser ? ($currentUser['username'] . " (ID: {$currentUser['id']})") : 'GUEST',
                    'product_name' => $product['nama_produk'],
                    'product_code' => $product['kode_produk'],
                    'customer_no'  => $customerNo,
                    'total_price'  => $totalPrice,
                    'harga_vendor' => $product['harga_modal'],
                    'vendor'       => strtoupper($product['vendor']),
                    'status'       => 'BERHASIL DIPROSES / PENDING VENDOR',
                    'message'      => $vendorMessage,
                    'raw_response' => $vendorResponse
                ]);
            }

            $pdo->commit();

            echo json_encode([
                'status'   => 'success',
                'message'  => 'Pesanan berhasil dibuat!',
                'redirect' => 'detail-transaksi.php?trx_id=' . $trxId
            ]);
            exit;

        } catch (Exception $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            echo json_encode(['status' => 'error', 'message' => 'Terjadi kesalahan sistem saat membuat transaksi: ' . $e->getMessage()]);
            exit;
        }
    }
}

// 2. AMBIL KATEGORI DARI DATABASE (categories)
$stmtCat = $pdo->query("SELECT id, nama_kategori, slug, img_url FROM categories WHERE status = 1 ORDER BY id ASC");
$categories = $stmtCat->fetchAll();

// 3. AMBIL BRAND DARI DATABASE (brands)
$stmtBrand = $pdo->query("
    SELECT b.id, b.category_id, b.nama_brand, b.slug, b.is_populer, b.img_url, b.keterangan, c.nama_kategori 
    FROM brands b 
    LEFT JOIN categories c ON b.category_id = c.id 
    WHERE b.status = 1 
    ORDER BY b.is_populer DESC, b.nama_brand ASC
");
$brands = $stmtBrand->fetchAll();

// 4. AMBIL BANNER SLIDER DARI DATABASE (banners)
$targetUserVal = $isGuest ? 'guest' : ($currentUser['user_type'] ?? 'umum');
$stmtBanner = $pdo->prepare("
    SELECT id, judul, deskripsi, gambar_url, link_url 
    FROM banners 
    WHERE status = 'aktif' 
      AND posisi = 'slider' 
      AND target_user IN ('all', :target_user)
      AND (tanggal_mulai IS NULL OR tanggal_mulai <= NOW())
      AND (tanggal_selesai IS NULL OR tanggal_selesai >= NOW())
    ORDER BY urutan ASC, id DESC
");
$stmtBanner->execute([':target_user' => $targetUserVal]);
$banners = $stmtBanner->fetchAll();

// 5. AMBIL JUMLAH NOTIFIKASI BELUM DIBACA (JIKA LOGIN)
$unreadNotifCount = 0;
if (!$isGuest && $currentUser) {
    $stmtUnread = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = :user_id AND is_read = 0");
    $stmtUnread->execute([':user_id' => $currentUser['id']]);
    $unreadNotifCount = (int)$stmtUnread->fetchColumn();
}

// 6. AMBIL AKTIVITAS TRANSAKSI TERAKHIR DARI DATABASE (transactions) UNTUK USER LOGIN
$recentTransactions = [];
if (!$isGuest && $currentUser) {
    $stmtTrx = $pdo->prepare("
        SELECT t.trx_id, t.ref_id, t.customer_no, t.status_payment, t.status_order, t.created_at, p.nama_produk 
        FROM transactions t 
        LEFT JOIN products p ON t.product_id = p.id 
        WHERE t.user_id = :user_id 
        ORDER BY t.id DESC 
        LIMIT 5
    ");
    $stmtTrx->execute([':user_id' => $currentUser['id']]);
    $recentTransactions = $stmtTrx->fetchAll();
}

// 7. AMBIL DATA FAQ DARI DATABASE (faqs) UNTUK TAMPILAN SECTION FAQ BERANDA
$stmtFaqs = $pdo->query("SELECT id, pertanyaan, jawaban, kategori, urutan FROM faqs WHERE status = 'aktif' ORDER BY urutan ASC, id ASC");
$faqs = $stmtFaqs->fetchAll();

// Inisial avatar user / Guest Initials
$userInitials = $currentUser ? strtoupper(substr($currentUser['username'], 0, 2)) : 'GT';

// Variabel Situs
$siteName  = htmlspecialchars($siteSettings['nama_website'] ?? 'PUSATCHIP');
$siteLogo  = !empty($siteSettings['logo_url']) ? htmlspecialchars($siteSettings['logo_url']) : 'https://via.placeholder.com/100';
$siteWaUrl = !empty($siteSettings['whatsapp_url']) ? htmlspecialchars($siteSettings['whatsapp_url']) : ('https://wa.me/' . htmlspecialchars($siteSettings['phone_number'] ?? '6281234567890'));
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    
    <title><?= $siteName ?> - Topup Game & Digital Ecosystem</title>
    <meta name="description" content="<?= htmlspecialchars($siteSettings['deskripsi'] ?? 'Platform top up game tercepat, termurah, dan terpercaya.') ?>">
    <?php if (!empty($siteSettings['favicon_url'])): ?>
        <link rel="shortcut icon" href="<?= htmlspecialchars($siteSettings['favicon_url']) ?>">
    <?php endif; ?>

    <!-- LINK CDN ICON TABLER ICONS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@latest/tabler-icons.min.css">
    <!-- FONT PREMIUM - OUTFIT -->
    <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=Outfit:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <style>
        :root {
            --bg: #f2f3f5;
            --surface: #ffffff;
            --surface-card: #ffffff;
            --glass: #ffffff;
            --glass-strong: #ffffff;
            --glass-border: transparent;
            --glass-border-heavy: rgba(0, 0, 0, 0.09);
            --premium-shadow: none;
            --soft-shadow: none;
            --inner-glow: none;
            --primary: #8a704c; 
            --accent: #a88b63; 
            --text-main: #222222; 
            --text-muted: #6b7280; 
            --gradient-gold: linear-gradient(135deg, #bfa074 0%, #9a7e56 100%);
            --gradient-surface: #ffffff;
            --danger: #d9534f;
            --success: #4ba373;
            --info: #4a77a5;
            --sidebar-width: 260px;
            --transition-premium: 200ms ease;
        }

        .preloader-container {
            position: fixed;
            top: 0; left: 0; width: 100%; height: 100%;
            background: var(--bg);
            display: flex; flex-direction: column;
            align-items: center; justify-content: center;
            z-index: 99999; opacity: 1; visibility: visible;
            transition: opacity 0.6s cubic-bezier(0.16, 1, 0.3, 1), visibility 0.6s ease;
        }

        .preloader-container.fade-out {
            opacity: 0; visibility: hidden;
        }

        .preloader-box { text-align: center; }

        .preloader-logo-ring {
            position: relative; width: 80px; height: 80px;
            margin: 0 auto 20px; display: flex; 
            align-items: center; justify-content: center;
        }

        .preloader-logo {
            width: 50px; height: 50px;
            background: var(--gradient-gold); color: #ffffff;
            border-radius: 12px; display: flex; 
            align-items: center; justify-content: center;
            font-size: 18px; font-weight: 800; z-index: 2;
            box-shadow: 0 8px 24px rgba(191, 160, 116, 0.35); overflow: hidden;
        }

        .preloader-logo img { width: 100%; height: 100%; object-fit: cover; }

        .preloader-ring {
            position: absolute; top: 0; left: 0; width: 100%; height: 100%;
            border: 3px solid var(--glass-border-heavy);
            border-top: 3px solid var(--primary);
            border-radius: 50%; animation: spinRing 1s linear infinite; z-index: 1;
        }

        .preloader-text {
            font-size: 11.5px; font-weight: 700; color: var(--primary);
            text-transform: uppercase; letter-spacing: 2px; margin-top: 10px;
        }

        .preloader-subtitle {
            font-size: 9px; color: var(--text-muted); margin-top: 4px; font-weight: 500;
        }

        @keyframes spinRing {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        * { 
            box-sizing: border-box; margin: 0; padding: 0; 
            font-family: 'Outfit', sans-serif; -webkit-tap-highlight-color: transparent; 
            letter-spacing: -0.01em; touch-action: manipulation;
        }
        
        body { 
            background: var(--bg); color: var(--text-main); font-size: 11px;
            padding-bottom: 90px; min-height: 100vh; display: flex; position: relative;
        }

        .admin-sidebar-premium {
            position: fixed; top: 12px; left: calc(-1 * var(--sidebar-width) - 20px);
            width: var(--sidebar-width); height: calc(100vh - 24px);
            background: var(--surface); border: none; border-radius: 8px; z-index: 9995;
            transition: transform var(--transition-premium), left var(--transition-premium);
            display: flex; flex-direction: column; padding: 20px 16px; will-change: left;
        }

        .admin-sidebar-premium.active { left: 12px; }

        .sidebar-brand-wrapper {
            display: flex; align-items: center; gap: 10px;
            padding-bottom: 16px; border: none; margin-bottom: 16px;
        }

        .sidebar-brand-logo {
            width: 32px; height: 32px; background: var(--primary); color: #ffffff;
            border-radius: 6px; display: flex; align-items: center; justify-content: center;
            font-size: 11px; font-weight: 800; overflow: hidden;
        }

        .sidebar-brand-logo img { width: 100%; height: 100%; object-fit: cover; }

        .sidebar-brand-info h2 {
            font-size: 12px; font-weight: 800; letter-spacing: -0.3px; color: var(--text-main);
        }

        .sidebar-brand-info p {
            font-size: 8px; color: var(--text-muted); text-transform: uppercase;
            letter-spacing: 0.8px; font-weight: 700; margin-top: 1px;
        }

        .sidebar-menu-navigation {
            display: flex; flex-direction: column; gap: 4px; flex-grow: 1;
        }

        .sidebar-menu-item {
            display: flex; align-items: center; gap: 10px; padding: 9px 12px;
            color: var(--text-muted); text-decoration: none; border-radius: 6px;
            font-size: 11px; font-weight: 600; transition: var(--transition-premium);
        }

        .sidebar-menu-item i {
            font-size: 16px; color: var(--text-muted); transition: var(--transition-premium);
        }

        .sidebar-menu-item:hover {
            background: #e9ecef; color: var(--text-main); padding-left: 14px;
        }

        .sidebar-menu-item.active { background: #e2e6ea; color: var(--text-main); }
        .sidebar-menu-item.active i { color: var(--primary); }

        .sidebar-footer-profile {
            display: flex; align-items: center; gap: 10px;
            padding-top: 14px; border-top: 1px solid #f0f0f0;
        }

        .sidebar-avatar-box {
            width: 30px; height: 30px; border-radius: 6px; background: #e2e6ea;
            display: flex; align-items: center; justify-content: center;
            color: var(--primary); font-weight: 700; font-size: 10px;
        }

        .sidebar-user-meta h4 { font-size: 11px; font-weight: 700; color: var(--text-main); }
        .sidebar-user-meta p { font-size: 9px; color: var(--text-muted); margin-top: 1px; }

        .sidebar-glass-overlay {
            position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
            background: rgba(0, 0, 0, 0.25); z-index: 9990; display: none;
        }

        .premium-layout-wrapper {
            width: 100%; position: relative; background: transparent;
            min-height: 100vh; padding: 0; transition: var(--transition-premium);
        }

        /* BANNER PWA DI PALING ATAS DI ATAS HEADER */
        .pwa-top-banner {
            background: linear-gradient(135deg, #2b2b2b 0%, #1a1a1a 100%);
            color: #ffffff; padding: 8px 16px; display: flex;
            align-items: center; justify-content: space-between; gap: 10px;
            z-index: 9999; font-size: 10.5px; font-weight: 600;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }

        .pwa-top-banner-content {
            display: flex; align-items: center; gap: 8px; flex: 1; overflow: hidden;
        }

        .pwa-banner-icon {
            font-size: 16px; color: #f3c26b; min-width: 18px;
        }

        .pwa-banner-text {
            white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #f0f0f0;
        }

        .pwa-banner-actions {
            display: flex; align-items: center; gap: 6px; flex-shrink: 0;
        }

        .btn-pwa-add {
            background: var(--gradient-gold); color: #ffffff; border: none;
            padding: 4px 12px; border-radius: 6px; font-size: 10px; font-weight: 800;
            cursor: pointer; transition: var(--transition-premium); outline: none;
        }

        .btn-pwa-add:hover { opacity: 0.9; }

        .btn-pwa-close {
            background: rgba(255, 255, 255, 0.1); color: #cccccc; border: none;
            width: 22px; height: 22px; border-radius: 50%; display: flex;
            align-items: center; justify-content: center; font-size: 12px;
            cursor: pointer; transition: var(--transition-premium);
        }

        .btn-pwa-close:hover { background: rgba(255, 255, 255, 0.25); color: #ffffff; }

        .dashboard-header {
            position: sticky; top: 0; left: 0; right: 0; z-index: 8000;
            background: var(--surface); padding: 10px 16px; border-radius: 0 0 8px 8px;
            display: flex; justify-content: space-between; align-items: center; margin: 0; width: 100%;
        }
        
        .user-profile-bar { display: flex; align-items: center; gap: 10px; }

        .btn-sidebar-trigger {
            background: var(--bg); border: none; color: var(--text-main);
            font-size: 16px; cursor: pointer; width: 32px; height: 32px;
            display: flex; align-items: center; justify-content: center;
            border-radius: 6px; transition: var(--transition-premium);
        }
        .btn-sidebar-trigger:hover { background: #e2e6ea; }

        .site-logo-img {
            width: 30px; height: 30px; background: var(--primary); color: #ffffff;
            border-radius: 6px; display: flex; align-items: center; justify-content: center;
            font-size: 10px; font-weight: 800; overflow: hidden;
        }

        .site-logo-img img { width: 100%; height: 100%; object-fit: cover; }

        .brand-text-header { font-size: 12px; font-weight: 800; color: var(--text-main); letter-spacing: -0.2px; }

        .header-right-actions { display: flex; align-items: center; gap: 8px; }

        .header-balance-box {
            display: flex; align-items: center; gap: 6px; background: var(--bg);
            padding: 4px 4px 4px 10px; border-radius: 8px; font-size: 10px;
            font-weight: 700; color: var(--text-main);
        }

        .header-balance-box i.ti-wallet { color: var(--primary); font-size: 18px; }

        .btn-header-deposit {
            background: var(--primary); color: #ffffff; border: none; width: 26px; height: 26px;
            border-radius: 6px; display: flex; align-items: center; justify-content: center;
            font-size: 14px; cursor: pointer; transition: var(--transition-premium);
            margin-left: 2px; text-decoration: none;
        }

        .btn-header-deposit:hover { background: var(--accent); }

        .btn-header-login {
            background: var(--primary); color: #ffffff; border: none; padding: 6px 12px;
            border-radius: 6px; font-size: 10.5px; font-weight: 700; display: flex;
            align-items: center; gap: 6px; text-decoration: none; transition: var(--transition-premium);
        }

        .btn-header-login:hover { background: var(--accent); color: #ffffff; }

        .btn-header-notif {
            background: var(--bg); border: none; color: var(--text-main); font-size: 16px;
            cursor: pointer; width: 32px; height: 32px; display: flex; align-items: center;
            justify-content: center; border-radius: 6px; transition: var(--transition-premium); position: relative;
        }
        .btn-header-notif:hover { background: #e2e6ea; color: var(--primary); }
        .notif-badge-dot {
            position: absolute; top: 6px; right: 6px; width: 6px; height: 6px;
            background: var(--danger); border-radius: 50%;
        }

        .main-content-container {
            width: 100%; padding: 12px; display: flex; flex-direction: column; gap: 4px;
        }

        .section-tag { 
            padding: 14px 2px 6px 2px; font-size: 10px; font-weight: 800; 
            color: var(--text-muted); letter-spacing: 0.8px; display: flex; align-items: center; gap: 8px;
        }
        .section-tag::after { content: ''; flex-grow: 1; height: 1px; background: #e2e6ea; }

        .banner-slider-container {
            width: 100%; position: relative; overflow: hidden; border-radius: 8px; margin-top: 2px;
        }

        .banner-slider-track { display: flex; transition: transform 0.4s ease-in-out; width: 100%; }

        .banner-slide { min-width: 100%; height: 130px; border-radius: 8px; overflow: hidden; }

        .banner-slide img { width: 100%; height: 100%; object-fit: cover; border-radius: 8px; display: block; }

        .banner-dots {
            position: absolute; bottom: 8px; left: 50%; transform: translateX(-50%);
            display: flex; gap: 4px; z-index: 10;
        }

        .banner-dots .dot {
            width: 6px; height: 6px; border-radius: 50%; background: rgba(255, 255, 255, 0.5);
            cursor: pointer; transition: var(--transition-premium);
        }

        .banner-dots .dot.active { background: #ffffff; width: 14px; border-radius: 4px; }

        .category-toggle-container {
            display: flex; align-items: center; gap: 6px; overflow-x: auto;
            white-space: nowrap; padding: 2px 0 6px 0; -webkit-overflow-scrolling: touch; scrollbar-width: none;
        }
        .category-toggle-container::-webkit-scrollbar { display: none; }

        .category-toggle-btn {
            display: flex; align-items: center; gap: 6px; background: var(--surface-card);
            border: none; padding: 7px 12px; border-radius: 6px; color: var(--text-muted);
            text-decoration: none; font-size: 10px; font-weight: 700; white-space: nowrap;
            transition: var(--transition-premium); cursor: pointer; flex-shrink: 0;
        }

        .category-toggle-btn i { font-size: 14px; color: var(--primary); transition: var(--transition-premium); }
        .category-toggle-btn:hover { background: #ffffff; color: var(--text-main); }
        .category-toggle-btn.active { background: var(--primary); color: #ffffff; }
        .category-toggle-btn.active i { color: #ffffff; }

        .game-cards-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; width: 100%; }

        .game-card {
            background: var(--surface-card); border: none; border-radius: 8px; overflow: hidden;
            text-decoration: none; color: var(--text-main); display: flex; flex-direction: column;
            transition: var(--transition-premium); position: relative; cursor: pointer;
        }

        .game-card:hover { transform: translateY(-2px); background: #ffffff; }

        .game-card-banner { width: 100%; height: 90px; position: relative; overflow: hidden; background: #e2e6ea; }

        .game-card-banner img { width: 100%; height: 100%; object-fit: cover; transition: transform 0.3s ease; }

        .game-card:hover .game-card-banner img { transform: scale(1.04); }

        .game-badge-fast {
            position: absolute; top: 6px; right: 6px; background: rgba(0, 0, 0, 0.65);
            color: #fff; padding: 2px 6px; border-radius: 4px; font-size: 7.5px;
            font-weight: 800; display: flex; align-items: center; gap: 3px;
        }

        .game-badge-fast i { color: #f3c26b; font-size: 9px; }

        .game-card-body { padding: 10px; display: flex; flex-direction: column; gap: 2px; }

        .game-card-title {
            font-size: 11px; font-weight: 800; color: var(--text-main);
            white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
        }

        .game-card-publisher {
            font-size: 8.5px; font-weight: 600; color: var(--text-muted);
            white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
        }

        .game-card-footer { display: flex; align-items: center; justify-content: space-between; margin-top: 4px; padding-top: 4px; }

        .game-card-status { font-size: 8.5px; font-weight: 700; color: var(--success); display: flex; align-items: center; gap: 3px; }

        .game-card-btn {
            width: 18px; height: 18px; border-radius: 4px; background: var(--bg);
            color: var(--primary); display: flex; align-items: center; justify-content: center;
            font-size: 11px; transition: var(--transition-premium);
        }

        .game-card:hover .game-card-btn { background: var(--primary); color: #fff; }

        /* FAQ ACCORDION STYLES */
        .faq-accordion-container { display: flex; flex-direction: column; gap: 8px; width: 100%; }

        .faq-accordion-item {
            background: var(--surface); border-radius: 8px; overflow: hidden;
            transition: var(--transition-premium); border: 1px solid #e2e6ea;
        }

        .faq-accordion-header {
            padding: 11px 14px; display: flex; align-items: center;
            justify-content: space-between; cursor: pointer; user-select: none;
            transition: var(--transition-premium); background: var(--surface);
        }

        .faq-accordion-header:hover { background: #f8f9fa; }

        .faq-accordion-header.active {
            border-bottom: 1px solid #e2e6ea; background: #fdfdfd;
        }

        .faq-accordion-title {
            font-size: 10.5px; font-weight: 700; color: var(--text-main);
            display: flex; align-items: center; gap: 8px;
        }

        .faq-accordion-title i { color: var(--primary); font-size: 15px; min-width: 16px; }

        .faq-accordion-icon {
            font-size: 15px; color: var(--text-muted); transition: transform 0.25s ease;
        }

        .faq-accordion-header.active .faq-accordion-icon {
            transform: rotate(180deg); color: var(--primary);
        }

        .faq-accordion-body {
            padding: 12px 14px; display: none; background: #fafafa;
            font-size: 10px; color: var(--text-muted); line-height: 1.5;
        }

        /* STYLE AKTIVITAS TOP UP TERAKHIR (PROFESIONAL & CLEAN CARD) */
        .history-list-wrapper { display: flex; flex-direction: column; gap: 10px; width: 100%; }

        .history-log-card-pro {
            background: var(--surface); border: 1px solid #e2e6ea; border-radius: 10px;
            padding: 12px 14px; display: flex; flex-direction: column; gap: 10px;
            transition: var(--transition-premium); cursor: pointer; position: relative;
        }

        .history-log-card-pro:hover {
            border-color: var(--primary); box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            transform: translateY(-1px);
        }

        .history-card-top {
            display: flex; justify-content: space-between; align-items: center;
            border-bottom: 1px dashed #e2e6ea; padding-bottom: 8px; font-size: 9.5px;
        }

        .history-trx-id {
            font-weight: 800; color: var(--primary); font-family: monospace; font-size: 10.5px;
            display: flex; align-items: center; gap: 4px;
        }

        .history-trx-id i { font-size: 13px; }

        .history-date { color: var(--text-muted); font-weight: 600; font-size: 9px; }

        .history-card-middle {
            display: flex; justify-content: space-between; align-items: flex-start; gap: 10px;
        }

        .history-prod-info h4 {
            font-size: 11px; font-weight: 800; color: var(--text-main); margin-bottom: 3px;
        }

        .history-customer-no { font-size: 9.5px; color: var(--text-muted); font-weight: 600; }
        .history-customer-no span { color: var(--text-main); font-weight: 700; font-family: monospace; }

        .history-badges-column {
            display: flex; flex-direction: column; align-items: flex-end; gap: 4px; shrink: 0;
        }

        .history-badge {
            font-size: 8px; font-weight: 800; padding: 3px 8px; border-radius: 4px;
            text-transform: uppercase; letter-spacing: 0.3px; white-space: nowrap;
        }

        .badge-pay-sukses { background: rgba(75, 163, 115, 0.12); color: #2e7d32; }
        .badge-pay-pending { background: rgba(234, 179, 8, 0.15); color: #854d0e; }
        .badge-pay-gagal, .badge-pay-refund { background: rgba(217, 83, 79, 0.12); color: #c62828; }

        .badge-order-sukses { background: rgba(75, 163, 115, 0.12); color: #2e7d32; }
        .badge-order-diproses { background: rgba(138, 112, 76, 0.15); color: #8a704c; }
        .badge-order-pending { background: rgba(234, 179, 8, 0.15); color: #854d0e; }
        .badge-order-gagal { background: rgba(217, 83, 79, 0.12); color: #c62828; }

        .history-pending-notice {
            background: #fffbeb; border: 1px solid #fef08a; color: #b45309;
            font-size: 9.5px; font-weight: 700; padding: 7px 10px; border-radius: 6px;
            display: flex; align-items: center; gap: 6px; margin-top: 2px;
        }

        .history-pending-notice i { font-size: 14px; color: #d97706; }

        #view-order { display: none; flex-direction: column; gap: 12px; width: 100%; padding-bottom: 20px; }

        .btn-back-home {
            display: inline-flex; align-items: center; gap: 6px; background: var(--surface);
            border: none; padding: 8px 14px; border-radius: 6px; font-size: 11px;
            font-weight: 700; color: var(--text-main); cursor: pointer; transition: var(--transition-premium);
            align-self: flex-start; margin-bottom: 14px; text-decoration: none;
        }

        .btn-back-home:hover { background: #e2e6ea; color: var(--primary); }

        .order-brand-header {
            background: var(--surface); border-radius: 8px; padding: 14px 16px;
            display: flex; align-items: center; gap: 14px;
        }

        .order-brand-img { width: 64px; height: 64px; min-width: 64px; border-radius: 8px; overflow: hidden; background: #e2e6ea; }

        .order-brand-img img { width: 100%; height: 100%; object-fit: cover; }

        .order-brand-info h2 { font-size: 14px; font-weight: 800; color: var(--text-main); }

        .order-brand-info p { font-size: 9.5px; color: var(--text-muted); margin-top: 2px; line-height: 1.35; }

        .order-step-card {
            background: var(--surface); border-radius: 8px; padding: 14px 16px;
            display: flex; flex-direction: column; gap: 12px;
        }

        .order-step-title { font-size: 11px; font-weight: 800; color: var(--text-main); display: flex; align-items: center; gap: 8px; }

        .order-step-num {
            width: 20px; height: 20px; background: var(--primary); color: #ffffff;
            border-radius: 50%; display: flex; align-items: center; justify-content: center;
            font-size: 9.5px; font-weight: 800;
        }

        .order-form-input {
            width: 100%; height: 40px; background: var(--bg); border: 1px solid transparent;
            border-radius: 6px; padding: 0 12px; font-size: 11px; font-weight: 600;
            color: var(--text-main); outline: none; transition: var(--transition-premium);
        }

        .order-form-input:focus { background: #ffffff; border-color: var(--primary); }

        .btn-check-id {
            background: var(--primary); color: #ffffff; border: none; padding: 0 14px;
            height: 40px; border-radius: 6px; font-size: 10px; font-weight: 800; cursor: pointer;
            display: inline-flex; align-items: center; gap: 4px; transition: var(--transition-premium); white-space: nowrap;
        }

        .btn-check-id:hover { background: var(--accent); }

        .product-types-tab-container {
            display: flex; gap: 6px; overflow-x: auto; white-space: nowrap; padding-bottom: 4px; scrollbar-width: none;
        }
        .product-types-tab-container::-webkit-scrollbar { display: none; }

        .product-type-btn {
            background: var(--bg); border: none; padding: 6px 12px; border-radius: 6px;
            font-size: 10px; font-weight: 700; color: var(--text-muted); cursor: pointer;
            transition: var(--transition-premium); flex-shrink: 0;
        }

        .product-type-btn.active { background: var(--primary); color: #ffffff; }

        .products-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; }

        .product-item-card {
            background: var(--bg); border: 1.5px solid transparent; border-radius: 8px;
            padding: 10px 12px; cursor: pointer; transition: var(--transition-premium);
            display: flex; align-items: center; gap: 10px;
        }

        .product-item-card:hover, .product-item-card.selected { background: #ffffff; border-color: var(--primary); }

        .product-item-icon-box {
            width: 32px; height: 32px; min-width: 32px; border-radius: 6px;
            background: #ffffff; display: flex; align-items: center; justify-content: center;
            overflow: hidden; border: 1px solid #e2e6ea; color: var(--primary); font-size: 16px;
        }

        .product-item-icon-box img { width: 100%; height: 100%; object-fit: cover; }

        .product-item-meta { display: flex; flex-direction: column; gap: 2px; flex-grow: 1; overflow: hidden; }

        .product-item-title { font-size: 10.5px; font-weight: 700; color: var(--text-main); line-height: 1.3; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

        .product-item-price { font-size: 11px; font-weight: 800; color: var(--primary); }

        .payment-accordion-container { display: flex; flex-direction: column; gap: 8px; }

        .payment-accordion-item {
            background: var(--bg); border: 1px solid #e2e6ea; border-radius: 8px;
            overflow: hidden; transition: var(--transition-premium);
        }

        .payment-accordion-header {
            padding: 12px 14px; background: var(--surface); display: flex;
            align-items: center; justify-content: space-between; cursor: pointer;
            user-select: none; transition: var(--transition-premium);
        }

        .payment-accordion-header:hover { background: #f8f9fa; }
        .payment-accordion-header.active { border-bottom: 1px solid #e2e6ea; }

        .payment-accordion-title { font-size: 11px; font-weight: 800; color: var(--text-main); display: flex; align-items: center; gap: 8px; }
        .payment-accordion-title i { color: var(--primary); font-size: 16px; }

        .payment-accordion-icon { font-size: 16px; color: var(--text-muted); transition: transform 0.25s ease; }
        .payment-accordion-header.active .payment-accordion-icon { transform: rotate(180deg); color: var(--primary); }

        .payment-accordion-body { padding: 10px; display: none; background: var(--bg); }

        .payment-methods-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; }

        .payment-card {
            background: var(--surface); border: 1.5px solid transparent; border-radius: 8px;
            padding: 8px 10px; cursor: pointer; display: flex; align-items: center;
            justify-content: space-between; gap: 8px; transition: var(--transition-premium);
        }

        .payment-card:hover, .payment-card.selected { background: #ffffff; border-color: var(--primary); }

        .payment-card.disabled-guest { opacity: 0.55; cursor: not-allowed; background: #f5f5f5; }

        .payment-card-left { display: flex; align-items: center; gap: 8px; overflow: hidden; }

        .payment-card-logo {
            width: 28px; height: 28px; min-width: 28px; border-radius: 4px;
            background: #ffffff; display: flex; align-items: center; justify-content: center;
            overflow: hidden; border: 1px solid #e2e6ea;
        }

        .payment-card-logo img { width: 100%; height: 100%; object-fit: contain; }

        .payment-card-name { font-size: 10px; font-weight: 700; color: var(--text-main); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

        .payment-card-fee { font-size: 8.5px; font-weight: 700; color: var(--text-muted); white-space: nowrap; }

        .btn-submit-order {
            width: 100%; height: 42px; background: var(--primary); color: #ffffff;
            border: none; border-radius: 6px; font-size: 11px; font-weight: 800; cursor: pointer;
            display: flex; align-items: center; justify-content: center; gap: 6px; transition: var(--transition-premium);
        }

        .btn-submit-order:hover { background: var(--accent); }

        .modal-overlay {
            position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
            background: rgba(0, 0, 0, 0.45); z-index: 99990; display: none;
            align-items: center; justify-content: center; padding: 16px;
        }

        .modal-overlay.active { display: flex; }

        .modal-box-card {
            background: var(--surface); border-radius: 12px; width: 100%; max-width: 440px;
            padding: 18px 20px; display: flex; flex-direction: column; gap: 14px;
            animation: modalPop 0.25s cubic-bezier(0.16, 1, 0.3, 1);
        }

        @keyframes modalPop {
            0% { transform: scale(0.92); opacity: 0; }
            100% { transform: scale(1); opacity: 1; }
        }

        .modal-header { display: flex; align-items: center; justify-content: space-between; padding-bottom: 10px; border-bottom: 1px solid #e2e6ea; }

        .modal-title { font-size: 13px; font-weight: 800; color: var(--text-main); display: flex; align-items: center; gap: 6px; }

        .modal-close-btn {
            background: var(--bg); border: none; width: 26px; height: 26px; border-radius: 6px;
            display: flex; align-items: center; justify-content: center; color: var(--text-muted); cursor: pointer; font-size: 14px;
        }

        .modal-close-btn:hover { color: var(--text-main); }

        .confirm-detail-list { display: flex; flex-direction: column; gap: 8px; background: var(--bg); padding: 12px; border-radius: 8px; }

        .confirm-detail-row { display: flex; justify-content: space-between; align-items: center; font-size: 10.5px; }

        .confirm-detail-label { color: var(--text-muted); font-weight: 600; }

        .confirm-detail-val { color: var(--text-main); font-weight: 800; text-align: right; }

        .confirm-detail-total { border-top: 1px dashed #ccc; padding-top: 6px; margin-top: 2px; }

        .confirm-detail-total .confirm-detail-val { color: var(--primary); font-size: 12px; }

        .modal-actions-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-top: 2px; }

        .btn-modal-cancel {
            background: var(--bg); color: var(--text-main); border: none; height: 38px;
            border-radius: 6px; font-size: 10.5px; font-weight: 700; cursor: pointer; transition: var(--transition-premium);
        }

        .btn-modal-cancel:hover { background: #e2e6ea; }

        .btn-modal-confirm {
            background: var(--primary); color: #ffffff; border: none; height: 38px;
            border-radius: 6px; font-size: 10.5px; font-weight: 800; cursor: pointer;
            transition: var(--transition-premium); display: flex; align-items: center; justify-content: center; gap: 6px;
        }

        .btn-modal-confirm:hover { background: var(--accent); }

        /* BOTTOM CONSOLE NAVIGATION BAR UNTUK HALAMAN BERANDA */
        .bottom-console {
            position: fixed; bottom: 12px; left: 12px; width: calc(100% - 24px); height: 54px;
            background: var(--surface); border: none; border-radius: 8px; display: flex; 
            justify-content: space-around; align-items: center; z-index: 9000; padding: 0 4px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.06);
        }
        
        .c-link { 
            text-align: center; color: var(--text-muted); text-decoration: none; flex: 1; 
            display: flex; flex-direction: column; align-items: center; gap: 2px; 
            height: calc(100% - 8px); justify-content: center; border-radius: 6px; transition: var(--transition-premium);
        }
        
        .c-link i { font-size: 18px; transition: var(--transition-premium); }
        .c-link span { font-size: 8.5px; font-weight: 700; }
        .c-link.active { color: var(--text-main); background: var(--bg); }
        .c-link.active i { color: var(--primary); }

        /* BOTTOM FLOATING BAR DENGAN TOTAL HARGA DAN TOMBOL PEMBELIAN */
        .spa-bottom-bar {
            position: fixed; bottom: 0; left: 0; width: 100%; height: 62px;
            background: var(--surface); border-top: 1px solid #e2e6ea;
            display: none; align-items: center; justify-content: space-between;
            padding: 8px 16px; z-index: 9005; box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.08);
        }

        .spa-bottom-info { display: flex; flex-direction: column; }
        .spa-bottom-label { font-size: 9px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px; }
        .spa-bottom-price { font-size: 14px; font-weight: 800; color: var(--primary); }

        .spa-bottom-btn {
            background: var(--primary); color: #ffffff; border: none; padding: 0 20px;
            height: 42px; border-radius: 8px; font-size: 11px; font-weight: 800;
            display: flex; align-items: center; gap: 6px; cursor: pointer;
            transition: var(--transition-premium); box-shadow: 0 4px 12px rgba(138, 112, 76, 0.25);
        }
        .spa-bottom-btn:hover { background: var(--accent); }

        .custom-snackbar {
            position: fixed; bottom: 76px; left: 50%; transform: translateX(-50%) translateY(20px);
            background: #222222; border-radius: 6px; padding: 8px 16px; display: flex; 
            align-items: center; gap: 8px; min-width: 240px; max-width: 90%; z-index: 9999; 
            opacity: 0; pointer-events: none; transition: var(--transition-premium);
        }
        
        .custom-snackbar.show { opacity: 1; transform: translateX(-50%) translateY(0); }
        .custom-snackbar .snack-text { color: #ffffff; font-size: 9.5px; font-weight: 600; }
        .custom-snackbar i { color: var(--accent); font-size: 14px; }

        @media (min-width: 640px) {
            .game-cards-grid, .products-grid, .payment-methods-grid { grid-template-columns: repeat(3, 1fr); }
        }

        @media (min-width: 1024px) {
            body { padding-bottom: 20px; }
            .admin-sidebar-premium { left: 12px; }
            .sidebar-glass-overlay { display: none !important; }
            .btn-sidebar-trigger { display: none; }
            .premium-layout-wrapper { padding-left: calc(var(--sidebar-width) + 12px); }
            .dashboard-header { padding: 12px 24px; }
            .bottom-console { display: none !important; }
            .spa-bottom-bar { padding-left: calc(var(--sidebar-width) + 24px); padding-right: 24px; }
            .main-content-container { max-width: 1280px; padding: 16px 24px; }
            .banner-slide { height: 220px; }
            .game-cards-grid, .products-grid, .payment-methods-grid { grid-template-columns: repeat(4, 1fr); gap: 14px; }
            .custom-snackbar { bottom: 20px; left: calc(50% + (var(--sidebar-width) / 2)); }
        }
    </style>
</head>
<body>

<!-- PRELOADER ANIMATION -->
<div class="preloader-container" id="appPreloader">
    <div class="preloader-box">
        <div class="preloader-logo-ring">
            <div class="preloader-ring"></div>
            <div class="preloader-logo">
                <img src="<?= $siteLogo ?>" alt="<?= $siteName ?> Logo">
            </div>
        </div>
        <div class="preloader-text"><?= $siteName ?></div>
        <div class="preloader-subtitle">Memuat Halaman...</div>
    </div>
</div>

<!-- SIDEBAR OVERLAY BACKDROP -->
<div class="sidebar-glass-overlay" id="sidebarBackdrop"></div>

<!-- SIDEBAR NAVIGATION -->
<div class="admin-sidebar-premium" id="appSidebar">
    <div class="sidebar-brand-wrapper">
        <div class="sidebar-brand-logo">
            <img src="<?= $siteLogo ?>" alt="<?= $siteName ?> Logo">
        </div>
        <div class="sidebar-brand-info">
            <h2><?= $siteName ?></h2>
            <p>Topup Terpercaya</p>
        </div>
    </div>
    
    <div class="sidebar-menu-navigation">
        <a href="dashboard.php" class="sidebar-menu-item active">
            <i class="ti ti-device-gamepad-2"></i>
            <span>Home Top Up</span>
        </a>
        <a href="history.php" class="sidebar-menu-item">
            <i class="ti ti-history"></i>
            <span>Riwayat Transaksi</span>
        </a>
        <a href="deposit.php" class="sidebar-menu-item">
            <i class="ti ti-wallet"></i>
            <span>Isi Saldo</span>
        </a>
        <a href="account.php" class="sidebar-menu-item">
            <i class="ti ti-user"></i>
            <span>Akun</span>
        </a>
        <a href="<?= $siteWaUrl ?>" target="_blank" class="sidebar-menu-item">
            <i class="ti ti-headset"></i>
            <span>Bantuan CS</span>
        </a>
    </div>

    <div class="sidebar-footer-profile">
        <?php if ($currentUser): ?>
            <div class="sidebar-avatar-box"><?= htmlspecialchars($userInitials) ?></div>
            <div class="sidebar-user-meta">
                <h4><?= htmlspecialchars($currentUser['username']) ?></h4>
                <p>ID: <?= htmlspecialchars($currentUser['referral_code']) ?> &bull; <?= strtoupper($currentUser['user_type']) ?></p>
            </div>
        <?php else: ?>
            <div class="sidebar-avatar-box"><i class="ti ti-user-x"></i></div>
            <div class="sidebar-user-meta" style="flex-grow: 1;">
                <h4>Pengguna Guest</h4>
                <p>Belum Masuk Akun</p>
            </div>
            <a href="login.php" class="btn-header-login" style="padding: 4px 8px; font-size: 9px;">Login</a>
        <?php endif; ?>
    </div>
</div>

<!-- MAIN LAYOUT WRAPPER -->
<div class="premium-layout-wrapper">

    <!-- REQ 1: BANNER PWA INSTALL DI BAGIAN PALING ATAS DI ATAS HEADER -->
    <div class="pwa-top-banner" id="pwaTopBanner">
        <div class="pwa-top-banner-content">
            <i class="ti ti-device-mobile pwa-banner-icon"></i>
            <span class="pwa-banner-text">Tambahkan <strong><?= $siteName ?></strong> ke layar beranda Anda.</span>
        </div>
        <div class="pwa-banner-actions">
            <button class="btn-pwa-add" id="pwaInstallBtn" type="button" onclick="triggerPwaInstall()">Tambah</button>
            <button class="btn-pwa-close" type="button" onclick="closePwaBanner()"><i class="ti ti-x"></i></button>
        </div>
    </div>

    <!-- FULL WIDTH HEADER -->
    <div class="dashboard-header">
        <div class="user-profile-bar">
            <button class="btn-sidebar-trigger" type="button" onclick="togglePremiumSidebar()">
                <i class="ti ti-menu-2"></i>
            </button>
            <div class="site-logo-img">
                <img src="<?= $siteLogo ?>" alt="<?= $siteName ?> Logo">
            </div>
            <span class="brand-text-header"><?= $siteName ?></span>
        </div>

        <div class="header-right-actions">
            <?php if ($currentUser): ?>
                <div class="header-balance-box">
                    <i class="ti ti-wallet"></i>
                    <span id="user_balance">Rp <?= number_format((float)$currentUser['saldo'], 0, ',', '.') ?></span>
                    <a href="deposit.php" class="btn-header-deposit" title="Isi Saldo">
                        <i class="ti ti-plus"></i>
                    </a>
                </div>
            <?php else: ?>
                <a href="login.php" class="btn-header-login">
                    <i class="ti ti-login"></i>
                    <span>Masuk</span>
                </a>
            <?php endif; ?>

            <?php if (!$isGuest): ?>
                <button class="btn-header-notif" type="button" onclick="openNotificationModal()">
                    <i class="ti ti-bell"></i>
                    <?php if ($unreadNotifCount > 0): ?>
                        <span class="notif-badge-dot"></span>
                    <?php endif; ?>
                </button>
            <?php endif; ?>
        </div>
    </div>

    <!-- MAIN CONTENT CONTAINER -->
    <div class="main-content-container">

        <!-- VIEW 1: MAIN DASHBOARD BERANDA HOME -->
        <div id="view-home">

            <div class="banner-slider-container">
                <div class="banner-slider-track">
                    <?php if (!empty($banners)): ?>
                        <?php foreach ($banners as $b): ?>
                            <div class="banner-slide">
                                <?php if (!empty($b['link_url'])): ?>
                                    <a href="<?= htmlspecialchars($b['link_url']) ?>">
                                        <img src="<?= htmlspecialchars($b['gambar_url']) ?>" alt="<?= htmlspecialchars($b['judul']) ?>">
                                    </a>
                                <?php else: ?>
                                    <img src="<?= htmlspecialchars($b['gambar_url']) ?>" alt="<?= htmlspecialchars($b['judul']) ?>">
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="banner-slide">
                            <img src="https://images.unsplash.com/photo-1542751371-adc38448a05e?q=80&w=1200&auto=format&fit=crop" alt="Banner Default">
                        </div>
                    <?php endif; ?>
                </div>
                <div class="banner-dots">
                    <?php 
                    $totalBanners = !empty($banners) ? count($banners) : 1;
                    for ($i = 0; $i < $totalBanners; $i++): 
                    ?>
                        <span class="dot <?= $i === 0 ? 'active' : '' ?>"></span>
                    <?php endfor; ?>
                </div>
            </div>

            <div class="section-tag">Kategori Game & Voucher</div>
            <div class="category-toggle-container">
                <a href="#" class="category-toggle-btn active" onclick="filterCategory(this, 'all', 'Semua Game'); return false;">
                    <i class="ti ti-flame"></i>
                    <span>Semua Game</span>
                </a>
                <?php foreach ($categories as $cat): ?>
                    <a href="#" class="category-toggle-btn" onclick="filterCategory(this, '<?= (int)$cat['id'] ?>', '<?= htmlspecialchars($cat['nama_kategori'], ENT_QUOTES) ?>'); return false;">
                        <i class="ti ti-device-gamepad-2"></i>
                        <span><?= htmlspecialchars($cat['nama_kategori']) ?></span>
                    </a>
                <?php endforeach; ?>
            </div>

            <div class="section-tag">Game Terpopuler</div>
            <div class="game-cards-grid">

                <?php if (!empty($brands)): ?>
                    <?php foreach ($brands as $brand): ?>
                        <a href="#<?= htmlspecialchars($brand['slug'], ENT_QUOTES) ?>" class="game-card" data-category-id="<?= (int)$brand['category_id'] ?>" onclick="openBrandOrderView('<?= htmlspecialchars($brand['slug'], ENT_QUOTES) ?>'); return false;">
                            <div class="game-card-banner">
                                <img src="<?= !empty($brand['img_url']) ? htmlspecialchars($brand['img_url']) : 'https://images.unsplash.com/photo-1542751371-adc38448a05e?q=80&w=600&auto=format&fit=crop' ?>" alt="<?= htmlspecialchars($brand['nama_brand']) ?>">
                                <div class="game-badge-fast">
                                    <i class="ti ti-bolt"></i> <?= $brand['is_populer'] == 1 ? 'POPULER' : 'DETIK' ?>
                                </div>
                            </div>
                            <div class="game-card-body">
                                <div class="game-card-title"><?= htmlspecialchars($brand['nama_brand']) ?></div>
                                <div class="game-card-publisher"><?= htmlspecialchars($brand['nama_kategori'] ?? 'Publisher Game') ?></div>
                                <div class="game-card-footer">
                                    <div class="game-card-status"><i class="ti ti-circle-check"></i> Auto Processing</div>
                                    <div class="game-card-btn"><i class="ti ti-chevron-right"></i></div>
                                </div>
                            </div>
                        </a>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div style="grid-column: 1 / -1; text-align: center; padding: 20px; color: var(--text-muted);">
                        Belum ada brand game yang tersedia.
                    </div>
                <?php endif; ?>

            </div>

            <!-- SECTION FAQ DI HALAMAN BERANDA DIBAWAH BRAND -->
            <div class="section-tag">Pertanyaan Sering Diajukan (FAQ)</div>
            <div class="faq-accordion-container">
                <?php if (!empty($faqs)): ?>
                    <?php foreach ($faqs as $faq): ?>
                        <div class="faq-accordion-item">
                            <div class="faq-accordion-header" onclick="toggleFaqAccordion(this)">
                                <div class="faq-accordion-title">
                                    <i class="ti ti-help-circle"></i>
                                    <span><?= htmlspecialchars($faq['pertanyaan']) ?></span>
                                </div>
                                <i class="ti ti-chevron-down faq-accordion-icon"></i>
                            </div>
                            <div class="faq-accordion-body">
                                <?= nl2br(htmlspecialchars($faq['jawaban'])) ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div style="text-align: center; padding: 15px; color: var(--text-muted); background: var(--surface-card); border-radius: 8px;">
                        Belum ada pertanyaan FAQ yang tersedia.
                    </div>
                <?php endif; ?>
            </div>

            <!-- SECTION AKTIVITAS TOP UP TERAKHIR (DESAIN PROFESIONAL DAN PAS) -->
            <?php if (!$isGuest): ?>
                <div class="section-tag">Aktivitas Top Up Terakhir</div>
                <div class="history-list-wrapper">
                    <?php if (!empty($recentTransactions)): ?>
                        <?php foreach ($recentTransactions as $rTrx): 
                            $dateFormatted = !empty($rTrx['created_at']) ? date('d M Y, H:i', strtotime($rTrx['created_at'])) . ' WIB' : '-';
                            $statusPay = strtolower($rTrx['status_payment']);
                            $statusOrd = strtolower($rTrx['status_order']);
                        ?>
                            <div class="history-log-card-pro" onclick="window.location.href='detail-transaksi.php?trx_id=<?= htmlspecialchars($rTrx['trx_id']) ?>'">
                                <div class="history-card-top">
                                    <span class="history-trx-id">
                                        <i class="ti ti-receipt"></i> <?= htmlspecialchars($rTrx['trx_id']) ?>
                                    </span>
                                    <span class="history-date"><?= $dateFormatted ?></span>
                                </div>

                                <div class="history-card-middle">
                                    <div class="history-prod-info">
                                        <h4><?= htmlspecialchars($rTrx['nama_produk'] ?? 'Top Up Produk') ?></h4>
                                        <p class="history-customer-no">Customer No: <span><?= htmlspecialchars($rTrx['customer_no']) ?></span></p>
                                    </div>
                                    <div class="history-badges-column">
                                        <span class="history-badge badge-pay-<?= $statusPay ?>">
                                            BAYAR: <?= strtoupper($rTrx['status_payment']) ?>
                                        </span>
                                        <span class="history-badge badge-order-<?= $statusOrd ?>">
                                            ORDER: <?= strtoupper($rTrx['status_order']) ?>
                                        </span>
                                    </div>
                                </div>

                                <?php if ($rTrx['status_payment'] === 'pending'): ?>
                                    <div class="history-pending-notice">
                                        <i class="ti ti-info-circle"></i>
                                        <span>selesaikan pembayaran untuk melanjutkan pesanan</span>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div style="text-align: center; padding: 20px; color: var(--text-muted); background: var(--surface-card); border-radius: 8px; border: 1px solid #e2e6ea;">
                            Belum ada riwayat aktivitas top up.
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

        </div>

        <!-- VIEW 2: SPA MODE PEMBELIAN / TOPUP BRAND ORDER PAGE -->
        <div id="view-order">
            <button type="button" class="btn-back-home" onclick="goBackToHome()">
                <i class="ti ti-arrow-left"></i>
                <span>Kembali ke Beranda</span>
            </button>

            <div id="order-dynamic-content">
                <!-- DILOAD DINAMIS OLEH JAVASCRIPT SPA -->
            </div>
        </div>

    </div> 

    <!-- BOTTOM CONSOLE NAVIGATION BAR UNTUK BERANDA -->
    <div class="bottom-console">
        <a href="dashboard.php" class="c-link active" onclick="goBackToHome(); return false;">
            <i class="ti ti-device-gamepad-2"></i>
            <span>Home</span>
        </a>
        <a href="deposit.php" class="c-link">
            <i class="ti ti-wallet"></i>
            <span>Dompet</span>
        </a>
        <a href="history.php" class="c-link">
            <i class="ti ti-history"></i>
            <span>Riwayat</span>
        </a>
        <a href="account.php" class="c-link">
            <i class="ti ti-user"></i>
            <span>Akun</span>
        </a>
    </div>

    <!-- BOTTOM FLOATING BAR PROSES PEMBELIAN DENGAN TOTAL DAN TOMBOL KONFIRMASI -->
    <div class="spa-bottom-bar" id="spaBottomBar">
        <div class="spa-bottom-info">
            <span class="spa-bottom-label">Total Pembayaran</span>
            <span class="spa-bottom-price" id="spa_total_price_text">Rp 0</span>
        </div>
        <button type="button" class="spa-bottom-btn" onclick="openOrderConfirmationModal()">
            <i class="ti ti-shopping-cart-check"></i>
            <span>Beli Sekarang</span>
        </button>
    </div>

</div> 

<!-- POPUP MODAL KONFIRMASI PEMBELIAN -->
<div class="modal-overlay" id="modalOrderConfirm">
    <div class="modal-box-card">
        <div class="modal-header">
            <div class="modal-title">
                <i class="ti ti-shopping-cart-check" style="color: var(--primary);"></i>
                <span>Konfirmasi Pesanan</span>
            </div>
            <button type="button" class="modal-close-btn" onclick="closeOrderModal()">
                <i class="ti ti-x"></i>
            </button>
        </div>

        <div class="confirm-detail-list">
            <div class="confirm-detail-row">
                <span class="confirm-detail-label">Kategori</span>
                <span class="confirm-detail-val" id="m_category_name">-</span>
            </div>
            <div class="confirm-detail-row">
                <span class="confirm-detail-label">Brand / Game</span>
                <span class="confirm-detail-val" id="m_brand_name">-</span>
            </div>
            <div class="confirm-detail-row">
                <span class="confirm-detail-label">Target ID Akun</span>
                <span class="confirm-detail-val" id="m_user_target">-</span>
            </div>
            <div class="confirm-detail-row" id="m_guest_phone_row" style="display: none;">
                <span class="confirm-detail-label">WhatsApp (Guest)</span>
                <span class="confirm-detail-val" id="m_guest_phone_val">-</span>
            </div>
            <div class="confirm-detail-row">
                <span class="confirm-detail-label">Item Produk</span>
                <span class="confirm-detail-val" id="m_product_name">-</span>
            </div>
            <div class="confirm-detail-row">
                <span class="confirm-detail-label">Metode Pembayaran</span>
                <span class="confirm-detail-val" id="m_payment_name">-</span>
            </div>
            <div class="confirm-detail-row">
                <span class="confirm-detail-label">Harga Produk</span>
                <span class="confirm-detail-val" id="m_product_price">Rp 0</span>
            </div>
            <div class="confirm-detail-row">
                <span class="confirm-detail-label">Biaya Penanganan (Fee)</span>
                <span class="confirm-detail-val" id="m_fee_amount">Rp 0</span>
            </div>
            <div class="confirm-detail-row confirm-detail-total">
                <span class="confirm-detail-label">Total Pembayaran</span>
                <span class="confirm-detail-val" id="m_total_price">Rp 0</span>
            </div>
        </div>

        <div class="modal-actions-grid">
            <button type="button" class="btn-modal-cancel" onclick="closeOrderModal()">Batal</button>
            <button type="button" class="btn-modal-confirm" id="btnConfirmPay" onclick="processFinalCheckout()">
                <i class="ti ti-check"></i>
                <span>Konfirmasi & Bayar</span>
            </button>
        </div>
    </div>
</div>

<!-- POPUP MODAL NOTIFIKASI PENGGUNA LOGIN -->
<div class="modal-overlay" id="modalNotification">
    <div class="modal-box-card">
        <div class="modal-header">
            <div class="modal-title">
                <i class="ti ti-bell" style="color: var(--primary);"></i>
                <span>Pusat Notifikasi</span>
            </div>
            <button type="button" class="modal-close-btn" onclick="closeNotifModal()">
                <i class="ti ti-x"></i>
            </button>
        </div>
        <div id="notif-modal-content" style="display: flex; flex-direction: column; gap: 8px; max-height: 360px; overflow-y: auto;">
        </div>
    </div>
</div>

<!-- SNACKBAR ALERT NOTIFICATION -->
<div class="custom-snackbar" id="appSnackbar">
    <i class="ti ti-circle-check"></i>
    <span class="snack-text">Sistem Siap Digunakan</span>
</div>

<!-- OPTIMIZED FAST JAVASCRIPT & SPA ENGINE -->
<script>
// PWA INSTALLATION EVENT HANDLER
let deferredPwaPrompt = null;

window.addEventListener('beforeinstallprompt', (e) => {
    e.preventDefault();
    deferredPwaPrompt = e;
    $("#pwaTopBanner").slideDown(200);
});

function triggerPwaInstall() {
    if (deferredPwaPrompt) {
        deferredPwaPrompt.prompt();
        deferredPwaPrompt.userChoice.then((choiceResult) => {
            if (choiceResult.outcome === 'accepted') {
                showSnackbar('Aplikasi berhasil ditambahkan ke beranda!', 'success');
                closePwaBanner();
            }
            deferredPwaPrompt = null;
        });
    } else {
        showSnackbar('Pilih menu browser Anda lalu tekan "Tambahkan ke Layar Utama"', 'info');
    }
}

function closePwaBanner() {
    $("#pwaTopBanner").slideUp(200);
}

function toggleFaqAccordion(headerElem) {
    const targetBody = $(headerElem).next('.faq-accordion-body');
    const isAlreadyOpen = targetBody.is(':visible');

    $('.faq-accordion-body').slideUp(180);
    $('.faq-accordion-header').removeClass('active');

    if (!isAlreadyOpen) {
        targetBody.slideDown(180);
        $(headerElem).addClass('active');
    }
}

function togglePremiumSidebar() {
    if ($(window).width() < 1024) {
        const sidebar = $("#appSidebar");
        const backdrop = $("#sidebarBackdrop");
        
        if (sidebar.hasClass("active")) {
            sidebar.removeClass("active");
            backdrop.fadeOut(200);
        } else {
            sidebar.addClass("active");
            backdrop.fadeIn(200);
        }
    }
}

function filterCategory(element, categoryId, categoryName) {
    $(".category-toggle-btn").removeClass("active");
    $(element).addClass("active");

    if (categoryId === 'all') {
        $(".game-card").fadeIn(150);
    } else {
        $(".game-card").each(function() {
            if ($(this).attr("data-category-id") == categoryId) {
                $(this).fadeIn(150);
            } else {
                $(this).hide();
            }
        });
    }
    showSnackbar('Kategori dipilih: ' + categoryName, 'success');
}

let isOrderViewOpen = false;
let currentBrandData = null;
let currentBrandUserType = 'umum';
let isGuestUser = <?= $isGuest ? 'true' : 'false' ?>;
let selectedProductObj = null;
let selectedPaymentObj = null;

const categoryLabels = {
    'saldo': 'Saldo Akun Utama',
    'poin': 'Poin Reward',
    'qris': 'QRIS Instan (BCA, DANA, OVO, ShopeePay)',
    'ewallet': 'E-Wallet (GoPay, OVO, DANA, LinkAja)',
    'virtual_account': 'Virtual Account Bank',
    'bank_transfer': 'Transfer Bank Manual',
    'retail': 'Minimarket / Retail',
    'manual': 'Pembayaran Manual'
};

function showAppPreloader() {
    $("#appPreloader").removeClass("fade-out");
}

function hideAppPreloader() {
    $("#appPreloader").addClass("fade-out");
}

function openNotificationModal() {
    $("#modalNotification").addClass("active");
    $("#notif-modal-content").html('<div style="text-align: center; padding: 20px; color: var(--text-muted);"><i class="ti ti-loader spin"></i> Memuat notifikasi...</div>');

    $.ajax({
        url: 'dashboard.php',
        type: 'POST',
        data: { ajax: 'get_notifications' },
        dataType: 'json',
        success: function(res) {
            if (res.status === 'success') {
                $(".notif-badge-dot").remove();
                if (res.notifications && res.notifications.length > 0) {
                    let html = '';
                    res.notifications.forEach(function(n) {
                        let iconClass = n.icon ? n.icon : 'ti-bell';
                        let readBg = n.is_read == 1 ? 'var(--bg)' : '#ffffff';
                        let borderStyle = n.is_read == 0 ? 'border-left: 3px solid var(--primary);' : '';
                        let isLink = n.url ? `onclick="window.location.href='${n.url}'" style="cursor: pointer;"` : '';

                        html += `
                            <div class="history-log-card" ${isLink} style="background: ${readBg}; ${borderStyle} padding: 10px;">
                                <div class="log-meta-left" style="width: 100%;">
                                    <div class="log-icon-box"><i class="ti ${iconClass}"></i></div>
                                    <div class="log-details" style="width: calc(100% - 40px);">
                                        <h4>${n.judul}</h4>
                                        <p style="white-space: normal; line-height: 1.3;">${n.pesan}</p>
                                        <p style="font-size: 8px; color: var(--text-muted); margin-top: 2px;">${n.created_at}</p>
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                    $("#notif-modal-content").html(html);
                } else {
                    $("#notif-modal-content").html('<div style="text-align: center; padding: 20px; color: var(--text-muted);">Belum ada notifikasi baru.</div>');
                }
            } else {
                $("#notif-modal-content").html('<div style="text-align: center; padding: 20px; color: var(--danger);">' + (res.message || 'Gagal memuat notifikasi.') + '</div>');
            }
        },
        error: function() {
            $("#notif-modal-content").html('<div style="text-align: center; padding: 20px; color: var(--danger);">Gagal terhubung ke server.</div>');
        }
    });
}

function closeNotifModal() {
    $("#modalNotification").removeClass("active");
}

function openBrandOrderView(brandSlug, pushState = true) {
    if (!brandSlug) return;
    showAppPreloader();

    $.ajax({
        url: 'dashboard.php',
        type: 'POST',
        data: { ajax: 'get_brand_detail', slug: brandSlug },
        dataType: 'json',
        success: function(res) {
            hideAppPreloader();
            if (res.status === 'success') {
                currentBrandData = res.brand;
                currentBrandUserType = res.user_type ? res.user_type : 'umum';
                isGuestUser = !!res.is_guest;
                selectedProductObj = null;
                selectedPaymentObj = null;

                renderOrderViewHTML(res.brand, res.types, res.products, res.payment_methods);
                
                $("#view-home").hide();
                $(".bottom-console").hide();
                $("#spaBottomBar").css("display", "flex");
                $("#view-order").fadeIn(200);
                window.scrollTo({ top: 0, behavior: 'smooth' });
                isOrderViewOpen = true;

                updateSpaTotalPrice();

                if (pushState) {
                    history.pushState({ view: 'order', slug: brandSlug }, '', '#' + brandSlug);
                }
            } else {
                showSnackbar(res.message, 'danger');
            }
        },
        error: function() {
            hideAppPreloader();
            showSnackbar('Gagal memuat data produk!', 'danger');
        }
    });
}

function renderOrderViewHTML(brand, types, products, paymentMethods) {
    let brandImg = brand.img_url ? brand.img_url : 'https://images.unsplash.com/photo-1542751371-adc38448a05e?q=80&w=600&auto=format&fit=crop';
    let placeholderInput = brand.placeholder_input ? brand.placeholder_input : 'Masukkan User ID';
    let placeholderServer = brand.placeholder_server_id ? brand.placeholder_server_id : 'Masukkan Server ID';
    let brandDesc = brand.keterangan ? brand.keterangan : 'Top up instan 24 jam diproses otomatis.';

    let html = `
        <div class="order-brand-header">
            <div class="order-brand-img">
                <img src="${brandImg}" alt="${brand.nama_brand}">
            </div>
            <div class="order-brand-info">
                <h2>${brand.nama_brand}</h2>
                <p>${brand.nama_kategori ? brand.nama_kategori : 'Game Top Up'} &bull; ${brandDesc}</p>
            </div>
        </div>

        <div class="order-step-card">
            <div class="order-step-title">
                <span class="order-step-num">1</span>
                <span>Lengkapi Data Akun Game</span>
            </div>
            <div style="display: flex; gap: 8px; flex-wrap: wrap; align-items: center;">
                <input type="text" id="order_user_id" class="order-form-input" style="flex: 1; min-width: 150px;" placeholder="${placeholderInput}" required>
                ${brand.server_id == 1 ? `<input type="text" id="order_zone_id" class="order-form-input" style="flex: 1; max-width: 140px;" placeholder="${placeholderServer}">` : ''}
                ${brand.cek_id == 1 ? `<button type="button" class="btn-check-id" onclick="checkAccountNickname('${brand.kode_cek_id}')"><i class="ti ti-search"></i> Cek ID</button>` : ''}
            </div>
            ${isGuestUser ? `
                <div style="margin-top: 10px;">
                    <label style="font-size: 9.5px; font-weight: 700; color: var(--text-muted); margin-bottom: 4px; display: block;">Nomor WhatsApp (Wajib untuk Guest)</label>
                    <input type="tel" id="order_guest_phone" class="order-form-input" placeholder="Contoh: 081234567890" required>
                </div>
            ` : ''}
            <div id="check_id_result" style="font-size: 10px; font-weight: 700; color: var(--primary); display: none; margin-top: 4px;"></div>
        </div>
    `;

    html += `
        <div class="order-step-card">
            <div class="order-step-title">
                <span class="order-step-num">2</span>
                <span>Pilih Item Top Up</span>
            </div>
    `;

    if (types && types.length > 0) {
        html += `<div class="product-types-tab-container">`;
        html += `<button class="product-type-btn active" onclick="filterTypeProducts('all', this)">Semua Item</button>`;
        types.forEach(function(t) {
            html += `<button class="product-type-btn" onclick="filterTypeProducts('${t.id}', this)">${t.nama_type}</button>`;
        });
        html += `</div>`;
    }

    html += `<div class="products-grid" id="productsGridContainer">`;
    if (products && products.length > 0) {
        let isReseller = (currentBrandUserType === 'reseller');
        products.forEach(function(p) {
            let hargaNum = isReseller ? Number(p.harga_reseller) : Number(p.harga_umum);
            let hargaFormatted = 'Rp ' + hargaNum.toLocaleString('id-ID');
            p.display_price = hargaNum;

            let prodJson = JSON.stringify(p).replace(/'/g, "&apos;");
            
            let prodIconHtml = p.img_url 
                ? `<img src="${p.img_url}" alt="${p.nama_produk}">` 
                : `<i class="ti ti-box"></i>`;

            html += `
                <div class="product-item-card" data-type-id="${p.type_id}" onclick='selectProductCard(this, ${prodJson})'>
                    <div class="product-item-icon-box">
                        ${prodIconHtml}
                    </div>
                    <div class="product-item-meta">
                        <div class="product-item-title">${p.nama_produk}</div>
                        <div class="product-item-price">${hargaFormatted}</div>
                    </div>
                </div>
            `;
        });
    } else {
        html += `<div style="grid-column: 1 / -1; text-align: center; color: var(--text-muted); padding: 10px;">Belum ada item tersedia untuk brand ini.</div>`;
    }
    html += `</div></div>`;

    html += `
        <div class="order-step-card">
            <div class="order-step-title">
                <span class="order-step-num">3</span>
                <span>Pilih Metode Pembayaran</span>
            </div>
            <div class="payment-accordion-container">
    `;

    if (paymentMethods && paymentMethods.length > 0) {
        let groupedPayments = {};
        paymentMethods.forEach(function(pm) {
            let catKey = pm.kategori;
            if (!groupedPayments[catKey]) {
                groupedPayments[catKey] = [];
            }
            groupedPayments[catKey].push(pm);
        });

        for (let catKey in groupedPayments) {
            let labelCat = categoryLabels[catKey] ? categoryLabels[catKey] : catKey.toUpperCase();
            let catId = 'pay_acc_' + catKey;

            html += `
                <div class="payment-accordion-item">
                    <div class="payment-accordion-header" onclick="togglePaymentAccordion('${catId}', this)">
                        <div class="payment-accordion-title">
                            <i class="ti ti-wallet"></i>
                            <span>${labelCat}</span>
                        </div>
                        <i class="ti ti-chevron-down payment-accordion-icon"></i>
                    </div>
                    <div class="payment-accordion-body" id="${catId}">
                        <div class="payment-methods-grid">
            `;

            groupedPayments[catKey].forEach(function(pm) {
                let isSaldoCategory = (pm.kategori === 'saldo' || pm.slug === 'saldo');
                let isDisabledForGuest = isGuestUser && isSaldoCategory;

                let logoUrl = pm.img_url ? pm.img_url : 'https://via.placeholder.com/50?text=PAY';
                let feeText = 'Bebas Biaya';
                let bAdmin = Number(pm.biaya_admin);
                let bPersen = Number(pm.biaya_persen);
                
                if (bAdmin > 0 && bPersen > 0) {
                    feeText = '+Rp ' + bAdmin.toLocaleString('id-ID') + ' & ' + bPersen + '%';
                } else if (bAdmin > 0) {
                    feeText = '+Rp ' + bAdmin.toLocaleString('id-ID');
                } else if (bPersen > 0) {
                    feeText = '+' + bPersen + '%';
                }

                if (isDisabledForGuest) {
                    feeText = 'Khusus Member';
                }

                let pmJson = JSON.stringify(pm).replace(/'/g, "&apos;");

                html += `
                    <div class="payment-card ${isDisabledForGuest ? 'disabled-guest' : ''}" onclick='selectPaymentCard(this, ${pmJson}, ${isDisabledForGuest})'>
                        <div class="payment-card-left">
                            <div class="payment-card-logo">
                                <img src="${logoUrl}" alt="${pm.nama_metode}">
                            </div>
                            <div class="payment-card-name">${pm.nama_metode}</div>
                        </div>
                        <div class="payment-card-fee">${feeText}</div>
                    </div>
                `;
            });

            html += `</div></div></div>`;
        }
    } else {
        html += `<div style="text-align: center; color: var(--text-muted); padding: 10px;">Metode pembayaran tidak tersedia saat ini.</div>`;
    }

    html += `</div></div>`;

    $("#order-dynamic-content").html(html);

    setTimeout(function() {
        $(".payment-accordion-header").first().trigger("click");
    }, 50);
}

function checkAccountNickname(kodeCekId) {
    let uId = $("#order_user_id").val().trim();

    if (!uId) {
        showSnackbar('Masukkan User ID terlebih dahulu!', 'danger');
        return;
    }

    $("#check_id_result").css("color", "var(--primary)").html('<i class="ti ti-loader spin"></i> Memeriksa ID Akun...').fadeIn(150);

    setTimeout(function() {
        $("#check_id_result").css("color", "var(--success)").html('<i class="ti ti-circle-check"></i> Akun Terverifikasi').fadeIn(150);
        showSnackbar('ID Akun berhasil terverifikasi!', 'success');
    }, 600);
}

function togglePaymentAccordion(bodyId, headerElem) {
    const targetBody = $("#" + bodyId);
    const isAlreadyOpen = targetBody.is(":visible");

    $(".payment-accordion-body").slideUp(180);
    $(".payment-accordion-header").removeClass("active");

    if (!isAlreadyOpen) {
        targetBody.slideDown(180);
        $(headerElem).addClass("active");
    }
}

function filterTypeProducts(typeId, btn) {
    $(".product-type-btn").removeClass("active");
    $(btn).addClass("active");

    if (typeId === 'all') {
        $(".product-item-card").show();
    } else {
        $(".product-item-card").each(function() {
            if ($(this).attr("data-type-id") == typeId) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    }
}

function updateSpaTotalPrice() {
    if (!selectedProductObj) {
        $("#spa_total_price_text").text("Rp 0");
        return;
    }
    let basePrice = selectedProductObj.display_price ? Number(selectedProductObj.display_price) : Number(selectedProductObj.harga_umum);
    let calculatedFee = 0;
    
    if (selectedPaymentObj) {
        let feeAdmin = Number(selectedPaymentObj.biaya_admin || 0);
        let feePersen = Number(selectedPaymentObj.biaya_persen || 0);
        calculatedFee = feeAdmin + (basePrice * (feePersen / 100));
    }
    
    let total = basePrice + calculatedFee;
    $("#spa_total_price_text").text('Rp ' + Math.round(total).toLocaleString('id-ID'));
}

function selectProductCard(element, productObj) {
    $(".product-item-card").removeClass("selected");
    $(element).addClass("selected");
    selectedProductObj = productObj;
    updateSpaTotalPrice();
    let baseDisplayPrice = productObj.display_price ? Number(productObj.display_price) : Number(productObj.harga_umum);
    let hargaFormatted = 'Rp ' + baseDisplayPrice.toLocaleString('id-ID');
    showSnackbar('Item dipilih: ' + productObj.nama_produk + ' (' + hargaFormatted + ')', 'success');

    let customerNoVal = $("#order_user_id").length ? $("#order_user_id").val().trim() : '';
    if (customerNoVal !== '') {
        let paymentSection = $(".payment-accordion-container");
        if (paymentSection.length) {
            $('html, body').animate({
                scrollTop: paymentSection.offset().top - 80
            }, 400);
        }
    }
}

function selectPaymentCard(element, paymentObj, isDisabledForGuest) {
    if (isDisabledForGuest) {
        showSnackbar('Pembayaran via Saldo hanya tersedia untuk member yang sudah login!', 'danger');
        return;
    }
    $(".payment-card").removeClass("selected");
    $(element).addClass("selected");
    selectedPaymentObj = paymentObj;
    updateSpaTotalPrice();
    showSnackbar('Metode Pembayaran: ' + paymentObj.nama_metode, 'success');
}

function openOrderConfirmationModal() {
    let userId = $("#order_user_id").val().trim();
    let zoneId = $("#order_zone_id").length ? $("#order_zone_id").val().trim() : '';
    let guestPhone = $("#order_guest_phone").length ? $("#order_guest_phone").val().trim() : '';

    if (!userId) {
        showSnackbar('Harap isi User ID Akun Game Anda!', 'danger');
        return;
    }

    if (isGuestUser && !guestPhone) {
        showSnackbar('Harap isi Nomor WhatsApp Anda!', 'danger');
        return;
    }

    if (!selectedProductObj) {
        showSnackbar('Harap pilih item nominal produk terlebih dahulu!', 'danger');
        return;
    }

    if (!selectedPaymentObj) {
        showSnackbar('Harap pilih metode pembayaran!', 'danger');
        return;
    }

    let targetText = zoneId ? userId + ' (' + zoneId + ')' : userId;
    
    let basePrice = selectedProductObj.display_price ? Number(selectedProductObj.display_price) : Number(selectedProductObj.harga_umum);
    let feeAdmin = Number(selectedPaymentObj.biaya_admin);
    let feePersen = Number(selectedPaymentObj.biaya_persen);
    let calculatedFee = feeAdmin + (basePrice * (feePersen / 100));
    let totalPrice = basePrice + calculatedFee;

    let categoryName = currentBrandData && currentBrandData.nama_kategori ? currentBrandData.nama_kategori : 'Game Top Up';
    let brandName = currentBrandData && currentBrandData.nama_brand ? currentBrandData.nama_brand : '-';

    $("#m_category_name").text(categoryName);
    $("#m_brand_name").text(brandName);
    $("#m_user_target").text(targetText);

    if (isGuestUser && guestPhone) {
        $("#m_guest_phone_val").text(guestPhone);
        $("#m_guest_phone_row").show();
    } else {
        $("#m_guest_phone_row").hide();
    }

    $("#m_product_name").text(selectedProductObj.nama_produk);
    $("#m_payment_name").text(selectedPaymentObj.nama_metode);
    $("#m_product_price").text('Rp ' + basePrice.toLocaleString('id-ID'));
    $("#m_fee_amount").text(calculatedFee > 0 ? 'Rp ' + calculatedFee.toLocaleString('id-ID') : 'Rp 0 (Bebas Biaya)');
    $("#m_total_price").text('Rp ' + totalPrice.toLocaleString('id-ID'));

    $("#modalOrderConfirm").addClass("active");
}

function closeOrderModal() {
    $("#modalOrderConfirm").removeClass("active");
}

function processFinalCheckout() {
    let userIdTarget = $("#order_user_id").val().trim();
    let zoneIdTarget = $("#order_zone_id").length ? $("#order_zone_id").val().trim() : '';
    let guestPhone    = $("#order_guest_phone").length ? $("#order_guest_phone").val().trim() : '';

    if (!selectedProductObj || !selectedPaymentObj || !userIdTarget) {
        showSnackbar('Data pesanan tidak lengkap!', 'danger');
        return;
    }

    if (isGuestUser && !guestPhone) {
        showSnackbar('Nomor WhatsApp wajib diisi untuk transaksi Guest!', 'danger');
        return;
    }

    const btnPay = $("#btnConfirmPay");
    btnPay.prop("disabled", true).html('<i class="ti ti-loader spin"></i> <span>Memproses...</span>');

    $.ajax({
        url: 'dashboard.php',
        type: 'POST',
        data: {
            ajax: 'create_order',
            product_id: selectedProductObj.id,
            payment_method_id: selectedPaymentObj.id,
            user_id_target: userIdTarget,
            zone_id_target: zoneIdTarget,
            guest_phone: guestPhone
        },
        dataType: 'json',
        success: function(res) {
            btnPay.prop("disabled", false).html('<i class="ti ti-check"></i> <span>Konfirmasi & Bayar</span>');
            closeOrderModal();

            if (res.status === 'success') {
                showSnackbar(res.message, 'success');
                setTimeout(function() {
                    window.location.href = res.redirect;
                }, 1000);
            } else {
                showSnackbar(res.message, 'danger');
            }
        },
        error: function() {
            btnPay.prop("disabled", false).html('<i class="ti ti-check"></i> <span>Konfirmasi & Bayar</span>');
            closeOrderModal();
            showSnackbar('Terjadi kesalahan koneksi saat memproses orderan!', 'danger');
        }
    });
}

function goBackToHome(pushState = true) {
    if (isOrderViewOpen) {
        $("#view-order").hide();
        $("#spaBottomBar").hide();
        if ($(window).width() < 1024) {
            $(".bottom-console").css("display", "flex");
        }
        $("#view-home").fadeIn(200);
        window.scrollTo({ top: 0, behavior: 'smooth' });
        isOrderViewOpen = false;
        selectedProductObj = null;
        selectedPaymentObj = null;

        if (pushState) {
            history.pushState({ view: 'home' }, '', window.location.pathname);
        }
    }
}

function checkRouteByHash() {
    let hash = window.location.hash.replace('#', '').trim();
    if (hash && hash !== 'popular') {
        openBrandOrderView(hash, false);
    } else {
        if (isOrderViewOpen) {
            goBackToHome(false);
        }
    }
}

window.addEventListener('popstate', checkRouteByHash);
window.addEventListener('hashchange', checkRouteByHash);

$(window).on("load", function() {
    setTimeout(function() {
        hideAppPreloader();
    }, 400);
});

$(document).ready(function() {
    $("#sidebarBackdrop").on("click", function() {
        togglePremiumSidebar();
    });

    checkRouteByHash();

    let currentSlide = 0;
    const slides = $(".banner-slide");
    const totalSlides = slides.length;

    if (totalSlides > 1) {
        function goToSlide(index) {
            currentSlide = index;
            $(".banner-slider-track").css("transform", `translateX(-${currentSlide * 100}%)`);
            $(".banner-dots .dot").removeClass("active").eq(currentSlide).addClass("active");
        }

        setInterval(function() {
            currentSlide = (currentSlide + 1) % totalSlides;
            goToSlide(currentSlide);
        }, 3500);

        $(".banner-dots .dot").on("click", function() {
            goToSlide($(this).index());
        });
    }

    let snackbarTimer;
    function showSnackbar(message, type) {
        const snack = $("#appSnackbar");
        snack.find('.snack-text').text(message);
        snack.addClass('show');
        clearTimeout(snackbarTimer);
        snackbarTimer = setTimeout(function() { 
            snack.removeClass('show'); 
        }, 2500);
    }
    window.showSnackbar = showSnackbar;
});
</script>
</body>
</html>
