<?php
// Variabel yang sama seperti di kode lama
$dbf = $db->table("flashsale")->get();
foreach ($dbf->getResult() as $rf) {
    $mulai = $rf->mulai;
    $selesai = $rf->selesai;
    $sekarang = date("Y-m-d H:i:s");
    $start = strtotime($mulai);
    $off = strtotime($selesai);
}

$link = $func->arrEnc(array("category" => $data->idcat));
$set = $func->getSetting("semua");
$kategori = $func->getKategori($data->idcat, "semua");
$kategorinama = is_object($kategori) ? $kategori->nama : "";
$kategoriurl = is_object($kategori) ? $kategori->url : "";
$textorder = $data->preorder == 0 ? "Tambah Ke Keranjang" : "Pre Order";

$level = session()->get("lvl") ?? 0;
if ($level == 5) {
    $result = $data->hargadistri;
} elseif ($level == 4) {
    $result = $data->hargaagensp;
} elseif ($level == 3) {
    $result = $data->hargaagen;
} elseif ($level == 2) {
    $result = $data->hargareseller;
} else {
    $result = $data->harga;
}

$dbv = $db->table("produkvariasi")->where("idproduk", $data->id)->get();
$totalstok = 0;
$hargs = 0;
$harga = [];
foreach ($dbv->getResult() as $rv) {
    $totalstok += $rv->stok;
    if ($level == 5) {
        $harga[] = $rv->hargadistri;
    } elseif ($level == 4) {
        $harga[] = $rv->hargaagensp;
    } elseif ($level == 3) {
        $harga[] = $rv->hargaagen;
    } elseif ($level == 2) {
        $harga[] = $rv->hargareseller;
    } else {
        $harga[] = $rv->harga;
    }
    $hargs += $rv->harga;
}

if ($hargs > 0) {
    $hargaawal = "Rp " . $func->formUang(min($harga)) . " - " . $func->formUang(max($harga));
} else {
    $hargaawal = "Rp " . $func->formUang($result);
}

// Foto utama
$dbUpload = $db->table("upload")->where("idproduk", $data->id)->orderBy("jenis", "DESC")->get();
$fotos = $dbUpload->getResult();

// Rating dan ulasan
$ulasan = $func->getBintang($data->id);
$star = $ulasan["star"];
$laku = $func->getLaku($data->id);

// Stok dan kondisi
if ($dbv->getNumRows() == 0) {
    $totalstok = $data->stok;
}

// Flash sale
$tflash = ($data->flash == 1) ? "style = 'display: none;'" : "";

// Jasa atau produk
$keranjang = ($data->jasa == 1) ? " pesan jasa" : " + keranjang";

// Variabel untuk variasi produk
$warnaid = [];
$sizeid = [];
$variasi = [];
$har = [];
$harreseller = [];
$haragen = [];
$haragensp = [];
$hardistri = [];
$stok = [];
$stoks = [];

if ($dbv->getNumRows() > 0) {
    foreach ($dbv->getResult() as $var) {
        $dbf = $db->table("preorder")->where("variasi", $var->id)->get();
        $totalpre = 0;
        foreach ($dbf->getResult() as $rf) {
            $totalpre += $rf->jumlah;
        }

        $warnaid[] = $var->warna;
        $variasi[$var->warna][] = $var->id;
        $sizeid[$var->warna][] = $var->size;
        $har[$var->warna][] = $var->harga;
        $harreseller[$var->warna][] = $var->hargareseller;
        $haragen[$var->warna][] = $var->hargaagen;
        $haragensp[$var->warna][] = $var->hargaagensp;
        $hardistri[$var->warna][] = $var->hargadistri;
        
        $current_stok = ($data->preorder == 0) ? $var->stok : $var->stok - $totalpre;
        
        if (isset($stoks[$var->warna])) {
            $stoks[$var->warna] += $current_stok;
        } else {
            $stoks[$var->warna] = $current_stok;
        }
        $stok[$var->warna][] = $current_stok;
    }
    
    $warnaid = array_unique($warnaid);
    $warnaid = array_values($warnaid);
}

// Data review untuk rating
$review = $db->table("review")->where("idproduk", $data->id)->get();
$jumlah = 0;
$banyak = 0;
$bintang1 = $bintang2 = $bintang3 = $bintang4 = $bintang5 = 0;

foreach ($review->getResultArray() as $c) {
    $nilai = $c['nilai'];
    $jumlah += $nilai;
    $banyak += 1;
    
    if ($nilai == 1) {
        $bintang1 += 1;
    } else if ($nilai == 2) {
        $bintang2 += 1;
    } else if ($nilai == 3) {
        $bintang3 += 1;
    } else if ($nilai == 4) {
        $bintang4 += 1;
    } else if ($nilai == 5) {
        $bintang5 += 1;
    }
}

$rata2 = $banyak > 0 ? $jumlah / $banyak : 0;
$rata = round($rata2, 1);

$star1 = $banyak > 0 ? round($bintang1 / $banyak * 100) : 0;
$star2 = $banyak > 0 ? round($bintang2 / $banyak * 100) : 0;
$star3 = $banyak > 0 ? round($bintang3 / $banyak * 100) : 0;
$star4 = $banyak > 0 ? round($bintang4 / $banyak * 100) : 0;
$star5 = $banyak > 0 ? round($bintang5 / $banyak * 100) : 0;
?>
<style>
        /* Reset Base Styles khusus halaman ini (tidak menyentuh body/tema global) */
        .main-container, .main-container * {
            box-sizing: border-box;
        }

        .action-btn {
            background: none;
            border: none;
            color: #64748b;
            font-size: 18px;
            cursor: pointer;
        }
        
        /* Main Container */
        .main-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px 15px;
        }
        
        /* Product Gallery */
        .product-gallery {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            margin-bottom: 20px;
        }
        
        .gallery-image {
            width: 100%;
            height: 300px;
            object-fit: contain;
            background: #f1f5f9;
        }
        
        .gallery-thumbnails {
            display: flex;
            overflow-x: auto;
            padding: 10px;
            gap: 10px;
            background: white;
        }
        
        .thumbnail {
            width: 60px;
            height: 60px;
            border-radius: 8px;
            object-fit: cover;
            border: 2px solid transparent;
            cursor: pointer;
        }
        
        .thumbnail.active {
            border-color: #4f46e5;
        }
        
        /* Product Info Card */
        .product-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }
        
        .product-name {
            font-size: 22px;
            font-weight: 700;
            margin-bottom: 10px;
            color: #1e293b;
        }
        
        .product-meta {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }
        
        .rating-badge {
            display: flex;
            align-items: center;
            gap: 5px;
            background: #ffedd5;
            color: #ea580c;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
        }
        
        .stock-badge {
            background: <?= $totalstok > 0 ? '#d1fae5' : '#fee2e2' ?>;
            color: <?= $totalstok > 0 ? '#065f46' : '#991b1b' ?>;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
        }
        
        .flash-badge {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
        }
        
        .price-section {
            margin: 20px 0;
        }
        
        .current-price {
            font-size: 28px;
            font-weight: 800;
            color: #4f46e5;
            margin-bottom: 5px;
        }
        
        .original-price {
            color: #94a3b8;
            text-decoration: line-through;
            font-size: 16px;
        }
        
        .discount-badge {
            background: #ef4444;
            color: white;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 14px;
            margin-left: 10px;
        }
        
        /* Info Grid */
        .info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            margin: 20px 0;
        }
        
        .info-item {
            background: #f8fafc;
            border-radius: 8px;
            padding: 12px;
            border: 1px solid #e2e8f0;
        }
        
        .info-label {
            font-size: 12px;
            color: #64748b;
            margin-bottom: 4px;
        }
        
        .info-value {
            font-size: 14px;
            font-weight: 600;
            color: #1e293b;
        }
        
        /* Description */
        .description-box {
            background: #f8fafc;
            border-radius: 8px;
            padding: 15px;
            margin: 20px 0;
            border: 1px solid #e2e8f0;
        }
        
        .description-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 10px;
            color: #1e293b;
        }
        
        .description-content {
            color: #475569;
            line-height: 1.6;
        }
        
        /* Action Buttons */
        .action-buttons {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }
        
        .btn {
            flex: 1;
            padding: 14px 20px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 16px;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            color: white;
        }
        
        .btn-primary:hover {
            opacity: 0.9;
            transform: translateY(-2px);
        }
        
        .btn-whatsapp {
            background: linear-gradient(135deg, #25D366, #128C7E);
            color: white;
        }
        
        .btn-whatsapp:hover {
            opacity: 0.9;
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background: #f1f5f9;
            color: #475569;
            border: 1px solid #cbd5e1;
        }
        
        /* Tabs Section */
        .tabs-section {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            margin-top: 20px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }
        
        .tabs-header {
            display: flex;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .tab-btn {
            flex: 1;
            padding: 16px;
            background: none;
            border: none;
            color: #64748b;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            text-align: center;
        }
        
        .tab-btn.active {
            color: #4f46e5;
            border-bottom: 3px solid #4f46e5;
        }
        
        .tab-content {
            padding: 20px;
        }
        
        /* Review Item */
        .review-item {
            padding: 15px 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .review-item:last-child {
            border-bottom: none;
        }
        
        .review-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .reviewer-name {
            font-weight: 600;
            color: #1e293b;
        }
        
        .review-date {
            color: #94a3b8;
            font-size: 14px;
        }
        
        .review-rating {
            color: #f59e0b;
            margin-bottom: 10px;
        }
        
        .review-text {
            color: #475569;
            line-height: 1.6;
        }
        
        /* Rating Summary */
        .rating-summary {
            display: flex;
            align-items: center;
            gap: 30px;
            margin-bottom: 30px;
        }
        
        .rating-average {
            text-align: center;
            min-width: 120px;
        }
        
        .rating-score {
            font-size: 40px;
            font-weight: 700;
            color: #1e293b;
        }
        
        .rating-stars {
            color: #f59e0b;
            margin: 8px 0;
        }
        
        .rating-count {
            color: #64748b;
            font-size: 14px;
        }
        
        .rating-bars {
            flex: 1;
        }
        
        .rating-bar {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
        }
        
        .rating-label {
            width: 70px;
            color: #64748b;
            font-size: 14px;
        }
        
        .rating-progress {
            flex: 1;
            height: 8px;
            background: #e2e8f0;
            border-radius: 4px;
            overflow: hidden;
            margin: 0 10px;
        }
        
        .rating-fill {
            height: 100%;
            background: #f59e0b;
            border-radius: 4px;
        }
        
        .rating-percent {
            width: 40px;
            text-align: right;
            color: #64748b;
            font-size: 14px;
        }
        
        /* Modal */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            padding: 20px;
        }
        
        .modal-content {
            background: white;
            border-radius: 12px;
            max-width: 500px;
            width: 100%;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .modal-header {
            padding: 20px;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-title {
            font-size: 18px;
            font-weight: 600;
            margin: 0;
            color: #1e293b;
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            color: #64748b;
            cursor: pointer;
        }
        
        .modal-body {
            padding: 20px;
        }
        
        /* Form Styles */
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #374151;
        }
        
        .form-control {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            font-size: 16px;
        }
        
        .form-control:focus {
            outline: none;
            border-color: #4f46e5;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }
        
        /* Quantity Selector */
        .quantity-selector {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .qty-btn {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: white;
            border: 1px solid #d1d5db;
            font-size: 20px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .qty-input {
            width: 70px;
            height: 40px;
            text-align: center;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 600;
        }
        
        /* Flash Timer */
        .flash-timer {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            margin-top: 10px;
        }
        
        .timer-part {
            background: rgba(255, 255, 255, 0.2);
            padding: 4px 8px;
            border-radius: 4px;
            min-width: 30px;
            text-align: center;
        }
        
        /* Mobile Footer */
        .mobile-footer {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            border-top: 1px solid #e2e8f0;
            padding: 12px 15px;
            display: none;
            z-index: 100;
        }
        
        .footer-buttons {
            display: flex;
            gap: 10px;
        }
        
        .footer-btn {
            flex: 1;
            padding: 12px;
            border-radius: 8px;
            font-weight: 600;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .gallery-image {
                height: 250px;
            }
            
            .product-name {
                font-size: 20px;
            }
            
            .current-price {
                font-size: 24px;
            }
            
            .info-grid {
                grid-template-columns: 1fr;
            }
            
            .rating-summary {
                flex-direction: column;
                gap: 20px;
            }
            
            .mobile-footer {
                display: block;
            }
            
            body {
                padding-bottom: 100px;
            }
        }
        
        @media (max-width: 576px) {
            .main-container {
                padding: 15px 10px;
            }
            
            .action-buttons {
                flex-direction: column;
            }
            
            .btn {
                width: 100%;
            }
            
            .footer-buttons {
                flex-direction: column;
            }
        }
        
        /* Animations */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .animate-fade {
            animation: fadeIn 0.3s ease-out;
        }
    </style>
<?= view('customer/menu', ['func' => $func, 'db' => $db]) ?>

    <!-- Main Content -->
    <div class="main-container">
        
        <!-- Product Gallery -->
        <div class="product-gallery animate-fade">
            <div id="productGallery" class="carousel slide" data-ride="carousel">
                <div class="carousel-inner">
                    <?php 
                    $first = true;
                    foreach ($dbUpload->getResult() as $index => $res): 
                    ?>
                        <div class="carousel-item <?= $first ? 'active' : '' ?>">
                            <img src="<?= base_url("admin/uploads/" . $res->nama); ?>" 
                                 class="d-block w-100 gallery-image" 
                                 alt="<?= $data->nama ?>">
                        </div>
                    <?php 
                        $first = false;
                    endforeach; 
                    ?>
                </div>
                
                <?php if ($dbUpload->getNumRows() > 1): ?>
                    <a class="carousel-control-prev" href="#productGallery" role="button" data-slide="prev">
                        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                        <span class="sr-only">Previous</span>
                    </a>
                    <a class="carousel-control-next" href="#productGallery" role="button" data-slide="next">
                        <span class="carousel-control-next-icon" aria-hidden="true"></span>
                        <span class="sr-only">Next</span>
                    </a>
                <?php endif; ?>
            </div>
            
            <!-- Thumbnails -->
            <?php if ($dbUpload->getNumRows() > 1): ?>
                <div class="gallery-thumbnails">
                    <?php foreach ($dbUpload->getResult() as $index => $res): ?>
                        <img src="<?= base_url("admin/uploads/" . $res->nama); ?>" 
                             class="thumbnail <?= $index == 0 ? 'active' : '' ?>" 
                             onclick="changeSlide(<?= $index ?>)" 
                             alt="Thumbnail <?= $index + 1 ?>">
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            
            <!-- Flash Sale Timer -->
            <?php if ($data->flash == 1): ?>
                <div class="flash-timer ml-3 mt-2">
                    <i class="fas fa-bolt"></i>
                    <span id="flashDays">00</span>:<span id="flashHours">00</span>:<span id="flashMinutes">00</span>:<span id="flashSeconds">00</span>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Product Info Card -->
        <div class="product-card animate-fade" style="animation-delay: 0.1s">
            <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:10px">
                <h1 class="product-name" style="margin-bottom:0"><?= htmlspecialchars($data->nama, ENT_QUOTES, 'UTF-8') ?></h1>
                <button class="action-btn" onclick="openShareModal()" title="Bagikan produk ini">
                    <i class="fas fa-share-alt"></i>
                </button>
            </div>

            <div class="product-meta">
                <span class="rating-badge">
                    <i class="fas fa-star"></i>
                    <?= number_format($ulasan["star"], 1) ?>
                    <?php if ($ulasan["jml"] > 0): ?>
                        <span>(<?= $ulasan["jml"] ?>)</span>
                    <?php endif; ?>
                </span>
                
                <span class="stock-badge">
                    <?php if ($totalstok > 0): ?>
                        <i class="fas fa-check"></i> Stok: <?= $totalstok ?>
                    <?php else: ?>
                        <i class="fas fa-times"></i> Stok Habis
                    <?php endif; ?>
                </span>
                
                <?php if ($data->flash == 1): ?>
                    <span class="flash-badge">
                        <i class="fas fa-bolt"></i> Flash Sale
                    </span>
                <?php endif; ?>
                
                <?php if ($kategorinama): ?>
                    <span class="badge badge-light">
                        <?= $kategorinama ?>
                    </span>
                <?php endif; ?>
            </div>
            
            <!-- Price Section -->
            <div class="price-section">
                <div class="current-price">
                    <?php
                    if ($hargs > 0) {
                        echo "Rp " . $func->formUang(min($harga) - (min($harga) * $data->diskon) / 100) . " - " . $func->formUang(max($harga) - (max($harga) * $data->diskon) / 100);
                    } else {
                        echo "Rp " . $func->formUang($result - ($result * $data->diskon) / 100);
                    }
                    ?>
                </div>
                
                <?php if ($data->diskon > 0): ?>
                    <div class="original-price">
                        <?= $hargaawal ?>
                        <span class="discount-badge"><?= $data->diskon ?>% OFF</span>
                    </div>
                <?php endif; ?>
                
                <div class="text-muted small mt-2">
                    <i class="fas fa-eye"></i> Dilihat <?= $data->dilihat ?> kali
                    <?php if ($data->jasa != 1): ?>
                        | <i class="fas fa-shopping-bag"></i> Terjual <?= $laku["terjual"] ?> item
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Product Info Grid -->
            <div class="info-grid">
                <div class="info-item">
                    <div class="info-label">Status</div>
                    <div class="info-value">
                        <?php if ($data->preorder != 0): ?>
                            <span class="badge badge-warning">PREORDER</span>
                        <?php else: ?>
                            <span class="badge badge-success">Tersedia</span>
                        <?php endif; ?>
                    </div>
                </div>
                
                <?php if ($kategorinama): ?>
                    <div class="info-item">
                        <div class="info-label">Kategori</div>
                        <div class="info-value">
                            <a href="<?= base_url("kategori/" . $kategoriurl); ?>" class="text-primary">
                                <?= $kategorinama ?>
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
                
                <?php if ($data->berat): ?>
                    <div class="info-item">
                        <div class="info-label">Berat</div>
                        <div class="info-value"><?= $data->berat ?> gram</div>
                    </div>
                <?php endif; ?>
                
                <?php if ($data->minorder > 1): ?>
                    <div class="info-item">
                        <div class="info-label">Minimal Beli</div>
                        <div class="info-value"><?= $data->minorder ?> item</div>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- Description -->
            <?php if ($data->deskripsi): ?>
                <div class="description-box">
                    <div class="description-title">
                        <i class="fas fa-file-alt mr-2"></i> Deskripsi Produk
                    </div>
                    <div class="description-content">
                        <?= $data->deskripsi ?>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- Action Buttons (Desktop) -->
            <?php if ($totalstok > 0): ?>
                <div class="action-buttons d-none d-md-flex">
                    <?php if ($func->cekLogin() == true): ?>
                        <button class="btn btn-primary" onclick="openCartModal()">
                            <i class="fas fa-shopping-cart"></i>
                            <?= $textorder ?>
                        </button>
                    <?php else: ?>
                        <a href="<?= site_url("home/signin"); ?>" class="btn btn-primary">
                            <i class="fas fa-shopping-cart"></i>
                            <?= $textorder ?>
                        </a>
                    <?php endif; ?>
                    
                    <a href="https://wa.me/<?= $func->getRandomWasap() ?>/?text=Halo,%20saya%20ingin%20membeli%20produk%20*<?= urlencode($data->nama) ?>*%20apakah%20masih%20tersedia?" 
                       target="_blank" class="btn btn-whatsapp">
                        <i class="fab fa-whatsapp"></i>
                        Chat WA
                    </a>
                </div>
            <?php else: ?>
                <button class="btn btn-secondary" disabled>
                    <?php if ($data->preorder == 0): ?>
                        <i class="fas fa-times-circle"></i> Stok Habis
                    <?php else: ?>
                        <i class="fas fa-times-circle"></i> Kuota Penuh
                    <?php endif; ?>
                </button>
            <?php endif; ?>
        </div>
        
        <!-- Tabs Section -->
        <div class="tabs-section animate-fade" style="animation-delay: 0.2s">
            <div class="tabs-header">
                <button class="tab-btn active" onclick="switchTab('ulasan')">
                    <i class="fas fa-comment"></i> Ulasan (<?= $ulasan["jml"] ?>)
                </button>
                <button class="tab-btn" onclick="switchTab('rating')">
                    <i class="fas fa-star"></i> Rating
                </button>
            </div>
            
            <div class="tab-content">
                <!-- Ulasan Tab -->
                <div id="tabUlasan" class="tab-pane active">
                    <?php
                    $re = $db->table("review")->where("idproduk", $data->id)->orderBy("nilai,id DESC")->limit(8)->get();
                    
                    if ($re->getNumRows() > 0):
                        foreach ($re->getResult() as $rev):
                            $stars = '';
                            for ($i = 1; $i <= 5; $i++) {
                                $stars .= ($i <= $rev->nilai) ? '<i class="fas fa-star text-warning"></i>' : '<i class="far fa-star text-warning"></i>';
                            }
                    ?>
                            <div class="review-item">
                                <div class="review-header">
                                    <div class="reviewer-name">
                                        <?= $func->getProfil($rev->usrid, "nama", "usrid") ?>
                                    </div>
                                    <div class="review-date">
                                        <?= $func->ubahTgl("d/m/Y", $rev->tgl) ?>
                                    </div>
                                </div>
                                <div class="review-rating">
                                    <?= $stars ?>
                                </div>
                                <div class="review-text">
                                    <?= nl2br(htmlspecialchars($rev->keterangan)) ?>
                                </div>
                            </div>
                    <?php 
                        endforeach;
                    else:
                    ?>
                        <div class="text-center py-4">
                            <i class="fas fa-comment-slash fa-3x text-muted mb-3"></i>
                            <p class="text-muted">Belum ada ulasan untuk produk ini</p>
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- Rating Tab -->
                <div id="tabRating" class="tab-pane" style="display: none;">
                    <div class="rating-summary">
                        <div class="rating-average">
                            <div class="rating-score"><?= number_format($rata, 1) ?></div>
                            <div class="rating-stars">
                                <?php
                                $fullStars = floor($rata);
                                $hasHalfStar = ($rata - $fullStars) >= 0.5;
                                
                                for ($i = 1; $i <= 5; $i++) {
                                    if ($i <= $fullStars) {
                                        echo '<i class="fas fa-star"></i>';
                                    } elseif ($i == $fullStars + 1 && $hasHalfStar) {
                                        echo '<i class="fas fa-star-half-alt"></i>';
                                    } else {
                                        echo '<i class="far fa-star"></i>';
                                    }
                                }
                                ?>
                            </div>
                            <div class="rating-count"><?= $banyak ?> ulasan</div>
                        </div>
                        
                        <div class="rating-bars">
                            <?php for ($i = 5; $i >= 1; $i--): 
                                $percent = ${'star' . $i};
                            ?>
                                <div class="rating-bar">
                                    <div class="rating-label"><?= $i ?> bintang</div>
                                    <div class="rating-progress">
                                        <div class="rating-fill" style="width: <?= $percent ?>%"></div>
                                    </div>
                                    <div class="rating-percent"><?= $percent ?>%</div>
                                </div>
                            <?php endfor; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Produk Terkait -->
        <?php if (is_object($kategori)): ?>
        <div class="animate-fade" style="animation-delay: 0.3s">
            <?= view('customer/main/produks_terkait', ['func' => $func, 'db' => $db, 'kategori' => $kategori, 'data' => $data]) ?>
        </div>
        <?php endif; ?>
        
    </div>
    
    <!-- Mobile Footer -->
    <?php if ($totalstok > 0): ?>
        <div class="mobile-footer">
            <div class="footer-buttons">
                <?php if ($func->cekLogin() == true): ?>
                    <button class="footer-btn btn-primary" onclick="openCartModal()">
                        <i class="fas fa-shopping-cart"></i>
                        <?= $textorder ?>
                    </button>
                <?php else: ?>
                    <a href="<?= site_url("home/signin"); ?>" class="footer-btn btn-primary">
                        <i class="fas fa-shopping-cart"></i>
                        <?= $textorder ?>
                    </a>
                <?php endif; ?>
                
                <a href="https://wa.me/<?= $func->getRandomWasap() ?>/?text=Halo,%20saya%20ingin%20membeli%20produk%20*<?= urlencode($data->nama) ?>*%20apakah%20masih%20tersedia?" 
                   target="_blank" class="footer-btn btn-whatsapp">
                    <i class="fab fa-whatsapp"></i>
                    Chat WA
                </a>
            </div>
        </div>
    <?php endif; ?>
    
    <!-- Share Modal -->
    <div id="shareModal" class="modal-overlay">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Bagikan Produk</h5>
                <button class="modal-close" onclick="closeModal('shareModal')">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label">Link Produk</label>
                    <input type="text" class="form-control" id="shareUrl" 
                           value="<?= site_url('produk/' . $data->url); ?>" readonly>
                </div>
                
                <div class="text-center mt-3">
                    <button class="btn btn-primary" onclick="copyToClipboard()">
                        <i class="fas fa-copy"></i> Salin Link
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Cart Modal -->
    <div id="cartModal" class="modal-overlay">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Tambah ke Keranjang</h5>
                <button class="modal-close" onclick="closeModal('cartModal')">&times;</button>
            </div>
            <div class="modal-body">
                <form id="keranjangForm">
                    <input type="hidden" name="<?= csrf_token(); ?>" value="<?= csrf_hash(); ?>">
                    <input type="hidden" name="idproduk" value="<?= $data->id; ?>">
                    <input type="hidden" id="variasiInput" name="variasi" value="0">
                    <input type="hidden" id="hargaInput" name="harga" value="<?= $result - ($result * $data->diskon) / 100 ?>">
                    
                    <div class="row mb-4">
                        <div class="col-4">
                            <?php if ($dbUpload->getNumRows() > 0): ?>
                                <img src="<?= base_url("admin/uploads/" . $dbUpload->getRow()->nama); ?>" 
                                     class="img-fluid rounded" alt="<?= $data->nama ?>">
                            <?php endif; ?>
                        </div>
                        <div class="col-8">
                            <h6><?= htmlspecialchars($data->nama) ?></h6>
                            <div class="current-price mb-2" id="hargaDisplay">
                                <?php
                                if ($hargs > 0) {
                                    echo "Rp " . $func->formUang(min($harga) - (min($harga) * $data->diskon) / 100) . " - " . $func->formUang(max($harga) - (min($harga) * $data->diskon) / 100);
                                } else {
                                    echo "Rp " . $func->formUang($result - ($result * $data->diskon) / 100);
                                }
                                ?>
                            </div>
                            <div class="badge badge-warning" id="stokDisplay">
                                STOK: <?= $totalstok ?>
                            </div>
                        </div>
                    </div>
                    
                    <?php if ($dbv->getNumRows() > 0): ?>
                        <div class="form-group">
                            <label class="form-label"><?= $data->variasi ?></label>
                            <select class="form-control" id="warnaSelect" required>
                                <option value="">Pilih <?= $data->variasi ?></option>
                                <?php for ($i = 0; $i < count($warnaid); $i++):
                                    if ($stoks[$warnaid[$i]] > 0): ?>
                                        <option value="<?= $warnaid[$i] ?>">
                                            <?= $func->getWarna($warnaid[$i], "nama") ?>
                                        </option>
                                    <?php endif;
                                endfor; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label"><?= $data->subvariasi ?></label>
                            <select class="form-control" id="sizeSelect" required>
                                <option value="">Pilih <?= $data->variasi ?> dulu</option>
                            </select>
                        </div>
                    <?php endif; ?>
                    
                    <div class="form-group">
                        <label class="form-label">Jumlah</label>
                        <div class="quantity-selector">
                            <button type="button" class="qty-btn" onclick="decreaseQty()">-</button>
                            <input type="number" class="qty-input" id="qtyInput" 
                                   name="jumlah" value="<?= $data->minorder ?>" 
                                   min="<?= $data->minorder ?>" max="<?= $totalstok ?>">
                            <button type="button" class="qty-btn" onclick="increaseQty()">+</button>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Keterangan (opsional)</label>
                        <textarea class="form-control" name="keterangan" rows="2"></textarea>
                    </div>
                    
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-shopping-cart"></i> <?= $textorder ?>
                    </button>
                    
                    <div id="loadingSpinner" class="text-center mt-3" style="display: none;">
                        <div class="spinner-border text-primary" role="status">
                            <span class="sr-only">Loading...</span>
                        </div>
                        <p class="mt-2">Memproses...</p>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- JavaScript Libraries -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
    // CSRF Token Setup
    var csrfToken = '<?= csrf_hash() ?>';
    var csrfName = '<?= csrf_token() ?>';
    
    // Product Data
    var productId = <?= $data->id ?>;
    var productName = '<?= addslashes($data->nama) ?>';
    var isJasa = <?= $data->jasa == 1 ? 'true' : 'false' ?>;
    var isPreorder = <?= $data->preorder != 0 ? 'true' : 'false' ?>;
    
    // Modal Functions
    function openModal(modalId) {
        document.getElementById(modalId).style.display = 'flex';
        document.body.style.overflow = 'hidden';
    }
    
    function closeModal(modalId) {
        document.getElementById(modalId).style.display = 'none';
        document.body.style.overflow = 'auto';
    }
    
    function openShareModal() {
        openModal('shareModal');
    }
    
    function openCartModal() {
        openModal('cartModal');
    }
    
    // Copy to Clipboard
    function copyToClipboard() {
        var copyText = document.getElementById("shareUrl");
        copyText.select();
        copyText.setSelectionRange(0, 99999);
        document.execCommand("copy");
        alert("Link berhasil disalin!");
    }
    
    // Tab Switching
    function switchTab(tabName) {
        // Update buttons
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        event.target.classList.add('active');
        
        // Update content
        document.getElementById('tabUlasan').style.display = 'none';
        document.getElementById('tabRating').style.display = 'none';
        document.getElementById('tab' + tabName.charAt(0).toUpperCase() + tabName.slice(1)).style.display = 'block';
    }
    
    // Quantity Control
    function decreaseQty() {
        var input = document.getElementById('qtyInput');
        var value = parseInt(input.value) || 1;
        var min = parseInt(input.min) || 1;
        if (value > min) {
            input.value = value - 1;
        }
    }
    
    function increaseQty() {
        var input = document.getElementById('qtyInput');
        var value = parseInt(input.value) || 1;
        var max = parseInt(input.max) || 999;
        if (value < max) {
            input.value = value + 1;
        }
    }
    
    // Variasi Selection
    <?php if ($dbv->getNumRows() > 0): ?>
        // Generate options for each warna
        var variasiOptions = {};
        <?php for ($i = 0; $i < count($warnaid); $i++): ?>
            variasiOptions[<?= $warnaid[$i] ?>] = `<option value="">Pilih <?= $data->subvariasi ?></option>`;
            <?php for ($a = 0; $a < count($sizeid[$warnaid[$i]]); $a++): ?>
                <?php if ($stok[$warnaid[$i]][$a] > 0): ?>
                    <?php
                    if ($level == 5) {
                        $harga_var = $hardistri[$warnaid[$i]][$a];
                    } elseif ($level == 4) {
                        $harga_var = $haragensp[$warnaid[$i]][$a];
                    } elseif ($level == 3) {
                        $harga_var = $haragen[$warnaid[$i]][$a];
                    } elseif ($level == 2) {
                        $harga_var = $harreseller[$warnaid[$i]][$a];
                    } else {
                        $harga_var = $har[$warnaid[$i]][$a];
                    }
                    $harga_var = $harga_var - ($harga_var * $data->diskon) / 100;
                    ?>
                    variasiOptions[<?= $warnaid[$i] ?>] += 
                        `<option value="<?= $sizeid[$warnaid[$i]][$a] ?>" 
                                data-stok="<?= $stok[$warnaid[$i]][$a] ?>" 
                                data-harga="<?= $harga_var ?>" 
                                data-variasi="<?= $variasi[$warnaid[$i]][$a] ?>">
                            <?= $func->getSize($sizeid[$warnaid[$i]][$a], "nama") ?>
                        </option>`;
                <?php endif; ?>
            <?php endfor; ?>
        <?php endfor; ?>
        
        // Event listener for warna select
        document.getElementById('warnaSelect').addEventListener('change', function() {
            var warnaId = this.value;
            var sizeSelect = document.getElementById('sizeSelect');
            
            if (warnaId && variasiOptions[warnaId]) {
                sizeSelect.innerHTML = variasiOptions[warnaId];
                sizeSelect.disabled = false;
            } else {
                sizeSelect.innerHTML = '<option value="">Pilih <?= $data->variasi ?> dulu</option>';
                sizeSelect.disabled = true;
            }
            
            // Reset harga and stok display
            document.getElementById('stokDisplay').textContent = 'STOK: <?= $totalstok ?>';
        });
        
        // Event listener for size select
        document.getElementById('sizeSelect').addEventListener('change', function() {
            var selectedOption = this.options[this.selectedIndex];
            if (selectedOption.value) {
                var stok = selectedOption.getAttribute('data-stok');
                var harga = selectedOption.getAttribute('data-harga');
                var variasi = selectedOption.getAttribute('data-variasi');
                
                document.getElementById('variasiInput').value = variasi;
                document.getElementById('hargaInput').value = harga;
                document.getElementById('hargaDisplay').textContent = 'Rp ' + formatUang(harga);
                document.getElementById('stokDisplay').textContent = 'STOK: ' + stok;
                
                // Update max quantity
                document.getElementById('qtyInput').max = stok;
                if (parseInt(document.getElementById('qtyInput').value) > stok) {
                    document.getElementById('qtyInput').value = stok;
                }
            }
        });
    <?php endif; ?>
    
    // Form Submission
    document.getElementById('keranjangForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        // Validate form
        <?php if ($dbv->getNumRows() > 0): ?>
            if (!document.getElementById('warnaSelect').value || !document.getElementById('sizeSelect').value) {
                alert('Silakan pilih variasi produk terlebih dahulu');
                return;
            }
        <?php endif; ?>
        
        var formData = new FormData(this);
        formData.append(csrfName, csrfToken);
        
        // Show loading
        document.getElementById('loadingSpinner').style.display = 'block';
        
        // Determine endpoint
        var endpoint = isPreorder ? '<?= site_url("assync/prosespreorder") ?>' : '<?= site_url("assync/prosesbeli") ?>';
        
        fetch(endpoint, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            document.getElementById('loadingSpinner').style.display = 'none';
            
            if (data.success) {
                // Facebook Pixel
                if (typeof fbq !== 'undefined') {
                    fbq('track', 'AddToCart', {
                        content_ids: productId.toString(),
                        content_type: 'product',
                        content_name: productName,
                        currency: 'IDR',
                        value: data.total
                    });
                }
                
                alert(isPreorder ? 'Berhasil mengikuti preorder!' : 'Produk berhasil ditambahkan ke keranjang!');
                closeModal('cartModal');
                
                // Redirect based on type
                if (isJasa) {
                    window.location.href = '<?= site_url("home/keranjangjasa") ?>';
                } else if (isPreorder) {
                    window.location.href = '<?= site_url("home/invoicepreorder") ?>?inv=' + data.inv;
                } else {
                    window.location.href = '<?= site_url("home/keranjang") ?>';
                }
            } else {
                alert('Gagal: ' + (data.msg || 'Terjadi kesalahan'));
            }
        })
        .catch(error => {
            document.getElementById('loadingSpinner').style.display = 'none';
            console.error('Error:', error);
            alert('Terjadi kesalahan saat memproses permintaan');
        });
    });
    
    // Carousel Controls
    function changeSlide(index) {
        $('#productGallery').carousel(index);
        updateThumbnails(index);
    }
    
    function updateThumbnails(activeIndex) {
        document.querySelectorAll('.thumbnail').forEach((thumb, index) => {
            thumb.classList.remove('active');
            if (index === activeIndex) {
                thumb.classList.add('active');
            }
        });
    }
    
    // Initialize carousel
    $(document).ready(function() {
        $('#productGallery').on('slid.bs.carousel', function (e) {
            var activeIndex = $(this).find('.carousel-item.active').index();
            updateThumbnails(activeIndex);
        });
    });
    
    // Flash Sale Timer
    <?php if ($data->flash == 1): ?>
        function startFlashTimer() {
            var endTime = new Date("<?= $selesai ?>").getTime();
            
            var timer = setInterval(function() {
                var now = new Date().getTime();
                var distance = endTime - now;
                
                if (distance < 0) {
                    clearInterval(timer);
                    document.getElementById('flashDays').textContent = '00';
                    document.getElementById('flashHours').textContent = '00';
                    document.getElementById('flashMinutes').textContent = '00';
                    document.getElementById('flashSeconds').textContent = '00';
                    return;
                }
                
                var days = Math.floor(distance / (1000 * 60 * 60 * 24));
                var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                var seconds = Math.floor((distance % (1000 * 60)) / 1000);
                
                document.getElementById('flashDays').textContent = days.toString().padStart(2, '0');
                document.getElementById('flashHours').textContent = hours.toString().padStart(2, '0');
                document.getElementById('flashMinutes').textContent = minutes.toString().padStart(2, '0');
                document.getElementById('flashSeconds').textContent = seconds.toString().padStart(2, '0');
            }, 1000);
        }
        
        // Start timer when page loads
        window.addEventListener('load', startFlashTimer);
    <?php endif; ?>
    
    // Utility function to format currency
    function formatUang(angka) {
        var number_string = angka.toString().replace(/[^,\d]/g, ''),
            split = number_string.split(','),
            sisa = split[0].length % 3,
            rupiah = split[0].substr(0, sisa),
            ribuan = split[0].substr(sisa).match(/\d{3}/gi);
            
        if (ribuan) {
            separator = sisa ? '.' : '';
            rupiah += separator + ribuan.join('.');
        }
        
        rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
        return rupiah;
    }
    
    // Close modal when clicking outside
    window.onclick = function(event) {
        if (event.target.classList.contains('modal-overlay')) {
            event.target.style.display = 'none';
            document.body.style.overflow = 'auto';
        }
    }
    </script>
</body>