<?php
session_start();
require_once '../includes/product-card.php';
require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

// إعدادات الموقع
try {
    $stmt = $db->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('site_name', 'logo_text', 'default_currency')");
    $stmt->execute();
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    $site_name = $settings['site_name'] ?? 'Roz Skin';
    $logo_text = $settings['logo_text'] ?? 'Roz Skin';
    $currency = $settings['default_currency'] ?? 'EGP';
} catch (PDOException $e) {
    $site_name = 'Roz Skin';
    $logo_text = 'Roz Skin';
    $currency = 'EGP';
}

$currency_symbols = ['EGP' => 'ج.م', 'USD' => '$', 'EUR' => '€', 'AED' => 'د.إ'];
$currency_symbol = $currency_symbols[$currency] ?? 'ج.م';

// عدد السلة
$cart_count = 0;
if (isset($_SESSION['user_id'])) {
    try {
        require_once '../models/cart.php';
        $cart_model = new Cart($db);
        $cart_count = $cart_model->getCartCount($_SESSION['user_id']);
    } catch (Exception $e) {
        $cart_count = 0;
    }
}

// جلب المنتج
$product_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($product_id <= 0) {
    header('Location: products.php');
    exit;
}

try {
    $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$product) {
        header('Location: products.php');
        exit;
    }
} catch (PDOException $e) {
    header('Location: products.php');
    exit;
}

// منتجات مشابهة
try {
    $stmt = $db->prepare("SELECT * FROM products WHERE category_id = ? AND id != ? LIMIT 4");
    $stmt->execute([$product['category_id'], $product_id]);
    $related = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $related = [];
}

// Fix image path
if (!empty($product['image'])) {
    if (strpos($product['image'], 'uploads/') === 0) {
        $imageUrl = '../' . $product['image'];
    } else {
        $imageUrl = '../uploads/products/' . $product['image'];
    }
} else {
    $imageUrl = 'https://images.unsplash.com/photo-1556228578-8c89e6adf883?w=800&h=1000&fit=crop';
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($product['name']); ?> - <?php echo htmlspecialchars($site_name); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../assets/css/global-theme.css">
    <link rel="stylesheet" href="../assets/css/pinterest-style.css">
    <link rel="stylesheet" href="../assets/css/product-enhancements.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .product-container {
            max-width: 1200px;
            margin: 80px auto 40px;
            padding: 0 20px;
        }
        .product-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 60px;
            margin-bottom: 60px;
        }
        .product-image-main {
            position: sticky;
            top: 100px;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 8px 30px rgba(0,0,0,0.12);
        }
        .product-image-main img {
            width: 100%;
            height: auto;
            display: block;
        }
        .product-details {
            padding: 20px 0;
        }
        .product-name {
            font-size: 42px;
            font-weight: 800;
            color: #111;
            margin-bottom: 16px;
            line-height: 1.2;
        }
        .product-price {
            font-size: 32px;
            font-weight: 700;
            color: #E57393;
            margin-bottom: 24px;
        }
        .product-description {
            font-size: 16px;
            line-height: 1.8;
            color: #5F5F5F;
            margin-bottom: 32px;
        }
        .product-actions {
            display: flex;
            gap: 16px;
            margin-bottom: 32px;
        }
        .btn-add-to-cart {
            background: linear-gradient(135deg, #E57393 0%, #D1537A 100%);
            color: white;
            border: none;
            padding: 18px 32px;
            border-radius: 50px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 8px 20px rgba(229, 115, 147, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .btn-add-to-cart:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 28px rgba(229, 115, 147, 0.4);
        }
        .btn-add-to-cart:active {
            transform: translateY(0);
        }
        .btn-buy-now {
            background: linear-gradient(135deg, #111111 0%, #374151 100%);
            color: white;
            border: none;
            padding: 18px 32px;
            border-radius: 50px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 8px 20px rgba(17, 17, 17, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .btn-buy-now:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 28px rgba(17, 17, 17, 0.4);
            background: linear-gradient(135deg, #000000 0%, #1F2937 100%);
        }
        .btn-buy-now:active {
            transform: translateY(0);
        }
        .btn-wishlist {
            width: 60px;
            height: 60px;
            border: 2px solid #E5E7EB;
            background: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        .btn-wishlist:hover {
            border-color: #E57393;
            background: #FFF5F7;
        }
        .product-meta {
            padding: 24px;
            background: #F9FAFB;
            border-radius: 16px;
            margin-bottom: 32px;
        }
        .meta-item {
            display: flex;
            justify-content: space-between;
            padding: 12px 0;
            border-bottom: 1px solid #E5E7EB;
        }
        .meta-item:last-child {
            border-bottom: none;
        }
        .meta-label {
            color: #6B7280;
            font-weight: 500;
        }
        .meta-value {
            color: #111;
            font-weight: 600;
        }
        .related-section {
            margin-top: 80px;
        }
        .section-title {
            font-size: 28px;
            font-weight: 700;
            text-align: center;
            margin-bottom: 40px;
            color: #111;
        }
        .related-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 24px;
        }
        .related-card {
            background: white;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            transition: all 0.3s;
            cursor: pointer;
        }
        .related-card:hover {
            transform: translateY(-8px);
            box-shadow: 0 8px 24px rgba(0,0,0,0.12);
        }
        .related-image {
            width: 100%;
            height: 250px;
            object-fit: cover;
        }
        .related-info {
            padding: 16px;
        }
        .related-name {
            font-size: 16px;
            font-weight: 600;
            color: #111;
            margin-bottom: 8px;
        }
        .related-price {
            font-size: 18px;
            font-weight: 700;
            color: #E57393;
        }
        .toast-notification {
            position: fixed;
            top: 20px;
            right: 20px;
            background: linear-gradient(135deg, #E57393 0%, #D1537A 100%);
            color: white;
            padding: 16px 24px;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(229, 115, 147, 0.4);
            z-index: 9999;
            font-weight: 600;
            font-size: 16px;
            animation: slideIn 0.3s ease-out;
            max-width: 350px;
        }
        .toast-notification.hidden {
            display: none;
        }
        @keyframes slideIn {
            from {
                transform: translateX(400px);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        @media (max-width: 768px) {
            .product-grid {
                grid-template-columns: 1fr;
                gap: 32px;
            }
            .product-image-main {
                position: static;
            }
            .product-name {
                font-size: 32px;
            }
            .product-price {
                font-size: 24px;
            }
            .related-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 16px;
            }
            .toast-notification {
                right: 10px;
                left: 10px;
                max-width: calc(100% - 20px);
            }
            .btn-add-to-cart, .btn-buy-now {
                font-size: 16px;
                padding: 16px 24px;
            }
        }
        
        /* Star Rating Input Styles */
        .star-rating-input {
            display: flex;
            flex-direction: row-reverse;
            justify-content: center;
            gap: 8px;
            margin: 16px 0;
        }
        
        .star-rating-input input[type="radio"] {
            display: none;
        }
        
        .star-rating-input label {
            font-size: 36px;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
        }
        
        /* Outline style when not selected */
        .star-rating-input label {
            color: transparent;
            -webkit-text-stroke: 2px #E57393;
            text-stroke: 2px #E57393;
        }
        
        /* Filled pink when selected or hovered */
        .star-rating-input input[type="radio"]:checked ~ label,
        .star-rating-input label:hover,
        .star-rating-input label:hover ~ label {
            color: #E57393;
            -webkit-text-stroke: 0;
            text-stroke: 0;
            transform: scale(1.1);
        }
    </style>
    <link rel="stylesheet" href="../assets/css/product-cards.css">
    <link rel="stylesheet" href="assets/css/product-elegant-design.css">
</head>
<body>

    <!-- Navigation -->
    <nav id="mainNav" style="background: rgba(255, 255, 255, 0.8); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid rgba(229, 115, 147, 0.08); position: fixed; top: 0; left: 0; right: 0; z-index: 1000; transition: transform 0.3s ease;">
        <div style="max-width: 1400px; margin: 0 auto; padding: 0 24px;">
            <div style="display: flex; align-items: center; justify-content: space-between; height: 60px;">
                
                <!-- Actions - Right Side -->
                <div style="display: flex; align-items: center; gap: 20px;">
                    <!-- Burger Menu -->
                    <button id="burgerBtn" onclick="toggleBurgerMenu()" style="background: transparent; border: none; padding: 8px; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.2s;" onmouseover="this.style.opacity='0.7'" onmouseout="this.style.opacity='1'">
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="3" y1="12" x2="21" y2="12"></line>
                            <line x1="3" y1="6" x2="21" y2="6"></line>
                            <line x1="3" y1="18" x2="21" y2="18"></line>
                        </svg>
                    </button>
                </div>

                <!-- Logo - Left Side -->
                <a href="index.php" style="font-size: 22px; font-weight: 800; background: linear-gradient(135deg, #E57393 0%, #D1537A 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; text-decoration: none; letter-spacing: -0.3px;">
                    <?php echo htmlspecialchars($logo_text); ?>
                </a>
            </div>
        </div>
    </nav>

    <!-- Floating Cart Button -->
    <button onclick="window.location.href='cart.php'" title="السلة" style="position: fixed; bottom: 24px; right: 24px; z-index: 999; background: linear-gradient(135deg, #E57393 0%, #D1537A 100%); border: none; width: 56px; height: 56px; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 16px rgba(229, 115, 147, 0.4); transition: all 0.3s;" onmouseover="this.style.transform='scale(1.1)'; this.style.boxShadow='0 6px 24px rgba(229, 115, 147, 0.5)'" onmouseout="this.style.transform='scale(1)'; this.style.boxShadow='0 4px 16px rgba(229, 115, 147, 0.4)'">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="9" cy="21" r="1"></circle>
            <circle cx="20" cy="21" r="1"></circle>
            <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
        </svg>
        <?php if ($cart_count > 0): ?>
            <span id="cartBadge" style="position: absolute; top: -4px; right: -4px; background: white; color: #E57393; font-size: 11px; font-weight: 800; min-width: 22px; height: 22px; border-radius: 11px; display: flex; align-items: center; justify-content: center; padding: 0 6px; box-shadow: 0 2px 8px rgba(0,0,0,0.15);"><?php echo $cart_count; ?></span>
        <?php else: ?>
            <span id="cartBadge" style="display: none;"></span>
        <?php endif; ?>
    </button>

    <script>
        // Hide/Show navbar on scroll
        let lastScrollTop = 0;
        const navbar = document.getElementById('mainNav');
        
        window.addEventListener('scroll', function() {
            let scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            
            if (scrollTop > lastScrollTop && scrollTop > 100) {
                // Scrolling down
                navbar.style.transform = 'translateY(-100%)';
            } else {
                // Scrolling up
                navbar.style.transform = 'translateY(0)';
            }
            
            lastScrollTop = scrollTop;
        });
    </script>

    <div style="height: 60px;"></div>

    <!-- Burger Menu Overlay -->
    <div id="burgerMenu" style="position: fixed; top: 0; right: -100%; width: 320px; height: 100vh; background: white; box-shadow: -4px 0 20px rgba(0,0,0,0.1); z-index: 9999; transition: right 0.3s ease; overflow-y: auto;">
        <div style="padding: 20px;">
            <!-- Close Button -->
            <button onclick="toggleBurgerMenu()" style="background: rgba(229, 115, 147, 0.1); border: none; width: 40px; height: 40px; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; margin-bottom: 30px; transition: all 0.3s;" onmouseover="this.style.background='rgba(229, 115, 147, 0.2)'" onmouseout="this.style.background='rgba(229, 115, 147, 0.1)'">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2.5">
                    <line x1="18" y1="6" x2="6" y2="18"></line>
                    <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
            </button>

            <!-- Menu Items -->
            <div style="display: flex; flex-direction: column; gap: 8px;">
                <?php if (isset($_SESSION['user_id'])): ?>
                    <a href="account.php" style="display: flex; align-items: center; gap: 12px; padding: 14px 16px; border-radius: 12px; text-decoration: none; color: #333; font-weight: 600; transition: all 0.3s;" onmouseover="this.style.background='rgba(229, 115, 147, 0.1)'" onmouseout="this.style.background='transparent'">
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2">
                            <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                            <circle cx="12" cy="7" r="4"></circle>
                        </svg>
                        حسابي
                    </a>
                <?php else: ?>
                    <a href="#" onclick="alert('يرجى تسجيل الدخول'); return false;" style="display: flex; align-items: center; gap: 12px; padding: 14px 16px; border-radius: 12px; text-decoration: none; color: #333; font-weight: 600; transition: all 0.3s;" onmouseover="this.style.background='rgba(229, 115, 147, 0.1)'" onmouseout="this.style.background='transparent'">
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2">
                            <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"></path>
                            <polyline points="10 17 15 12 10 7"></polyline>
                            <line x1="15" y1="12" x2="3" y2="12"></line>
                        </svg>
                        تسجيل الدخول
                    </a>
                <?php endif; ?>

                <a href="blog.php" style="display: flex; align-items: center; gap: 12px; padding: 14px 16px; border-radius: 12px; text-decoration: none; color: #333; font-weight: 600; transition: all 0.3s;" onmouseover="this.style.background='rgba(229, 115, 147, 0.1)'" onmouseout="this.style.background='transparent'">
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2">
                        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
                        <polyline points="14 2 14 8 20 8"></polyline>
                        <line x1="16" y1="13" x2="8" y2="13"></line>
                        <line x1="16" y1="17" x2="8" y2="17"></line>
                    </svg>
                    روز فيد
                </a>

                <div style="height: 1px; background: rgba(229, 115, 147, 0.1); margin: 12px 0;"></div>

                <a href="products.php" style="display: flex; align-items: center; gap: 12px; padding: 14px 16px; border-radius: 12px; text-decoration: none; color: #333; font-weight: 600; transition: all 0.3s;" onmouseover="this.style.background='rgba(229, 115, 147, 0.1)'" onmouseout="this.style.background='transparent'">
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2">
                        <circle cx="9" cy="21" r="1"></circle>
                        <circle cx="20" cy="21" r="1"></circle>
                        <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
                    </svg>
                    المنتجات
                </a>

                <a href="services.php" style="display: flex; align-items: center; gap: 12px; padding: 14px 16px; border-radius: 12px; text-decoration: none; color: #333; font-weight: 600; transition: all 0.3s;" onmouseover="this.style.background='rgba(229, 115, 147, 0.1)'" onmouseout="this.style.background='transparent'">
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2">
                        <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                        <line x1="16" y1="2" x2="16" y2="6"></line>
                        <line x1="8" y1="2" x2="8" y2="6"></line>
                        <line x1="3" y1="10" x2="21" y2="10"></line>
                    </svg>
                    الخدمات
                </a>
            </div>
        </div>
    </div>

    <!-- Burger Menu Backdrop -->
    <div id="burgerBackdrop" onclick="toggleBurgerMenu()" style="position: fixed; top: 0; left: 0; width: 100%; height: 100vh; background: rgba(0,0,0,0.5); z-index: 9998; display: none; opacity: 0; transition: opacity 0.3s;"></div>

    <script>
        function toggleBurgerMenu() {
            const menu = document.getElementById('burgerMenu');
            const backdrop = document.getElementById('burgerBackdrop');
            const isOpen = menu.style.right === '0px';
            
            if (isOpen) {
                menu.style.right = '-100%';
                backdrop.style.display = 'none';
                backdrop.style.opacity = '0';
                document.body.style.overflow = '';
            } else {
                menu.style.right = '0';
                backdrop.style.display = 'block';
                setTimeout(() => backdrop.style.opacity = '1', 10);
                document.body.style.overflow = 'hidden';
            }
        }
    </script>

    <!-- Product Details -->
    <div class="product-container">
        <!-- Breadcrumb Navigation -->
        <nav class="breadcrumb">
            <a href="index.php" class="breadcrumb-item">الرئيسية</a>
            <span class="breadcrumb-separator">›</span>
            <a href="products.php" class="breadcrumb-item">المنتجات</a>
            <span class="breadcrumb-separator">›</span>
            <span class="breadcrumb-item active"><?php echo htmlspecialchars($product['name']); ?></span>
        </nav>
        
        <div class="product-grid">
            <!-- Product Image Gallery -->
            <div class="product-image-gallery">
                <div class="main-image-container">
                    <img src="<?php echo $imageUrl; ?>" 
                         alt="<?php echo htmlspecialchars($product['name']); ?>" 
                         class="main-product-image">
                    <div class="zoom-icon">
                        <i class="fas fa-search-plus"></i>
                    </div>
                </div>
                
                <!-- Thumbnails -->
                <div class="thumbnail-gallery">
                    <div class="thumbnail-item active" data-image="<?php echo $imageUrl; ?>">
                        <img src="<?php echo $imageUrl; ?>" alt="Thumbnail">
                    </div>
                    <?php 
                    $gallery = !empty($product['gallery_images']) ? json_decode($product['gallery_images'], true) : [];
                    foreach ($gallery as $img): 
                    ?>
                        <div class="thumbnail-item" data-image="../<?php echo htmlspecialchars($img); ?>">
                            <img src="../<?php echo htmlspecialchars($img); ?>" alt="Thumbnail">
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Product Info -->
            <div class="product-details" data-product-id="<?php echo $product['id']; ?>">
                <h1 class="product-name"><?php echo htmlspecialchars($product['name']); ?></h1>
                
                <!-- Stock Indicator -->
                <?php
                $stock = $product['stock_quantity'];
                if ($stock > 10):
                    $stockClass = 'in-stock';
                    $stockText = "متوفر ({$stock} قطعة)";
                elseif ($stock > 3):
                    $stockClass = 'low-stock';
                    $stockText = "كمية محدودة ({$stock} قطع فقط!)";
                elseif ($stock > 0):
                    $stockClass = 'last-item';
                    $stockText = "آخر {$stock} قطع! اطلب الآن";
                else:
                    $stockClass = 'out-of-stock';
                    $stockText = "نفذت الكمية";
                endif;
                ?>
                <div class="stock-indicator <?php echo $stockClass; ?>">
                    <span class="stock-dot"></span>
                    <span><?php echo $stockText; ?></span>
                </div>
                
                <!-- Size & Certification -->
                <div style="display: flex; gap: 16px; margin-bottom: 16px; flex-wrap: wrap;">
                    <?php if (!empty($product['size'])): ?>
                        <div style="background: #F3F4F6; padding: 8px 16px; border-radius: 8px; display: inline-flex; align-items: center; gap: 8px;">
                            <i class="fas fa-ruler-horizontal" style="color: #6B7280;"></i>
                            <span style="font-weight: 600; color: #374151;">الحجم:</span>
                            <span style="color: #6B7280;"><?php echo htmlspecialchars($product['size']); ?></span>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($product['certification'])): ?>
                        <div style="background: #FEF3C7; padding: 8px 16px; border-radius: 8px; display: inline-flex; align-items: center; gap: 8px;">
                            <i class="fas fa-certificate" style="color: #D97706;"></i>
                            <span style="font-weight: 600; color: #92400E;"><?php echo htmlspecialchars($product['certification']); ?></span>
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="product-price-container">
                    <?php if (!empty($product['discount_price']) && $product['discount_price'] < $product['price']): ?>
                        <!-- السعر بعد الخصم -->
                        <div class="price-with-discount">
                            <span class="original-price"><?php echo $currency_symbol; ?> <?php echo number_format($product['price'], 0); ?></span>
                            <span class="discount-price" data-price="<?php echo $product['discount_price']; ?>">
                                <?php echo $currency_symbol; ?> <span class="total-price"><?php echo number_format($product['discount_price'], 0); ?></span>
                            </span>
                            <?php 
                            $discount_percent = round((($product['price'] - $product['discount_price']) / $product['price']) * 100);
                            ?>
                            <span class="discount-badge">-<?php echo $discount_percent; ?>%</span>
                        </div>
                    <?php else: ?>
                        <!-- السعر العادي -->
                        <div class="product-price" data-price="<?php echo $product['price']; ?>">
                            <?php echo $currency_symbol; ?> <span class="total-price"><?php echo number_format($product['price'], 0); ?></span>
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- Short Description -->
                <?php if (!empty($product['short_description'])): ?>
                    <div style="background: #F9FAFB; border-right: 4px solid #E57393; padding: 16px; border-radius: 8px; margin-bottom: 16px;">
                        <p style="color: #374151; line-height: 1.6; margin: 0;">
                            <?php echo nl2br(htmlspecialchars($product['short_description'])); ?>
                        </p>
                    </div>
                <?php endif; ?>
                
                <!-- Regular Description -->
                <?php if (!empty($product['description'])): ?>
                    <p class="product-description">
                        <?php echo nl2br(htmlspecialchars($product['description'])); ?>
                    </p>
                <?php endif; ?>

                <!-- Quantity Selector -->
                <div class="quantity-selector">
                    <span class="quantity-label">الكمية:</span>
                    <div class="quantity-controls">
                        <button class="qty-btn qty-minus" type="button">−</button>
                        <input type="number" 
                               class="qty-input" 
                               value="1" 
                               min="1" 
                               max="<?php echo $product['stock_quantity']; ?>"
                               data-max="<?php echo $product['stock_quantity']; ?>">
                        <button class="qty-btn qty-plus" type="button">+</button>
                    </div>
                    <span class="stock-info">متوفر: <?php echo $product['stock_quantity']; ?> قطعة</span>
                </div>
                
                <!-- Actions with Elegant Design -->
                <div class="elegant-actions-container">
                    <button class="elegant-btn elegant-btn-primary" id="addToCartBtn" data-product-id="<?php echo $product['id']; ?>">
                        <span class="btn-icon">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
                                <circle cx="9" cy="21" r="1"></circle>
                                <circle cx="20" cy="21" r="1"></circle>
                                <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
                            </svg>
                        </span>
                        <span class="btn-text">أضف للسلة</span>
                        <span class="btn-shimmer"></span>
                    </button>
                    
                    <button class="elegant-btn elegant-btn-secondary" id="buyNowBtn" data-product-id="<?php echo $product['id']; ?>">
                        <span class="btn-icon">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
                                <path d="M5 12h14"></path>
                                <path d="m12 5 7 7-7 7"></path>
                            </svg>
                        </span>
                        <span class="btn-text">اشتري الآن</span>
                        <span class="btn-shimmer"></span>
                    </button>
                    
                    <button class="elegant-btn elegant-btn-wishlist" id="wishlistBtn" data-product-id="<?php echo $product['id']; ?>" title="إضافة للمفضلة">
                        <span class="btn-icon">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
                                <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
                            </svg>
                        </span>
                        <span class="btn-shimmer"></span>
                    </button>
                </div>

                <!-- Shipping Info -->
                <div class="shipping-info-box">
                    <div class="shipping-info-title">
                        <i class="fas fa-truck"></i>
                        مميزات الشراء
                    </div>
                    <div class="shipping-info-item">
                        <div class="shipping-icon">🚚</div>
                        <div class="shipping-text">
                            <strong>شحن مجاني</strong> للطلبات أكثر من 200 ج.م
                        </div>
                    </div>
                    <div class="shipping-info-item">
                        <div class="shipping-icon">📦</div>
                        <div class="shipping-text">
                            التوصيل خلال <strong>2-3 أيام عمل</strong>
                        </div>
                    </div>
                    <div class="shipping-info-item">
                        <div class="shipping-icon">🔄</div>
                        <div class="shipping-text">
                            إرجاع مجاني خلال <strong>14 يوم</strong>
                        </div>
                    </div>
                    <div class="shipping-info-item">
                        <div class="shipping-icon">💳</div>
                        <div class="shipping-text">
                            <strong>الدفع عند الاستلام</strong> متاح
                        </div>
                    </div>
                </div>
                
                <!-- Share Section -->
                <div class="share-section">
                    <div class="share-title">شارك هذا المنتج:</div>
                    <div class="share-buttons-icons">
                        <button class="share-icon-btn whatsapp" data-share="whatsapp" title="مشاركة عبر WhatsApp">
                            <i class="fab fa-whatsapp"></i>
                        </button>
                        <button class="share-icon-btn facebook" data-share="facebook" title="مشاركة عبر Facebook">
                            <i class="fab fa-facebook-f"></i>
                        </button>
                        <button class="share-icon-btn twitter" data-share="twitter" title="مشاركة عبر Twitter">
                            <i class="fab fa-twitter"></i>
                        </button>
                        <button class="share-icon-btn copy" data-share="copy" title="نسخ الرابط">
                            <i class="fas fa-link"></i>
                        </button>
                    </div>
                </div>
                
                <!-- Quick Links -->
                <div style="display: flex; gap: 16px; margin-top: 24px;">
                    <a href="cart.php" style="color: #E57393; text-decoration: none; font-weight: 600; display: flex; align-items: center; gap: 8px;">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="9" cy="21" r="1"></circle>
                            <circle cx="20" cy="21" r="1"></circle>
                            <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
                        </svg>
                        عرض السلة
                    </a>
                    <a href="products.php" style="color: #6B7280; text-decoration: none; font-weight: 600; display: flex; align-items: center; gap: 8px;">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="15 18 9 12 15 6"></polyline>
                        </svg>
                        العودة للمنتجات
                    </a>
                </div>

                <!-- Product Meta -->
                <div class="product-meta">
                    <div class="meta-item">
                        <span class="meta-label">الحالة</span>
                        <span class="meta-value">
                            <?php echo $product['stock_quantity'] > 0 ? 'متوفر' : 'غير متوفر'; ?>
                        </span>
                    </div>
                    <div class="meta-item">
                        <span class="meta-label">المخزون</span>
                        <span class="meta-value"><?php echo $product['stock_quantity']; ?> قطعة</span>
                    </div>
                    <div class="meta-item">
                        <span class="meta-label">رمز المنتج</span>
                        <span class="meta-value">#<?php echo str_pad($product['id'], 5, '0', STR_PAD_LEFT); ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Additional Product Information -->
        <div style="max-width: 1200px; margin: 40px auto; padding: 0 20px;">
            
            <!-- Detailed Description -->
            <?php if (!empty($product['detailed_description'])): ?>
                <div style="background: white; border-radius: 16px; padding: 32px; margin-bottom: 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
                    <h2 style="font-size: 24px; font-weight: 700; color: #111827; margin-bottom: 24px; display: flex; align-items: center; gap: 12px;">
                        <i class="fas fa-file-alt" style="color: #6366F1;"></i>
                        الوصف التفصيلي والميزات
                    </h2>
                    <div style="color: #374151; line-height: 1.8; font-size: 16px;">
                        <?php echo nl2br(htmlspecialchars($product['detailed_description'])); ?>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- How to Use -->
            <?php if (!empty($product['how_to_use'])): ?>
                <div style="background: white; border-radius: 16px; padding: 32px; margin-bottom: 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
                    <h2 style="font-size: 24px; font-weight: 700; color: #111827; margin-bottom: 24px; display: flex; align-items: center; gap: 12px;">
                        <i class="fas fa-list-ol" style="color: #10B981;"></i>
                        طريقة الاستخدام
                    </h2>
                    <div style="color: #374151; line-height: 1.8; font-size: 16px; background: #F0FDF4; padding: 20px; border-radius: 12px; border-right: 4px solid #10B981;">
                        <?php echo nl2br(htmlspecialchars($product['how_to_use'])); ?>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- Additional Tips -->
            <?php if (!empty($product['additional_tips'])): ?>
                <div style="background: white; border-radius: 16px; padding: 32px; margin-bottom: 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
                    <h2 style="font-size: 24px; font-weight: 700; color: #111827; margin-bottom: 24px; display: flex; align-items: center; gap: 12px;">
                        <i class="fas fa-lightbulb" style="color: #F59E0B;"></i>
                        نصائح إضافية
                    </h2>
                    <div style="color: #374151; line-height: 1.8; font-size: 16px; background: #FFFBEB; padding: 20px; border-radius: 12px; border-right: 4px solid #F59E0B;">
                        <?php echo nl2br(htmlspecialchars($product['additional_tips'])); ?>
                    </div>
                </div>
            <?php endif; ?>
            
        </div>

        <!-- Reviews Section -->
        <div class="reviews-section" id="reviews">
            <div class="reviews-header">
                <h2 style="font-size: 24px; font-weight: 700; color: #111827; display: flex; align-items: center; gap: 12px;">
                    <i class="fas fa-star" style="color: #F59E0B;"></i>
                    تقييمات العملاء
                </h2>
            </div>
            
            <?php
            // جلب التقييمات من قاعدة البيانات
            try {
                $stmt = $db->prepare("
                    SELECT r.*, u.name as user_name 
                    FROM reviews r 
                    LEFT JOIN users u ON r.user_id = u.id 
                    WHERE r.product_id = ? AND r.status = 'approved'
                    ORDER BY r.created_at DESC
                    LIMIT 10
                ");
                $stmt->execute([$product_id]);
                $reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                // حساب متوسط التقييم
                $stmt = $db->prepare("
                    SELECT AVG(rating) as avg_rating, COUNT(*) as total_reviews 
                    FROM reviews 
                    WHERE product_id = ? AND status = 'approved'
                ");
                $stmt->execute([$product_id]);
                $rating_data = $stmt->fetch(PDO::FETCH_ASSOC);
                $avg_rating = round($rating_data['avg_rating'] ?? 0, 1);
                $total_reviews = $rating_data['total_reviews'] ?? 0;
            } catch (PDOException $e) {
                $reviews = [];
                $avg_rating = 0;
                $total_reviews = 0;
            }
            ?>
            
            <?php if ($total_reviews > 0): ?>
                <div class="reviews-summary-box">
                    <div class="rating-overview">
                        <div class="rating-number"><?php echo $avg_rating; ?></div>
                        <div>
                            <div class="rating-stars">
                                <?php 
                                for ($i = 1; $i <= 5; $i++) {
                                    echo $i <= $avg_rating ? '⭐' : '☆';
                                }
                                ?>
                            </div>
                            <div class="rating-count"><?php echo $total_reviews; ?> تقييم</div>
                        </div>
                    </div>
                    <?php if (isset($_SESSION['user_id'])): ?>
                        <button class="write-review-btn" onclick="showReviewForm()">
                            <i class="fas fa-pen"></i>
                            اكتب تقييمك
                        </button>
                    <?php else: ?>
                        <button class="write-review-btn" onclick="window.location.href='../admin/login.php?redirect=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>'">
                            <i class="fas fa-sign-in-alt"></i>
                            سجل دخول للتقييم
                        </button>
                    <?php endif; ?>
                </div>
                
                <!-- قائمة التقييمات -->
                <div class="reviews-list">
                    <?php foreach ($reviews as $review): ?>
                        <div class="review-item">
                            <div class="review-header">
                                <div class="reviewer-info">
                                    <div class="reviewer-avatar">
                                        <?php echo mb_substr($review['user_name'] ?? 'عميل', 0, 1); ?>
                                    </div>
                                    <div>
                                        <div class="reviewer-name"><?php echo htmlspecialchars($review['user_name'] ?? 'عميل'); ?></div>
                                        <div class="review-date"><?php echo date('d/m/Y', strtotime($review['created_at'])); ?></div>
                                    </div>
                                </div>
                                <div class="review-rating">
                                    <?php 
                                    for ($i = 1; $i <= 5; $i++) {
                                        echo $i <= $review['rating'] ? '⭐' : '☆';
                                    }
                                    ?>
                                </div>
                            </div>
                            <div class="review-content">
                                <?php echo nl2br(htmlspecialchars($review['comment'])); ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="no-reviews">
                    <i class="fas fa-star" style="font-size: 48px; color: #F59E0B; margin-bottom: 16px;"></i>
                    <p style="font-size: 18px; color: #6B7280; margin-bottom: 16px;">لا توجد تقييمات بعد</p>
                    <p style="color: #9CA3AF;">كن أول من يقيم هذا المنتج!</p>
                    <?php if (isset($_SESSION['user_id'])): ?>
                        <button class="write-review-btn" onclick="showReviewForm()" style="margin-top: 20px;">
                            <i class="fas fa-pen"></i>
                            اكتب أول تقييم
                        </button>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            
            <!-- نموذج إضافة تقييم -->
            <div id="reviewFormModal" class="review-modal" style="display: none;">
                <div class="review-modal-content">
                    <div class="review-modal-header">
                        <h3>اكتب تقييمك</h3>
                        <button class="review-modal-close" onclick="hideReviewForm()">×</button>
                    </div>
                    <form id="reviewForm" onsubmit="submitReview(event)">
                        <div class="form-group">
                            <label>التقييم:</label>
                            <div class="star-rating-input">
                                <input type="radio" name="rating" value="5" id="star5" required>
                                <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="form-group">
                            <label for="reviewComment">تعليقك:</label>
                            <textarea id="reviewComment" name="comment" rows="4" required 
                                      placeholder="شاركنا رأيك في المنتج..."></textarea>
                        </div>
                        <button type="submit" class="submit-review-btn">
                            <i class="fas fa-paper-plane"></i>
                            إرسال التقييم
                        </button>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- Related Products -->
        <?php if (!empty($related)): ?>
            <div class="related-section">
                <h2 class="section-title">منتجات مشابهة</h2>
                <div class="related-grid">
                    <?php foreach($related as $item): 
                        // Fix image path for related products
                        if (!empty($item['image'])) {
                            // إذا كان المسار يبدأ بـ uploads/ فهو صحيح
                            if (strpos($item['image'], 'uploads/') === 0) {
                                $relatedImg = '../' . $item['image'];
                            } else {
                                // إذا كان اسم ملف فقط، أضف المسار الكامل
                                $relatedImg = '../uploads/products/' . $item['image'];
                            }
                            // تحقق من وجود الملف
                            if (!file_exists($relatedImg)) {
                                $relatedImg = 'https://images.unsplash.com/photo-1556228578-8c89e6adf883?w=400&h=500&fit=crop';
                            }
                        } else {
                            $relatedImg = 'https://images.unsplash.com/photo-1556228578-8c89e6adf883?w=400&h=500&fit=crop';
                        }
                    ?>
                        <div class="related-card" onclick="window.location.href='product.php?id=<?php echo $item['id']; ?>'">
                            <img src="<?php echo $relatedImg; ?>" alt="<?php echo htmlspecialchars($item['name']); ?>" class="related-image">
                            <div class="related-info">
                                <div class="related-name"><?php echo htmlspecialchars($item['name']); ?></div>
                                <?php if (!empty($item['discount_price']) && $item['discount_price'] < $item['price']): ?>
                                <div class="related-price-container">
                                    <span class="related-original-price"><?php echo $currency_symbol; ?> <?php echo number_format($item['price'], 0); ?></span>
                                    <span class="related-discount-price"><?php echo $currency_symbol; ?> <?php echo number_format($item['discount_price'], 0); ?></span>
                                    <span class="related-discount-badge">-<?php echo round((($item['price'] - $item['discount_price']) / $item['price']) * 100); ?>%</span>
                                </div>
                            <?php else: ?>
                                <?php if (!empty($item['discount_price']) && $item['discount_price'] < $item['price']): ?>
                                <div class="related-price-container">
                                    <span class="related-original-price"><?php echo $currency_symbol; ?> <?php echo number_format($item['price'], 0); ?></span>
                                    <span class="related-discount-price"><?php echo $currency_symbol; ?> <?php echo number_format($item['discount_price'], 0); ?></span>
                                    <span class="related-discount-badge">-<?php echo round((($item['price'] - $item['discount_price']) / $item['price']) * 100); ?>%</span>
                                </div>
                            <?php else: ?>
                                <div class="related-price"><?php echo $currency_symbol; ?> <?php echo number_format($item['price'], 0); ?></div>
                            <?php endif; ?>
                            <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Toast -->
    <div id="toast" class="toast-notification hidden"></div>
    
    <!-- Sticky Add to Cart Bar (Mobile) -->
    <div class="sticky-cart-bar" data-product-id="<?php echo $product['id']; ?>">
        <div class="sticky-price">
            <?php echo $currency_symbol; ?> <?php echo number_format($product['price'], 0); ?>
        </div>
        <button class="sticky-add-btn" data-product-id="<?php echo $product['id']; ?>">
            <i class="fas fa-shopping-cart"></i>
            <span>أضف للسلة</span>
        </button>
    </div>

    <script>
        function showToast(msg) {
            const toast = document.getElementById('toast');
            toast.textContent = msg;
            toast.classList.remove('hidden');
            setTimeout(() => toast.classList.add('hidden'), 3000);
        }

        function addToCart(productId) {
            const qtyInput = document.querySelector('.qty-input');
            const quantity = qtyInput ? parseInt(qtyInput.value) : 1;
            
            fetch('../api/cart/add.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: 'product_id=' + productId + '&quantity=' + quantity
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    const qtyInput = document.querySelector('.qty-input');
                    const qty = qtyInput ? parseInt(qtyInput.value) : 1;
                    showToast(`✓ تم إضافة ${qty} قطعة للسلة بنجاح`);
                    const badge = document.getElementById('cartBadge'); // استخدام ID محدد للسلة
                    if (badge) {
                        badge.textContent = data.cart_count;
                        badge.style.display = 'flex';
                    } else {
                        // إنشاء badge إذا لم يكن موجود
                        const cartBtn = document.querySelector('.nav-icon-btn:last-child');
                        if (cartBtn && !cartBtn.querySelector('#cartBadge')) {
                            const newBadge = document.createElement('span');
                            newBadge.className = 'nav-badge';
                            newBadge.id = 'cartBadge';
                            newBadge.textContent = data.cart_count;
                            cartBtn.appendChild(newBadge);
                        }
                    }
                } else {
                    showToast('⚠ ' + (data.message || 'حدث خطأ'));
                }
            })
            .catch(err => {
                console.error('Error:', err);
                showToast('❌ حدث خطأ في الاتصال');
            });
        }

        function buyNow(productId) {
            const qtyInput = document.querySelector('.qty-input');
            const quantity = qtyInput ? parseInt(qtyInput.value) : 1;
            
            // إضافة للسلة ثم الانتقال للدفع
            fetch('../api/cart/add.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: 'product_id=' + productId + '&quantity=' + quantity
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showToast('✓ جاري الانتقال للدفع...');
                    setTimeout(() => window.location.href = 'cart.php', 800);
                } else {
                    showToast('⚠ ' + (data.message || 'حدث خطأ'));
                }
            })
            .catch(err => {
                console.error('Error:', err);
                showToast('❌ حدث خطأ في الاتصال');
            });
        }

        function toggleWishlist(productId) {
            fetch('../api/wishlist/toggle.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: 'product_id=' + productId
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showToast('💜 ' + data.message);
                } else {
                    showToast('⚠ ' + (data.message || 'حدث خطأ'));
                }
            })
            .catch(err => {
                console.error('Error:', err);
                showToast('❌ حدث خطأ في الاتصال');
            });
        }

        const searchInput = document.getElementById('searchInput');
        if (searchInput) {
            searchInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && this.value.trim()) {
                    window.location.href = 'products.php?search=' + encodeURIComponent(this.value.trim());
                }
            });
        }
    </script>
    
    <!-- Product Enhancements Script -->
    <script src="../assets/js/product-enhancements.js"></script>
    
    <!-- Review Form Functions -->
    <script>
    // دالة عرض الإشعارات
    function showToast(message, duration = 3000) {
        let toast = document.getElementById('toast');
        if (!toast) {
            toast = document.createElement('div');
            toast.id = 'toast';
            toast.className = 'toast-notification';
            document.body.appendChild(toast);
        }
        
        toast.textContent = message;
        toast.classList.remove('hidden');
        toast.style.display = 'block';
        
        setTimeout(() => {
            toast.classList.add('hidden');
            toast.style.display = 'none';
        }, duration);
    }
    
    // دوال نموذج التقييم
    function showReviewForm() {
        const modal = document.getElementById('reviewFormModal');
        if (modal) {
            modal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }
    }

    function hideReviewForm() {
        const modal = document.getElementById('reviewFormModal');
        if (modal) {
            modal.style.display = 'none';
            document.body.style.overflow = '';
            document.getElementById('reviewForm').reset();
        }
    }

    function submitReview(event) {
        event.preventDefault();
        
        showToast('⏳ جاري التحضير...');
        
        const form = event.target;
        const formData = new FormData(form);
        const productId = <?php echo $product_id; ?>;
        
        // Get rating
        const rating = form.querySelector('input[name="rating"]:checked');
        const comment = form.querySelector('textarea[name="comment"]');
        
        console.log('Form data:', {
            productId: productId,
            rating: rating ? rating.value : 'not selected',
            comment: comment ? comment.value : 'empty'
        });
        
        // Validation
        if (!rating) {
            showToast('⚠️ الرجاء اختيار التقييم (النجوم)');
            return;
        }
        
        if (!comment || comment.value.trim().length < 10) {
            showToast('⚠️ الرجاء كتابة تعليق (10 أحرف على الأقل)');
            return;
        }
        
        formData.append('product_id', productId);
        
        // Disable submit button
        const submitBtn = form.querySelector('.submit-review-btn');
        if (!submitBtn) {
            showToast('❌ خطأ: زر الإرسال غير موجود');
            return;
        }
        
        const originalText = submitBtn.innerHTML;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> جاري الإرسال...';
        
        showToast('📤 جاري إرسال التقييم...');
        console.log('Submitting review for product:', productId);
        
        fetch('../api/reviews/submit.php', {
            method: 'POST',
            body: formData
        })
        .then(r => {
            console.log('Response status:', r.status);
            if (!r.ok) {
                throw new Error('HTTP error! status: ' + r.status);
            }
            return r.text();
        })
        .then(text => {
            console.log('Response text:', text);
            try {
                const data = JSON.parse(text);
                console.log('Response data:', data);
                
                if (data.success) {
                    showToast('✅ ' + data.message);
                    hideReviewForm();
                    
                    // Reload page after 2 seconds
                    setTimeout(() => {
                        window.location.reload();
                    }, 2000);
                } else {
                    showToast('⚠️ ' + (data.message || 'حدث خطأ في إرسال التقييم'));
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                }
            } catch (e) {
                console.error('JSON parse error:', e);
                showToast('❌ خطأ في معالجة الرد من السيرفر');
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            }
        })
        .catch(err => {
            console.error('Fetch error:', err);
            showToast('❌ حدث خطأ في الاتصال: ' + err.message);
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        });
    }

    // Close modal on outside click
    document.addEventListener('click', function(e) {
        const modal = document.getElementById('reviewFormModal');
        if (modal && e.target === modal) {
            hideReviewForm();
        }
    });

    // Close modal on Escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            hideReviewForm();
        }
    });
    </script>
    <script src="assets/js/product-elegant-design.js"></script>
</body>
</html>