<?php
session_start();

// Check admin access
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

require_once '../../config/database.php';

$database = new Database();
$db = $database->getConnection();

$message = '';
$message_type = 'success';
$product_id = $_GET['id'] ?? null;

if (!$product_id) {
    header('Location: index.php');
    exit;
}

// Get product
try {
    $query = "SELECT * FROM products WHERE id = ?";
    $stmt = $db->prepare($query);
    $stmt->execute([$product_id]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$product) {
        header('Location: index.php');
        exit;
    }
} catch (Exception $e) {
    die('خطأ: ' . $e->getMessage());
}

// Get categories
try {
    $query = "SELECT * FROM categories WHERE type = 'product' ORDER BY name";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $categories = [];
}

// Handle delete gallery image
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_gallery_image'])) {
    try {
        $image_to_delete = $_POST['image_path'];
        $gallery_images = $product['gallery_images'] ? json_decode($product['gallery_images'], true) : [];
        
        // Remove from array
        $gallery_images = array_filter($gallery_images, function($img) use ($image_to_delete) {
            return $img !== $image_to_delete;
        });
        
        // Delete file
        if (file_exists('../../' . $image_to_delete)) {
            unlink('../../' . $image_to_delete);
        }
        
        // Update database
        $gallery_json = !empty($gallery_images) ? json_encode(array_values($gallery_images)) : null;
        $query = "UPDATE products SET gallery_images = ? WHERE id = ?";
        $stmt = $db->prepare($query);
        $stmt->execute([$gallery_json, $product_id]);
        
        $message = 'تم حذف الصورة بنجاح!';
        $message_type = 'success';
        
        // Refresh product data
        $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
        $stmt->execute([$product_id]);
        $product = $stmt->fetch(PDO::FETCH_ASSOC);
        
    } catch (Exception $e) {
        $message = 'خطأ في حذف الصورة: ' . $e->getMessage();
        $message_type = 'error';
    }
}

// Handle delete main image
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_main_image'])) {
    try {
        // Delete file
        if ($product['image'] && file_exists('../../' . $product['image'])) {
            unlink('../../' . $product['image']);
        }
        
        // Update database
        $query = "UPDATE products SET image = NULL WHERE id = ?";
        $stmt = $db->prepare($query);
        $stmt->execute([$product_id]);
        
        $message = 'تم حذف الصورة الرئيسية بنجاح!';
        $message_type = 'success';
        
        // Refresh product data
        $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
        $stmt->execute([$product_id]);
        $product = $stmt->fetch(PDO::FETCH_ASSOC);
        
    } catch (Exception $e) {
        $message = 'خطأ في حذف الصورة: ' . $e->getMessage();
        $message_type = 'error';
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_product'])) {
    try {
        $name = $_POST['name'];
        $description = $_POST['description'] ?? '';
        $price = $_POST['price'];
        $discount_price = !empty($_POST['discount_price']) ? $_POST['discount_price'] : null;
        $category_id = !empty($_POST['category_id']) ? $_POST['category_id'] : null;
        $stock_quantity = $_POST['stock_quantity'] ?? 0;
        $status = $_POST['status'] ?? 'active';
        $sku = !empty($_POST['sku']) ? $_POST['sku'] : null;
        
        // New fields
        $size = $_POST['size'] ?? null;
        $certification = $_POST['certification'] ?? null;
        $short_description = $_POST['short_description'] ?? null;
        $detailed_description = $_POST['detailed_description'] ?? null;
        $how_to_use = $_POST['how_to_use'] ?? null;
        $additional_tips = $_POST['additional_tips'] ?? null;
        
        $image = $product['image'];
        $gallery_images = $product['gallery_images'] ? json_decode($product['gallery_images'], true) : [];
        
        // Handle main image upload
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = '../../uploads/products/';
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            $file_extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $new_filename = uniqid() . '.' . $file_extension;
            $upload_path = $upload_dir . $new_filename;
            
            if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_path)) {
                // Delete old image
                if ($product['image'] && file_exists('../../' . $product['image'])) {
                    unlink('../../' . $product['image']);
                }
                $image = 'uploads/products/' . $new_filename;
            }
        }
        
        // Handle gallery images upload
        if (isset($_FILES['gallery_images'])) {
            $upload_dir = '../../uploads/products/';
            foreach ($_FILES['gallery_images']['tmp_name'] as $key => $tmp_name) {
                if ($_FILES['gallery_images']['error'][$key] === UPLOAD_ERR_OK) {
                    $file_extension = pathinfo($_FILES['gallery_images']['name'][$key], PATHINFO_EXTENSION);
                    $new_filename = uniqid() . '.' . $file_extension;
                    $upload_path = $upload_dir . $new_filename;
                    
                    if (move_uploaded_file($tmp_name, $upload_path)) {
                        $gallery_images[] = 'uploads/products/' . $new_filename;
                    }
                }
            }
        }
        $gallery_json = !empty($gallery_images) ? json_encode($gallery_images) : $product['gallery_images'];
        
        // Update product
        $query = "UPDATE products 
                  SET name = ?, description = ?, price = ?, discount_price = ?, category_id = ?, 
                      stock_quantity = ?, status = ?, sku = ?, image = ?,
                      size = ?, certification = ?, short_description = ?, detailed_description = ?,
                      how_to_use = ?, additional_tips = ?, gallery_images = ?,
                      updated_at = NOW()
                  WHERE id = ?";
        $stmt = $db->prepare($query);
        $stmt->execute([$name, $description, $price, $discount_price, $category_id, $stock_quantity, $status, $sku, $image,
                       $size, $certification, $short_description, $detailed_description, $how_to_use, $additional_tips, $gallery_json,
                       $product_id]);
        
        $message = 'تم تحديث المنتج بنجاح!';
        $message_type = 'success';
        
        // Refresh product data
        $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
        $stmt->execute([$product_id]);
        $product = $stmt->fetch(PDO::FETCH_ASSOC);
        
    } catch (Exception $e) {
        $message = 'خطأ في تحديث المنتج: ' . $e->getMessage();
        $message_type = 'error';
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تعديل المنتج - Roz Skin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { font-family: 'Tajawal', sans-serif; }
        
        /* Modern Image Upload Styles */
        .upload-area {
            border: 2px dashed #d1d5db;
            border-radius: 12px;
            padding: 40px 20px;
            text-align: center;
            transition: all 0.3s ease;
            background: linear-gradient(135deg, #f9fafb 0%, #f3f4f6 100%);
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        
        .upload-area:hover {
            border-color: #9333ea;
            background: linear-gradient(135deg, #faf5ff 0%, #f3e8ff 100%);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(147, 51, 234, 0.15);
        }
        
        .upload-area.dragover {
            border-color: #9333ea;
            background: linear-gradient(135deg, #faf5ff 0%, #f3e8ff 100%);
            transform: scale(1.02);
        }
        
        .upload-icon {
            font-size: 48px;
            color: #9333ea;
            margin-bottom: 16px;
            animation: float 3s ease-in-out infinite;
        }
        
        @keyframes float {
            0%, 100% { transform: translateY(0px); }
            50% { transform: translateY(-10px); }
        }
        
        .image-preview-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 16px;
            margin-top: 20px;
        }
        
        .image-preview-item {
            position: relative;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            aspect-ratio: 1;
        }
        
        .image-preview-item:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 20px rgba(0,0,0,0.15);
        }
        
        .image-preview-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .image-delete-btn {
            position: absolute;
            top: 8px;
            right: 8px;
            background: rgba(239, 68, 68, 0.95);
            color: white;
            border: none;
            border-radius: 50%;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            opacity: 0;
            transition: all 0.3s ease;
            backdrop-filter: blur(4px);
        }
        
        .image-preview-item:hover .image-delete-btn {
            opacity: 1;
        }
        
        .image-delete-btn:hover {
            background: rgba(220, 38, 38, 1);
            transform: scale(1.1);
        }
        
        .main-image-badge {
            position: absolute;
            bottom: 8px;
            left: 8px;
            background: linear-gradient(135deg, #9333ea 0%, #7e22ce 100%);
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            box-shadow: 0 2px 8px rgba(147, 51, 234, 0.3);
        }
        
        .file-input-hidden {
            display: none;
        }
        
        .preview-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
            gap: 12px;
        }
    </style>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-20">
            <div class="flex items-center justify-between px-6 py-4">
                <div class="flex items-center space-x-4 space-x-reverse">
                    <a href="index.php" class="text-gray-600 hover:text-gray-900">
                        <i class="fas fa-arrow-right text-xl"></i>
                    </a>
                    <h1 class="text-2xl font-bold text-gray-900">تعديل المنتج</h1>
                </div>
            </div>
        </header>

        <!-- Content -->
        <div class="p-6 max-w-4xl mx-auto">
            <?php if ($message): ?>
                <div class="mb-6 p-4 rounded-lg border-r-4 <?php echo $message_type === 'success' ? 'bg-green-50 border-green-400' : 'bg-red-50 border-red-400'; ?>">
                    <p class="text-sm <?php echo $message_type === 'success' ? 'text-green-700' : 'text-red-700'; ?>"><?php echo $message; ?></p>
                </div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data" class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- اسم المنتج -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-tag text-purple-600 ml-2"></i>اسم المنتج *
                        </label>
                        <input type="text" name="name" required value="<?php echo htmlspecialchars($product['name']); ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                    </div>

                    <!-- الوصف -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-align-right text-blue-600 ml-2"></i>الوصف
                        </label>
                        <textarea name="description" rows="4"
                                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"><?php echo htmlspecialchars($product['description'] ?? ''); ?></textarea>
                    </div>

                    <!-- السعر -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-dollar-sign text-green-600 ml-2"></i>السعر الأصلي (ج.م) *
                        </label>
                        <input type="number" name="price" step="0.01" required value="<?php echo $product['price']; ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                    </div>

                    <!-- السعر بعد الخصم -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-tag text-red-600 ml-2"></i>السعر بعد الخصم (ج.م)
                            <span class="text-xs text-gray-500">(اختياري)</span>
                        </label>
                        <input type="number" name="discount_price" step="0.01" value="<?php echo $product['discount_price'] ?? ''; ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                               placeholder="اترك فارغاً إذا لم يكن هناك خصم">
                        <p class="text-xs text-gray-500 mt-1">💡 سيظهر السعر الأصلي مشطوب والسعر الجديد بارز</p>
                    </div>

                    <!-- الكمية -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-boxes text-orange-600 ml-2"></i>الكمية المتاحة
                        </label>
                        <input type="number" name="stock_quantity" value="<?php echo $product['stock_quantity'] ?? 0; ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                    </div>

                    <!-- الفئة -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-folder text-yellow-600 ml-2"></i>الفئة
                        </label>
                        <select name="category_id" 
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                            <option value="">بدون فئة</option>
                            <?php foreach ($categories as $category): ?>
                                <option value="<?php echo $category['id']; ?>" <?php echo $product['category_id'] == $category['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($category['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- الحالة -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-toggle-on text-indigo-600 ml-2"></i>الحالة
                        </label>
                        <select name="status" 
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                            <option value="active" <?php echo $product['status'] === 'active' ? 'selected' : ''; ?>>نشط</option>
                            <option value="inactive" <?php echo $product['status'] === 'inactive' ? 'selected' : ''; ?>>غير نشط</option>
                        </select>
                    </div>

                    <!-- SKU -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-barcode text-gray-600 ml-2"></i>رمز المنتج (SKU)
                        </label>
                        <input type="text" name="sku" value="<?php echo htmlspecialchars($product['sku'] ?? ''); ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                    </div>

                    <!-- الحجم -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-ruler text-teal-600 ml-2"></i>الحجم
                        </label>
                        <input type="text" name="size" value="<?php echo htmlspecialchars($product['size'] ?? ''); ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                               placeholder="مثال: 10 مل، 50 جم">
                    </div>

                    <!-- الاعتماد والترخيص -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-certificate text-amber-600 ml-2"></i>الاعتماد والترخيص
                        </label>
                        <input type="text" name="certification" value="<?php echo htmlspecialchars($product['certification'] ?? ''); ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                               placeholder="مثال: مُرخص ومعتمد من وزارة الصحة المصرية">
                    </div>

                    <!-- الوصف المختصر -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-align-left text-blue-600 ml-2"></i>الوصف المختصر
                        </label>
                        <textarea name="short_description" rows="3"
                                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"><?php echo htmlspecialchars($product['short_description'] ?? ''); ?></textarea>
                    </div>

                    <!-- الوصف التفصيلي -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-file-alt text-indigo-600 ml-2"></i>الوصف التفصيلي
                        </label>
                        <textarea name="detailed_description" rows="6"
                                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"><?php echo htmlspecialchars($product['detailed_description'] ?? ''); ?></textarea>
                    </div>

                    <!-- طريقة الاستخدام -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-list-ol text-green-600 ml-2"></i>طريقة الاستخدام
                        </label>
                        <textarea name="how_to_use" rows="4"
                                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"><?php echo htmlspecialchars($product['how_to_use'] ?? ''); ?></textarea>
                    </div>

                    <!-- نصائح إضافية -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-lightbulb text-yellow-600 ml-2"></i>نصائح إضافية
                        </label>
                        <textarea name="additional_tips" rows="3"
                                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"><?php echo htmlspecialchars($product['additional_tips'] ?? ''); ?></textarea>
                    </div>

                    <!-- الصورة الرئيسية -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-3">
                            <i class="fas fa-image text-pink-600 ml-2"></i>الصورة الرئيسية
                        </label>
                        
                        <?php if ($product['image']): ?>
                            <!-- Current Main Image -->
                            <div class="image-preview-container">
                                <div class="image-preview-item">
                                    <img src="../../<?php echo htmlspecialchars($product['image']); ?>" alt="Product">
                                    <span class="main-image-badge">
                                        <i class="fas fa-star ml-1"></i>رئيسية
                                    </span>
                                    <button type="button" onclick="deleteMainImage()" class="image-delete-btn" title="حذف الصورة">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        <?php endif; ?>
                        
                        <!-- Upload New Main Image -->
                        <div class="upload-area mt-4" onclick="document.getElementById('mainImageInput').click()">
                            <div class="upload-icon">
                                <i class="fas fa-cloud-upload-alt"></i>
                            </div>
                            <h3 class="text-lg font-semibold text-gray-700 mb-2">
                                <?php echo $product['image'] ? 'تغيير الصورة الرئيسية' : 'ارفع الصورة الرئيسية'; ?>
                            </h3>
                            <p class="text-sm text-gray-500 mb-2">اسحب الصورة هنا أو اضغط للاختيار</p>
                            <p class="text-xs text-gray-400">PNG, JPG, WEBP (حتى 5MB)</p>
                            <input type="file" id="mainImageInput" name="image" accept="image/*" class="file-input-hidden" onchange="previewMainImage(this)">
                        </div>
                        
                        <!-- Preview for new main image -->
                        <div id="mainImagePreview" class="image-preview-container mt-4" style="display: none;"></div>
                    </div>

                    <!-- معرض الصور -->
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-3">
                            <i class="fas fa-images text-purple-600 ml-2"></i>معرض الصور
                            <span class="text-xs text-gray-500 font-normal">(صور إضافية للمنتج)</span>
                        </label>
                        
                        <?php 
                        $gallery = $product['gallery_images'] ? json_decode($product['gallery_images'], true) : [];
                        if (!empty($gallery)): 
                        ?>
                            <!-- Current Gallery Images -->
                            <div class="preview-grid mb-4">
                                <?php foreach ($gallery as $index => $img): ?>
                                    <div class="image-preview-item">
                                        <img src="../../<?php echo htmlspecialchars($img); ?>" alt="Gallery">
                                        <button type="button" onclick="deleteGalleryImage('<?php echo htmlspecialchars($img); ?>')" class="image-delete-btn" title="حذف الصورة">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                        
                        <!-- Upload New Gallery Images -->
                        <div class="upload-area" onclick="document.getElementById('galleryImagesInput').click()">
                            <div class="upload-icon">
                                <i class="fas fa-images"></i>
                            </div>
                            <h3 class="text-lg font-semibold text-gray-700 mb-2">إضافة صور للمعرض</h3>
                            <p class="text-sm text-gray-500 mb-2">اسحب الصور هنا أو اضغط للاختيار</p>
                            <p class="text-xs text-gray-400">يمكنك اختيار عدة صور مرة واحدة</p>
                            <input type="file" id="galleryImagesInput" name="gallery_images[]" accept="image/*" multiple class="file-input-hidden" onchange="previewGalleryImages(this)">
                        </div>
                        
                        <!-- Preview for new gallery images -->
                        <div id="galleryImagesPreview" class="preview-grid mt-4" style="display: none;"></div>
                    </div>
                </div>

                <!-- Buttons -->
                <div class="flex gap-3 mt-6 pt-6 border-t border-gray-200">
                    <button type="submit" name="update_product" 
                            class="flex-1 bg-purple-600 text-white px-6 py-3 rounded-lg font-medium hover:bg-purple-700 transition">
                        <i class="fas fa-save ml-2"></i>حفظ التغييرات
                    </button>
                    <a href="index.php" 
                       class="flex-1 bg-gray-600 text-white px-6 py-3 rounded-lg font-medium hover:bg-gray-700 transition text-center">
                        <i class="fas fa-times ml-2"></i>إلغاء
                    </a>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Delete Main Image
        function deleteMainImage() {
            if (confirm('هل أنت متأكد من حذف الصورة الرئيسية؟')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = '<input type="hidden" name="delete_main_image" value="1">';
                document.body.appendChild(form);
                form.submit();
            }
        }

        // Delete Gallery Image
        function deleteGalleryImage(imagePath) {
            if (confirm('هل أنت متأكد من حذف هذه الصورة؟')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = '<input type="hidden" name="delete_gallery_image" value="1">' +
                                '<input type="hidden" name="image_path" value="' + imagePath + '">';
                document.body.appendChild(form);
                form.submit();
            }
        }

        // Preview Main Image
        function previewMainImage(input) {
            const preview = document.getElementById('mainImagePreview');
            preview.innerHTML = '';
            
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.style.display = 'grid';
                    preview.innerHTML = `
                        <div class="image-preview-item">
                            <img src="${e.target.result}" alt="Preview">
                            <span class="main-image-badge">
                                <i class="fas fa-star ml-1"></i>جديدة
                            </span>
                        </div>
                    `;
                };
                reader.readAsDataURL(input.files[0]);
            }
        }

        // Preview Gallery Images
        function previewGalleryImages(input) {
            const preview = document.getElementById('galleryImagesPreview');
            preview.innerHTML = '';
            
            if (input.files && input.files.length > 0) {
                preview.style.display = 'grid';
                
                Array.from(input.files).forEach((file, index) => {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const div = document.createElement('div');
                        div.className = 'image-preview-item';
                        div.innerHTML = `
                            <img src="${e.target.result}" alt="Preview ${index + 1}">
                            <span class="main-image-badge" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                                <i class="fas fa-plus ml-1"></i>جديدة
                            </span>
                        `;
                        preview.appendChild(div);
                    };
                    reader.readAsDataURL(file);
                });
            }
        }

        // Drag and Drop for Main Image
        const mainUploadArea = document.querySelector('.upload-area');
        const mainImageInput = document.getElementById('mainImageInput');

        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            mainUploadArea.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            mainUploadArea.addEventListener(eventName, () => {
                mainUploadArea.classList.add('dragover');
            }, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            mainUploadArea.addEventListener(eventName, () => {
                mainUploadArea.classList.remove('dragover');
            }, false);
        });

        mainUploadArea.addEventListener('drop', function(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            
            if (files.length > 0) {
                mainImageInput.files = files;
                previewMainImage(mainImageInput);
            }
        }, false);

        // Drag and Drop for Gallery Images
        const galleryUploadAreas = document.querySelectorAll('.upload-area');
        const galleryImageInput = document.getElementById('galleryImagesInput');

        if (galleryUploadAreas.length > 1) {
            const galleryUploadArea = galleryUploadAreas[1];
            
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                galleryUploadArea.addEventListener(eventName, preventDefaults, false);
            });

            ['dragenter', 'dragover'].forEach(eventName => {
                galleryUploadArea.addEventListener(eventName, () => {
                    galleryUploadArea.classList.add('dragover');
                }, false);
            });

            ['dragleave', 'drop'].forEach(eventName => {
                galleryUploadArea.addEventListener(eventName, () => {
                    galleryUploadArea.classList.remove('dragover');
                }, false);
            });

            galleryUploadArea.addEventListener('drop', function(e) {
                const dt = e.dataTransfer;
                const files = dt.files;
                
                if (files.length > 0) {
                    galleryImageInput.files = files;
                    previewGalleryImages(galleryImageInput);
                }
            }, false);
        }

        // Smooth scroll to message
        <?php if ($message): ?>
        window.scrollTo({ top: 0, behavior: 'smooth' });
        <?php endif; ?>
    </script>
</body>
</html>
