<?php
// product.php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/facebook-pixel.php'; // Add this line

$slug = $_GET['slug'] ?? '';
$product = getProductBySlug($pdo, $slug);

if (!$product) {
    header('Location: shop.php');
    exit;
}

// Increment views
$stmt = $pdo->prepare("UPDATE products SET views = views + 1 WHERE id = ?");
$stmt->execute([$product['id']]);

// ========================================
// TRACK VIEW CONTENT EVENT
// ========================================
if (!empty(FACEBOOK_PIXEL_ID)) {
    $view_data = [
        'currency' => 'BDT',
        'value' => $product['sale_price'] ?: $product['price'],
        'content_name' => $product['name'],
        'content_id' => $product['id'],
        'content_type' => 'product',
        'content_category' => $product['category_name'] ?? 'General'
    ];
    
    $user_data = [
        'url' => (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
    ];
    
    trackFacebookEvent('ViewContent', $view_data, $user_data);
}

// Get product attributes
$stmt = $pdo->prepare("SELECT * FROM product_attributes WHERE product_id = ?");
$stmt->execute([$product['id']]);
$attributes = $stmt->fetchAll();

// Group attributes by name
$grouped_attributes = [];
foreach ($attributes as $attr) {
    $grouped_attributes[$attr['attribute_name']][] = $attr;
}

// Get gallery images
$gallery_images = [];
if ($product['gallery_images']) {
    $gallery_images = explode(',', $product['gallery_images']);
}

// Get category for breadcrumb
$stmt = $pdo->prepare("SELECT * FROM categories WHERE id = ?");
$stmt->execute([$product['category_id']]);
$category = $stmt->fetch();

// Get subcategory for breadcrumb
$subcategory = null;
if ($product['subcategory_id']) {
    $stmt = $pdo->prepare("SELECT * FROM subcategories WHERE id = ?");
    $stmt->execute([$product['subcategory_id']]);
    $subcategory = $stmt->fetch();
}

// Get related products
$stmt = $pdo->prepare("SELECT * FROM products WHERE category_id = ? AND id != ? AND status = 1 ORDER BY RAND() LIMIT 4");
$stmt->execute([$product['category_id'], $product['id']]);
$related_products = $stmt->fetchAll();

// Get delivery charges from settings or use defaults
$delivery_charges = [
    'Dhaka City' => 70,
    'Saver, Keranigonj, Gazipur & Narayanganj' => 100,
    'Other Districts' => 120
];

include __DIR__ . '/includes/header.php';
?>
<!-- Rest of the product.php content -->

<!-- Add this hidden input for selected variant -->
<input type="hidden" id="selected_variant_value" value="">
<input type="hidden" id="selected_variant_name" value="">

<style>
/* Product Page Styles */
.single_product_area {
    padding: 30px 0;
}

.zooming_image_content {
    position: relative;
    width: 100%;
    max-width: 400px;
    margin: 0 auto;
}

/* ===== IMAGE ZOOM CONTAINER ===== */
.zooming_show_image {
    overflow: hidden;
    border-radius: 10px;
    background: #f5f5f5;
    position: relative;
    width: 100%;
    aspect-ratio: 1/1;
}

.zooming_show_image img {
    width: 100%;
    height: 100%;
    object-fit: contain;
    transition: none;
    transform-origin: 0 0;
    will-change: transform;
}

.zooming_show_image {
    cursor: zoom-in;
}

.zooming_show_image.zoomed {
    cursor: zoom-out;
}

.zooming_show_image.zoomed img {
    transform: scale(2.5) !important;
}

.zoom_img_active .owl-dots {
    display: flex;
    gap: 6px;
    margin-top: 8px;
    overflow-x: auto;
    padding: 3px 0;
    justify-content: center;
    flex-wrap: wrap;
}

.zoom_img_active .owl-dots .owl-dot {
    border: 2px solid transparent;
    border-radius: 6px;
    overflow: hidden;
    transition: all 0.3s ease;
    width: 55px;
    height: 55px;
    cursor: pointer;
}

.zoom_img_active .owl-dots .owl-dot.active {
    border-color: #047dc3;
}

.zoom_img_active .owl-dots .owl-dot img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    cursor: pointer;
}

.zoom_img_active .owl-nav button {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 32px;
    height: 32px;
    background: rgba(0,0,0,0.5);
    color: #fff;
    border: none;
    border-radius: 50%;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    z-index: 10;
}

.zoom_img_active .owl-nav button:hover {
    background: #047dc3;
}

.zoom_img_active .owl-nav .owl-prev {
    left: 5px;
}

.zoom_img_active .owl-nav .owl-next {
    right: 5px;
}

.youtube_video {
    position: relative;
    padding-bottom: 56.25%;
    height: 0;
    overflow: hidden;
    border-radius: 10px;
    margin-bottom: 10px;
}

.youtube_video iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

/* Product Details */
.single_product_details {
    padding: 0 10px;
}

.single_product_list ul {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 3px;
    padding: 0;
    margin: 0 0 10px 0;
    list-style: none;
}

.single_product_list ul li {
    display: inline-flex;
    align-items: center;
    font-size: 13px;
}

.single_product_list ul li:not(:last-child)::after {
    content: "›";
    margin-left: 5px;
    color: #94a3b8;
    font-size: 16px;
}

.single_product_list_link {
    color: #33023d;
    font-size: 18px;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 3px;
}

.single_product_list_link:hover {
    color: #047dc3;
}

.single_product_name h2 {
    font-size: 20px;
    font-weight: 700;
    color: #2e1600;
    margin-bottom: 10px;
    line-height: 1.3;
}

.single_product_attribute {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;
}

.single_product_attribute strong {
    font-weight: 600;
    color: #2e1600;
    min-width: 50px;
    font-size: 14px;
}

.single_product_attribute_label {
    font-weight: 600;
    color: #2e1600;
    display: block;
    margin-bottom: 4px;
    font-size: 14px;
}

.single_product_new_price {
    font-size: 20px;
    font-weight: 700;
    color: #2e1600;
}

.single_product_discount_price {
    font-size: 15px;
    color: #2e1600;
    text-decoration: line-through;
    margin-left: 8px;
}

.select_attribute_container {
    margin: 10px 0;
}

.single_product_size_checkbox_list ul {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    padding: 0;
    margin: 0;
    list-style: none;
}

.single_product_size_checkbox_list_group {
    position: relative;
}

.single_product_size_checkbox_list_group input[type="radio"] {
    display: none;
}

.single_product_size_checkbox_list_group label {
    display: block;
    padding: 5px 14px;
    border: 2px solid #01224d;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 13px;
    font-weight: 500;
}

.single_product_size_checkbox_list_group input[type="radio"]:checked + label {
    border-color: #047dc3;
    background: #e0f2fe;
    color: #2e1600;
}

.single_product_size_checkbox_list_group label:hover {
    border-color: #047dc3;
}

.single_product_qty_with_buy_now_btn {
    margin-top: 12px;
}

.single_product_add_to_cart {
    width: 100%;
    padding: 10px;
    background: linear-gradient(95deg, #792f04 , #100036 50% ); 
    color: #fff;
    border: none;
    border-radius: 6px;
    font-weight: 600;
    font-size: 14px;
    transition: all 0.3s ease;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.single_product_add_to_cart:hover {
    background: #0369a1;
}

.single_product_buy_now_btn_link {
    display: block;
    width: 100%;
    padding: 10px;
    background: #ff8000;
    color: #fff;
    border: none;
    border-radius: 6px;
    font-weight: 600;
    font-size: 14px;
    text-align: center;
    transition: all 0.3s ease;
    text-decoration: none;
}

.single_product_buy_now_btn_link:hover {
    background: #e67300;
    color: #fff;
}

/* Contact Section */
.contact_us_container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
    margin-top: 12px;
}

.call_contact_us {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 12px;
    background: linear-gradient(95deg, #8f3d07 , #05454b 70% ); 
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    text-decoration: none;
    transition: all 0.3s ease;
}

.call_contact_us:hover {
    border-color: #047dc3;
    box-shadow: 0 3px 15px rgba(0,0,0,0.05);
    text-decoration: none;
}

.whats_up {
    width: 32px;
    height: 32px;
    background: #25d366;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 18px;
    flex-shrink: 0;
}

.call_icon {
    width: 32px;
    height: 32px;
    background: #047dc3;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #ffffff;
    font-size: 16px;
    flex-shrink: 0;
}

.contact_des h5 {
    font-size: 13px;
    font-weight: 500;
    color: #ffffff;
    margin: 0;
}

.contact_des h6 {
    font-size: 12px;
    font-weight: 600;
    color: #ffffff;
    margin: 0;
}

/* Specifications Column */
.single_product_specification_content {
    display: flex;
    flex-direction: column;
    gap: 10px;
    height: 100%;
}

.single_product_specification_list {
    background: #fff;
    border: 2px dotted #047dc3;
    border-radius: 8px;
    padding: 15px;
    flex: 1;
}

.single_product_specification_list ul {
    padding: 0;
    margin: 0;
    list-style: none;
}

.single_product_specification_list ul li {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 5px 0;
    border-bottom: 1px solid #f1f5f9;
    font-size: 13px;
}

.single_product_specification_list ul li:last-child {
    border-bottom: none;
}

.single_product_specification_list ul li i {
    color: #3a1b02;
    font-size: 14px;
    width: 18px;
}

.single_product_call_details {
    background: #fff;
    border: 2px dotted #047dc3;
    border-radius: 8px;
    padding: 15px;
}

.single_product_call_title p {
    font-size: 13px;
    color: #3a1b02;
    margin-bottom: 8px;
}

.single_product_call ul {
    padding: 0;
    margin: 0;
    list-style: none;
}

.single_product_call ul li {
    margin-bottom: 5px;
}

.single_product_call ul li:last-child {
    margin-bottom: 0;
}

.single_product_call_link {
    display: flex;
    align-items: center;
    gap: 8px;
    text-decoration: none;
}

.single_product_call_content {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    color: #1e293b;
}

.single_product_call_content i {
    color: #047dc3;
}

.single_product_call_payment_method p {
    margin: 0;
    font-size: 11px;
    color: #ef4444;
    border: 1px dashed #ef4444;
    padding: 1px 8px;
    border-radius: 4px;
}

/* Tabs Section */
.single_product_tab_area {
    padding: 30px 0 50px;
}

.single_product_tab_nav {
    border-bottom: 2px solid #e2e8f0;
    margin-bottom: 25px;
}

.single_product_tab_nav .single_product_tab_nav_link {
    border: none;
    padding: 10px 20px;
    font-weight: 600;
    color: #070707;
    background: transparent;
    border-radius: 0;
    transition: all 0.3s ease;
    font-size: 14px;
}

.single_product_tab_nav .single_product_tab_nav_link.active {
    color: #047dc3;
    border-bottom: 3px solid #047dc3;
}

.single_product_tab_nav .single_product_tab_nav_link:hover {
    color: #047dc3;
}

.single_product_tab_content {
    padding: 15px 0;
}

.single_product_tab_content p {
    margin-bottom: 10px;
    line-height: 1.8;
}

.single_product_tab_list ul {
    padding-left: 20px;
    list-style: disc;
}

.single_product_tab_list ul li {
    margin-bottom: 10px;
    line-height: 1.6;
}

/* Reviews Section */
.customer_comment_area {
    padding: 10px 0;
}

.customer_comment_title {
    display: flex;
    align-items: center;
    gap: 12px;
}

.customer_comment_avarage_rating {
    font-size: 32px;
    font-weight: 700;
    color: #1e293b;
}

.customer_comment_rating_name {
    display: flex;
    align-items: center;
    gap: 6px;
    background: #047dc3;
    color: #fff;
    padding: 3px 12px;
    border-radius: 5px;
    font-size: 14px;
}

.customer_comment_item {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 5px;
}

.customer_comment_item_star {
    display: flex;
    gap: 2px;
    color: #f59e0b;
    min-width: 90px;
    font-size: 14px;
}

.customer_comment_item_percentage_segment {
    flex: 1;
    height: 6px;
    background: #e2e8f0;
    border-radius: 3px;
    overflow: hidden;
}

.customer_comment_item_percentage_segment span {
    display: block;
    height: 100%;
    background: #047dc3;
    border-radius: 3px;
}

.customer_comment_item_percentage {
    min-width: 40px;
    text-align: right;
    color: #64748b;
    font-size: 13px;
}

.customer_comment_btn .customer_comment_btn_link {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 8px 20px;
    background: #047dc3;
    color: #fff;
    border: none;
    border-radius: 6px;
    font-weight: 500;
    font-size: 14px;
    transition: all 0.3s ease;
    cursor: pointer;
}

.customer_comment_btn .customer_comment_btn_link:hover {
    background: #0369a1;
}

/* Related Products */
.related-products {
    margin-top: 30px;
    border-top: 1px solid #e2e8f0;
    padding-top: 30px;
}

.related-products h4 {
    font-size: 20px;
    font-weight: 700;
    margin-bottom: 20px;
}

.product-card {
    background: #fff;
    border: 1px solid #e2e8f0;
    border-radius: 10px;
    padding: 10px;
    transition: all 0.3s ease;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.product-card:hover {
    box-shadow: 0 5px 20px rgba(0,0,0,0.08);
    transform: translateY(-3px);
}

.product-card .image {
    position: relative;
    aspect-ratio: 1/1;
    overflow: hidden;
    border-radius: 6px;
    background: #f8fafc;
}

.product-card .image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.5s ease;
}

.product-card:hover .image img {
    transform: scale(1.05);
}

.product-card .content {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding-top: 8px;
}

.product-card .content .name {
    font-size: 13px;
    font-weight: 500;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    flex: 1;
    color: #1e293b;
    transition: all 0.3s ease;
}

.product-card .content .name:hover {
    color: #047dc3;
}

.product-card .content .price {
    text-align: center;
    margin: 6px 0;
}

.product-card .content .price .current {
    font-size: 15px;
    font-weight: 700;
    color: #047dc3;
}

.product-card .content .price .old {
    font-size: 12px;
    color: #94a3b8;
    text-decoration: line-through;
    margin-left: 6px;
}

.product-card .content .btn-order {
    display: block;
    width: 100%;
    padding: 6px;
    background: #047dc3;
    color: #fff;
    text-align: center;
    border-radius: 5px;
    font-weight: 500;
    font-size: 13px;
    transition: all 0.3s ease;
    text-decoration: none;
}

.product-card .content .btn-order:hover {
    background: #ff8000;
    color: #fff;
}

/* Responsive */
@media (min-width: 992px) {
    .zooming_image_content {
        max-width: 100%;
    }
}

@media (max-width: 991px) {
    .zooming_image_content {
        max-width: 350px;
    }
    .single_product_details {
        padding: 0;
        margin-top: 15px;
    }
    .single_product_specification_content {
        margin-top: 15px;
    }
}

@media (max-width: 768px) {
    .zooming_image_content {
        max-width: 300px;
    }
    .single_product_name h2 {
        font-size: 18px;
    }
    .single_product_new_price {
        font-size: 18px;
    }
    .contact_us_container {
        grid-template-columns: 1fr 1fr;
    }
    .zoom_img_active .owl-dots .owl-dot {
        width: 45px;
        height: 45px;
    }
    .single_product_tab_nav .single_product_tab_nav_link {
        padding: 8px 12px;
        font-size: 13px;
    }
}

@media (max-width: 576px) {
    .single_product_area {
        padding: 15px 0;
    }
    .zooming_image_content {
        max-width: 100%;
    }
    .single_product_name h2 {
        font-size: 16px;
    }
    .single_product_new_price {
        font-size: 16px;
    }
    .single_product_discount_price {
        font-size: 13px;
    }
    .contact_us_container {
        grid-template-columns: 1fr 1fr;
    }
    .zoom_img_active .owl-dots .owl-dot {
        width: 40px;
        height: 40px;
    }
}

/* Rating Stars Modal */
.rating-stars {
    display: flex;
    flex-direction: row-reverse;
    justify-content: flex-end;
    gap: 5px;
}

.rating-stars input {
    display: none;
}

.rating-stars label {
    font-size: 30px;
    color: #e2e8f0;
    cursor: pointer;
    transition: all 0.2s ease;
}

.rating-stars input:checked ~ label {
    color: #f59e0b;
}

.rating-stars label:hover,
.rating-stars label:hover ~ label {
    color: #f59e0b;
}
</style>

<div class="single_product_area section_padding">
    <div class="container">
        <div class="row gy-sm-4 gx-sm-4 gy-3 gx-2">
            
            <!-- Column 1: Product Images -->
            <div class="col-xxl-4 col-xl-4 col-lg-4 col-md-12 col-sm-12 col-12">
                <div class="zooming_image_content">
                    <div id="video-url" data-url=""></div>
                    <div class="youtube_video" id="youtube_video" style="display: none;"></div>

                    <div class="zoom_img_active owl-carousel owl-loaded owl-drag">
                        <?php 
                        $main_image = $product['image'] ?: 'default.jpg';
                        $image_counter = 1;
                        ?>
                        
                        <div data-dot="<img src='<?php echo ASSETS_URL; ?>images/products/<?php echo $main_image; ?>' onclick='showImg(<?php echo $image_counter; ?>)' oncontextmenu='return false;' ondragstart='return false;'>" 
                             style="display: block;" 
                             id="main_image_<?php echo $image_counter; ?>" 
                             class="zooming_show_image"
                             data-scale="2.5">
                            <div class="project-picture" id="<?php echo $image_counter; ?>">
                                <img src="<?php echo ASSETS_URL; ?>images/products/<?php echo $main_image; ?>" alt="<?php echo $product['name']; ?>" oncontextmenu="return false;" ondragstart="return false;">
                            </div>
                        </div>
                        
                        <?php 
                        $image_counter++;
                        foreach ($gallery_images as $gallery_img): 
                            if (empty($gallery_img)) continue;
                        ?>
                        <div data-dot="<img src='<?php echo ASSETS_URL; ?>images/products/<?php echo $gallery_img; ?>' onclick='showImg(<?php echo $image_counter; ?>)' oncontextmenu='return false;' ondragstart='return false;'>" 
                             style="display: block;" 
                             id="main_image_<?php echo $image_counter; ?>" 
                             class="zooming_show_image"
                             data-scale="2.5">
                            <div class="project-picture" id="<?php echo $image_counter; ?>">
                                <img src="<?php echo ASSETS_URL; ?>images/products/<?php echo $gallery_img; ?>" alt="<?php echo $product['name']; ?>" oncontextmenu="return false;" ondragstart="return false;">
                            </div>
                        </div>
                        <?php 
                        $image_counter++;
                        endforeach; 
                        ?>
                    </div>
                </div>
            </div>

            <!-- Column 2: Product Details -->
            <div class="col-xxl-4 col-xl-4 col-lg-4 col-md-12 col-sm-12 col-12">
                <div class="single_product_details">
                    <!-- Breadcrumb -->
                    <div class="single_product_list">
                        <ul>
                            <li>
                                <a href="<?php echo BASE_URL; ?>" class="single_product_list_link">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
                                        <polyline points="9 22 9 12 15 12 15 22"></polyline>
                                    </svg>
                                </a>
                            </li>
                            <?php if ($category): ?>
                            <li>
                                <a href="<?php echo BASE_URL; ?>shop.php?category=<?php echo $category['slug']; ?>" class="single_product_list_link">
                                    <?php echo $category['name']; ?>
                                </a>
                            </li>
                            <?php endif; ?>
                            <?php if ($subcategory): ?>
                            <li>
                                <a href="<?php echo BASE_URL; ?>shop.php?subcategory=<?php echo $subcategory['slug']; ?>" class="single_product_list_link">
                                    <?php echo $subcategory['name']; ?>
                                </a>
                            </li>
                            <?php endif; ?>
                        </ul>
                    </div>
                    
                    <!-- Product Name -->
                    <div class="single_product_name">
                        <input type="hidden" id="product_id" value="<?php echo $product['id']; ?>">
                        <input type="hidden" id="product_stock" value="<?php echo $product['stock']; ?>">
                        <h2><?php echo $product['name']; ?></h2>
                    </div>

                    <!-- Product Code -->
                    <div class="single_product_attribute s_p_code">
                        <strong>Code:</strong>
                        <span><?php echo $product['product_code']; ?></span>
                    </div>
                    
                    <!-- Product Price -->
                    <div class="single_product_attribute s_p_price">
                        <strong>Price:</strong>
                        <div class="single_product_price">
                            <span class="single_product_new_price" id="variant_wise_price"><?php echo number_format($product['sale_price'] ?: $product['price']); ?> TK</span>
                            <?php if ($product['sale_price']): ?>
                            <span class="single_product_discount_price sigle_discount_text"><?php echo number_format($product['price']); ?> TK</span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Product Attributes - FIXED: Added "Select Size" label -->
                    <?php foreach ($grouped_attributes as $attr_name => $attr_values): ?>
                    <div class="select_attribute_container s_p_select">
                        <strong class="single_product_attribute_label">Select <?php echo ucfirst($attr_name); ?></strong>
                        <div class="single_product_attribute">
                            <div class="single_product_size_checkbox_list" id="product_variant_<?php echo strtolower($attr_name); ?>">
                                <ul>
                                    <?php foreach ($attr_values as $attr): ?>
                                    <li>
                                        <div class="single_product_size_checkbox_list_group variant">
                                            <input type="radio" name="variant<?php echo ucfirst($attr_name); ?>" 
                                                   value="<?php echo $attr['attribute_value']; ?>" 
                                                   data-attr-name="<?php echo ucfirst($attr_name); ?>"
                                                   onclick="getVariant(this.value, '<?php echo ucfirst($attr_name); ?>', <?php echo $attr['extra_price']; ?>, <?php echo $product['sale_price'] ?: $product['price']; ?>)" 
                                                   id="attr_<?php echo $attr['id']; ?>">
                                            <label for="attr_<?php echo $attr['id']; ?>">
                                                <div class="title">
                                                    <?php echo $attr['attribute_value']; ?>
                                                </div>
                                            </label>
                                        </div>
                                    </li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>

                    <!-- If no attributes from database, show static Size option -->
                    <?php if (empty($grouped_attributes)): ?>
                    <div class="select_attribute_container s_p_select">
                        <strong class="single_product_attribute_label">Select Size</strong>
                        <div class="single_product_attribute">
                            <div class="single_product_size_checkbox_list" id="product_variant_size">
                                <ul>
                                    <li>
                                        <div class="single_product_size_checkbox_list_group variant">
                                            <input type="radio" name="variantSize" value="M" data-attr-name="Size" onclick="getVariant(this.value, 'Size', 0, <?php echo $product['sale_price'] ?: $product['price']; ?>)" id="size_m">
                                            <label for="size_m">
                                                <div class="title">M</div>
                                            </label>
                                        </div>
                                    </li>
                                    <li>
                                        <div class="single_product_size_checkbox_list_group variant">
                                            <input type="radio" name="variantSize" value="L" data-attr-name="Size" onclick="getVariant(this.value, 'Size', 0, <?php echo $product['sale_price'] ?: $product['price']; ?>)" id="size_l">
                                            <label for="size_l">
                                                <div class="title">L</div>
                                            </label>
                                        </div>
                                    </li>
                                    <li>
                                        <div class="single_product_size_checkbox_list_group variant">
                                            <input type="radio" name="variantSize" value="XL" data-attr-name="Size" onclick="getVariant(this.value, 'Size', 0, <?php echo $product['sale_price'] ?: $product['price']; ?>)" id="size_xl">
                                            <label for="size_xl">
                                                <div class="title">XL</div>
                                            </label>
                                        </div>
                                    </li>
                                    <li>
                                        <div class="single_product_size_checkbox_list_group variant">
                                            <input type="radio" name="variantSize" value="XXL" data-attr-name="Size" onclick="getVariant(this.value, 'Size', 0, <?php echo $product['sale_price'] ?: $product['price']; ?>)" id="size_xxl">
                                            <label for="size_xxl">
                                                <div class="title">XXL</div>
                                            </label>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Add to Cart & Buy Now -->
                    <div class="single_product_qty_with_buy_now_btn">
                        <div class="row gx-2 gy-2">
                            <div class="col-12">
                                <button type="button" id="<?php echo $product['id']; ?>" 
                                        data-variant="<?php echo !empty($grouped_attributes) ? 1 : 0; ?>" 
                                        class="single_product_add_to_cart" 
                                        onclick="addToCard(event, this.id, this.getAttribute('data-variant'))">
                                    <i class="fa-solid fa-cart-shopping"></i>
                                    Add To Cart
                                </button>
                            </div>
                            
                            <div class="col-12">
                                <div class="single_product_buy_now_btn">
                                    <form id="buyNowForm" action="<?php echo BASE_URL; ?>buy-now.php" method="POST" onsubmit="return prepareBuyNowForm()">
                                        <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
                                        <input type="hidden" name="quantity" value="1">
                                        <!-- Hidden fields for variant will be added dynamically -->
                                        <div id="variant_hidden_fields"></div>
                                        <button type="submit" class="single_product_buy_now_btn_link">
                                            Order Now
                                            <i class="fa-solid fa-check"></i>
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Contact Section -->
                    <div class="contact_us_container mt-0 p-0">
                        <a href="https://wa.me/8801764197001" id="whatsappLink" class="call_contact_us call_whats">
                            <div class="whats_up">
                                <i class="fa-brands fa-whatsapp"></i>
                            </div>
                            <div class="contact_des">
                                <h5>Whatsapp Now</h5>
                                <h6>01764197001</h6>
                            </div>
                        </a>
                        <a href="tel:01764197001" class="call_contact_us call_whats">
                            <div class="call_icon">
                                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z">
                                    </path>
                                </svg>
                            </div>
                            <div class="contact_des">
                                <h5>Call Now</h5>
                                <h6>01764197001</h6>
                            </div>
                        </a>
                    </div>
                </div>
            </div>

            <!-- Column 3: Specifications -->
            <div class="col-xxl-4 col-xl-4 col-lg-4 col-md-12 col-sm-12 col-12">
                <div class="single_product_specification_content">
                    <div class="single_product_specification_list">
                        <ul>
                            <li>
                                <i class="fa-solid fa-check"></i>
                                Order today and receive it within 02 - 03 days
                            </li>
                            <li>
                                <i class="fa-solid fa-thumbs-up"></i>
                                Quality Product
                            </li>
                            <li>
                                <i class="fa-solid fa-handshake"></i>
                                Cash On Delivery Available
                            </li>
                            <?php if (!empty($delivery_charges)): ?>
                                <?php foreach ($delivery_charges as $area => $charge): ?>
                                <li>
                                    <i class="fa-solid fa-truck-fast"></i>
                                    Delivery Charge <?php echo $area; ?> - <?php echo $charge; ?>TK
                                </li>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </ul>
                    </div>
                    
                    <div class="single_product_call_details">
                        <div class="single_product_call_title">
                            <p>Have question about this product? Please call</p>
                        </div>
                        <div class="single_product_call">
                            <ul>
                                <li>
                                    <a href="tel:01764197001" class="single_product_call_link">
                                        <div class="single_product_call_content">
                                            <i class="fa-solid fa-phone"></i>
                                            01764197001
                                        </div>
                                    </a>
                                </li>
                                <li>
                                    <a href="tel:" class="single_product_call_link">
                                        <div class="single_product_call_content">
                                            <i class="fa-solid fa-phone"></i>
                                        </div>
                                        <div class="single_product_call_payment_method">
                                            <p>Bkash Personal</p>
                                        </div>
                                    </a>
                                </li>
                                <li>
                                    <a href="tel:" class="single_product_call_link">
                                        <div class="single_product_call_content">
                                            <i class="fa-solid fa-phone"></i>
                                        </div>
                                        <div class="single_product_call_payment_method">
                                            <p>Nagad Personal</p>
                                        </div>
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Tabs Section -->
<div class="single_product_tab_area section_padding_bottom">
    <div class="container">
        <div class="row">
            <div class="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                <div class="single_product_tab">
                    <ul class="nav nav-tabs single_product_tab_nav" id="myTab" role="tablist">
                        <li class="nav-item single_product_tab_nav_item active" role="presentation">
                            <button class="nav-link single_product_tab_nav_link active" id="home-tab" data-bs-toggle="tab" data-bs-target="#home" type="button" role="tab" aria-controls="home" aria-selected="true">
                                Description
                            </button>
                        </li>
                        <li class="nav-item single_product_tab_nav_item" role="presentation">
                            <button class="nav-link single_product_tab_nav_link" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile" type="button" role="tab" aria-controls="profile" aria-selected="false">
                                How To Order
                            </button>
                        </li>
                        <li class="nav-item single_product_tab_nav_item" role="presentation">
                            <button class="nav-link single_product_tab_nav_link" id="contact-tab" data-bs-toggle="tab" data-bs-target="#contact" type="button" role="tab" aria-controls="contact" aria-selected="false">
                                Reviews
                            </button>
                        </li>
                    </ul>
                    <div class="tab-content" id="myTabContent">
                        <!-- Description Tab -->
                        <div class="tab-pane fade active show" id="home" role="tabpanel" aria-labelledby="home-tab">
                            <div class="single_product_tab_content">
                                <?php 
                                $description = $product['description'] ?: 'No description available.';
                                echo nl2br($description); 
                                ?>
                                <?php if ($product['specification']): ?>
                                <div class="mt-3">
                                    <?php echo nl2br($product['specification']); ?>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- How To Order Tab -->
                        <div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">
                            <div class="single_product_tab_content">
                                <div class="single_product_tab_list">
                                    <ul>
                                        <li>Select number of product you want to buy.</li>
                                        <li>Click <strong>Add To Cart</strong> Button</li>
                                        <li>Then go to checkout page</li>
                                        <li>If you are a new customer, please click on Sign Up. Provide us your valid information.</li>
                                        <li>Complete your checkout, we received your order, and for order confirmation or customer service contact with you</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Reviews Tab -->
                        <div class="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab">
                            <div class="single_product_tab_content">
                                <div class="customer_comment_area section_padding_bottom">
                                    <div class="row">
                                        <div class="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                                            <div class="section_title text-center">
                                                <h2>Reviews</h2>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="section_top_space">
                                        <div class="row gy-4 gx-4">
                                            <div class="col-xxl-3 col-xl-4 col-lg-12 col-md-12 col-sm-12 col-12">
                                                <div class="customer_comment_title">
                                                    <span class="customer_comment_avarage_rating">0</span>
                                                    <span class="customer_comment_rating_name">
                                                        Reviews
                                                    </span>
                                                </div>
                                                <div class="customer_comment_rating"></div>
                                                <div class="customer_comment_rating_count">
                                                    <span>0 reviews</span>
                                                </div>
                                            </div>

                                            <div class="col-xxl-5 col-xl-5 col-lg-12 col-md-12 col-sm-12 col-12">
                                                <?php for ($i = 5; $i >= 1; $i--): ?>
                                                <div class="customer_comment_item">
                                                    <div class="customer_comment_item_star">
                                                        <?php for ($j = 1; $j <= 5; $j++): ?>
                                                            <span><i class="fa-<?php echo $j <= $i ? 'solid' : 'regular'; ?> fa-star"></i></span>
                                                        <?php endfor; ?>
                                                    </div>
                                                    <div class="customer_comment_item_percentage_segment">
                                                        <span style="width: 0%;"></span>
                                                    </div>
                                                    <div class="customer_comment_item_percentage">
                                                        <span>0%</span>
                                                    </div>
                                                </div>
                                                <?php endfor; ?>
                                            </div>

                                            <div class="col-xxl-3 col-xl-3 col-lg-12 col-md-12 col-sm-12 col-12">
                                                <div class="customer_comment_btn">
                                                    <button class="customer_comment_btn_link" data-bs-toggle="modal" data-product_slug="<?php echo $product['slug']; ?>" data-bs-target="#reviewModal">
                                                        <i class="fa-regular fa-pen-to-square"></i>
                                                        Write a Review
                                                    </button>
                                                </div>
                                            </div>

                                            <div class="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                                                <div class="customer_comment_review_content">
                                                    <div class="customer_comment_list">
                                                        <ul>
                                                            <li class="text-center text-muted">No reviews yet. Be the first to review!</li>
                                                        </ul>
                                                    </div>
                                                    <div class="comments_pagination"></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Related Products -->
<?php if (!empty($related_products)): ?>
<section class="related-products">
    <div class="container">
        <h4>Related Products</h4>
        <div class="row g-2 g-lg-3">
            <?php foreach ($related_products as $related): ?>
            <div class="col-xxl-3 col-xl-3 col-lg-3 col-md-4 col-sm-4 col-4">
                <div class="product-card">
                    <div class="image">
                        <a href="<?php echo BASE_URL; ?>product.php?slug=<?php echo $related['slug']; ?>">
                            <img src="<?php echo ASSETS_URL; ?>images/products/<?php echo $related['image'] ?: 'default.jpg'; ?>" alt="<?php echo $related['name']; ?>">
                        </a>
                    </div>
                    <div class="content">
                        <a href="<?php echo BASE_URL; ?>product.php?slug=<?php echo $related['slug']; ?>" class="name"><?php echo $related['name']; ?></a>
                        <div class="price">
                            <span class="current"><?php echo number_format($related['sale_price'] ?: $related['price']); ?> TK</span>
                            <?php if ($related['sale_price']): ?>
                            <span class="old"><?php echo number_format($related['price']); ?> TK</span>
                            <?php endif; ?>
                        </div>
                        <a href="<?php echo BASE_URL; ?>product.php?slug=<?php echo $related['slug']; ?>" class="btn-order">View Details</a>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- Review Modal -->
<div class="modal fade" id="reviewModal" tabindex="-1" aria-labelledby="reviewModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="reviewModalLabel">Write a Review</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="reviewForm">
                    <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
                    <div class="mb-3">
                        <label class="form-label">Your Name</label>
                        <input type="text" name="user_name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Rating</label>
                        <div class="rating-stars">
                            <input type="radio" name="rating" value="5" id="star5"><label for="star5">★</label>
                            <input type="radio" name="rating" value="4" id="star4"><label for="star4">★</label>
                            <input type="radio" name="rating" value="3" id="star3"><label for="star3">★</label>
                            <input type="radio" name="rating" value="2" id="star2"><label for="star2">★</label>
                            <input type="radio" name="rating" value="1" id="star1"><label for="star1">★</label>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Review</label>
                        <textarea name="review" class="form-control" rows="4" required></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary w-100">Submit Review</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
// ===== VARIABLE TO STORE SELECTED VARIANT =====
var selectedVariantValue = '';
var selectedVariantName = '';

// ===== VARIANT SELECTION FUNCTION =====
function getVariant(value, attrName, extraPrice, basePrice) {
    // Store selected variant
    selectedVariantValue = value;
    selectedVariantName = attrName;
    
    // Update price
    var price = basePrice + parseFloat(extraPrice);
    document.getElementById('variant_wise_price').textContent = price + ' TK';
    
    // Update hidden inputs
    document.getElementById('selected_variant_value').value = value;
    document.getElementById('selected_variant_name').value = attrName;
    
    // Add hidden fields to buy now form
    prepareVariantHiddenFields();
}

// ===== PREPARE VARIANT HIDDEN FIELDS FOR BUY NOW =====
function prepareVariantHiddenFields() {
    var container = document.getElementById('variant_hidden_fields');
    container.innerHTML = '';
    
    if (selectedVariantValue && selectedVariantName) {
        // Add hidden field for variant
        var input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'variant' + selectedVariantName;
        input.value = selectedVariantValue;
        container.appendChild(input);
    }
}

// ===== PREPARE BUY NOW FORM =====
function prepareBuyNowForm() {
    // Check if variant is required but not selected
    var hasVariant = <?php echo !empty($grouped_attributes) ? 1 : 0; ?>;
    
    if (hasVariant == 1 && !selectedVariantValue) {
        showToast('Please select a size first', 'warning');
        return false;
    }
    
    // Prepare hidden fields
    prepareVariantHiddenFields();
    return true;
}

// ===== CURSOR-BASED IMAGE ZOOM =====
document.addEventListener('DOMContentLoaded', function() {
    const zoomContainers = document.querySelectorAll('.zooming_show_image');
    
    zoomContainers.forEach(container => {
        const img = container.querySelector('img');
        const scale = parseFloat(container.dataset.scale) || 2.5;
        let isZoomed = false;
        
        container.addEventListener('mousemove', function(e) {
            if (!isZoomed) return;
            
            const rect = this.getBoundingClientRect();
            const x = (e.clientX - rect.left) / rect.width;
            const y = (e.clientY - rect.top) / rect.height;
            
            const offsetX = x * 100;
            const offsetY = y * 100;
            
            img.style.transform = `scale(${scale})`;
            img.style.transformOrigin = `${offsetX}% ${offsetY}%`;
        });
        
        container.addEventListener('mouseenter', function() {
            isZoomed = true;
            this.classList.add('zoomed');
            img.style.transition = 'none';
        });
        
        container.addEventListener('mouseleave', function() {
            isZoomed = false;
            this.classList.remove('zoomed');
            img.style.transition = 'transform 0.3s ease';
            img.style.transform = 'scale(1)';
            img.style.transformOrigin = 'center center';
        });
        
        // Touch support
        container.addEventListener('touchstart', function(e) {
            if (!isZoomed) {
                isZoomed = true;
                this.classList.add('zoomed');
                img.style.transition = 'none';
                
                const touch = e.touches[0];
                const rect = this.getBoundingClientRect();
                const x = (touch.clientX - rect.left) / rect.width;
                const y = (touch.clientY - rect.top) / rect.height;
                
                const offsetX = x * 100;
                const offsetY = y * 100;
                
                img.style.transform = `scale(${scale})`;
                img.style.transformOrigin = `${offsetX}% ${offsetY}%`;
                e.preventDefault();
            }
        });
        
        container.addEventListener('touchmove', function(e) {
            if (!isZoomed) return;
            
            const touch = e.touches[0];
            const rect = this.getBoundingClientRect();
            const x = (touch.clientX - rect.left) / rect.width;
            const y = (touch.clientY - rect.top) / rect.height;
            
            const offsetX = x * 100;
            const offsetY = y * 100;
            
            img.style.transform = `scale(${scale})`;
            img.style.transformOrigin = `${offsetX}% ${offsetY}%`;
            e.preventDefault();
        });
        
        container.addEventListener('touchend', function() {
            isZoomed = false;
            this.classList.remove('zoomed');
            img.style.transition = 'transform 0.3s ease';
            img.style.transform = 'scale(1)';
            img.style.transformOrigin = 'center center';
        });
    });
});

// ===== IMAGE GALLERY FUNCTIONS =====
function showImg(id) {
    var imgSrc = document.querySelector('#main_image_' + id + ' img').src;
    document.querySelector('#main_image_1 img').src = imgSrc;
    
    document.querySelectorAll('.owl-dot').forEach(function(dot, index) {
        dot.classList.remove('active');
        if (index === id - 1) {
            dot.classList.add('active');
        }
    });
}

// ========================================
// ADD TO CART FUNCTION
// ========================================
function addToCard(event, productId, hasVariant) {
    event.preventDefault();
    event.stopPropagation();
    
    console.log('Add to Cart clicked - Product ID:', productId);
    console.log('Has Variant:', hasVariant);
    
    // Check if variant is selected
    if (hasVariant == 1) {
        var selected = false;
        var variantInputs = document.querySelectorAll('input[type="radio"][name^="variant"]');
        variantInputs.forEach(function(input) {
            if (input.checked) {
                selected = true;
                console.log('Selected variant:', input.name, '=', input.value);
            }
        });
        if (!selected) {
            showToast('Please select a variant first', 'warning');
            return;
        }
    }
    
    // Get quantity
    var quantityInput = document.querySelector('.product_qty');
    var quantity = quantityInput ? parseInt(quantityInput.value) || 1 : 1;
    
    // Create FormData
    var formData = new FormData();
    formData.append('product_id', productId);
    formData.append('quantity', quantity);
    
    // Add selected variants
    var variantInputs = document.querySelectorAll('input[type="radio"][name^="variant"]:checked');
    variantInputs.forEach(function(input) {
        var name = input.getAttribute('name');
        formData.append(name, input.value);
        console.log('Adding variant:', name, '=', input.value);
    });
    
    // Show loading state
    var btn = event.currentTarget;
    var originalText = btn.innerHTML;
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Adding...';
    btn.disabled = true;
    
    // AJAX request
    fetch('add-to-cart.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(res => {
        console.log('Response:', res);
        
        if (res.success) {
            showToast('Added to cart successfully!', 'success');
            // Update cart count
            var cartCount = document.getElementById('cartCount');
            if (cartCount) {
                cartCount.textContent = res.cart_count + ' items';
            }
            // Update mobile cart count
            var mobileCartCount = document.querySelector('.mobile-cart .badge');
            if (mobileCartCount) {
                mobileCartCount.textContent = res.cart_count;
            }
        } else {
            showToast(res.message || 'Failed to add to cart', 'error');
        }
        
        // Reset button
        btn.innerHTML = originalText;
        btn.disabled = false;
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('Something went wrong. Please try again.', 'error');
        btn.innerHTML = originalText;
        btn.disabled = false;
    });
}

// ========================================
// TOAST NOTIFICATION
// ========================================
function showToast(message, type) {
    var colors = {
        success: '#22c55e',
        error: '#ef4444',
        warning: '#f59e0b',
        info: '#3b82f6'
    };
    
    var toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 24px;
        background: ${colors[type] || colors.info};
        color: #fff;
        border-radius: 8px;
        z-index: 9999;
        box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        animation: slideIn 0.3s ease;
        max-width: 400px;
    `;
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(function() {
        toast.style.opacity = '0';
        toast.style.transition = 'opacity 0.3s ease';
        setTimeout(function() { toast.remove(); }, 300);
    }, 3000);
}



// ===== INITIALIZE OWL CAROUSEL =====
$(document).ready(function() {
    $('.zoom_img_active').owlCarousel({
        loop: true,
        margin: 0,
        nav: true,
        dots: true,
        autoplay: false,
        navText: ['<i class="fa fa-angle-left"></i>', '<i class="fa fa-angle-right"></i>'],
        items: 1,
        dotsContainer: '.zoom_img_active .owl-dots'
    });
});

// ===== CSS ANIMATION =====
var style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0%); opacity: 1; }
    }
`;
document.head.appendChild(style);
</script>

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