<?php
require_once __DIR__ . '/config/database.php';
$settings = getAllSettings($pdo);

$id = (int)($_GET['id'] ?? 0);
if (!$id) redirect(BASE_URL . '/index.php');

$stmt = $pdo->prepare("SELECT p.*, c.name as cat_name, c.id as cat_id FROM products p LEFT JOIN categories c ON p.category_id = c.id WHERE p.id = ?");
$stmt->execute([$id]);
$product = $stmt->fetch();
if (!$product) redirect(BASE_URL . '/index.php');

// Variations
$varStmt = $pdo->prepare("SELECT * FROM product_variations WHERE product_id = ? ORDER BY variation_name, variation_value");
$varStmt->execute([$id]);
$variations = $varStmt->fetchAll();
$groupedVars = [];
foreach ($variations as $v) $groupedVars[$v['variation_name']][] = $v;

// Reviews (if enabled)
$reviewEnabled = ($settings['review_enabled'] ?? '1') == '1';
$reviewStmt = $pdo->prepare("SELECT r.*, u.name as user_name FROM reviews r LEFT JOIN users u ON r.user_id = u.id WHERE r.product_id = ? AND r.status = 'approved' ORDER BY r.created_at DESC LIMIT 10");
$reviewStmt->execute([$id]);
$reviews = $reviewStmt->fetchAll();

// Related products
$relStmt = $pdo->prepare("SELECT * FROM products WHERE category_id = ? AND id != ? AND stock > 0 LIMIT 6");
$relStmt->execute([$product['cat_id'], $id]);
$relatedProducts = $relStmt->fetchAll();

// Can user review?
$canReview = false;
if (isLoggedIn() && $reviewEnabled) {
    $checkOrder = $pdo->prepare("SELECT oi.id FROM order_items oi JOIN orders o ON oi.order_id = o.id WHERE o.user_id = ? AND oi.product_id = ? AND o.status = 'delivered' LIMIT 1");
    $checkOrder->execute([$_SESSION['user_id'], $id]);
    $canReview = (bool)$checkOrder->fetch();
}

// Post review
$reviewMsg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_review'])) {
    if (!isLoggedIn()) { $reviewMsg = '<div class="alert alert-error">রিভিউ দিতে লগইন করুন।</div>'; }
    elseif (!$reviewEnabled) { $reviewMsg = '<div class="alert alert-error">রিভিউ সিস্টেম বর্তমানে বন্ধ।</div>'; }
    else {
        $rating = (int)($_POST['rating'] ?? 5);
        $comment = trim($_POST['comment'] ?? '');
        $ins = $pdo->prepare("INSERT INTO reviews (product_id, user_id, rating, comment, status) VALUES (?,?,?,?,'pending')");
        $ins->execute([$id, $_SESSION['user_id'], $rating, $comment]);
        $reviewMsg = '<div class="alert alert-success">আপনার রিভিউ জমা হয়েছে। অনুমোদনের পর প্রকাশিত হবে।</div>';
    }
}

$firstVarId = '';
foreach ($groupedVars as $vGroup) { $firstVarId = $vGroup[0]['id']; break; }

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

<div class="container">
    <div class="breadcrumb">
        <a href="<?= BASE_URL ?>/index.php">হোম</a>
        <span>/</span>
        <a href="<?= BASE_URL ?>/category.php?id=<?= $product['cat_id'] ?>"><?= e($product['cat_name'] ?? 'পণ্য') ?></a>
        <span>/</span>
        <?= e($product['name']) ?>
    </div>
</div>

<div class="product-page">
    <div class="container">
        <div class="product-main-grid">
            <!-- Product Image -->
            <div class="product-images">
                <div class="product-main-img">
                    <?php if ($product['image']): ?>
                        <img src="<?= UPLOADS_URL . e($product['image']) ?>" alt="<?= e($product['name']) ?>">
                    <?php else: ?>
                        <div style="height:400px;display:flex;align-items:center;justify-content:center;background:var(--gray-100);color:var(--gray-400);font-size:4rem;"><i class="fas fa-image"></i></div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Product Info -->
            <div class="product-info">
                <h1><?= e($product['name']) ?></h1>

                <div id="displayPrice" class="product-price">৳<?= number_format($product['price'], 2) ?></div>

                <?php if ($product['stock'] > 0): ?>
                    <span class="stock-badge in-stock"><i class="fas fa-check-circle"></i> স্টকে আছে (<?= $product['stock'] ?> টি)</span>
                <?php else: ?>
                    <span class="stock-badge out-stock"><i class="fas fa-times-circle"></i> স্টক শেষ</span>
                <?php endif; ?>

                <?php if ($product['description']): ?>
                    <div class="product-desc"><?= nl2br(e($product['description'])) ?></div>
                <?php endif; ?>

                <!-- Variations -->
                <?php foreach ($groupedVars as $varName => $options): ?>
                    <div class="variation-group">
                        <div class="var-label"><?= e($varName) ?></div>
                        <div class="variation-options">
                            <?php foreach ($options as $opt): ?>
                                <button class="var-btn <?= $opt === $options[0] ? 'active' : '' ?>"
                                    data-var-id="<?= $opt['id'] ?>"
                                    data-extra-price="<?= $opt['extra_price'] ?>">
                                    <?= e($opt['variation_value']) ?>
                                    <?php if ($opt['extra_price'] > 0): ?>(+৳<?= $opt['extra_price'] ?>)<?php endif; ?>
                                </button>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endforeach; ?>

                <!-- Quantity -->
                <div class="form-group" style="margin-top:20px;">
                    <div class="var-label">পরিমাণ</div>
                    <div class="qty-controls" style="display:flex;align-items:center;gap:10px;">
                        <button type="button" class="qty-btn" id="qtyMinus" onclick="changeQty(-1)">−</button>
                        <input type="number" id="productQty" value="1" min="1" max="<?= $product['stock'] ?>"
                               style="width:64px;text-align:center;padding:8px;border:1.5px solid var(--gray-200);border-radius:6px;font-family:var(--font);font-size:1rem;" readonly>
                        <button type="button" class="qty-btn" id="qtyPlus" onclick="changeQty(1)">+</button>
                    </div>
                </div>

                <?php if ($product['stock'] > 0): ?>
                    <a id="buyNowBtn" href="<?= BASE_URL ?>/checkout-add.php?product_id=<?= $product['id'] ?>&variation_id=<?= $firstVarId ?>&qty=1"
                       class="btn-buy" style="font-size:1.05rem;padding:14px;"
                       data-pid="<?= $product['id'] ?>"
                       data-base-price="<?= $product['price'] ?>">
                        <i class="fas fa-bolt"></i> এখনই কিনুন
                    </a>
                <?php else: ?>
                    <button class="btn-buy" disabled style="opacity:0.5;cursor:not-allowed;font-size:1.05rem;padding:14px;">স্টক শেষ</button>
                <?php endif; ?>
            </div>
        </div>

        <!-- Reviews Section -->
        <?php if ($reviewEnabled): ?>
        <div class="reviews-section">
            <h2 class="page-title">ক্রেতাদের রিভিউ</h2>

            <?= $reviewMsg ?>

            <?php if ($reviews): ?>
                <?php foreach ($reviews as $rv): ?>
                <div class="review-card">
                    <div class="review-header">
                        <div>
                            <div class="review-name"><?= e($rv['user_name'] ?? 'অজ্ঞাত') ?></div>
                            <div class="review-stars">
                                <?= str_repeat('★', $rv['rating']) . str_repeat('☆', 5 - $rv['rating']) ?>
                            </div>
                        </div>
                        <div class="review-date"><?= date('d/m/Y', strtotime($rv['created_at'])) ?></div>
                    </div>
                    <div class="review-text"><?= e($rv['comment']) ?></div>
                </div>
                <?php endforeach; ?>
            <?php else: ?>
                <p style="color:var(--gray-400);">এখনো কোনো রিভিউ নেই।</p>
            <?php endif; ?>

            <?php if ($canReview): ?>
            <div class="content-card" style="margin-top:28px;">
                <h3>রিভিউ লিখুন</h3>
                <form method="POST">
                    <div class="form-group">
                        <label class="form-label">রেটিং দিন *</label>
                        <div class="star-widget" style="display:flex;gap:6px;margin-bottom:10px;cursor:pointer;">
                            <span class="sw-star lit" style="font-size:2rem;color:#D4AF37;transition:color .15s,transform .12s;" data-val="1">★</span>
                            <span class="sw-star lit" style="font-size:2rem;color:#D4AF37;transition:color .15s,transform .12s;" data-val="2">★</span>
                            <span class="sw-star lit" style="font-size:2rem;color:#D4AF37;transition:color .15s,transform .12s;" data-val="3">★</span>
                            <span class="sw-star lit" style="font-size:2rem;color:#D4AF37;transition:color .15s,transform .12s;" data-val="4">★</span>
                            <span class="sw-star lit" style="font-size:2rem;color:#D4AF37;transition:color .15s,transform .12s;" data-val="5">★</span>
                        </div>
                        <input type="hidden" name="rating" class="star-input" value="5">
                    </div>
                    <div class="form-group">
                        <label class="form-label">আপনার মতামত *</label>
                        <textarea class="form-control" name="comment" rows="4"
                                  placeholder="পণ্যটি সম্পর্কে আপনার অভিজ্ঞতা লিখুন..."></textarea>
                    </div>
                    <button type="submit" name="submit_review" class="btn-primary" style="width:auto;padding:10px 28px;">
                        রিভিউ জমা দিন
                    </button>
                </form>
            </div>
            <?php elseif (isLoggedIn() && $reviewEnabled): ?>
                <p style="color:var(--gray-400);margin-top:20px;"><i class="fas fa-info-circle"></i> শুধুমাত্র ডেলিভারি প্রাপ্ত অর্ডারের ক্রেতারা রিভিউ দিতে পারবেন।</p>
            <?php elseif (!isLoggedIn()): ?>
                <p style="margin-top:16px;"><a href="<?= BASE_URL ?>/login.php" class="btn-sm btn-sm-navy">রিভিউ দিতে লগইন করুন</a></p>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <!-- Related Products -->
        <?php if ($relatedProducts): ?>
        <div class="category-section">
            <div class="cat-header">
                <h3>সংশ্লিষ্ট পণ্য</h3>
            </div>
            <div class="carousel-wrapper">
                <div class="carousel-track">
                    <?php foreach ($relatedProducts as $rp):
                        $rvars = $pdo->prepare("SELECT * FROM product_variations WHERE product_id = ? LIMIT 1");
                        $rvars->execute([$rp['id']]);
                        $rv = $rvars->fetch();
                    ?>
                    <div class="product-card">
                        <a href="<?= BASE_URL ?>/product.php?id=<?= $rp['id'] ?>">
                            <?php if ($rp['image']): ?>
                                <img class="card-img" src="<?= UPLOADS_URL . e($rp['image']) ?>" alt="<?= e($rp['name']) ?>" loading="lazy">
                            <?php else: ?>
                                <div class="card-img-placeholder"><i class="fas fa-image"></i></div>
                            <?php endif; ?>
                        </a>
                        <div class="card-body">
                            <div class="card-title"><?= e($rp['name']) ?></div>
                            <div class="card-price">৳<?= number_format($rp['price'], 2) ?></div>
                            <a href="<?= BASE_URL ?>/checkout-add.php?product_id=<?= $rp['id'] ?>&variation_id=<?= $rv['id'] ?? '' ?>&qty=1" class="btn-buy">এখনই কিনুন</a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
// ===== QUANTITY CONTROL =====
const qtyInput = document.getElementById('productQty');
const maxStock = <?= $product['stock'] ?>;

function changeQty(delta) {
    let v = parseInt(qtyInput.value) + delta;
    if (v < 1) v = 1;
    if (v > maxStock) v = maxStock;
    qtyInput.value = v;
    refreshBuyLink();
}

// ===== VARIATION SELECTION =====
document.querySelectorAll('.variation-group').forEach(group => {
    const btns = group.querySelectorAll('.var-btn');
    btns.forEach(btn => {
        btn.addEventListener('click', () => {
            btns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            refreshBuyLink();
            updatePrice();
        });
    });
});

function refreshBuyLink() {
    const buyBtn = document.getElementById('buyNowBtn');
    if (!buyBtn) return;
    const pid  = buyBtn.dataset.pid;
    const qty  = qtyInput ? parseInt(qtyInput.value) : 1;
    const activeVar = document.querySelector('.var-btn.active');
    const varId = activeVar ? (activeVar.dataset.varId || '') : '';
    buyBtn.href = '<?= BASE_URL ?>/checkout-add.php?product_id=' + pid + '&variation_id=' + varId + '&qty=' + qty;
}

function updatePrice() {
    const basePrice = parseFloat('<?= $product['price'] ?>');
    const activeVar = document.querySelector('.var-btn.active');
    const extra = activeVar ? parseFloat(activeVar.dataset.extraPrice || 0) : 0;
    const priceEl = document.getElementById('displayPrice');
    if (priceEl) priceEl.textContent = '৳' + (basePrice + extra).toFixed(2);
}

// ===== STAR RATING FIX (sw-star) =====
document.querySelectorAll('.star-widget').forEach(widget => {
    const stars  = widget.querySelectorAll('.sw-star');
    const hidden = widget.nextElementSibling; // input[type=hidden]
    let selected = 5;

    function paint(n) {
        stars.forEach((s, i) => {
            s.style.color = i < n ? '#D4AF37' : '#e8e6e1';
        });
    }

    stars.forEach((star, idx) => {
        star.addEventListener('click', () => {
            selected = idx + 1;
            if (hidden) hidden.value = selected;
            paint(selected);
        });
        star.addEventListener('mouseenter', () => paint(idx + 1));
    });
    widget.addEventListener('mouseleave', () => paint(selected));
    paint(selected);
});

// Init
refreshBuyLink();
updatePrice();
</script>

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