<?php
// admin.php - Control Panel
include 'db.php';

// Handle Category Addition
if (isset($_POST['add_category'])) {
    $name = $_POST['category_name'];
    $stmt = $db->prepare("INSERT INTO categories (name) VALUES (?)");
    $stmt->execute([$name]);
    header("Location: admin.php");
    exit;
}

// Handle Category Update
if (isset($_POST['update_category'])) {
    $id = $_POST['category_id'];
    $name = $_POST['category_name'];
    $stmt = $db->prepare("UPDATE categories SET name = ? WHERE id = ?");
    $stmt->execute([$name, $id]);
    header("Location: admin.php");
    exit;
}

// Handle Category Delete
if (isset($_GET['delete_category'])) {
    $id = $_GET['delete_category'];
    $db->prepare("DELETE FROM product_images WHERE product_id IN (SELECT id FROM products WHERE category_id = ?)")->execute([$id]);
    $db->prepare("DELETE FROM products WHERE category_id = ?")->execute([$id]);
    $db->prepare("DELETE FROM categories WHERE id = ?")->execute([$id]);
    header("Location: admin.php");
    exit;
}

// Handle Product Addition
if (isset($_POST['add_product'])) {
    $code = $_POST['product_code'];
    $name = $_POST['product_name'];
    $description = $_POST['product_desc'];
    $category_id = $_POST['category_id'];
    
    $main_image = "";
    if ($_FILES['main_image']['name']) {
        $main_image = 'uploads/' . time() . '_' . $_FILES['main_image']['name'];
        move_uploaded_file($_FILES['main_image']['tmp_name'], $main_image);
    }
    
    $stmt = $db->prepare("INSERT INTO products (code, name, description, category_id, main_image) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$code, $name, $description, $category_id, $main_image]);
    $product_id = $db->lastInsertId();
    
    if (!empty($_FILES['sub_images']['name'][0])) {
        foreach ($_FILES['sub_images']['tmp_name'] as $key => $tmp_name) {
            $sub_image = 'uploads/sub_' . time() . '_' . $_FILES['sub_images']['name'][$key];
            move_uploaded_file($tmp_name, $sub_image);
            $stmt = $db->prepare("INSERT INTO product_images (product_id, image_path) VALUES (?, ?)");
            $stmt->execute([$product_id, $sub_image]);
        }
    }
    header("Location: admin.php");
    exit;
}

// Handle Product Update
if (isset($_POST['update_product'])) {
    $id = $_POST['product_id'];
    $code = $_POST['product_code'];
    $name = $_POST['product_name'];
    $description = $_POST['product_desc'];
    $category_id = $_POST['category_id'];
    
    $main_image = $_POST['existing_main_image'];
    if ($_FILES['main_image']['name']) {
        $main_image = 'uploads/' . time() . '_' . $_FILES['main_image']['name'];
        move_uploaded_file($_FILES['main_image']['tmp_name'], $main_image);
    }
    
    $stmt = $db->prepare("UPDATE products SET code = ?, name = ?, description = ?, category_id = ?, main_image = ? WHERE id = ?");
    $stmt->execute([$code, $name, $description, $category_id, $main_image, $id]);
    header("Location: admin.php");
    exit;
}

// Handle Product Delete
if (isset($_GET['delete_product'])) {
    $id = $_GET['delete_product'];
    $db->prepare("DELETE FROM product_images WHERE product_id = ?")->execute([$id]);
    $db->prepare("DELETE FROM products WHERE id = ?")->execute([$id]);
    header("Location: admin.php");
    exit;
}

// Handle Settings
if (isset($_POST['save_settings'])) {
    $c_name = $_POST['company_name'];
    $c_phone = $_POST['company_phone'];
    
    if ($_FILES['background']['name']) {
        $bg = 'uploads/bg_' . time() . '_' . $_FILES['background']['name'];
        move_uploaded_file($_FILES['background']['tmp_name'], $bg);
        $db->prepare("UPDATE company_settings SET background = ? WHERE id = 1")->execute([$bg]);
    }
    
    $db->prepare("UPDATE company_settings SET name = ?, phone = ? WHERE id = 1")->execute([$c_name, $c_phone]);
    header("Location: admin.php");
    exit;
}

$categories = $db->query("SELECT * FROM categories")->fetchAll(PDO::FETCH_ASSOC);
$settings = $db->query("SELECT * FROM company_settings WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
$products = $db->query("SELECT p.*, c.name as cat_name FROM products p LEFT JOIN categories c ON p.category_id = c.id")->fetchAll(PDO::FETCH_ASSOC);

// Auto-generate product code
$lastProduct = $db->query("SELECT code FROM products ORDER BY id DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
if ($lastProduct) {
    $lastCode = intval(substr($lastProduct['code'], 1));
    $newCode = 'P' . str_pad($lastCode + 1, 3, '0', STR_PAD_LEFT);
} else {
    $newCode = 'P001';
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>لوحة التحكم - المجلة التفاعلية</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { font-family: 'Cairo', sans-serif; }
        .modal { display: none; }
        .modal.active { display: flex; }
        .product-card:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0,0,0,0.15); }
        .btn-icon { width: 36px; height: 36px; display: inline-flex; align-items: center; justify-content: center; border-radius: 8px; transition: all 0.3s; }
        .btn-icon:hover { transform: scale(1.1); }
    </style>
</head>
<body class="bg-gradient-to-br from-gray-100 to-gray-200 min-h-screen p-4 md:p-8">
    <div class="max-w-6xl mx-auto space-y-6">
        <!-- Header -->
        <div class="bg-white rounded-2xl shadow-lg p-6 flex items-center justify-between">
            <div class="flex items-center gap-4">
                <div class="w-12 h-12 bg-blue-600 rounded-xl flex items-center justify-center">
                    <i class="fas fa-book-open text-white text-xl"></i>
                </div>
                <div>
                    <h1 class="text-2xl font-bold text-gray-800">لوحة التحكم</h1>
                    <p class="text-gray-500 text-sm">إدارة المجلة التفاعلية</p>
                </div>
            </div>
            <a href="index.php" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-xl flex items-center gap-2 transition">
                <i class="fas fa-external-link-alt"></i>
                <span>المجلة</span>
            </a>
        </div>

        <!-- Settings -->
        <section class="bg-white rounded-2xl shadow-lg p-6">
            <div class="flex items-center gap-3 mb-6">
                <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-cog text-blue-600"></i>
                </div>
                <h2 class="text-xl font-bold">إعدادات الشركة</h2>
            </div>
            <form method="POST" enctype="multipart/form-data" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-600 mb-1">اسم الشركة</label>
                    <input type="text" name="company_name" value="<?php echo $settings['name']; ?>" class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-600 mb-1">رقم الهاتف</label>
                    <input type="text" name="company_phone" value="<?php echo $settings['phone']; ?>" class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                </div>
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-600 mb-1">خلفية المجلة</label>
                    <input type="file" name="background" class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                </div>
                <button type="submit" name="save_settings" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-xl font-bold md:col-span-2 flex items-center justify-center gap-2 transition">
                    <i class="fas fa-save"></i>
                    <span>حفظ الإعدادات</span>
                </button>
            </form>
        </section>

        <!-- Categories -->
        <section class="bg-white rounded-2xl shadow-lg p-6">
            <div class="flex items-center justify-between mb-6">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-tags text-purple-600"></i>
                    </div>
                    <h2 class="text-xl font-bold">التصنيفات</h2>
                </div>
            </div>
            
            <form method="POST" class="flex gap-3 mb-6">
                <input type="text" name="category_name" placeholder="اسم التصنيف الجديد" class="flex-1 px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-transparent" required>
                <button type="submit" name="add_category" class="bg-purple-600 hover:bg-purple-700 text-white px-6 py-2 rounded-xl font-bold flex items-center gap-2 transition">
                    <i class="fas fa-plus"></i>
                    <span>إضافة</span>
                </button>
            </form>
            
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                <?php foreach ($categories as $cat): ?>
                    <div class="bg-gray-50 p-4 rounded-xl border border-gray-200 flex items-center justify-between">
                        <form method="POST" class="flex-1 flex items-center gap-2">
                            <input type="hidden" name="category_id" value="<?php echo $cat['id']; ?>">
                            <input type="text" name="category_name" value="<?php echo $cat['name']; ?>" class="flex-1 px-3 py-1 border border-gray-300 rounded-lg text-sm">
                            <button type="submit" name="update_category" class="btn-icon bg-blue-500 hover:bg-blue-600 text-white" title="تعديل">
                                <i class="fas fa-edit text-sm"></i>
                            </button>
                        </form>
                        <a href="admin.php?delete_category=<?php echo $cat['id']; ?>" class="btn-icon bg-red-500 hover:bg-red-600 text-white mr-2" onclick="return confirm('هل أنت متأكد؟')" title="حذف">
                            <i class="fas fa-trash text-sm"></i>
                        </a>
                    </div>
                <?php endforeach; ?>
            </div>
        </section>

        <!-- Products -->
        <section class="bg-white rounded-2xl shadow-lg p-6">
            <div class="flex items-center justify-between mb-6">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 bg-indigo-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-box-open text-indigo-600"></i>
                    </div>
                    <h2 class="text-xl font-bold">المنتجات</h2>
                    <span class="bg-gray-100 text-gray-600 px-3 py-1 rounded-full text-sm"><?php echo count($products); ?> منتج</span>
                </div>
                <button onclick="openModal('addProductModal')" class="bg-indigo-600 hover:bg-indigo-700 text-white px-5 py-2 rounded-xl font-bold flex items-center gap-2 transition">
                    <i class="fas fa-plus-circle"></i>
                    <span>إضافة منتج جديد</span>
                </button>
            </div>
            
            <!-- Products Grid -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <?php foreach ($products as $prod): ?>
                    <div class="bg-gray-50 rounded-xl border border-gray-200 overflow-hidden product-card transition duration-300">
                        <div class="h-40 bg-white flex items-center justify-center overflow-hidden">
                            <?php if ($prod['main_image']): ?>
                                <img src="<?php echo $prod['main_image']; ?>" class="w-full h-full object-cover">
                            <?php else: ?>
                                <i class="fas fa-image text-gray-300 text-4xl"></i>
                            <?php endif; ?>
                        </div>
                        <div class="p-4">
                            <div class="flex justify-between items-start mb-2">
                                <span class="bg-indigo-100 text-indigo-700 px-2 py-1 rounded text-xs"><?php echo $prod['cat_name']; ?></span>
                                <span class="text-gray-400 text-xs">#<?php echo $prod['code']; ?></span>
                            </div>
                            <h3 class="font-bold text-gray-800 mb-1"><?php echo $prod['name']; ?></h3>
                            <?php if (!empty($prod['price']) && $prod['price'] > 0): ?>
                                <div class="mb-1">
                                    <span class="text-green-600 font-bold text-sm"><?php echo number_format($prod['price'], 2); ?> ريال</span>
                                </div>
                            <?php endif; ?>
                            <p class="text-gray-500 text-sm line-clamp-2"><?php echo $prod['description']; ?></p>
                            <div class="flex gap-2 mt-3">
                                <button onclick="showEditProduct(<?php echo $prod['id']; ?>, '<?php echo addslashes($prod['code']); ?>', '<?php echo addslashes($prod['name']); ?>', '<?php echo addslashes($prod['description']); ?>', '<?php echo $prod['category_id']; ?>', '<?php echo addslashes($prod['main_image']); ?>', '<?php echo $prod['price'] ?? 0; ?>')" class="flex-1 bg-blue-500 hover:bg-blue-600 text-white py-2 rounded-lg text-sm flex items-center justify-center gap-1 transition">
                                    <i class="fas fa-edit"></i>
                                    <span>تعديل</span>
                                </button>
                                <a href="admin.php?delete_product=<?php echo $prod['id']; ?>" onclick="return confirm('هل أنت متأكد من الحذف؟')" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg text-sm flex items-center justify-center gap-1 transition">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </section>
    </div>

    <!-- Add Product Modal -->
    <div id="addProductModal" class="modal fixed inset-0 bg-black bg-opacity-60 flex items-center justify-center z-50 p-4">
        <div class="bg-white rounded-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div class="p-6 border-b border-gray-200 flex items-center justify-between sticky top-0 bg-white rounded-t-2xl">
                <h3 class="text-xl font-bold flex items-center gap-2">
                    <i class="fas fa-plus-circle text-indigo-600"></i>
                    إضافة منتج جديد
                </h3>
                <button onclick="closeModal('addProductModal')" class="w-10 h-10 bg-gray-100 hover:bg-gray-200 rounded-full flex items-center justify-center transition">
                    <i class="fas fa-times text-gray-600"></i>
                </button>
            </div>
            <form method="POST" enctype="multipart/form-data" class="p-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">كود المنتج</label>
                        <input type="text" name="product_code" value="<?php echo $newCode; ?>" readonly class="w-full px-4 py-2 border border-gray-300 rounded-xl bg-gray-100 text-gray-600 cursor-not-allowed">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">اسم المنتج</label>
                        <input type="text" name="product_name" placeholder="اسم المنتج" class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent" required>
                    </div>
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-600 mb-1">التصنيف</label>
                        <select name="category_id" class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent" required>
                            <option value="">اختر التصنيف</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>"><?php echo $cat['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-600 mb-1">وصف المنتج</label>
                        <textarea name="product_desc" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent"></textarea>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">الصورة الرئيسية</label>
                        <input type="file" name="main_image" class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">صور فرعية (متعدد)</label>
                        <input type="file" name="sub_images[]" multiple class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent">
                    </div>
                </div>
                <div class="flex gap-3 mt-6">
                    <button type="submit" name="add_product" class="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2 transition">
                        <i class="fas fa-plus"></i>
                        إضافة المنتج
                    </button>
                    <button type="button" onclick="closeModal('addProductModal')" class="bg-gray-200 hover:bg-gray-300 text-gray-700 px-6 py-3 rounded-xl font-bold transition">
                        إلغاء
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Product Modal -->
    <div id="editProductModal" class="modal fixed inset-0 bg-black bg-opacity-60 flex items-center justify-center z-50 p-4">
        <div class="bg-white rounded-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div class="p-6 border-b border-gray-200 flex items-center justify-between sticky top-0 bg-white rounded-t-2xl">
                <h3 class="text-xl font-bold flex items-center gap-2">
                    <i class="fas fa-edit text-blue-600"></i>
                    تعديل منتج
                </h3>
                <button onclick="closeEditProduct()" class="w-10 h-10 bg-gray-100 hover:bg-gray-200 rounded-full flex items-center justify-center transition">
                    <i class="fas fa-times text-gray-600"></i>
                </button>
            </div>
            <form method="POST" enctype="multipart/form-data" class="p-6">
                <input type="hidden" name="product_id" id="edit_product_id">
                <input type="hidden" name="existing_main_image" id="edit_existing_main_image">
                <input type="hidden" name="update_product" value="1">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">كود المنتج</label>
                        <input type="text" name="product_code" id="edit_product_code" class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">اسم المنتج</label>
                        <input type="text" name="product_name" id="edit_product_name" class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                    </div>
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-600 mb-1">التصنيف</label>
                        <select name="category_id" id="edit_category_id" class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                            <option value="">اختر التصنيف</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>"><?php echo $cat['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-600 mb-1">وصف المنتج</label>
                        <textarea name="product_desc" id="edit_product_desc" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent"></textarea>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">الصورة الرئيسية (اختياري)</label>
                        <input type="file" name="main_image" class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <img id="edit_image_preview" class="mt-2 w-24 h-24 object-cover rounded-lg hidden" src="">
                    </div>
                </div>
                <div class="flex gap-3 mt-6">
                    <button type="submit" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2 transition">
                        <i class="fas fa-save"></i>
                        حفظ التعديلات
                    </button>
                    <button type="button" onclick="closeEditProduct()" class="bg-gray-200 hover:bg-gray-300 text-gray-700 px-6 py-3 rounded-xl font-bold transition">
                        إلغاء
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function openModal(modalId) {
            document.getElementById(modalId).classList.add('active');
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).classList.remove('active');
        }
        
        function showEditProduct(id, code, name, description, categoryId, mainImage, price) {
            document.getElementById('edit_product_id').value = id;
            document.getElementById('edit_product_code').value = code;
            document.getElementById('edit_product_name').value = name;
            document.getElementById('edit_product_desc').value = description;
            document.getElementById('edit_category_id').value = categoryId;
            document.getElementById('edit_existing_main_image').value = mainImage;
            document.getElementById('edit_product_price').value = price;
            
            if (mainImage) {
                document.getElementById('edit_image_preview').src = mainImage;
                document.getElementById('edit_image_preview').classList.remove('hidden');
            } else {
                document.getElementById('edit_image_preview').classList.add('hidden');
            }
            
            document.getElementById('editProductModal').classList.add('active');
        }
        
        function closeEditProduct() {
            document.getElementById('editProductModal').classList.remove('active');
        }
        
        // Close modal when clicking outside
        document.querySelectorAll('.modal').forEach(modal => {
            modal.addEventListener('click', function(e) {
                if (e.target === this) {
                    this.classList.remove('active');
                }
            });
        });
    </script>
</body>
</html>
