<?php 
include("inc/header.php");


$product_id = (int)($_GET['id'] ?? 0);

/* PRODUCT */
$product = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT p.*, c.name as category_name,c.slug as slug
    FROM products p
    LEFT JOIN categories c ON c.id = p.category_id
    WHERE p.id = $product_id
"));

if(!$product){
    die("Product not found");
}

/* VARIANTS (Your table names) */
$variants = [];
$res = mysqli_query($conn,"
    SELECT pv.*, vg.name as group_name
    FROM product_variants pv
    JOIN variant_groups vg ON vg.id = pv.variant_group_id
    WHERE pv.product_id = $product_id
    AND pv.status='active'
    AND vg.status='active'
    ORDER BY vg.sort_order ASC, pv.sort_order ASC
");

while($row = mysqli_fetch_assoc($res)){
    $variants[$row['variant_group_id']]['group_name'] = $row['group_name'];
    $variants[$row['variant_group_id']]['options'][] = $row;
}
?>
<style>
/* TABS */
.product-tabs {
    margin-top: 60px;
}

/* TAB HEADER */
.tab-head {
    display: flex;
    gap: 40px;
    border-bottom: 1px solid #e5e5e5;
    margin-bottom: 20px;
}

.tab-btn {
    background: none;
    border: none;
    font-size: 15px;
    font-weight: 600;
    padding: 12px 0;
    cursor: pointer;
    position: relative;
    color: #888;
    text-transform: capitalize;
}

/* ACTIVE TAB */
.tab-btn.active {
    color: #000;
}

.tab-btn.active::after {
    content: "";
    position: absolute;
    bottom: -1px;
    left: 0;
    width: 100%;
    height: 2px;
    background: #e11d2e;
    /* red underline */
}

/* TAB CONTENT */
.tab-content {
    display: none;
    padding-top: 10px;
    color: #555;
    line-height: 1.9;
    font-size: 15px;
}

.tab-content.active {
    display: block;
}


/* RELATED PRODUCTS */
.related-products-section {
    margin-top: 70px;
}

.related-products h3 {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 25px;
}

/* CARD */
.related-card {
    background: #fff;
    border: none;
    text-align: center;
    transition: 0.3s;
}

/* IMAGE */
.related-card img {
    width: 100%;
    height: 200px;
    object-fit: cover;
    margin-bottom: 10px;
}

/* TITLE */
.related-card h4 {
    font-size: 15px;
    font-weight: 500;
    margin-bottom: 5px;
    color: #222;
}

/* CATEGORY TEXT (optional if you add later) */
.related-card small {
    display: block;
    color: #999;
    font-size: 12px;
    margin-bottom: 5px;
}

/* PRICE */
.related-card span {
    display: block;
    color: #e11d2e;
    font-weight: 600;
    font-size: 14px;
    margin-bottom: 10px;
}

/* BUTTON */
.related-card .btn {
    background: #111;
    color: #fff;
    border-radius: 0;
    font-size: 13px;
    padding: 8px 12px;
    border: none;
}

.related-card .btn:hover {
    background: #e11d2e;
}

.single-product-sec-box {
    border: 1px solid #DADADA;
    background: #FFF;
    padding: 175px 0px 12px;
    margin-top: -150px;
}
</style>


<section class="inner-banner-row">
    <div class="container">
        <div class="inner-banner-sec"></div>
    </div>
</section>

<section class="single-product-row">
    <div class="container">

        <nav class="single-breadcrumb">
            <span><a href="./">Home</a></span>
            <i class="fa fa-angle-right"></i>
            <span class="pname"><?= htmlspecialchars($product['category_name']); ?></span>
            <i class="fa fa-angle-right"></i>
            <span class="pname"><?= htmlspecialchars($product['name']); ?></span>
        </nav>

        <div class="row align-items-center">

            <!-- LEFT IMAGE -->
            <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
                <div class="product-lft-sec">
                    <div class="zoom-container">
                        <img src="<?= 
                !empty($product['featured_image'])
                ? 'admin/uploads/products/'.$product['featured_image']
                : 'assets/images/product-img1.jpg';
            ?>" alt="product image" class="zoom-image">
                    </div>
                </div>
            </div>

            <!-- RIGHT SIDE -->
            <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
                <div class="product-rgt-sec">

                    <h2><?= htmlspecialchars($product['name']); ?></h2>

                    <!-- PRICE -->
                    <p id="productPrice">
                        $<?= number_format($product['base_price'],2); ?>
                    </p>



                    <?php if(!empty($variants)): ?>
                    <?php foreach($variants as $group): ?>
                    <div class="variant-group" style="margin-bottom:15px;">
                        <strong class="group-title"><?= htmlspecialchars($group['group_name']); ?>:</strong>

                        <select class="variant-select form-control" style="margin-top:5px;">
                            <option value="">Choose an Option</option>

                            <?php foreach($group['options'] as $opt): ?>
                            <option value="<?= $opt['id']; ?>" data-price="<?= $opt['price']; ?>">
                                <?= htmlspecialchars($opt['label']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>

<!-- CALCULATOR LINK -->
<div style="margin: 10px 0;">
    <a href="javascript:void(0)"
       data-bs-toggle="modal"
       data-bs-target="#calculatorModal"
       style="color:#e11d2e; font-weight:600; text-decoration:underline; cursor:pointer;">
        Open Calculator
    </a>
</div>



                    <!-- QUANTITY -->
                    <div class="quantity">
                        <button class="minus" aria-label="Decrease">&minus;</button>
                        <input type="number" class="input-box" value="1" min="1" max="10">
                        <button class="plus" aria-label="Increase">&plus;</button>
                    </div>

                    <a href="cart.php">
                        <button class="btn btn-primary w-btn">Add to cart</button>
                    </a>

                    <div class="product_meta">
                        <!-- <span class="sku_wrapper">
        SKU: <span class="sku">
            <?= htmlspecialchars($product['sku'] ?? 'N/A'); ?>
        </span> -->
                        </span>

                        <span class="posted_in">
                            Category:
                            <a href="product-category.php?category=<?= htmlspecialchars($product['slug']); ?>">
                                <?= htmlspecialchars($product['category_name']); ?>
                            </a>
                        </span>
                    </div>

                </div>
            </div>
        </div>

        <!-- TABS SECTION -->
        <div class="product-tabs">

            <!-- TAB HEADINGS -->
            <div class="tab-head">
                <button class="tab-btn active" data-tab="desc">Description</button>
                <button class="tab-btn" data-tab="info">Additional Information</button>
            </div>

            <!-- TAB CONTENT -->
            <div class="tab-content active" id="desc">
                <p><?= nl2br(htmlspecialchars($product['description'])); ?></p>
            </div>

            <div class="tab-content" id="info">
                <p><strong>SKU:</strong> <?= htmlspecialchars($product['sku'] ?? 'N/A'); ?></p>
                <p><strong>Category:</strong> <?= htmlspecialchars($product['category_name']); ?></p>
            </div>

        </div>

        <?php
$related = mysqli_query($conn,"
    SELECT * FROM products 
    WHERE category_id = '".intval($product['category_id'])."' 
    AND id != '".intval($product_id)."' 
    LIMIT 4
");

$related_count = mysqli_num_rows($related);
?>

        <div class="related-products-section">
            <div class="related-products">
                <h3>Related products</h3>

                <?php if($related_count > 0): ?>

                <div class="row">
                    <?php while($r = mysqli_fetch_assoc($related)): ?>
                    <div class="col-md-3">
                        <div class="related-card">

                            <img src="<?= !empty($r['featured_image']) 
                                ? 'admin/uploads/products/'.$r['featured_image'] 
                                : 'assets/images/product-img1.jpg'; ?>">
                            <div class="single-product-sec-box">
                                <h4><?= htmlspecialchars($r['name']); ?></h4>
                                <small><?= htmlspecialchars($product['category_name']); ?></small>



                                <span>$<?= number_format($r['base_price'],2); ?></span>


                                <a href="single-product.php?id=<?= $r['id']; ?>" class="btn btn-dark">
                                    Add To Cart
                                </a>
                            </div>
                        </div>
                    </div>
                    <?php endwhile; ?>
                </div>

                <?php else: ?>

                <p style="color:#777; font-size:16px;">No related products</p>

                <?php endif; ?>

            </div>
        </div>
</section>

<div class="modal fade" id="calculatorModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-centered">

    <div class="modal-content" style="background:#111; color:#fff;">

      <div class="modal-header">
        <h5 class="modal-title">Stone Calculator</h5>

        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body p-0">

        <iframe 
            src="custom_calculator/calculator.php?product_id=<?= $product['id']; ?>" 
            style="width:100%; height:80vh; border:none;">
        </iframe>

      </div>

    </div>

  </div>
</div>

<?php include("inc/footer.php"); ?>

<script>
const basePrice = <?= $product['base_price']; ?>;
const selects = document.querySelectorAll('.variant-select');
const priceBox = document.getElementById('productPrice');

function updatePrice() {

    let selectedPrice = null;

    selects.forEach(select => {
        if (select.value !== "") {
            selectedPrice = select.options[select.selectedIndex].getAttribute('data-price');
        }
    });

    if (selectedPrice) {
        priceBox.innerHTML = '$' + parseFloat(selectedPrice).toFixed(2);
    } else {
        priceBox.innerHTML = '$' + parseFloat(basePrice).toFixed(2);
    }
}

selects.forEach(select => {
    select.addEventListener('change', updatePrice);
});
</script>
<script>
document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', function() {

        document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));

        this.classList.add('active');
        document.getElementById(this.dataset.tab).classList.add('active');
    });
});
</script>