<?php
session_start();

// 1. SECURITY: FORCE LOGIN
if (!isset($_SESSION['user_id'])) {
    $_SESSION['redirect_url'] = $_SERVER['REQUEST_URI'];
    header("Location: login.php?error=Please login to view product details");
    exit(); 
}

require 'config/db.php';
require_once 'includes/functions.php'; // Essential for currency conversion
include 'includes/header.php';

// --- 2. FETCH DATA ---

// Get Product ID
if (!isset($_GET['id'])) {
    echo "<script>window.location.href='index.php';</script>";
    exit();
}
$product_id = $_GET['id'];

// Fetch Product Details
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$product_id]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$product) {
    echo "<div class='container' style='padding:50px; text-align:center;'>
            <h2>Product not found.</h2>
            <a href='index.php' class='btn btn-primary' style='width:auto; display:inline-block; margin-top:10px;'>Back to Shop</a>
          </div>";
    include 'includes/footer.php';
    exit();
}

// Fetch Variants (Pricing)
$vStmt = $pdo->prepare("SELECT * FROM product_variants WHERE product_id = ? AND is_active = 1 ORDER BY price ASC");
$vStmt->execute([$product_id]);
$variants = $vStmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch Active Coupons
$cStmt = $pdo->query("SELECT * FROM coupons WHERE status = 1 ORDER BY value DESC");
$coupons = $cStmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch Approved Reviews
$rStmt = $pdo->prepare("SELECT * FROM reviews WHERE product_id = ? AND status = 1 ORDER BY id DESC");
$rStmt->execute([$product_id]);
$reviews = $rStmt->fetchAll();

// Fetch Related Products (Same Category)
$relStmt = $pdo->prepare("
    SELECT * FROM products 
    WHERE category_id = (SELECT category_id FROM products WHERE id = ?) 
    AND id != ? 
    AND is_active = 1 
    LIMIT 3
");
$relStmt->execute([$product_id, $product_id]);
$related_products = $relStmt->fetchAll(PDO::FETCH_ASSOC);

// Contact Config
$whatsapp_number = "15852502693";
$telegram_user = "digibossx";
?>

<!-- Internal CSS -->
<style>
    /* Layout */
    .product-detail-container { display: flex; flex-wrap: wrap; gap: 40px; background: #fff; padding: 40px; border-radius: 12px; box-shadow: 0 5px 20px rgba(0,0,0,0.05); margin-top: 30px; }
    .product-image { flex: 1; min-width: 300px; }
    .product-image img { width: 100%; border-radius: 12px; border: 1px solid #eee; }
    .product-info { flex: 1.2; min-width: 300px; }
    
    /* Typography */
    .product-title { margin-top: 0; color: #2c3e50; font-size: 28px; font-weight: 800; }
    
    /* Short Description Style (Top) */
    .short-desc { 
        color: #555; 
        font-size: 16px; 
        line-height: 1.6; 
        margin-bottom: 25px; 
        font-weight: 500;
        border-left: 4px solid #3498db;
        padding-left: 15px;
        background: #f9fcff; /* Subtle background to make it stand out */
        padding: 15px;
        border-radius: 0 8px 8px 0;
    }
    /* Allow HTML in short desc */
    .short-desc ul, .short-desc ol { margin-left: 20px; margin-bottom: 10px; }
    .short-desc li { margin-bottom: 5px; }

    /* Long Description Style (Bottom) */
    .long-desc { margin-top: 40px; padding-top: 30px; border-top: 1px solid #eee; }
    .long-desc h2 { font-size: 24px; color: #2c3e50; margin-bottom: 20px; border-bottom: 2px solid #eee; padding-bottom: 10px; }
    
    /* ADDED SUBHEADING COLORS */
    .long-desc h3 { font-size: 20px; color: #3498db; margin-top: 25px; margin-bottom: 10px; font-weight: 700; }
    .long-desc h4 { font-size: 18px; color: #e67e22; margin-top: 20px; margin-bottom: 8px; font-weight: 600; }
    
    .long-desc ul, .long-desc ol { margin-bottom: 15px; padding-left: 20px; }
    .long-desc li { margin-bottom: 8px; }
    .long-desc p { font-size: 16px; color: #444; line-height: 1.8; margin-bottom: 15px; }
    
    /* Variant Selector */
    .variant-selector { margin: 20px 0; display: flex; flex-wrap: wrap; gap: 10px; }
    .variant-option { 
        display: block; 
        padding: 12px 20px; 
        border: 2px solid #eee; 
        border-radius: 8px; 
        cursor: pointer; 
        transition: all 0.2s;
        position: relative;
        min-width: 120px;
    }
    .variant-option:hover { border-color: #3498db; }
    .variant-option input { position: absolute; opacity: 0; cursor: pointer; }
    .variant-option.selected { border-color: #3498db; background: #f0f8ff; color: #2980b9; }
    .variant-price { font-size: 18px; font-weight: bold; margin-top: 5px; }
    
    /* Stock Warning */
    .low-stock { color: #e74c3c; font-size: 11px; font-weight: bold; display: block; margin-top: 5px; }
    .out-stock { color: gray; font-size: 11px; display: block; margin-top: 5px; }
    .variant-option.disabled { opacity: 0.5; cursor: not-allowed; background: #f9f9f9; }

    /* Offers & Coupons */
    .offers-box { background: #fffcf5; border: 1px dashed #f1c40f; padding: 15px; border-radius: 8px; margin-bottom: 25px; }
    .coupon-item { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; font-size: 14px; color: #7f8c8d; }
    .code-badge { background: #fff; border: 1px solid #f1c40f; padding: 4px 10px; font-weight: bold; border-radius: 4px; cursor: pointer; font-family: monospace; color: #d35400; transition: 0.2s; }
    .code-badge:hover { background: #f1c40f; color: #fff; }

    /* Buttons */
    .btn-group { display: flex; flex-direction: column; gap: 12px; margin-top: 15px; }
    .btn-row { display: flex; gap: 12px; }
    .btn { flex: 1; display: flex; align-items: center; justify-content: center; gap: 8px; font-size: 16px; padding: 12px; border-radius: 6px; cursor: pointer; text-decoration: none; font-weight: bold; border: none; }
    
    /* Button Colors (Old Style Restored) */
    .btn-buy { background-color: #2c3e50; color: white; }
    .btn-buy:hover { background-color: #34495e; }
    
    .btn-cart { background-color: #e67e22; color: white; }
    .btn-cart:hover { background-color: #d35400; }
    
    .btn-whatsapp { background-color: #25D366; color: white; }
    .btn-whatsapp:hover { background-color: #128C7E; }
    
    .btn-telegram { background-color: #0088cc; color: white; }
    .btn-telegram:hover { background-color: #0077b5; }
    
    /* Reviews & Related */
    .review-section, .related-section { margin-top: 40px; background: #fff; padding: 30px; border-radius: 12px; box-shadow: 0 5px 20px rgba(0,0,0,0.05); }
    .review-item { border-bottom: 1px solid #eee; padding: 15px 0; }
    .stars { color: #f1c40f; letter-spacing: 2px; }
    
    /* Related Products Grid */
    .related-section .product-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 20px; }
    .related-section .card { box-shadow: none; border: 1px solid #eee; padding: 15px; border-radius: 8px; transition: transform 0.2s; display: flex; flex-direction: column; }
    .related-section .card:hover { box-shadow: 0 5px 15px rgba(0,0,0,0.1); transform: translateY(-3px); }
    .related-section img { width: 100%; height: 150px; object-fit: cover; border-radius: 5px; margin-bottom: 10px; }
    .related-section h3 { font-size: 16px; margin: 0 0 5px; color: #333; }
    .related-section .btn-view { margin-top: auto; display: block; text-align: center; background: #f8f9fa; color: #333; border: 1px solid #ddd; padding: 10px; border-radius: 5px; text-decoration: none; font-size: 14px; }
    .related-section .btn-view:hover { background: #eee; }

    @media (max-width: 600px) { .product-detail-container { padding: 20px; } .btn-row { flex-direction: column; } }
</style>

<div class="container">
    
    <!-- MAIN PRODUCT CARD -->
    <div class="product-detail-container">
        
        <!-- Left: Image -->
        <div class="product-image">
            <img src="<?php echo $product['thumbnail_url'] ? $product['thumbnail_url'] : 'https://via.placeholder.com/500'; ?>" alt="<?php echo htmlspecialchars($product['name']); ?>">
            
            <div style="margin-top: 20px; background: #e8f4fd; padding: 15px; border-radius: 8px; font-size: 13px; color: #0c5460; display: flex; align-items: center; gap: 10px;">
                <i class="fas fa-bolt" style="font-size: 20px;"></i> 
                <div>
                    <strong>Instant Delivery</strong><br>
                    License key sent to Email & Dashboard immediately.
                </div>
            </div>
        </div>

        <!-- Right: Details -->
        <div class="product-info">
            <h1 class="product-title"><?php echo htmlspecialchars($product['name']); ?></h1>
            
            <!-- SHORT DESCRIPTION (Raw HTML Output) -->
            <div class="short-desc">
                <?php echo $product['short_description']; ?>
            </div>
            
            <hr style="border: 0; border-top: 1px solid #eee; margin: 20px 0;">

            <!-- FORM: ADD TO CART -->
            <form action="/cart_action.php" method="POST">
                
                <h3 style="margin-bottom: 10px; font-size: 16px;">Choose Your Plan:</h3>
                <div class="variant-selector">
                    <?php foreach ($variants as $index => $variant): ?>
                        <?php 
                            // 1. Currency Conversion
                            $display_price = convertPrice($variant['price']); 
                            
                            // 2. Stock Logic (Scarcity)
                            $stock_html = "";
                            $is_disabled = false;
                            $stock_style = "";

                            if ($variant['stock_qty'] == 0) {
                                $stock_html = '<span class="out-stock">❌ Out of Stock</span>';
                                $is_disabled = true;
                                $stock_style = "disabled";
                            } elseif ($variant['stock_qty'] > 0 && $variant['stock_qty'] < 10) {
                                $stock_html = '<span class="low-stock">🔥 Only ' . $variant['stock_qty'] . ' left!</span>';
                            }
                        ?>
                        <label class="variant-option <?php echo $index === 0 && !$is_disabled ? 'selected' : ''; ?> <?php echo $stock_style; ?>" 
                               onclick="<?php echo $is_disabled ? '' : 'selectVariant(this)'; ?>">
                            
                            <input type="radio" name="variant_id" value="<?php echo $variant['id']; ?>" 
                                   data-price="<?php echo $display_price; ?>" 
                                   data-name="<?php echo $variant['name']; ?>"
                                   <?php echo ($index === 0 && !$is_disabled) ? 'checked' : ''; ?>
                                   <?php echo $is_disabled ? 'disabled' : ''; ?>>
                            
                            <span style="font-size: 14px;"><?php echo $variant['name']; ?></span>
                            <div class="variant-price"><?php echo $display_price; ?></div>
                            <?php echo $stock_html; ?>
                        </label>
                    <?php endforeach; ?>
                </div>

                <!-- AVAILABLE COUPONS -->
                <?php if(!empty($coupons)): ?>
                <div class="offers-box">
                    <strong style="display:block; margin-bottom: 10px; color: #d35400; font-size: 14px;">
                        <i class="fas fa-gift"></i> Special Offers Available:
                    </strong>
                    <?php foreach($coupons as $c): ?>
                        <div class="coupon-item">
                            <span>Get <strong><?php echo $c['type'] == 'fixed' ? 'FLAT OFF' : $c['value'].'% OFF'; ?></strong></span>
                            <span class="code-badge" onclick="copyCode('<?php echo $c['code']; ?>')">
                                <?php echo $c['code']; ?> <i class="far fa-copy"></i>
                            </span>
                        </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>

                <!-- INSTANT COUPON INPUT -->
                <div style="margin-bottom: 20px; background: #f9f9f9; padding: 15px; border-radius: 8px; border: 1px solid #eee;">
                    <label style="font-size: 13px; font-weight: bold; color: #555; display: block; margin-bottom: 8px;">
                        <i class="fas fa-ticket-alt"></i> Apply Coupon Code
                    </label>
                    <div style="display: flex; gap: 10px;">
                        <input type="text" name="coupon_code" placeholder="Enter Code (e.g. SAVE10)" 
                               style="flex: 1; padding: 10px; border: 1px solid #ddd; border-radius: 4px; text-transform: uppercase;">
                    </div>
                </div>

                <!-- ACTION BUTTONS (4 Buttons Restored) -->
                <div class="btn-group">
                    <div class="btn-row">
                        <!-- 1. Buy Now -->
                        <button type="submit" name="action" value="buy_now" class="btn btn-buy">
                            <i class="fas fa-bolt"></i> Buy Now
                        </button>
                        <!-- 2. Add to Cart -->
                        <button type="submit" name="action" value="add_to_cart" class="btn btn-cart">
                            <i class="fas fa-shopping-cart"></i> Add to Cart
                        </button>
                    </div>

                    <div class="btn-row">
                        <!-- 3. WhatsApp -->
                        <a href="#" id="wa-link" target="_blank" class="btn btn-whatsapp">
                            <i class="fab fa-whatsapp"></i> Buy on WhatsApp
                        </a>
                        <!-- 4. Telegram -->
                        <a href="https://t.me/<?php echo $telegram_user; ?>" target="_blank" class="btn btn-telegram">
                            <i class="fab fa-telegram"></i> Chat on Telegram
                        </a>
                    </div>
                </div>

                <!-- WISHLIST BUTTON -->
                <div style="text-align: right; margin-top: 15px;">
                    <a href="/wishlist_action.php?add=<?php echo $product_id; ?>" 
                       style="color: #e74c3c; text-decoration: none; font-size: 14px; font-weight: bold;">
                       <i class="far fa-heart"></i> Add to Wishlist
                    </a>
                </div>

            </form>
        </div>
    </div>

    <!-- LONG DESCRIPTION (Bottom Section) -->
    <div class="long-desc">
        <h2>Product Details</h2>
        <!-- Raw HTML Output for formatted content -->
        <?php echo $product['description']; ?>
    </div>

    <!-- REVIEWS SECTION -->
    <div class="review-section">
        <h3>Customer Reviews (<?php echo count($reviews); ?>)</h3>
        
        <?php if($reviews): ?>
            <?php foreach($reviews as $r): ?>
                <div class="review-item">
                    <div style="display: flex; justify-content: space-between;">
                        <strong><?php echo htmlspecialchars($r['user_name']); ?></strong>
                        <span class="stars"><?php echo str_repeat("★", $r['rating']); ?></span>
                    </div>
                    <p style="color: #666; margin-top: 5px; font-size: 14px;"><?php echo htmlspecialchars($r['comment']); ?></p>
                    
                    <?php if(!empty($r['image'])): ?>
                        <img src="/<?php echo $r['image']; ?>" style="max-width: 100px; border-radius: 5px; margin-top: 5px; border: 1px solid #ddd;">
                    <?php endif; ?>
                    
                    <small style="color: #aaa; display:block; margin-top:5px;"><?php echo date('d M Y', strtotime($r['created_at'])); ?></small>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <p style="color: #777; font-style: italic;">No reviews yet. Be the first to review this product!</p>
        <?php endif; ?>

        <!-- Write Review Form -->
        <div style="margin-top: 30px; border-top: 1px solid #eee; padding-top: 20px;">
            <h4>Write a Review</h4>
            <form method="POST" action="/submit_review.php" enctype="multipart/form-data">
                <input type="hidden" name="product_id" value="<?php echo $product_id; ?>">
                
                <div class="btn-row" style="margin-bottom: 10px;">
                    <input type="text" name="user_name" placeholder="Your Name" required 
                           style="flex: 1; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
                    
                    <select name="rating" style="flex: 1; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
                        <option value="5">★★★★★ (Excellent)</option>
                        <option value="4">★★★★ (Good)</option>
                        <option value="3">★★★ (Average)</option>
                    </select>
                </div>
                
                <textarea name="comment" placeholder="Share your experience..." required rows="3"
                          style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; font-family: inherit;"></textarea>
                
                <div style="margin-top: 10px;">
                    <label style="font-size: 12px; font-weight: bold; display: block; margin-bottom: 5px;">Add a Photo (Optional):</label>
                    <input type="file" name="review_image" accept="image/*" style="font-size: 12px;">
                </div>

                <button type="submit" class="btn btn-primary" style="width: auto; margin-top: 10px; background-color: #3498db; border: none; padding: 10px 20px; border-radius: 4px; color: white; cursor: pointer;">Submit Review</button>
            </form>
        </div>
    </div>

    <!-- RELATED PRODUCTS SECTION -->
    <?php if(count($related_products) > 0): ?>
    <div class="related-section">
        <h3 style="margin-bottom: 20px; color: #2c3e50;">You Might Also Like</h3>
        <div class="product-grid">
            <?php foreach ($related_products as $rel): 
                // Get min price
                $pStmt = $pdo->prepare("SELECT MIN(price) as min_price FROM product_variants WHERE product_id = ?");
                $pStmt->execute([$rel['id']]);
                $priceData = $pStmt->fetch();
                $rel_price = $priceData['min_price'] ? $priceData['min_price'] : 0;
            ?>
            <div class="card">
                <a href="product.php?id=<?php echo $rel['id']; ?>">
                    <img src="<?php echo $rel['thumbnail_url'] ? $rel['thumbnail_url'] : 'https://via.placeholder.com/300'; ?>" loading="lazy">
                </a>
                <h3><?php echo htmlspecialchars($rel['name']); ?></h3>
                <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px;">
                    <span style="color: #666; font-size: 13px;">Starting at:</span>
                    <span style="font-size: 16px; color: #2c3e50; font-weight: bold;">
                        <?php echo convertPrice($rel_price); ?>
                    </span>
                </div>
                <a href="product.php?id=<?php echo $rel['id']; ?>" class="btn-view" style="margin-top: 15px; display: block; text-align: center; background: #f8f9fa; color: #333; border: 1px solid #ddd; padding: 10px; border-radius: 5px; text-decoration: none;">View Details</a>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

</div>

<!-- JAVASCRIPT LOGIC -->
<script>
    function selectVariant(element) {
        if(element.classList.contains('disabled')) return;
        document.querySelectorAll('.variant-option').forEach(el => el.classList.remove('selected'));
        element.classList.add('selected');
        // Update hidden radio manually if needed
        element.querySelector('input').checked = true;
        updateLinks();
    }

    const waBase = "https://wa.me/<?php echo $whatsapp_number; ?>?text=";
    const productBase = "Hi Team, I want to buy: <?php echo $product['name']; ?>";
    
    function updateLinks() {
        const selected = document.querySelector('input[name="variant_id"]:checked');
        if(selected) {
            const variantName = selected.getAttribute('data-name');
            const price = selected.getAttribute('data-price');
            const msg = encodeURIComponent(`${productBase} (${variantName}) - Price: ${price}`);
            document.getElementById('wa-link').href = waBase + msg;
        }
    }

    function copyCode(code) {
        navigator.clipboard.writeText(code);
        alert("Coupon " + code + " copied!");
        const input = document.querySelector('input[name="coupon_code"]');
        if(input) input.value = code;
    }

    updateLinks();
</script>

<?php include 'includes/footer.php'; ?>