<?php
require_once __DIR__ . '/functions.php';
$db = db();

$slug = $_GET['slug'] ?? '';
$product = $db->prepare("SELECT p.*, c.name as category_name, c.slug as category_slug FROM products p LEFT JOIN categories c ON p.category_id = c.id WHERE p.slug = ? AND p.is_active = 1");
$product->execute([$slug]);
$product = $product->fetch();

if (!$product) {
    http_response_code(404);
    $page_title = 'Product Not Found';
    require_once __DIR__ . '/includes/header.php';
    echo '<div class="text-center py-20"><i class="fas fa-box-open text-gray-300 text-6xl mb-4"></i><h1 class="text-2xl font-bold text-gray-800">Product Not Found</h1><p class="text-gray-500 mt-2">The product you\'re looking for doesn\'t exist.</p><a href="catalog.php" class="inline-block mt-4 bg-primary-600 text-white px-6 py-2 rounded-lg">Browse Products</a></div>';
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

$page_title = $product['name'];
$meta_description = $product['meta_description'] ?: $product['short_description'];

$images = $db->prepare("SELECT * FROM product_images WHERE product_id = ? ORDER BY sort_order, is_primary DESC");
$images->execute([$product['id']]);
$images = $images->fetchAll();

$variants = $db->prepare("SELECT * FROM product_variants WHERE product_id = ? AND is_active = 1");
$variants->execute([$product['id']]);
$variants = $variants->fetchAll();

$variantGroups = [];
$variantImagesMap = [];
foreach ($variants as $v) {
    $variantGroups[$v['type']][] = $v;
    $imgs = $db->prepare("SELECT image_path FROM variant_images WHERE variant_id = ? ORDER BY sort_order, is_primary DESC");
    $imgs->execute([$v['id']]);
    $variantImagesMap[$v['id']] = $imgs->fetchAll(PDO::FETCH_COLUMN);
}

$reviews = $db->prepare("SELECT r.*, u.name as user_name FROM reviews r JOIN users u ON r.user_id = u.id WHERE r.product_id = ? AND r.is_approved = 1 ORDER BY r.created_at DESC");
$reviews->execute([$product['id']]);
$reviews = $reviews->fetchAll();

$ratingData = getProductRating($product['id']);

$related = $db->prepare("SELECT p.*, (SELECT image_path FROM product_images WHERE product_id = p.id AND is_primary = 1 LIMIT 1) as image FROM products p WHERE p.category_id = ? AND p.id != ? AND p.is_active = 1 ORDER BY p.created_at DESC LIMIT 8");
$related->execute([$product['category_id'], $product['id']]);
$related = $related->fetchAll();

$offers = $db->query("SELECT * FROM offers WHERE is_active = 1 ORDER BY sort_order, id")->fetchAll();

$discountPct = $product['compare_price'] > $product['price'] ? round((1 - $product['price'] / $product['compare_price']) * 100) : 0;
$isDealActive = false;
$dealEndTime = '';
$dealStart = $product['deal_start'] ?? null;
$dealEnd = $product['deal_end'] ?? null;
if ($dealStart && $dealEnd) {
    $now = date('Y-m-d H:i:s');
    if ($dealStart <= $now && $dealEnd >= $now) {
        $isDealActive = true;
        $dealEndTime = date('Y/m/d H:i:s', strtotime($product['deal_end']));
    }
}

require_once __DIR__ . '/includes/header.php';
?>

<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 pb-20 sm:pb-4">
    <!-- Breadcrumb -->
    <div class="text-xs text-gray-500 mb-4">
        <a href="index.php" class="hover:text-blue-600 hover:underline">Home</a>
        <span class="mx-1.5 text-gray-300">›</span>
        <?php if ($product['category_name']): ?>
        <a href="catalog.php?category=<?= h($product['category_slug']) ?>" class="hover:text-blue-600 hover:underline"><?= h($product['category_name']) ?></a>
        <span class="mx-1.5 text-gray-300">›</span>
        <?php endif; ?>
        <span class="text-gray-800"><?= h($product['name']) ?></span>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-[auto_1fr_auto] gap-4 sm:gap-6" id="product-grid">
        <!-- ==================== LEFT: Image Gallery ==================== -->
        <div class="w-full lg:w-[480px] xl:w-[520px]" id="image-column">
            <div class="flex flex-col sm:flex-row gap-2 sm:gap-3 relative" style="overflow:visible">
                <!-- Main image (first on mobile) -->
                <div class="flex-1 order-1 sm:order-2 min-w-0 relative" style="overflow:visible">
                    <div class="aspect-square bg-white rounded border border-gray-200 flex items-center justify-center relative cursor-crosshair" id="img-container">
                        <?php if (count($images) > 0): ?>
                        <img src="<?= h($images[0]['image_path']) ?>" alt="<?= h($product['name']) ?>" class="w-full h-full object-contain" id="main-image">
                        <?php else: ?>
                        <i class="fas fa-box text-gray-300 text-8xl"></i>
                        <?php endif; ?>
                        <?php if ($isDealActive): ?>
                        <span class="absolute top-2 left-2 bg-red-600 text-white text-[10px] font-bold px-1.5 py-0.5 rounded-sm uppercase tracking-wide">Limited time deal</span>
                        <?php elseif ($discountPct > 0): ?>
                        <span class="absolute top-2 left-2 bg-red-600 text-white text-xs font-bold px-1.5 py-0.5 rounded-sm">-<?= $discountPct ?>%</span>
                        <?php endif; ?>
                    </div>
                    <!-- Zoom panel (appears to the right of the image) -->
                    <div class="hidden sm:block absolute top-0 left-full ml-4 w-[400px] aspect-square rounded border border-gray-300 overflow-hidden bg-white shadow-xl z-20 pointer-events-none opacity-0 transition-opacity duration-200" id="zoom-panel">
                        <div class="w-full h-full" id="zoom-image" style="background-repeat:no-repeat;background-size:250%"></div>
                    </div>
                </div>
                <!-- Thumbnails (horizontal row on mobile, vertical on desktop) -->
                <?php if (count($images) > 1): ?>
                <div class="flex flex-row sm:flex-col gap-2 order-2 sm:order-1 shrink-0 overflow-x-auto sm:overflow-y-auto sm:max-h-[500px] pb-1 sm:pb-0" id="thumb-gallery">
                    <?php foreach ($images as $i => $img): ?>
                    <div class="w-14 h-14 sm:w-16 sm:h-16 border-2 rounded overflow-hidden cursor-pointer shrink-0 <?= $i === 0 ? 'border-[#007185]' : 'border-gray-200 hover:border-gray-400' ?>" onclick="switchImage(this, '<?= h($img['image_path']) ?>')">
                        <img src="<?= h($img['image_path']) ?>" alt="" class="w-full h-full object-cover">
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- ==================== CENTER: Product Details ==================== -->
        <div class="min-w-0">
            <!-- Brand -->
            <?php if ($product['category_name']): ?>
            <p class="text-xs text-blue-600 font-medium mb-1">
                <a href="catalog.php?category=<?= h($product['category_slug']) ?>" class="hover:text-blue-800 hover:underline"><?= h($product['category_name']) ?></a>
            </p>
            <?php endif; ?>

            <!-- Title -->
            <h1 class="text-lg sm:text-xl lg:text-2xl font-bold text-gray-900 leading-snug"><?= h($product['name']) ?></h1>

            <!-- SKU -->
            <?php if ($product['sku']): ?>
            <p class="text-xs text-gray-400 mt-0.5">SKU: <?= h($product['sku']) ?></p>
            <?php endif; ?>

            <!-- Rating -->
            <div class="flex items-center gap-2 mt-2">
                <div class="flex items-center gap-0.5">
                    <?php for ($i = 1; $i <= 5; $i++): ?>
                    <i class="fas fa-star text-xs <?= $i <= round($ratingData['avg_rating']) ? 'text-yellow-400' : 'text-gray-200' ?>"></i>
                    <?php endfor; ?>
                </div>
                <?php if ($ratingData['count'] > 0): ?>
                <a href="#reviews-section" class="text-xs text-blue-600 hover:text-blue-800 hover:underline"><?= sprintf('%.1f', $ratingData['avg_rating']) ?> (<?= $ratingData['count'] ?>)</a>
                <?php else: ?>
                <span class="text-xs text-gray-400">No reviews yet</span>
                <?php endif; ?>
            </div>

            <!-- Price -->
            <div class="mt-3 pb-3 border-b border-gray-200">
                <?php if ($isDealActive): ?>
                <div class="flex items-center gap-2 mb-1">
                    <span class="bg-red-600 text-white text-[10px] font-bold px-1.5 py-0.5 rounded-sm uppercase tracking-wide">Limited time deal</span>
                    <span class="text-xs text-red-600 font-medium flex items-center gap-1" id="deal-countdown"><i class="far fa-clock"></i> <span id="deal-timer"></span></span>
                </div>
                <?php endif; ?>
                <div class="flex items-baseline gap-2">
                    <span class="text-2xl sm:text-3xl font-bold <?= $isDealActive ? 'text-red-600' : 'text-gray-900' ?>" id="price-display"><?= '₹' . number_format($product['price'], 2) ?></span>
                    <?php if ($discountPct > 0): ?>
                    <span class="text-base text-gray-400 line-through"><?= '₹' . number_format($product['compare_price'], 2) ?></span>
                    <span class="text-sm font-medium <?= $isDealActive ? 'text-red-600' : 'text-green-700' ?>">-<?= $discountPct ?>%</span>
                    <?php endif; ?>
                </div>
                <p class="text-xs text-gray-500 mt-1">inclusive of all taxes</p>
                <?php if ($discountPct > 0): ?>
                <p class="text-xs text-gray-400 mt-0.5">M.R.P.: <span class="line-through"><?= '₹' . number_format($product['compare_price'], 2) ?></span></p>
                <?php endif; ?>
            </div>

            <!-- Offers -->
            <?php if (count($offers) > 0): ?>
            <div class="mt-3 pb-3 border-b border-gray-200">
                <h3 class="text-sm font-semibold text-gray-800 flex items-center gap-1.5 mb-2"><i class="fas fa-tag text-green-600 text-xs"></i> Offers</h3>
                <div class="space-y-1.5">
                    <?php foreach ($offers as $o): ?>
                    <div class="flex items-start gap-2 text-xs text-gray-600">
                        <i class="fas <?= h($o['icon'] ?: 'fa-tag') ?> text-green-500 mt-0.5"></i>
                        <span><?php if ($o['badge_text']): ?><strong class="text-green-700"><?= h($o['badge_text']) ?></strong> <?php endif; ?><?= h($o['description'] ?: $o['title']) ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- About this item -->
            <div class="mt-3 pb-3 border-b border-gray-200">
                <h3 class="text-sm font-semibold text-gray-800 mb-1.5">About this item</h3>
                <ul class="text-xs sm:text-sm text-gray-700 space-y-1 list-disc list-inside leading-relaxed">
                    <?php
                    $bullets = $product['short_description'] ? explode("\n", $product['short_description']) : [$product['description']];
                    foreach (array_slice($bullets, 0, 6) as $b):
                        $b = trim($b);
                        if ($b):
                    ?>
                    <li class="text-gray-600"><?= h($b) ?></li>
                    <?php endif; endforeach; ?>
                </ul>
            </div>

            <!-- Variants -->
            <?php foreach ($variantGroups as $type => $vals): ?>
            <?php $isColor = strtolower($type) === 'color'; ?>
            <div class="mt-3 pb-3 border-b border-gray-200 flex items-baseline gap-3 flex-wrap">
                <div class="text-sm text-gray-700 shrink-0">
                    <span class="font-medium"><?= h(ucfirst($type)) ?>:</span>
                    <b class="text-gray-900" id="variant-label-<?= h($type) ?>"><?= h($vals[0]['value']) ?></b>
                </div>
                <div class="flex flex-wrap gap-1.5">
<?php foreach ($vals as $i => $v):
                        $hex = $v['value'];
                        $imgPath = $v['image_path'] ? BASE_PATH . '/' . h($v['image_path']) : '';
                        $imgAttr = $imgPath ? 'data-image-path="' . $imgPath . '"' : '';
                        $vImgs = $variantImagesMap[$v['id']] ?? [];
                        $allImgs = array_merge($imgPath ? [$imgPath] : [], array_map(fn($p) => BASE_PATH . '/' . h($p), $vImgs));
                        $imgDataAttr = $allImgs ? 'data-images=\'' . h(json_encode($allImgs)) . '\'' : '';
                        $isSelected = $i === 0;
                    ?>
                    <button type="button" data-variant-id="<?= $v['id'] ?>" data-price-modifier="<?= $v['price_modifier'] ?>" data-variant-type="<?= h($type) ?>" data-variant-value="<?= h($v['value']) ?>" <?= $imgAttr ?> <?= $imgDataAttr ?> class="variant-btn inline-flex items-center gap-1.5 px-2.5 py-1.5 border rounded-lg text-sm cursor-pointer transition-all duration-100 <?= $isSelected ? 'border-2 border-[#007185] bg-[#F0F8FF]' : 'border border-[#D5D9D9] hover:border-[#007185]' ?> <?= $v['stock'] <= 0 ? 'opacity-50 cursor-not-allowed' : '' ?>">
                        <?php if ($imgPath): ?>
                        <img src="<?= $imgPath ?>" class="w-6 h-6 rounded object-cover border border-gray-200 shrink-0">
                        <?php elseif ($isColor && preg_match('/^#[0-9a-f]{6}$/i', $hex)): ?>
                        <span class="w-4 h-4 rounded-full border border-gray-300 shrink-0" style="background:<?= h($hex) ?>"></span>
                        <?php endif; ?>
                        <span class="text-gray-900 leading-none"><?= h($v['value']) ?></span>
                        <?php if ($v['price_modifier'] > 0): ?>
                        <span class="text-gray-500 text-xs leading-none"><?= '₹' . number_format($v['price_modifier'], 0) ?></span>
                        <?php endif; ?>
                    </button>
<?php endforeach; ?>
                </div>
            </div>
            <?php endforeach; ?>

            <!-- Delivery -->
            <div class="mt-3 pb-3 border-b border-gray-200">
                <h3 class="text-sm font-semibold text-gray-800 flex items-center gap-1.5 mb-2"><i class="fas fa-truck text-gray-500 text-xs"></i> Delivery</h3>
                <div class="flex gap-2">
                    <input type="text" id="pincode-input" placeholder="Enter delivery pincode" maxlength="6" class="flex-1 border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500">
                    <button type="button" onclick="checkPincode()" class="bg-blue-600 text-white px-4 py-2 rounded text-sm font-medium hover:bg-blue-700 shrink-0">Check</button>
                </div>
                <div id="pincode-msg" class="mt-2 text-xs hidden"></div>
                <p class="text-xs text-gray-400 mt-1.5">Enter pincode to check availability & estimated delivery date</p>
            </div>
        </div>

        <!-- ==================== RIGHT: Buy Box ==================== -->
        <div class="w-full lg:w-[280px] xl:w-[320px]">
            <div class="border border-gray-300 rounded-lg p-4 lg:sticky lg:top-24">
                <!-- Price -->
                <div class="flex items-baseline gap-2 mb-1">
                    <span class="text-2xl font-bold <?= $isDealActive ? 'text-red-600' : 'text-gray-900' ?>" id="buy-price-display"><?= '₹' . number_format($product['price'], 2) ?></span>
                    <?php if ($discountPct > 0): ?>
                    <span class="text-sm text-gray-400 line-through"><?= '₹' . number_format($product['compare_price'], 2) ?></span>
                    <?php endif; ?>
                </div>
                <?php if ($discountPct > 0): ?>
                <p class="text-xs <?= $isDealActive ? 'text-red-600' : 'text-green-700' ?> font-medium mb-2">You Save: <?= '₹' . number_format($product['compare_price'] - $product['price'], 2) ?> (<?= $discountPct ?>%)</p>
                <?php endif; ?>

                <p class="text-xs text-gray-500 mb-3">inclusive of all taxes</p>

                <!-- Stock -->
                <?php if ($product['stock_quantity'] > 0): ?>
                <p class="text-green-700 text-sm font-medium flex items-center gap-1.5 mb-3"><i class="fas fa-check-circle text-green-500"></i> In Stock</p>
                <?php else: ?>
                <p class="text-red-600 text-sm font-medium flex items-center gap-1.5 mb-3"><i class="fas fa-times-circle"></i> Currently unavailable</p>
                <?php endif; ?>

                <!-- Quantity + Add to Cart -->
                <form id="add-to-cart-form" onsubmit="return addToCart(event)">
                    <input type="hidden" name="action" value="add">
                    <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                    <input type="hidden" name="variant_id" id="selected-variant" value="">

                    <div class="flex items-center gap-2 mb-3">
                        <label class="text-sm text-gray-600">Qty:</label>
                        <select name="quantity" class="border border-gray-300 rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500">
                            <?php for ($i = 1; $i <= min(10, $product['stock_quantity'] ?: 1); $i++): ?>
                            <option value="<?= $i ?>"><?= $i ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>

                    <button type="submit" id="add-to-cart-btn" <?= $product['stock_quantity'] <= 0 ? 'disabled' : '' ?> class="w-full text-center py-2.5 rounded-full text-sm font-semibold transition mb-2 <?= $product['stock_quantity'] > 0 ? 'bg-yellow-400 hover:bg-yellow-500 text-black' : 'bg-gray-200 text-gray-500 cursor-not-allowed' ?>">
                        <i class="fas fa-shopping-cart mr-1.5"></i> Add to Cart
                    </button>
                </form>

                <!-- Buy Now -->
                <form action="<?= BASE_PATH ?>/checkout.php" method="GET" onsubmit="return buyNow(event)">
                    <input type="hidden" name="buy_now" value="<?= $product['id'] ?>">
                    <input type="hidden" name="variant_id" id="buy-variant-id" value="">
                    <button type="submit" id="buy-now-btn" <?= $product['stock_quantity'] <= 0 ? 'disabled' : '' ?> class="w-full text-center py-2.5 rounded-full text-sm font-semibold transition <?= $product['stock_quantity'] > 0 ? 'bg-orange-400 hover:bg-orange-500 text-black' : 'bg-gray-200 text-gray-500 cursor-not-allowed' ?>">
                        Buy Now
                    </button>
                </form>

                <!-- Secure transaction -->
                <div class="mt-3 text-xs text-gray-500 flex items-center gap-1.5 justify-center">
                    <i class="fas fa-lock text-gray-400"></i>
                    <span>Secure transaction</span>
                </div>

                <!-- Wishlist -->
                <button onclick="toggleWishlist(<?= $product['id'] ?>)" id="wishlist-btn" class="mt-3 w-full text-center text-sm text-gray-600 hover:text-red-500 border border-gray-200 rounded-full py-2 transition flex items-center justify-center gap-1.5">
                    <i class="far fa-heart"></i> <span>Add to Wishlist</span>
                </button>

                <div id="cart-msg" class="mt-2 text-sm text-green-600 hidden text-center"><i class="fas fa-check-circle"></i> Added to cart!</div>
            </div>
        </div>
    </div>

    <!-- Mobile sticky bottom bar (Add to Cart / Buy Now) -->
    <div class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-300 p-3 z-30 block sm:hidden shadow-2xl" id="mobile-buy-bar">
        <div class="flex items-center gap-2">
            <div class="flex-1">
                <p class="text-sm font-bold <?= $isDealActive ? 'text-red-600' : 'text-gray-900' ?>" id="mobile-price"><?= '₹' . number_format($product['price'], 2) ?></p>
                <?php if ($discountPct > 0): ?>
                <p class="text-xs text-gray-400 line-through"><?= '₹' . number_format($product['compare_price'], 2) ?></p>
                <?php endif; ?>
            </div>
            <?php if ($product['stock_quantity'] > 0): ?>
            <button type="button" onclick="document.getElementById('add-to-cart-btn').click()" class="bg-yellow-400 text-black px-5 py-2.5 rounded-full text-sm font-semibold">Add to Cart</button>
            <button type="button" onclick="document.getElementById('buy-now-btn').click()" class="bg-orange-400 text-black px-5 py-2.5 rounded-full text-sm font-semibold">Buy Now</button>
            <?php else: ?>
            <button type="button" disabled class="bg-gray-200 text-gray-500 px-5 py-2.5 rounded-full text-sm font-semibold cursor-not-allowed">Out of Stock</button>
            <?php endif; ?>
        </div>
    </div>

    <!-- ==================== Product Description ==================== -->
    <?php if ($product['description']): ?>
    <div class="mt-10 lg:mt-14 bg-white rounded border border-gray-200 p-6 sm:p-8">
        <h2 class="text-lg font-bold text-gray-900 mb-4">Product Description</h2>
        <div class="text-sm text-gray-600 leading-relaxed whitespace-pre-line"><?= h($product['description']) ?></div>
    </div>
    <?php endif; ?>

    <!-- ==================== Customer Reviews ==================== -->
    <div class="mt-10 lg:mt-14" id="reviews-section">
        <h2 class="text-lg font-bold text-gray-900 mb-6">Customer Reviews</h2>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <div class="bg-white rounded border border-gray-200 p-6 text-center">
                <div class="text-4xl font-bold text-gray-900"><?= sprintf('%.1f', $ratingData['avg_rating']) ?></div>
                <div class="flex items-center justify-center gap-0.5 mt-1">
                    <?php for ($i = 1; $i <= 5; $i++): ?>
                    <i class="fas fa-star text-sm <?= $i <= round($ratingData['avg_rating']) ? 'text-yellow-400' : 'text-gray-200' ?>"></i>
                    <?php endfor; ?>
                </div>
                <p class="text-xs text-gray-500 mt-1"><?= $ratingData['count'] ?> rating(s)</p>
            </div>
            <div class="md:col-span-2 bg-white rounded border border-gray-200 p-6">
                <h3 class="text-sm font-semibold text-gray-800 mb-3">Rate this product</h3>
                <?php if (isLoggedIn()): ?>
                <form action="api/review.php" method="POST" class="space-y-3">
                    <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                    <div class="flex gap-1 text-lg" id="rating-stars">
                        <?php for ($i = 1; $i <= 5; $i++): ?>
                        <i class="far fa-star text-gray-300 cursor-pointer hover:text-yellow-400 text-xl" data-rating="<?= $i ?>" onclick="setRating(<?= $i ?>)"></i>
                        <?php endfor; ?>
                    </div>
                    <input type="hidden" name="rating" id="rating-input" value="5">
                    <input type="text" name="title" placeholder="Review title (optional)" class="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500">
                    <textarea name="comment" rows="2" placeholder="Write your review..." class="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"></textarea>
                    <button type="submit" class="bg-blue-600 text-white px-6 py-2 rounded text-sm font-semibold hover:bg-blue-700">Submit Review</button>
                </form>
                <?php else: ?>
                <p class="text-sm text-gray-500">Please <a href="login.php" class="text-blue-600 hover:underline">login</a> to write a review.</p>
                <?php endif; ?>
            </div>
        </div>

        <?php if (count($reviews) > 0): ?>
        <div class="space-y-4">
            <?php foreach ($reviews as $r): ?>
            <div class="bg-white border border-gray-200 rounded p-5">
                <div class="flex items-center justify-between mb-2">
                    <div class="flex items-center gap-2.5">
                        <div class="w-9 h-9 bg-blue-50 rounded-full flex items-center justify-center">
                            <span class="text-sm font-bold text-blue-600"><?= strtoupper(substr($r['user_name'], 0, 1)) ?></span>
                        </div>
                        <div>
                            <span class="font-medium text-gray-800 text-sm"><?= h($r['user_name']) ?></span>
                            <span class="text-xs text-gray-400 ml-2"><?= timeAgo($r['created_at']) ?></span>
                        </div>
                    </div>
                    <div class="flex gap-0.5">
                        <?php for ($i = 1; $i <= 5; $i++): ?>
                        <i class="fas fa-star text-xs <?= $i <= $r['rating'] ? 'text-yellow-400' : 'text-gray-200' ?>"></i>
                        <?php endfor; ?>
                    </div>
                </div>
                <?php if ($r['title']): ?>
                <h4 class="font-semibold text-gray-700 text-sm"><?= h($r['title']) ?></h4>
                <?php endif; ?>
                <?php if ($r['comment']): ?>
                <p class="text-gray-600 text-sm mt-1"><?= h($r['comment']) ?></p>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <p class="text-sm text-gray-500 bg-white rounded border border-gray-200 p-6">No reviews yet. Be the first to review this product!</p>
        <?php endif; ?>
    </div>

    <!-- ==================== Related Products ==================== -->
    <?php if (count($related) > 0): ?>
    <div class="mt-10 lg:mt-14">
        <h2 class="text-lg font-bold text-gray-900 mb-6">Related Products</h2>
        <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4 sm:gap-6">
            <?php foreach ($related as $rp): ?>
            <a href="product.php?slug=<?= h($rp['slug']) ?>" class="bg-white rounded shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition group">
                <div class="aspect-square bg-gray-50 flex items-center justify-center overflow-hidden">
                    <?php if ($rp['image']): ?>
                    <img src="<?= h($rp['image']) ?>" alt="" class="w-full h-full object-cover group-hover:scale-105 transition duration-300">
                    <?php else: ?>
                    <i class="fas fa-box text-gray-300 text-4xl"></i>
                    <?php endif; ?>
                </div>
                <div class="p-3">
                    <h3 class="font-medium text-gray-800 text-xs sm:text-sm line-clamp-2"><?= h($rp['name']) ?></h3>
                    <div class="mt-1.5 flex items-baseline gap-1.5">
                        <span class="font-bold text-gray-900 text-sm"><?= formatPrice($rp['price']) ?></span>
                        <?php if ($rp['compare_price'] > $rp['price']): ?>
                        <span class="text-xs text-gray-400 line-through"><?= formatPrice($rp['compare_price']) ?></span>
                        <?php endif; ?>
                    </div>
                </div>
            </a>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
function setRating(rating) {
    document.getElementById('rating-input').value = rating;
    document.querySelectorAll('#rating-stars i').forEach((el, i) => {
        el.className = i < rating ? 'fas fa-star text-yellow-400 cursor-pointer text-xl' : 'far fa-star text-gray-300 cursor-pointer text-xl';
    });
}

function formatPrice(amount) {
    return '₹' + Number(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

var origImages = <?= json_encode(array_map(fn($img) => BASE_PATH . '/' . $img['image_path'] ?? $img['image_path'], $images)) ?>;
var origThumbsHtml = document.getElementById('thumb-gallery') ? document.getElementById('thumb-gallery').innerHTML : '';

var selectedVariantPrice = 0;

// Init first variant as selected
var firstBtn = document.querySelector('.variant-btn');
if (firstBtn && !firstBtn.classList.contains('opacity-50')) { firstBtn.click(); }

document.querySelectorAll('.variant-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        var type = this.dataset.variantType;
        var val = this.dataset.variantValue;
        document.querySelectorAll('.variant-btn').forEach(b => {
            b.classList.remove('border-2', 'border-[#007185]', 'bg-[#F0F8FF]');
            b.classList.add('border', 'border-[#D5D9D9]');
        });
        this.classList.remove('border', 'border-[#D5D9D9]');
        this.classList.add('border-2', 'border-[#007185]', 'bg-[#F0F8FF]');
        document.getElementById('selected-variant').value = this.dataset.variantId;
        document.getElementById('buy-variant-id').value = this.dataset.variantId;
        var label = document.getElementById('variant-label-' + type);
        if (label) label.textContent = val;

        var imgs = this.dataset.images ? JSON.parse(this.dataset.images) : null;
        var mainImg = document.getElementById('main-image');
        var thumbGallery = document.getElementById('thumb-gallery');

        if (imgs && imgs.length > 0) {
            mainImg.src = imgs[0];
            if (thumbGallery) {
                thumbGallery.innerHTML = imgs.map(function(src, i) {
                    var cls = i === 0 ? 'w-14 h-14 sm:w-16 sm:h-16 border-2 rounded overflow-hidden cursor-pointer shrink-0 border-[#007185]' : 'w-14 h-14 sm:w-16 sm:h-16 border-2 rounded overflow-hidden cursor-pointer shrink-0 border-gray-200 hover:border-gray-400';
                    return '<div class="' + cls + '" onclick="document.getElementById(\'main-image\').src=\'' + src + '\'; document.querySelectorAll(\'#thumb-gallery > div\').forEach(function(el){el.classList.remove(\'border-[#007185]\')}); this.classList.add(\'border-[#007185]\')"><img src="' + src + '" class="w-full h-full object-cover"></div>';
                }).join('');
            }
        } else {
            if (origImages.length > 0) {
                mainImg.src = origImages[0];
            }
            if (thumbGallery && origThumbsHtml) {
                thumbGallery.innerHTML = origThumbsHtml;
            }
        }

        var vPrice = parseFloat(this.dataset.priceModifier) || 0;
        selectedVariantPrice = vPrice;
        var priceEl = document.getElementById('price-display');
        var buyPriceEl = document.getElementById('buy-price-display');
        var mobilePriceEl = document.getElementById('mobile-price');
        if (vPrice > 0) {
            var fp = formatPrice(vPrice);
            if (priceEl) priceEl.textContent = fp;
            if (buyPriceEl) buyPriceEl.textContent = fp;
            if (mobilePriceEl) mobilePriceEl.textContent = fp;
        } else {
            var basePrice = <?= $product['price'] ?>;
            var fp = formatPrice(basePrice);
            if (priceEl) priceEl.textContent = fp;
            if (buyPriceEl) buyPriceEl.textContent = fp;
            if (mobilePriceEl) mobilePriceEl.textContent = fp;
        }
    });
});

async function toggleWishlist(productId) {
    const r = await fetch('api/wishlist.php', { method: 'POST', headers: {'Content-Type':'application/x-www-form-urlencoded'}, body: 'product_id=' + productId });
    const d = await r.json();
    const btn = document.getElementById('wishlist-btn');
    btn.innerHTML = d.action === 'added' ? '<i class="fas fa-heart text-red-500"></i> <span>Remove from Wishlist</span>' : '<i class="far fa-heart"></i> <span>Add to Wishlist</span>';
}

async function addToCart(event) {
    event.preventDefault();
    const form = document.getElementById('add-to-cart-form');
    const btn = document.getElementById('add-to-cart-btn');
    const data = new URLSearchParams(new FormData(form));
    btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Adding...';
    try {
        const r = await fetch('<?= BASE_PATH ?>/api/cart.php', { method: 'POST', body: data });
        const d = await r.json();
        if (d.success) {
            window.location.href = '<?= BASE_PATH ?>/cart.php';
        }
    } catch(e) {
        console.error(e);
    }
    btn.disabled = false; btn.innerHTML = '<i class="fas fa-shopping-cart mr-1.5"></i> Add to Cart';
    return false;
}

async function buyNow(event) {
    event.preventDefault();
    var variantId = document.getElementById('buy-variant-id').value;
    var url = '<?= BASE_PATH ?>/checkout.php?buy_now=<?= $product['id'] ?>';
    if (variantId) url += '&variant_id=' + variantId;
    window.location.href = url;
    return false;
}

async function checkPincode() {
    const pincode = document.getElementById('pincode-input').value.trim();
    const msg = document.getElementById('pincode-msg');
    msg.classList.add('hidden');
    if (!/^\d{6}$/.test(pincode)) {
        msg.className = 'mt-2 text-xs text-red-600'; msg.textContent = 'Enter a valid 6-digit pincode.'; msg.classList.remove('hidden');
        return;
    }
    try {
        const r = await fetch('<?= BASE_PATH ?>/api/pincode.php?pincode=' + pincode);
        const d = await r.json();
        msg.classList.remove('hidden');
        if (d.success) {
            msg.className = 'mt-2 text-xs text-green-700 bg-green-50 border border-green-200 rounded px-3 py-2';
            msg.innerHTML = '<i class="fas fa-check-circle mr-1"></i> ' + d.message;
        } else {
            msg.className = 'mt-2 text-xs text-red-700 bg-red-50 border border-red-200 rounded px-3 py-2';
            msg.innerHTML = '<i class="fas fa-times-circle mr-1"></i> ' + d.message;
        }
    } catch(e) {
        msg.classList.remove('hidden');
        msg.className = 'mt-2 text-xs text-red-600'; msg.textContent = 'Error checking pincode.';
    }
}

// Image zoom on hover
(function() {
    var container = document.getElementById('img-container');
    var img = document.getElementById('main-image');
    var zoomPanel = document.getElementById('zoom-panel');
    var zoomImg = document.getElementById('zoom-image');
    if (!container || !img || !zoomPanel || !zoomImg) return;
    var visible = false;
    container.addEventListener('mouseenter', function() {
        visible = true;
        zoomPanel.classList.remove('opacity-0');
        zoomImg.style.backgroundImage = 'url(' + img.src + ')';
    });
    container.addEventListener('mousemove', function(e) {
        if (!visible) return;
        var rect = this.getBoundingClientRect();
        var x = ((e.clientX - rect.left) / rect.width) * 100;
        var y = ((e.clientY - rect.top) / rect.height) * 100;
        zoomImg.style.backgroundPosition = x + '% ' + y + '%';
    });
    container.addEventListener('mouseleave', function() {
        visible = false;
        zoomPanel.classList.add('opacity-0');
    });
})();

// Countdown timer for deal
<?php if ($isDealActive): ?>
(function() {
    var end = new Date('<?= $dealEndTime ?>').getTime();
    var timer = document.getElementById('deal-timer');
    if (!timer) return;
    function tick() {
        var now = new Date().getTime();
        var diff = end - now;
        if (diff <= 0) { timer.textContent = 'Ended'; return; }
        var h = Math.floor(diff / 3600000);
        var m = Math.floor((diff % 3600000) / 60000);
        var s = Math.floor((diff % 60000) / 1000);
        timer.textContent = h + 'h ' + m + 'm ' + s + 's';
    }
    tick();
    setInterval(tick, 1000);
})();
<?php endif; ?>

function switchImage(thumb, src) {
    var mainImg = document.getElementById('main-image');
    mainImg.src = src;
    document.querySelectorAll('#thumb-gallery > div').forEach(function(el) {
        el.classList.remove('border-[#007185]');
        el.classList.add('border-gray-200');
    });
    if (thumb) { thumb.classList.remove('border-gray-200'); thumb.classList.add('border-[#007185]'); }
}
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
