<?php

$host = 'localhost';
$dbname = 'med';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// جلب بيانات المنتج
$product_id = $_GET['id'] ?? null;

if (!$product_id) {
    die("معرف المنتج غير محدد");
}

// جلب تفاصيل المنتج
$product = [];
$product_attributes = [];
$product_images = [];
$product_variants = [];
$delivery_info = [];
$delivery_prices_home = [];
$delivery_prices_office = [];
$wilayas = [];

try {
    // جلب بيانات المنتج الأساسية
    $stmt = $pdo->prepare("
        SELECT p.*, c.name AS category_name,
               (SELECT GROUP_CONCAT(dc.id) FROM product_delivery_companies pdc 
                JOIN delivery_companies dc ON pdc.delivery_company_id = dc.id 
                WHERE pdc.product_id = p.id) AS delivery_company_ids
        FROM products p 
        LEFT JOIN categories c ON p.category_id = c.id 
        WHERE p.id = ?
    ");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$product) {
        die("المنتج غير موجود");
    }
    
    // جلب خصائص المنتج
    $stmt = $pdo->prepare("
        SELECT a.id, a.name, pa.value, a.input_type, a.values_list 
        FROM product_attributes pa
        JOIN attributes a ON pa.attribute_id = a.id
        WHERE pa.product_id = ?
    ");
    $stmt->execute([$product_id]);
    $product_attributes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // جلب صور المنتج
    $stmt = $pdo->prepare("SELECT image_url FROM product_images WHERE product_id = ? ORDER BY is_primary DESC");
    $stmt->execute([$product_id]);
    $product_images = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // جلب المتغيرات والخصائص
    $stmt = $pdo->prepare("
        SELECT pv.id, pv.sku, pv.price, pv.stock, pv.is_default
        FROM product_variants pv
        WHERE pv.product_id = ?
    ");
    $stmt->execute([$product_id]);
    $product_variants = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // جلب خصائص كل متغير
    foreach ($product_variants as &$variant) {
        $stmt = $pdo->prepare("
            SELECT a.name AS attribute_name, va.attribute_value
            FROM variant_attributes va
            JOIN attributes a ON va.attribute_id = a.id
            WHERE va.variant_id = ?
        ");
        $stmt->execute([$variant['id']]);
        $variant['variant_attrs'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    unset($variant);
    
    // جلب معلومات التوصيل
    if (!empty($product['delivery_company_ids'])) {
        $delivery_company_ids = explode(',', $product['delivery_company_ids']);
        $first_company_id = $delivery_company_ids[0];
        
        $stmt = $pdo->prepare("
            SELECT dc.id, dc.name 
            FROM delivery_companies dc
            WHERE dc.id = ?
        ");
        $stmt->execute([$first_company_id]);
        $delivery_info = $stmt->fetch(PDO::FETCH_ASSOC);

        // أسعار التوصيل للمنزل
        $stmt = $pdo->prepare("
            SELECT dp.wilaya_id, dp.price, w.name AS wilaya_name
            FROM delivery_prices dp
            JOIN wilayas w ON dp.wilaya_id = w.id
            WHERE dp.delivery_company_id = ? AND dp.delivery_type = 'home'
        ");
        $stmt->execute([$first_company_id]);
        $delivery_prices_home = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // أسعار التوصيل للمكتب
        $stmt = $pdo->prepare("
            SELECT dp.wilaya_id, dp.price, w.name AS wilaya_name
            FROM delivery_prices dp
            JOIN wilayas w ON dp.wilaya_id = w.id
            WHERE dp.delivery_company_id = ? AND dp.delivery_type = 'office'
        ");
        $stmt->execute([$first_company_id]);
        $delivery_prices_office = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    // جلب جميع الولايات
    $stmt = $pdo->prepare("SELECT id, name FROM wilayas ORDER BY name");
    $stmt->execute();
    $wilayas = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    die("Error fetching product details: " . $e->getMessage());
}

$default_variant = !empty($product_variants) ? $product_variants[0] : null;

// جلب الأقسام للقائمة
$stmt = $pdo->prepare("SELECT id, name FROM categories ORDER BY name");
$stmt->execute();
$categories = $stmt->fetchAll(PDO::FETCH_ASSOC);

// جلب المنتجات ذات الصلة
$related_products = [];
try {
    $stmt = $pdo->prepare("
        SELECT p.*, pi.image_url AS image
        FROM products p
        LEFT JOIN product_images pi ON p.id = pi.product_id AND pi.is_primary = 1
        WHERE p.category_id = ? AND p.id != ? AND p.is_active = 1
        LIMIT 4
    ");
    $stmt->execute([$product['category_id'], $product_id]);
    $related_products = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $related_products_error = "حدث خطأ في جلب المنتجات ذات الصلة";
}
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($product['name']); ?> - متجرنا</title>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Font -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800;900&display=swap" rel="stylesheet">
    
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <!-- Header Top -->
    <div class="header-top">
        <div class="container">
            <div class="header-top-links">
                <a href="#"><i class="fas fa-phone-alt"></i> 0551234567</a>
                <a href="#"><i class="fas fa-envelope"></i> info@example.com</a>
            </div>
        </div>
    </div>
    
    <!-- Header Main -->
    <header class="header">
        <div class="header-main">
            <div class="container">
                <a href="#" class="logo">B&A<span>SHOP</span></a>
                <div class="search-box">
                    <input type="text" placeholder="ابحث عن منتجات...">
                    <button><i class="fas fa-search"></i></button>
                </div>
            </div>
        </div>
        
        <!-- Desktop Navigation -->
        <nav class="navbar">
            <div class="container">
                <ul class="nav-list">
                    <li class="nav-item"><a href="#">الرئيسية</a></li>
                    <li class="nav-item">
                        <a href="#">المنتجات</a>
                        <div class="dropdown">
                            <a href="#">كل المنتجات</a>
                            <a href="#">العروض الخاصة</a>
                            <a href="#">المنتجات الجديدة</a>
                            <a href="#">الأكثر مبيعاً</a>
                        </div>
                    </li>
                    <li class="nav-item">
                        <a href="#">الأقسام</a>
                        <div class="dropdown">
                            <?php foreach ($categories as $category): ?>
                                <a href="?category=<?php echo $category['id']; ?>"><?php echo htmlspecialchars($category['name']); ?></a>
                            <?php endforeach; ?>
                        </div>
                    </li>
                    <li class="nav-item"><a href="#">عنا</a></li>
                    <li class="nav-item"><a href="#">اتصل بنا</a></li>
                </ul>
            </div>
        </nav>
    </header>
    
    <!-- Product Details -->
    <main class="container">
        <div class="product-details">
            <div class="product-gallery">
                <div class="thumbnail-list">
                    <?php
                    if (!empty($product_images)) {
                        $displayed_images = array_slice($product_images, 0, 4);
                        $remaining_images = count($product_images) > 4 ? array_slice($product_images, 4) : [];
                        
                     foreach ($displayed_images as $index => $image) {
    $image_url = !empty($image['image_url']) ? $image['image_url'] : '';
    $image_path = $_SERVER['DOCUMENT_ROOT'] . '/anon-ecommerce-website-master/exemple/' . $image_url;
    $active = $index === 0 ? 'active' : '';
    if ($image_path && file_exists($image_path)) {
        echo '<div class="thumbnail-item ' . $active . '">
            <img src="' . BASE_URL . 'exemple/' . htmlspecialchars($image_url) . '" alt="صورة مصغرة للمنتج">
        </div>';
    } else {
        error_log("Image not found: $image_path");
        echo '<div class="thumbnail-item ' . $active . '">
            <div class="thumbnail-default">
                <i class="fas fa-image"></i>
            </div>
        </div>';
    }
}
                        
                        if (!empty($remaining_images)) {
                            echo '<div class="show-more-btn" onclick="showAllImages()">
                                <span>+ ' . count($remaining_images) . ' أكثر</span>
                            </div>';
                        }
                    } else {
                        echo '<div class="thumbnail-item active">
                            <div class="thumbnail-default">
                                <i class="fas fa-image"></i>
                            </div>
                        </div>';
                    }
                    ?>
                </div>
                
                <div class="main-image">
                    <?php
$main_image = !empty($product_images) && file_exists($_SERVER['DOCUMENT_ROOT'] . '/anon-ecommerce-website-master/exemple/' . $product_images[0]['image_url']) ? BASE_URL . 'exemple/' . $product_images[0]['image_url'] : '';
if ($main_image) {
    echo '<img src="' . htmlspecialchars($main_image) . '" alt="صورة المنتج">';
} else {
    echo '<div class="default-image">
        <i class="fas fa-image"></i>
    </div>';
}
                    ?>
                </div>
            </div>
            
            <div class="product-info">        
                <h1 class="product-title"><?php echo htmlspecialchars($product['name']); ?></h1>
                
                <!-- Product Attributes -->
                <?php if (!empty($product_attributes)): ?>
                <div class="product-specs">
                    <h3>الخصائص:</h3>
                    <ul class="specs-list">
                        <?php foreach ($product_attributes as $attr): ?>
                            <li>
                                <span class="spec-name"><?php echo htmlspecialchars($attr['name']); ?>:</span>
                                <span class="spec-value"><?php echo htmlspecialchars($attr['value']); ?></span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>
                
                <!-- Variant Selector -->
                <?php if (!empty($product_variants)): ?>
                <div class="variant-selector">
                    <?php
                    $variant_attributes = [];
                    foreach ($product_variants as $variant) {
                        foreach ($variant['variant_attrs'] as $attr) {
                            $attr_name = $attr['attribute_name'];
                            $attr_value = $attr['attribute_value'];
                            
                            if (!isset($variant_attributes[$attr_name])) {
                                $variant_attributes[$attr_name] = [];
                            }
                            
                            if (!in_array($attr_value, $variant_attributes[$attr_name])) {
                                $variant_attributes[$attr_name][] = $attr_value;
                            }
                        }
                    }
                    
                    foreach ($variant_attributes as $attr_name => $attr_values): ?>
                    <div class="variant-option">
                        <label><?php echo htmlspecialchars($attr_name); ?>:</label>
                        <div class="variant-values">
                            <?php foreach ($attr_values as $value): ?>
                            <div class="variant-value" 
                                 data-attribute="<?php echo htmlspecialchars($attr_name); ?>" 
                                 data-value="<?php echo htmlspecialchars($value); ?>">
                                <?php echo htmlspecialchars($value); ?>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
                
                <div class="product-price">
                    <span class="current-price" id="variant-price-display">
                        <?php 
                        if ($default_variant) {
                            echo number_format($default_variant['price'], 2);
                        } else if ($product['discounted_price'] && $product['discounted_price'] < $product['price']) {
                            echo number_format($product['discounted_price'], 2);
                        } else {
                            echo number_format($product['price'], 2);
                        }
                        ?> دج
                    </span>
                    <?php if ($product['discounted_price'] && $product['discounted_price'] < $product['price'] && empty($product_variants)): ?>
                        <span class="old-price"><?php echo number_format($product['price'], 2); ?> دج</span>
                        <?php 
                            $discount_percent = round(($product['price'] - $product['discounted_price']) / $product['price'] * 100);
                        ?>
                        <span class="discount-percent">توفير <?php echo $discount_percent; ?>%</span>
                    <?php endif; ?>
                </div>
                
                <div class="product-stock">
                    <?php 
                    $stock_quantity = $default_variant ? $default_variant['stock'] : $product['stock_quantity'];
                    if ($stock_quantity > 0): ?>
                        <span class="stock-status in-stock">متوفر في المخزن</span>
                        <div class="stock-bar">
                            <div class="stock-progress" style="width: <?php echo min(100, ($stock_quantity / 50 * 100)); ?>%"></div>
                        </div>
                        <span id="variant-stock-display"><?php echo $stock_quantity; ?></span> قطعة متبقية
                    <?php else: ?>
                        <span class="stock-status out-of-stock">غير متوفر</span>
                    <?php endif; ?>
                </div>
                
                <div class="product-shipping">
                    <div class="shipping-item">
                        <i class="fas fa-truck"></i>
                        <span class="shipping-company"><?php echo htmlspecialchars($delivery_info['name'] ?? 'غير محدد'); ?></span>
                        <span class="shipping-price">تكلفة التوصيل تختلف حسب الولاية</span>
                    </div>
                </div>
                
                <!-- Direct Order Container -->
                <div class="direct-order-container">
                    <h3 class="direct-order-title">الطلب المباشر</h3>
                    <div class="attribute-combination-unavailable" id="combinationUnavailable">
                        هذه التركيبة غير متوفرة حالياً
                    </div>
                    <div class="order-summary">
                        <div class="summary-item">
                            <div class="summary-label">الكمية</div>
                            <div class="quantity-selector">
                                <button class="quantity-btn minus">-</button>
                                <input type="number" class="quantity-input" value="1" min="1" max="<?php echo $stock_quantity; ?>">
                                <button class="quantity-btn plus">+</button>
                            </div>
                        </div>
                        
                        <div class="summary-item">
                            <div class="summary-label">السعر الإجمالي</div>
                            <div class="summary-value" id="order-total-price">
                                <?php 
                                $price = $default_variant ? $default_variant['price'] : ($product['discounted_price'] ?? $product['price']);
                                echo number_format($price, 2); 
                                ?> دج
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="wilaya-select">الولاية:</label>
                        <select id="wilaya-select" class="form-control" required>
                            <option value="">اختر ولايتك</option>
                            <?php foreach ($wilayas as $wilaya): ?>
                                <option value="<?php echo $wilaya['id']; ?>">
                                    <?php echo htmlspecialchars($wilaya['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="unavailable-wilaya" id="unavailableWilayaMsg">
                            التوصيل غير متوفر لهذه الولاية حالياً، سيتم إضافتها قريباً إن شاء الله
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>نوع التوصيل:</label>
                        <div class="shipping-type-options" id="shippingTypeOptions">
                            <label>
                                <input type="radio" name="delivery_type" value="home">
                                <span class="shipping-type-option">توصيل إلى المنزل</span>
                            </label>
                            <label>
                                <input type="radio" name="delivery_type" value="office">
                                <span class="shipping-type-option">توصيل إلى المكتب</span>
                            </label>
                        </div>
                    </div>
                    
                    <button class="btn btn-primary direct-order-btn disabled" id="directOrderBtn" disabled>
                        <i class="fas fa-shopping-bag"></i>
                        طلب مباشر الآن
                    </button>
                </div>
               
                <div class="product-share">
                    <span>مشاركة المنتج:</span>
                    <div class="social-links">
                        <a href="#"><i class="fab fa-facebook-f"></i></a>
                        <a href="#"><i class="fab fa-twitter"></i></a>
                        <a href="#"><i class="fab fa-whatsapp"></i></a>
                        <a href="#"><i class="fab fa-telegram"></i></a>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Direct Order Modal -->
        <div id="orderModal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="modal-title">تأكيد الطلب المباشر</h2>
                    <span class="close">&times;</span>
                </div>
                
                <form id="orderForm" action="submit_order.php" method="POST">
                    <div class="form-group">
                        <label for="customer_name">الاسم الكامل:</label>
                        <input type="text" id="customer_name" name="customer_name" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="phone">رقم الهاتف:</label>
                        <input type="tel" id="phone" name="phone" required>
                    </div>
                    
                    <div class="trans-group">
                        <label for="address">العنوان:</label>
                        <textarea id="address" name="address" required></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="wilaya_id">الولاية:</label>
                        <select id="wilaya_id" name="wilaya_id" required>
                            <option value="">اختر الولاية</option>
                            <?php foreach ($wilayas as $wilaya): ?>
                                <option value="<?php echo $wilaya['id']; ?>">
                                    <?php echo htmlspecialchars($wilaya['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>نوع التوصيل:</label>
                        <div class="shipping-type-options" id="modalShippingTypeOptions">
                            <label>
                                <input type="radio" name="delivery_type" value="home">
                                <span class="shipping-type-option">توصيل إلى المنزل</span>
                            </label>
                            <label>
                                <input type="radio" name="delivery_type" value="office">
                                <span class="shipping-type-option">توصيل إلى المكتب</span>
                            </label>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>الخصائص المختارة:</label>
                        <div id="selected-attributes-display">لم يتم اختيار خصائص بعد</div>
                        <input type="hidden" id="selected_attributes" name="selected_attributes">
                    </div>
                    
                    <div class="form-group">
                        <label for="modal_quantity">الكمية:</label>
                        <input type="number" id="modal_quantity" name="quantity" value="1" min="1" max="<?php echo $stock_quantity; ?>">
                    </div>
                    
                    <div class="total-price">
                        السعر الإجمالي: <span id="totalPriceSpan">
                            <?php 
                            $price = $default_variant ? $default_variant['price'] : ($product['discounted_price'] ?? $product['price']);
                            echo number_format($price, 2); 
                            ?> دج
                        </span>
                    </div>
                    
                    <input type="hidden" name="product_id" value="<?php echo $product_id; ?>">
                    <input type="hidden" id="variant_id" name="variant_id" value="<?php echo $default_variant['id'] ?? ''; ?>">
                    <input type="hidden" name="delivery_company_id" value="<?php echo $delivery_info['id'] ?? ''; ?>">
                    
                    <button type="submit" class="btn btn-primary">تأكيد الطلب</button>
                </form>
            </div>
        </div>
        
        <!-- Product Tabs -->
        <div class="product-tabs">
            <div class="tabs-header">
                <button class="tab-btn active" data-tab="description">الوصف</button>
                <button class="tab-btn" data-tab="reviews">التقييمات</button>
                <button class="tab-btn" data-tab="shipping">الشحن والتوصيل</button>
            </div>
            
            <div class="tabs-content">
                <div id="description" class="tab-content active">
                    <p><?php echo htmlspecialchars($product['description']); ?></p>
                </div>
                
                <div id="reviews" class="tab-content">
                    <p>لا توجد تقييمات بعد.</p>
                </div>
                
                <div id="shipping" class="tab-content">
                    <h3>سياسة الشحن والتوصيل</h3>
                    <p>نقدم خدمة التوصيل لجميع ولايات الجزائر. تكلفة التوصيل تختلف حسب الولاية ونوع التوصيل (منزل أو مكتب).</p>
                    
                    <?php if (!empty($delivery_info)): ?>
                    <div class="shipping-type-selector">
                        <h4>نوع التوصيل:</h4>
                        <div class="shipping-type-options">
                            <div class="shipping-type-option selected" data-type="home">
                                <i class="fas fa-home"></i> توصيل إلى المنزل
                            </div>
                            <div class="shipping-type-option" data-type="office">
                                <i class="fas fa-building"></i> توصيل إلى المكتب
                            </div>
                        </div>
                    </div>
                    
                    <h4>أسعار التوصيل:</h4>
                    <div id="home-shipping-prices">
                        <table class="shipping-price-table">
                            <thead>
                                <tr>
                                    <th>الولاية</th>
                                    <th>سعر التوصيل (دج)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($delivery_prices_home as $price): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($price['wilaya_name']); ?></td>
                                    <td><?php echo number_format($price['price'], 2); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <div id="office-shipping-prices" style="display:none;">
                        <table class="shipping-price-table">
                            <thead>
                                <tr>
                                    <th>الولاية</th>
                                    <th>سعر التوصيل (دج)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($delivery_prices_office as $price): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($price['wilaya_name']); ?></td>
                                    <td><?php echo number_format($price['price'], 2); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="shipping-notice">
                        <p><i class="fas fa-info-circle"></i> مدة التوصيل تتراوح بين 2-5 أيام عمل حسب الولاية.</p>
                    </div>
                    <?php else: ?>
                    <p>لا تتوفر معلومات الشحن لهذا المنتج حالياً.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Related Products -->
        <section class="related-products">
            <div class="section-title">
                <h2>منتجات ذات صلة</h2>
            </div>
            
            <div class="products-container">
                <?php
                if (isset($related_products_error)) {
                    echo '<p>' . htmlspecialchars($related_products_error) . '</p>';
                } else {
                    foreach ($related_products as $related) {
                        $image_path = !empty($related['image']) && file_exists($related['image']) ? $related['image'] : '';
                        echo '<div class="product-card">
                            ' . ($image_path ? 
                                '<img src="' . htmlspecialchars($image_path) . '" alt="صورة المنتج" class="product-img">' :
                                '<div class="product-img default-image"><i class="fas fa-image"></i></div>') . '
                            <div class="product-content">
                                <h3 class="product-title">' . htmlspecialchars($related['name']) . '</h3>
                                <div class="product-price">
                                    <span class="current-price">' . number_format($related['price'], 2) . ' دج</span>
                                </div>
                                <a href="product.php?id=' . $related['id'] . '" class="btn btn-primary" style="width:100%;">اطلب الآن</a>
                            </div>
                        </div>';
                    }
                }
                ?>
            </div>
        </section>
    </main>
    
    <!-- Footer -->
    <footer class="footer">
        <div class="container">
            <div class="footer-grid">
                <div>
                    <h3 class="footer-title">معلومات عنا</h3>
                    <p>متجرنا هو وجهتكم لأفضل المنتجات بأسعار تنافسية.</p>
                </div>
                <div>
                    <h3 class="footer-title">روابط سريعة</h3>
                    <ul class="footer-links">
                        <li><a href="#"><i class="fas fa-angle-left"></i> الرئيسية</a></li>
                        <li><a href="#"><i class="fas fa-angle-left"></i> المنتجات</a></li>
                        <li><a href="#"><i class="fas fa-angle-left"></i> الأقسام</a></li>
                        <li><a href="#"><i class="fas fa-angle-left"></i> اتصل بنا</a></li>
                    </ul>
                </div>
                <div>
                    <h3 class="footer-title">تواصلوا معنا</h3>
                    <ul class="footer-links">
                        <li><a href="#"><i class="fab fa-facebook-f"></i> فيسبوك</a></li>
                        <li><a href="#"><i class="fab fa-twitter"></i> تويتر</a></li>
                        <li><a href="#"><i class="fab fa-whatsapp"></i> واتساب</a></li>
                        <li><a href="#"><i class="fab fa-telegram"></i> تيليغرام</a></li>
                    </ul>
                </div>
            </div>
            <div class="footer-bottom">
                <p>&copy; <?php echo date('Y'); ?> B&ASHOP. جميع الحقوق محفوظة.</p>
            </div>
        </div>
    </footer>
<!-- Mobile Navigation -->
<nav class="mobile-nav">
    <ul class="mobile-nav-list">
        <a href="index.php">
            <li class="mobile-nav-item ">
                <i class="fas fa-home mobile-nav-icon"></i>
                <span>الرئيسية</span>
            </li>
        </a>
        <a href="track_order.php">
            <li class="mobile-nav-item">
                <i class="fas fa-shopping-bag mobile-nav-icon"></i>
                <span>طلباتي</span>
            </li>
        </a>
    </ul>
</nav>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // تحديد العنصر النشط في القائمة
    const navItems = document.querySelectorAll('.mobile-nav-item');
    
    navItems.forEach(item => {
        item.addEventListener('click', function() {
            navItems.forEach(i => i.classList.remove('active'));
            this.classList.add('active');
        });
    });
    
    // إخفاء التنقل العادي على الهاتف
    if (window.innerWidth <= 768) {
        document.querySelector('.navbar').style.display = 'none';
    }
    
    window.addEventListener('resize', function() {
        if (window.innerWidth <= 768) {
            document.querySelector('.navbar').style.display = 'none';
        } else {
            document.querySelector('.navbar').style.display = 'block';
        }
    });
});
</script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const variantValues = document.querySelectorAll('.variant-value');
            const variantPriceDisplay = document.getElementById('variant-price-display');
            const variantStockDisplay = document.getElementById('variant-stock-display');
            const orderTotalPrice = document.getElementById('order-total-price');
            const selectedAttributesDisplay = document.getElementById('selected-attributes-display');
            const selectedAttributesInput = document.getElementById('selected_attributes');
            const variantIdInput = document.getElementById('variant_id');
            const modalQuantity = document.getElementById('modal_quantity');
            const totalPriceSpan = document.getElementById('totalPriceSpan');
            const combinationUnavailable = document.getElementById('combinationUnavailable');
            const directOrderBtn = document.getElementById('directOrderBtn');
            const wilayaSelect = document.getElementById('wilaya-select');
            const unavailableWilayaMsg = document.getElementById('unavailableWilayaMsg');
            const shippingTypeOptions = document.getElementById('shippingTypeOptions');
            const modalShippingTypeOptions = document.getElementById('modalShippingTypeOptions');

            // Store selected attributes
            let selectedAttributes = {};
            
            // Product variants data
            const productVariants = <?php echo json_encode($product_variants); ?>;
            
            // Delivery prices data
            const deliveryPrices = {
                home: <?php echo json_encode(array_column($delivery_prices_home, 'price', 'wilaya_id')); ?>,
                office: <?php echo json_encode(array_column($delivery_prices_office, 'price', 'wilaya_id')); ?>
            };
            
            // Initialize default variant
            let currentVariant = <?php echo json_encode($default_variant); ?>;
            
            // Update available variant values
            function updateAvailableVariants() {
                variantValues.forEach(value => {
                    const attribute = value.dataset.attribute;
                    const attrValue = value.dataset.value;
                    
                    // Check if this value is valid with current selections
                    const tempAttributes = { ...selectedAttributes };
                    tempAttributes[attribute] = attrValue;
                    
                    const isValid = productVariants.some(variant => {
                        return Object.entries(tempAttributes).every(([attr, val]) => {
                            return variant.variant_attrs.some(va => 
                                va.attribute_name === attr && va.attribute_value === val
                            );
                        }) && variant.stock > 0;
                    });
                    
                    if (isValid) {
                        value.classList.remove('out-of-stock');
                    } else {
                        value.classList.add('out-of-stock');
                    }
                });
            }
            
            // Handle variant selection
            variantValues.forEach(value => {
                value.addEventListener('click', function() {
                    if (this.classList.contains('out-of-stock')) return;
                    
                    const attribute = this.dataset.attribute;
                    const attrValue = this.dataset.value;
                    
                    // Update selected attributes
                    selectedAttributes[attribute] = attrValue;
                    
                    // Remove selected class from same attribute group
                    document.querySelectorAll(`.variant-value[data-attribute="${attribute}"]`)
                        .forEach(val => val.classList.remove('selected'));
                    
                    // Add selected class to clicked value
                    this.classList.add('selected');
                    
                    // Update available variants
                    updateAvailableVariants();
                    
                    // Find matching variant
                    const matchingVariant = productVariants.find(variant => {
                        return Object.keys(selectedAttributes).every(attr => {
                            return variant.variant_attrs.some(va => 
                                va.attribute_name === attr && va.attribute_value === selectedAttributes[attr]
                            );
                        });
                    });
                    
                    // Update UI based on variant availability
                    if (matchingVariant && matchingVariant.stock > 0) {
                        currentVariant = matchingVariant;
                        variantPriceDisplay.textContent = Number(matchingVariant.price).toFixed(2) + ' دج';
                        variantStockDisplay.textContent = matchingVariant.stock;
                        orderTotalPrice.textContent = Number(matchingVariant.price * modalQuantity.value).toFixed(2) + ' دج';
                        variantIdInput.value = matchingVariant.id;
                        
                        // Update stock bar
                        const stockBar = document.querySelector('.stock-progress');
                        stockBar.style.width = Math.min(100, (matchingVariant.stock / 50 * 100)) + '%';
                        
                        // Update selected attributes display
                        const attributesText = Object.entries(selectedAttributes)
                            .map(([key, val]) => `${key}: ${val}`)
                            .join(', ');
                        selectedAttributesDisplay.textContent = attributesText || 'لم يتم اختيار خصائص';
                        selectedAttributesInput.value = JSON.stringify(selectedAttributes);
                        
                        // Hide unavailable combination message and enable order button if wilaya is selected
                        combinationUnavailable.style.display = 'none';
                        if (wilayaSelect.value) {
                            directOrderBtn.disabled = false;
                            directOrderBtn.classList.remove('disabled');
                        }
                        
                        // Update total price in modal
                        updateShippingPrice();
                    } else {
                        // Show unavailable combination message and disable order button
                        combinationUnavailable.style.display = 'block';
                        directOrderBtn.disabled = true;
                        directOrderBtn.classList.add('disabled');
                        
                        // Update display to show unavailable status
                        variantPriceDisplay.textContent = 'غير متوفر';
                        variantStockDisplay.textContent = '0';
                        orderTotalPrice.textContent = '0.00 دج';
                        variantIdInput.value = '';
                        const stockBar = document.querySelector('.stock-progress');
                        stockBar.style.width = '0%';
                        
                        // Update selected attributes display
                        const attributesText = Object.entries(selectedAttributes)
                            .map(([key, val]) => `${key}: ${val}`)
                            .join(', ');
                        selectedAttributesDisplay.textContent = attributesText || 'لم يتم اختيار خصائص';
                        selectedAttributesInput.value = JSON.stringify(selectedAttributes);
                    }
                });
            });
            
            // Quantity buttons
            const quantityInput = document.querySelector('.quantity-input');
            modalQuantity.addEventListener('change', () => {
                if (modalQuantity.value < 1) modalQuantity.value = 1;
                if (parseInt(modalQuantity.value) > parseInt(currentVariant ? currentVariant.stock : 0)) {
                    modalQuantity.value = currentVariant ? currentVariant.stock : 1;
                }
                quantityInput.value = modalQuantity.value;
                updateTotalPrice();
            });
            
            document.querySelector('.quantity-btn.minus').addEventListener('click', () => {
                if (quantityInput.value > 1) {
                    quantityInput.value--;
                    modalQuantity.value = quantityInput.value;
                    updateTotalPrice();
                }
            });
            
            document.querySelector('.quantity-btn.plus').addEventListener('click', () => {
                if (parseInt(quantityInput.value) < parseInt(currentVariant ? currentVariant.stock : 0)) {
                    quantityInput.value++;
                    modalQuantity.value = quantityInput.value;
                    updateTotalPrice();
                }
            });
            
            // Update total price
            function updateTotalPrice() {
                if (!currentVariant) return;
                const quantity = parseInt(modalQuantity.value);
                const price = parseFloat(currentVariant ? currentVariant.price : <?php echo $product['discounted_price'] ?? $product['price']; ?>);
                const total = price * quantity;
                orderTotalPrice.textContent = total.toFixed(2) + ' دج';
                updateShippingPrice();
            }
            
            // Modal handling
            const modal = document.getElementById('orderModal');
            const closeBtn = document.querySelector('.close');
            
            directOrderBtn.addEventListener('click', () => {
                if (!directOrderBtn.disabled) {
                    modal.style.display = 'block';
                    document.getElementById('wilaya_id').value = wilayaSelect.value;
                    updateModalShippingOptions();
                    updateShippingPrice();
                }
            });
            
            closeBtn.addEventListener('click', () => {
                modal.style.display = 'none';
            });
            
            window.addEventListener('click', (event) => {
                if (event.target === modal) {
                    modal.style.display = 'none';
                }
            });
            
            // Wilaya selection
            wilayaSelect.addEventListener('change', () => {
                const wilayaId = wilayaSelect.value;
                if (wilayaId) {
                    // Check available delivery types
                    const homeAvailable = deliveryPrices.home[wilayaId] !== undefined;
                    const officeAvailable = deliveryPrices.office[wilayaId] !== undefined;
                    
                    if (homeAvailable || officeAvailable) {
                        unavailableWilayaMsg.style.display = 'none';
                        shippingTypeOptions.style.display = 'flex';
                        
                        // Show only available delivery types
                        shippingTypeOptions.querySelector('input[value="home"]').parentElement.style.display = homeAvailable ? 'block' : 'none';
                        shippingTypeOptions.querySelector('input[value="office"]').parentElement.style.display = officeAvailable ? 'block' : 'none';
                        
                        // Auto-select the available option if only one is available
                        if (homeAvailable && !officeAvailable) {
                            shippingTypeOptions.querySelector('input[value="home"]').checked = true;
                        } else if (!homeAvailable && officeAvailable) {
                            shippingTypeOptions.querySelector('input[value="office"]').checked = true;
                        } else {
                            shippingTypeOptions.querySelector('input[value="home"]').checked = true;
                        }
                        
                        if (currentVariant) {
                            directOrderBtn.disabled = false;
                            directOrderBtn.classList.remove('disabled');
                        }
                        updateShippingPrice();
                    } else {
                        unavailableWilayaMsg.style.display = 'block';
                        shippingTypeOptions.style.display = 'none';
                        directOrderBtn.disabled = true;
                        directOrderBtn.classList.add('disabled');
                    }
                } else {
                    unavailableWilayaMsg.style.display = 'none';
                    shippingTypeOptions.style.display = 'none';
                    directOrderBtn.disabled = true;
                    directOrderBtn.classList.add('disabled');
                }
            });
            
            // Update modal shipping options
            function updateModalShippingOptions() {
                const wilayaId = document.getElementById('wilaya_id').value;
                if (wilayaId) {
                    const homeAvailable = deliveryPrices.home[wilayaId] !== undefined;
                    const officeAvailable = deliveryPrices.office[wilayaId] !== undefined;
                    
                    modalShippingTypeOptions.querySelector('input[value="home"]').parentElement.style.display = homeAvailable ? 'block' : 'none';
                    modalShippingTypeOptions.querySelector('input[value="office"]').parentElement.style.display = officeAvailable ? 'block' : 'none';
                    
                    if (homeAvailable && !officeAvailable) {
                        modalShippingTypeOptions.querySelector('input[value="home"]').checked = true;
                    } else if (!homeAvailable && officeAvailable) {
                        modalShippingTypeOptions.querySelector('input[value="office"]').checked = true;
                    } else {
                        modalShippingTypeOptions.querySelector('input[value="home"]').checked = true;
                    }
                }
            }
            
            // Update shipping price
            document.getElementById('wilaya_id').addEventListener('change', () => {
                updateModalShippingOptions();
                updateShippingPrice();
            });
            
            document.querySelectorAll('input[name="delivery_type"]').forEach(radio => {
                radio.addEventListener('change', updateShippingPrice);
            });
            
            function updateShippingPrice() {
                if (!currentVariant) return;
                const wilayaId = document.getElementById('wilaya_id').value || wilayaSelect.value;
                const deliveryType = document.querySelector('input[name="delivery_type"]:checked')?.value || 'home';
                const quantity = parseInt(modalQuantity.value);
                const productPrice = parseFloat(currentVariant ? currentVariant.price : <?php echo $product['discounted_price'] ?? $product['price']; ?>);
                
                if (wilayaId && deliveryPrices[deliveryType][wilayaId] !== undefined) {
                    const shippingPrice = deliveryPrices[deliveryType][wilayaId] || 0;
                    const totalPrice = (productPrice * quantity) + parseFloat(shippingPrice);
                    totalPriceSpan.textContent = totalPrice.toFixed(2) + ' دج';
                } else {
                    const totalPrice = productPrice * quantity;
                    totalPriceSpan.textContent = totalPrice.toFixed(2) + ' دج';
                }
            }
            
            // Handle thumbnail images
            function showAllImages() {
                const thumbnailList = document.querySelector('.thumbnail-list');
                const remainingImages = <?php echo json_encode($remaining_images); ?>;
                
                remainingImages.forEach(image => {
                    const image_path = '<?php echo BASE_URL; ?>' + image.image_url;
                    const thumbnail = document.createElement('div');
                    thumbnail.className = 'thumbnail-item';
                    thumbnail.innerHTML = `<img src="${image_path}" alt="صورة مصغرة للمنتج">`;
                    thumbnail.addEventListener('click', () => {
                        document.querySelector('.main-image img').src = image_path;
                        document.querySelectorAll('.thumbnail-item').forEach(item => item.classList.remove('active'));
                        thumbnail.classList.add('active');
                    });
                    thumbnailList.insertBefore(thumbnail, document.querySelector('.show-more-btn'));
                });
                
                document.querySelector('.show-more-btn').remove();
            }
            
            // Handle thumbnail click
            document.querySelectorAll('.thumbnail-item').forEach(thumbnail => {
                thumbnail.addEventListener('click', () => {
                    const imgSrc = thumbnail.querySelector('img')?.src || '<?php echo BASE_URL; ?>images/default-placeholder.png';
                    document.querySelector('.main-image img').src = imgSrc;
                    document.querySelectorAll('.thumbnail-item').forEach(item => item.classList.remove('active'));
                    thumbnail.classList.add('active');
                });
            });
            
            // Handle tabs
            const tabButtons = document.querySelectorAll('.tab-btn');
            const tabContents = document.querySelectorAll('.tab-content');
            
            tabButtons.forEach(button => {
                button.addEventListener('click', () => {
                    tabButtons.forEach(btn => btn.classList.remove('active'));
                    tabContents.forEach(content => content.classList.remove('active'));
                    
                    button.classList.add('active');
                    document.getElementById(button.dataset.tab).classList.add('active');
                });
            });
            
            // Handle shipping type toggle
            document.querySelectorAll('.shipping-type-option').forEach(option => {
                option.addEventListener('click', () => {
                    document.querySelectorAll('.shipping-type-option').forEach(opt => opt.classList.remove('selected'));
                    option.classList.add('selected');
                    document.getElementById('home-shipping-prices').style.display = option.dataset.type === 'home' ? 'block' : 'none';
                    document.getElementById('office-shipping-prices').style.display = option.dataset.type === 'office' ? 'block' : 'none';
                });
            });
        });
    </script>
</body>
</html>