<?php
// Note: This script assumes 'db.php' correctly establishes a PDO connection named $pdo.
include "db.php";
include "header.php";

// --- PHP Logic ---
if (!isset($_GET['id']) || empty($_GET['id'])) {
    die("Product ID missing"); 
}

$id = intval($_GET['id']);

$stmt = $pdo->prepare("SELECT * FROM products WHERE id=?");
$stmt->execute([$id]);
$p = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$p) die("Product not found");

// Decode JSON data from database fields
$images = json_decode($p['images'], true);
$sizes = json_decode($p['sizes'], true);
// IMPORTANT: The structure of $price_variants is currently {"250g":{"with":220,"without":240}, ...}
$price_variants = json_decode($p['price_variants'], true);

// --- Define Spice Levels (Used for UI generation) ---
$spice_levels = ['Light', 'Medium', 'Hot']; 

if (empty($images)) {
    $images = ['/path/to/placeholder-image.jpg']; 
}
?>

<!DOCTYPE html>
<html>
<head>
<title><?= $p['product_name'] ?></title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
/* ---------------------------------- */
/* ---------- FONT IMPORT ----------- */
/* ---------------------------------- */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800&display=swap');


/* ---------------------------------- */
/* ---------- COLOR THEME ----------- */
/* ---------------------------------- */
:root {
    --primary: #002344; /* Deep Navy Blue (Original) */
    --primary-light: #013b73; /* Lighter Blue for hover */
    --text-dark: #222; 
    --background-color: #f8f8f8; 
    --border-color: #ddd; 
}

/* ---------------------------------- */
/* ------------ GLOBAL -------------- */
/* ---------------------------------- */
body {
    font-family: 'Poppins', system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    background: var(--background-color);
    margin: 0;
    padding: 0px;
    color: var(--text-dark);
    line-height: 1.5;
}

.container {
    max-width: 1100px;
    margin: auto;
    margin-top:20px;
    display: flex;
    gap: 40px; 
    flex-wrap: wrap;
}

/* ---------------------------------- */
/* ---------- LEFT SIDE (Images) ---- */
/* ---------------------------------- */
.left {
    flex: 1;
    min-width: 320px;
}

.main-img-container {
    width: 100%;
    height: 420px;
    overflow: hidden; 
    border-radius: 12px;
    border: 1px solid var(--border-color);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); 
    cursor: zoom-in; 
    background: #fff;
    padding: 15px;
    display: flex; 
    align-items: center;
    justify-content: center;
}

.main-img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
    transition: transform 0.3s ease;
    padding: 0;
}

.main-img-container.zoomed .main-img {
    transform: scale(1.8);
    cursor: zoom-out;
    max-width: none;
    max-height: none; 
}

@media(max-width:600px){
    .main-img-container{
        height: 320px;
    }
}

.thumbs {
    display: flex;
    gap: 10px;
    margin-top: 15px; 
}

.thumbs img {
    width: 70px; 
    height: 70px;
    border-radius: 8px;
    background: #fff;
    padding: 5px;
    object-fit: contain;
    cursor: pointer;
    border: 2px solid transparent;
    transition: all 0.2s; 
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.thumbs img.active,
.thumbs img:hover {
    border-color: var(--primary);
    transform: translateY(-2px); 
}

/* ---------------------------------- */
/* ---------- RIGHT SIDE (Details) -- */
/* ---------------------------------- */
.right {
    flex: 1;
    min-width: 320px;
    background: white;
    padding: 30px; 
    border-radius: 12px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.1); 
}

.right h2 {
    font-size: 28px; 
    font-weight: 800; 
    margin-top: 0;
    margin-bottom: 10px;
    color: var(--text-dark); 
}


/* ---------------------------------- */
/* ------- PILL BUTTON SELECTOR ----- */
/* ---------------------------------- */

.option-title {
    font-weight: 700;
    font-size: 16px;
    margin-top: 25px; 
    margin-bottom: 10px; 
    color: var(--primary); 
    border-bottom: none; 
}

.pill-group {
    display: flex;
    gap: 8px; 
    flex-wrap: wrap;
    margin-bottom: 15px; 
}

.pill {
    padding: 8px 15px; 
    border: 1px solid var(--border-color); 
    border-radius: 5px; 
    cursor: pointer;
    font-size: 15px;
    background: white;
    transition: all 0.2s;
    user-select: none;
}

.pill.active {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
    box-shadow: none; 
}

.pill:hover:not(.active) {
    border-color: var(--primary-light); 
    background: #f9f9f9; 
}

/* ---------------------------------- */
/* -------------- PRICE ------------- */
/* ---------------------------------- */
.price {
    font-size: 34px; 
    font-weight: 800;
    color: var(--text-dark); 
    margin-top: 15px;
    margin-bottom: 25px;
    padding-top: 15px;
    border-top: none; 
    display: block; 
}

/* ---------------------------------- */
/* -------- QUANTITY & BUTTON ------- */
/* ---------------------------------- */

.action-row {
    display: flex;
    align-items: center;
    gap: 15px; 
    margin-bottom: 20px;
}

.quantity-input {
    display: flex;
    align-items: center;
    border: 1px solid var(--border-color);
    border-radius: 5px;
    overflow: hidden;
    width: 120px; 
}

.quantity-input button {
    background: #f0f0f0;
    border: none;
    padding: 10px 15px;
    cursor: pointer;
    font-size: 18px;
    font-weight: 600;
    color: var(--primary); 
    transition: background 0.2s;
}

.quantity-input button:hover {
    background: #e0e0e0;
}

.quantity-input input {
    width: 30px;
    text-align: center;
    border: none;
    font-size: 16px;
    font-weight: 600;
    padding: 10px 0;
    -moz-appearance: textfield; 
}
.quantity-input input::-webkit-outer-spin-button,
.quantity-input input::-webkit-inner-spin-button {
    -webkit-appearance: none; 
    margin: 0;
}


.btn {
    flex-grow: 1; 
    background: var(--primary); 
    color: white;
    padding: 12px 20px; 
    font-size: 16px;
    border: none;
    border-radius: 5px; 
    cursor: pointer;
    font-weight: 600;
    transition: all 0.2s;
    box-shadow: 0 3px 10px rgba(0, 35, 68, 0.3); 
}

.btn:hover {
    background: var(--primary-light);
    box-shadow: 0 5px 15px rgba(0, 35, 68, 0.4);
}


/* ---------------------------------- */
/* --------- FOOTER LINKS/QUICK FACTS */
/* ---------------------------------- */
.footer-links {
    margin-top: 25px;
    font-size: 14px;
    color: #555;
}
.footer-links div {
    margin-bottom: 8px;
}
.footer-links strong {
    font-weight: 600;
    margin-right: 5px;
    color: #333;
}
.footer-links .data-label {
    color: var(--primary); 
    font-weight: 700;
}
.footer-links .data-value {
    font-weight: 400;
    color: #555;
}


/* ---------------------------------- */
/* ---------- ACCORDION STYLES ------ */
/* ---------------------------------- */
.accordion-group {
    background: white;
    margin-top: 30px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.08);
    overflow: hidden; 
}

.accordion-item {
    border-bottom: 1px solid #eee;
}

.accordion-item:last-child {
    border-bottom: none;
}

.accordion-header {
    background: #fcfcfc;
    padding: 18px 25px;
    cursor: pointer;
    font-size: 17px;
    font-weight: 700;
    color: var(--primary); 
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: background 0.2s;
}

.accordion-header:hover {
    background: #f0f0f0;
}

.accordion-header .icon {
    font-size: 24px;
    font-weight: 600;
    line-height: 1; 
    transition: transform 0.3s;
    width: 20px;
    text-align: center;
}

.accordion-content {
    max-height: 0;
    overflow: hidden;
    padding: 0 25px;
    transition: max-height 0.3s ease-out, padding 0.3s ease-out;
    background: white;
}

.accordion-content.open {
    max-height: 500px; 
    padding: 15px 25px 25px;
}

.accordion-content p {
    margin: 0;
    line-height: 1.6;
    color: #555;
}

</style>
</head>
<body>

<div class="container">

<div class="left">
    <div class="main-img-container" id="mainImgContainer" onclick="toggleZoom()">
        <img id="mainImage" src="<?= htmlspecialchars($images[0]) ?>" class="main-img" alt="Main Product Image">
    </div>

    <div class="thumbs">
        <?php foreach($images as $i=>$img): ?>
        <img src="<?= htmlspecialchars($img) ?>" class="thumb <?= $i==0?'active':'' ?>" onclick="changeImg(this)" alt="Product Thumbnail <?= $i+1 ?>">
        <?php endforeach; ?>
    </div>
</div>

<div class="right">

    <h2><?= htmlspecialchars($p['product_name']) ?></h2>

    <div class="price" id="priceBox">Rs. 0.00</div>

    <div class="option-title">SIZE: <span id="selectedSizeDisplay"><?= htmlspecialchars($sizes[0]) ?></span></div>
    <div class="pill-group" id="sizeGroup">
        <?php foreach($sizes as $s): ?>
            <div class="pill <?= $s == $sizes[0] ? 'active' : '' ?>" data-size="<?= htmlspecialchars($s) ?>"><?= htmlspecialchars($s) ?></div>
        <?php endforeach; ?>
    </div>

    <div class="option-title">PREFERENCE: <span id="selectedGarlicDisplay">WITH GARLIC</span></div>
    <div class="pill-group" id="garlicGroup">
        <div class="pill active" data-garlic="with">With Garlic</div>
        <div class="pill" data-garlic="without">Without Garlic</div>
    </div>
    
    <div class="option-title">SPICE LEVEL: <span id="selectedSpiceDisplay"><?= htmlspecialchars($spice_levels[0]) ?></span></div>
    <div class="pill-group" id="spiceGroup">
        <?php foreach($spice_levels as $sl): ?>
            <div class="pill <?= $sl == $spice_levels[0] ? 'active' : '' ?>" data-spice="<?= htmlspecialchars(strtolower($sl)) ?>"><?= htmlspecialchars($sl) ?></div>
        <?php endforeach; ?>
    </div>
    
    <div class="action-row">
        <div class="quantity-input">
            <button onclick="updateQuantity(-1)">-</button>
            <input type="number" id="quantity" value="1" min="1" readonly>
            <button onclick="updateQuantity(1)">+</button>
        </div>
        <button class="btn" id="addToCartBtn">ADD TO CART</button>
    </div>

    <div class="footer-links">
        <div>
            <strong>Sizes Available:</strong> <span class="data-value"><?= htmlspecialchars(implode(', ', $sizes)) ?></span>
        </div>
        <div>
            <strong>Preference:</strong> <span class="data-value">with Garlic, without Garlic</span>
        </div>
        <div>
            <strong>Spice Levels:</strong> <span class="data-value"><?= htmlspecialchars(implode(', ', $spice_levels)) ?></span>
        </div>
        <?php if ($p['shelf_life']): ?>
        <div>
            <span class="data-label">Shelf Life:</span> <span class="data-value"><?= htmlspecialchars($p['shelf_life']) ?></span>
        </div>
        <?php endif; ?>
        <?php if ($p['packaging']): ?>
        <div>
            <span class="data-label">Packaging:</span> <span class="data-value"><?= htmlspecialchars($p['packaging']) ?></span>
        </div>
        <?php endif; ?>
        <?php if ($p['origin']): ?>
        <div>
            <span class="data-label">Origin:</span> <span class="data-value"><?= htmlspecialchars($p['origin']) ?></span>
        </div>
        <?php endif; ?>
    </div>

</div>
</div>

<div class="container" style="padding-bottom: 50px;">
<div class="accordion-group" style="flex:1">

    <div class="accordion-item">
        <div class="accordion-header active" data-content="description-content">
            Description <span class="icon" data-icon-state="minus">-</span>
        </div>
        <div class="accordion-content open" id="description-content">
            <p><?= nl2br(htmlspecialchars($p['description'])) ?></p>
        </div>
    </div>

    <?php if ($p['ingredients']): ?>
    <div class="accordion-item">
        <div class="accordion-header" data-content="ingredients-content">
            Ingredients <span class="icon" data-icon-state="plus">+</span>
        </div>
        <div class="accordion-content" id="ingredients-content">
            <p><?= nl2br(htmlspecialchars($p['ingredients'])) ?></p>
        </div>
    </div>
    <?php endif; ?>
    
    <?php 
    // ADDED 'category_id' to this exclusion list to prevent it from being displayed
    $excluded_accordion_keys = ['id', 'product_name', 'images', 'sizes', 'price_variants', 'description', 'ingredients', 'shelf_life', 'origin', 'packaging', 'created_at', 'category_id'];
    foreach ($p as $key => $value): 
        if (!empty($value) && !in_array($key, $excluded_accordion_keys)):
    ?>
    <div class="accordion-item">
        <div class="accordion-header" data-content="<?= $key ?>-content">
            <?= htmlspecialchars(ucwords(str_replace('_', ' ', $key))) ?> <span class="icon" data-icon-state="plus">+</span>
        </div>
        <div class="accordion-content" id="<?= $key ?>-content">
            <p><?= nl2br(htmlspecialchars($value)) ?></p>
        </div>
    </div>
    <?php 
        endif;
    endforeach; 
    ?>

</div>
</div>

<script>
// --- JavaScript Logic ---

// Price data is 2-dimensional: prices[size][garlic] = PRICE_NUMBER
let prices = <?= json_encode($price_variants) ?>;

// Initialize state variables
let selectedSize = "<?= $sizes[0] ?>";
let selectedGarlic = "with";
let selectedSpice = "<?= strtolower($spice_levels[0]) ?>"; 

// Get DOM elements
const priceBox = document.getElementById("priceBox");
const selectedSizeDisplay = document.getElementById("selectedSizeDisplay");
const selectedGarlicDisplay = document.getElementById("selectedGarlicDisplay");
const selectedSpiceDisplay = document.getElementById("selectedSpiceDisplay"); 
const mainImgContainer = document.getElementById('mainImgContainer');
const quantityInput = document.getElementById('quantity'); 

/**
 * Calculates and updates the displayed price based on selected options and quantity.
 * This version uses the 2-level price lookup: prices[size][garlic].
 */
function updatePriceAndDisplay(){
    let unitPrice = 0.00;
    let displayPrice = 'Rs. 0.00';
    let priceColor = 'var(--text-dark)';
    
    // 1. UPDATED PRICE LOOKUP: Only check for the two levels (Size and Garlic)
    if(prices[selectedSize] && 
       prices[selectedSize][selectedGarlic] !== undefined){
            
        // Direct access to the price number, since spice level doesn't affect it
        unitPrice = parseFloat(prices[selectedSize][selectedGarlic]);
    }

    // 2. Get the current quantity
    const quantity = parseInt(quantityInput.value);
    
    // 3. Calculate total price and update display
    if (unitPrice > 0) {
        const totalPrice = unitPrice * quantity;
        displayPrice = "Rs. " + totalPrice.toFixed(2);
        priceColor = 'var(--text-dark)';
    } else {
        // This will display if the 2-level combo is not found
        displayPrice = "N/A - Combo Unavailable";
        priceColor = 'red';
    }
    
    priceBox.innerText = displayPrice;
    priceBox.style.color = priceColor;

    // Update displays for current selection
    selectedSizeDisplay.innerText = selectedSize;
    selectedGarlicDisplay.innerText = selectedGarlic.toUpperCase();
    selectedSpiceDisplay.innerText = selectedSpice.charAt(0).toUpperCase() + selectedSpice.slice(1);
}

// --- Option Event Listeners ---

// Size Selector
document.querySelectorAll("#sizeGroup .pill").forEach(p => {
    p.addEventListener("click", function(){
        document.querySelectorAll("#sizeGroup .pill").forEach(x => x.classList.remove("active"));
        this.classList.add("active");
        selectedSize = this.dataset.size;
        updatePriceAndDisplay();
    });
});

// Garlic Selector
document.querySelectorAll("#garlicGroup .pill").forEach(p => {
    p.addEventListener("click", function(){
        document.querySelectorAll("#garlicGroup .pill").forEach(x => x.classList.remove("active"));
        this.classList.add("active");
        selectedGarlic = this.dataset.garlic;
        updatePriceAndDisplay();
    });
});

// Spice Selector (Updates display, price remains constant)
document.querySelectorAll("#spiceGroup .pill").forEach(p => {
    p.addEventListener("click", function(){
        document.querySelectorAll("#spiceGroup .pill").forEach(x => x.classList.remove("active"));
        this.classList.add("active");
        selectedSpice = this.dataset.spice;
        updatePriceAndDisplay(); 
    });
});

updatePriceAndDisplay(); // Initial call to set the price and displays correctly

// --- Image & Quantity Helpers ---

function changeImg(el){
    document.getElementById('mainImage').src = el.src;
    document.querySelectorAll('.thumb').forEach(t=>t.classList.remove('active'));
    el.classList.add('active');
    mainImgContainer.classList.remove('zoomed'); 
}

function toggleZoom() {
    mainImgContainer.classList.toggle('zoomed');
}

function updateQuantity(change) {
    let current = parseInt(quantityInput.value);
    let newValue = current + change;
    if (newValue >= 1) {
        quantityInput.value = newValue;
        updatePriceAndDisplay(); 
    }
}


// --- ACCORDION LOGIC ---
document.querySelectorAll(".accordion-header").forEach(header => {
    header.addEventListener("click", function() {
        const contentId = this.dataset.content;
        const content = document.getElementById(contentId);
        const icon = this.querySelector(".icon");

        // Close all other open accordions
        document.querySelectorAll(".accordion-header.active").forEach(h => {
            if (h !== this) {
                h.classList.remove("active");
                document.getElementById(h.dataset.content).classList.remove("open");
                h.querySelector(".icon").textContent = '+'; 
            }
        });

        // Toggle the clicked accordion
        this.classList.toggle("active");
        content.classList.toggle("open");

        // Change icon based on active state
        if (this.classList.contains("active")) {
            icon.textContent = '-';
        } else {
            icon.textContent = '+';
        }
    });
});

// ADD TO CART AJAX
document.getElementById("addToCartBtn").addEventListener("click", function () {
    let productId = <?= $id ?>;
    let qty = parseInt(document.getElementById("quantity").value);

    let formData = new FormData();
    formData.append("id", productId);
    formData.append("size", selectedSize);
    formData.append("garlic", selectedGarlic);
    formData.append("spice", selectedSpice);
    formData.append("qty", qty);

    fetch("add_to_cart.php", {
        method: "POST",
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        if (data.status === "success") {
            updateCartIcon(data.count);
        }
    });
});

// Update Header Cart Count
function updateCartIcon(count) {
    let cartIcon = document.querySelector(".cart-count");

    if (cartIcon) {
        cartIcon.innerText = count;
    } else {
        let newBadge = document.createElement("span");
        newBadge.classList.add("cart-count");
        newBadge.innerText = count;
        document.querySelector('.icon[href="cart.php"]').appendChild(newBadge);
    }
}




</script>

</body>
</html>