<?php
/**
 * meals.php - إدارة الوجبات المتكاملة مع نظام الأقسام
 * @version 5.1.0
 */

require_once 'config.php';
checkAdminAuth();

// ============================================
// دوال مساعدة للأقسام
// ============================================

function getMealPortions($meal_id) {
    global $conn;
    $result = $conn->query("SELECT * FROM meal_portions WHERE meal_id = $meal_id ORDER BY price");
    $portions = [];
    while ($row = $result->fetch_assoc()) {
        $portions[] = $row;
    }
    return $portions;
}

function saveMealPortions($meal_id, $portions_names, $portions_prices) {
    global $conn;
    
    // حذف الأقسام القديمة
    $conn->query("DELETE FROM meal_portions WHERE meal_id = $meal_id");
    
    // إضافة الأقسام الجديدة
    for ($i = 0; $i < count($portions_names); $i++) {
        $name = trim($portions_names[$i] ?? '');
        $price = floatval($portions_prices[$i] ?? 0);
        
        if (!empty($name) && $price > 0) {
            $name_esc = $conn->real_escape_string($name);
            $conn->query("INSERT INTO meal_portions (meal_id, name, price) VALUES ($meal_id, '$name_esc', $price)");
        }
    }
}

// ============================================
// معالجة النماذج
// ============================================

// إضافة وجبة
if (isPost() && isset($_POST['add'])) {
    $name = $conn->real_escape_string($_POST['name']);
    $price = (float)$_POST['price'];
    $category = (int)$_POST['category'];
    $has_portions = isset($_POST['has_portions']) ? 1 : 0;
    
    $image = null;
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $upload = uploadImage($_FILES['image']);
        if ($upload['success']) $image = $upload['filename'];
    }
    
    $img_sql = $image ? "'$image'" : "NULL";
    
    // بدء المعاملة
    $conn->begin_transaction();
    
    try {
        // إضافة الوجبة
        $conn->query("INSERT INTO meals (name, price, category_id, image, has_portions, created_at) 
                      VALUES ('$name', $price, $category, $img_sql, $has_portions, NOW())");
        
        $meal_id = $conn->insert_id;
        
        // إضافة الأقسام إذا كانت موجودة
        if ($has_portions && isset($_POST['portion_name']) && is_array($_POST['portion_name'])) {
            saveMealPortions($meal_id, $_POST['portion_name'], $_POST['portion_price']);
        }
        
        $conn->commit();
        $cache->clear();
        $_SESSION['success'] = 'تمت إضافة الوجبة بنجاح';
        
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error'] = 'حدث خطأ أثناء الإضافة';
    }
    
    header('Location: meals.php' . (isset($_GET['category']) ? '?category=' . $_GET['category'] : ''));
    exit();
}

// تعديل وجبة
if (isPost() && isset($_POST['edit'])) {
    $id = (int)$_POST['id'];
    $name = $conn->real_escape_string($_POST['name']);
    $price = (float)$_POST['price'];
    $category = (int)$_POST['category'];
    $has_portions = isset($_POST['has_portions']) ? 1 : 0;
    
    // Handle image upload
    $image = null;
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $upload = uploadImage($_FILES['image']);
        if ($upload['success']) {
            $image = $upload['filename'];
            // Delete old image
            $old = $conn->query("SELECT image FROM meals WHERE id=$id")->fetch_assoc();
            if ($old['image']) deleteImage($old['image']);
        }
    }
    
    // بدء المعاملة
    $conn->begin_transaction();
    
    try {
        // تحديث الوجبة
        if ($image) {
            $conn->query("UPDATE meals SET name='$name', price=$price, category_id=$category, image='$image', has_portions=$has_portions WHERE id=$id");
        } else {
            $conn->query("UPDATE meals SET name='$name', price=$price, category_id=$category, has_portions=$has_portions WHERE id=$id");
        }
        
        // تحديث الأقسام
        if ($has_portions && isset($_POST['portion_name']) && is_array($_POST['portion_name'])) {
            saveMealPortions($id, $_POST['portion_name'], $_POST['portion_price']);
        } else {
            $conn->query("DELETE FROM meal_portions WHERE meal_id = $id");
        }
        
        $conn->commit();
        $cache->clear();
        $_SESSION['success'] = 'تم تعديل الوجبة بنجاح';
        
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error'] = 'حدث خطأ أثناء التعديل';
    }
    
    header('Location: meals.php' . (isset($_GET['category']) ? '?category=' . $_GET['category'] : ''));
    exit();
}

// حذف وجبة
if (isPost() && isset($_POST['delete'])) {
    $id = (int)$_POST['id'];
    $img = $conn->query("SELECT image FROM meals WHERE id=$id")->fetch_assoc();
    if ($img['image']) deleteImage($img['image']);
    
    $conn->begin_transaction();
    $conn->query("DELETE FROM meal_portions WHERE meal_id=$id");
    $conn->query("DELETE FROM meals WHERE id=$id");
    $conn->commit();
    
    $cache->clear();
    $_SESSION['success'] = 'تم حذف الوجبة بنجاح';
    header('Location: meals.php' . (isset($_GET['category']) ? '?category=' . $_GET['category'] : ''));
    exit();
}

// تغيير حالة الوجبة
if (isPost() && isset($_POST['toggle'])) {
    $id = (int)$_POST['id'];
    $conn->query("UPDATE meals SET is_active = NOT is_active WHERE id=$id");
    $cache->clear();
    header('Location: meals.php' . (isset($_GET['category']) ? '?category=' . $_GET['category'] : ''));
    exit();
}

// ============================================
// جلب البيانات مع التصفية
// ============================================

// جلب التصنيفات
$categories = $cache->get('categories_list');
if (!$categories) {
    $result = $conn->query("SELECT id, name FROM categories ORDER BY name");
    $categories = [];
    while ($row = $result->fetch_assoc()) {
        $categories[] = $row;
    }
    $cache->set('categories_list', $categories, 3600);
}

// معاملات التصفية
$selected_category = isset($_GET['category']) ? (int)$_GET['category'] : 0;
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';

// بناء استعلام الوجبات مع التصفية
$where = [];
if ($selected_category > 0) {
    $where[] = "m.category_id = $selected_category";
}
if (!empty($search)) {
    $where[] = "(m.name LIKE '%$search%' OR m.description LIKE '%$search%')";
}
if ($status_filter == 'active') {
    $where[] = "m.is_active = 1";
} elseif ($status_filter == 'inactive') {
    $where[] = "m.is_active = 0";
}

$where_sql = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";

// جلب الوجبات
$cache_key = 'meals_' . md5($selected_category . $search . $status_filter);
$meals = $cache->get($cache_key);
if (!$meals) {
    $result = $conn->query("
        SELECT m.*, c.name as category_name 
        FROM meals m 
        LEFT JOIN categories c ON m.category_id = c.id 
        $where_sql 
        ORDER BY m.id DESC 
        LIMIT 200
    ");
    $meals = [];
    while ($row = $result->fetch_assoc()) {
        $row['portions'] = getMealPortions($row['id']);
        $meals[] = $row;
    }
    $cache->set($cache_key, $meals, 300);
}

// جلب بيانات وجبة محددة للتعديل (AJAX)
if (isset($_GET['get_meal'])) {
    $id = (int)$_GET['get_meal'];
    $meal = $conn->query("SELECT * FROM meals WHERE id=$id")->fetch_assoc();
    $meal['portions'] = getMealPortions($id);
    header('Content-Type: application/json');
    echo json_encode($meal);
    exit();
}

$page_title = 'الوجبات';
include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
/* ===== تحسينات إضافية ===== */
.filter-bar {
    background: white;
    border-radius: 20px;
    padding: 1.2rem;
    margin-bottom: 1.5rem;
    box-shadow: 0 4px 20px rgba(0,0,0,.02);
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
    align-items: center;
}

.filter-group {
    flex: 1;
    min-width: 150px;
}

.filter-group label {
    display: block;
    font-size: 0.8rem;
    color: #64748b;
    margin-bottom: 0.3rem;
    font-weight: 500;
}

.filter-control {
    width: 100%;
    padding: 0.6rem 1rem;
    border: 2px solid #e2e8f0;
    border-radius: 12px;
    transition: 0.2s;
}

.filter-control:focus {
    border-color: #F57C00;
    outline: none;
    box-shadow: 0 0 0 3px rgba(245,124,0,.1);
}

.filter-actions {
    display: flex;
    gap: 0.5rem;
    margin-top: 1.5rem;
}

/* ===== نظام الأقسام ===== */
.portions-section {
    background: #f8fafc;
    border-radius: 16px;
    padding: 1rem;
    margin-top: 1rem;
    border: 1px solid #e2e8f0;
}

.portions-title {
    font-size: 0.9rem;
    font-weight: 600;
    color: #F57C00;
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.portion-item {
    background: white;
    border-radius: 12px;
    padding: 0.8rem;
    margin-bottom: 0.5rem;
    border: 1px solid #e2e8f0;
    transition: 0.2s;
}

.portion-item:hover {
    border-color: #F57C00;
    box-shadow: 0 2px 10px rgba(245,124,0,.05);
}

.portion-badge {
    display: inline-block;
    background: #FFF3E0;
    color: #F57C00;
    padding: 0.2rem 0.5rem;
    border-radius: 20px;
    font-size: 0.7rem;
    font-weight: 600;
    margin-right: 0.3rem;
}

/* ===== تحسينات الجوال ===== */
@media (max-width: 768px) {
    .filter-bar {
        flex-direction: column;
        gap: 0.8rem;
    }
    
    .filter-group {
        width: 100%;
    }
    
    .filter-actions {
        width: 100%;
    }
    
    .filter-actions button,
    .filter-actions a {
        flex: 1;
    }
}

.meal-card {
    transition: 0.2s;
}

.meal-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(0,0,0,.05);
}

.btn-icon {
    width: 36px;
    height: 36px;
    padding: 0;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 10px;
}
</style>

<div class="main-content">
    <!-- الهيدر العلوي -->
    <div class="top-bar">
        <i class="bi bi-egg-fried text-primary fs-4 me-2"></i>
        <span><strong>إدارة الوجبات</strong></span>
        <span class="ms-auto text-muted small">
            <i class="bi bi-grid-3x3-gap-fill me-1"></i><?php echo count($meals); ?> وجبة
        </span>
    </div>

    <!-- شريط التصفية -->
    <div class="filter-bar">
        <form method="GET" class="w-100">
            <div class="row g-2">
                <div class="col-md-4">
                    <div class="filter-group">
                        <label><i class="bi bi-search me-1"></i>بحث</label>
                        <input type="text" class="filter-control" name="search" placeholder="اسم الوجبة..." value="<?php echo e($search); ?>">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="filter-group">
                        <label><i class="bi bi-tags me-1"></i>التصنيف</label>
                        <select class="filter-control" name="category">
                            <option value="">جميع التصنيفات</option>
                            <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>" <?php echo $selected_category == $cat['id'] ? 'selected' : ''; ?>>
                                <?php echo e($cat['name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="filter-group">
                        <label><i class="bi bi-activity me-1"></i>الحالة</label>
                        <select class="filter-control" name="status">
                            <option value="">جميع الحالات</option>
                            <option value="active" <?php echo $status_filter == 'active' ? 'selected' : ''; ?>>نشط</option>
                            <option value="inactive" <?php echo $status_filter == 'inactive' ? 'selected' : ''; ?>>غير نشط</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="filter-actions">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="bi bi-funnel"></i> تصفية
                        </button>
                        <a href="meals.php" class="btn btn-outline-secondary">
                            <i class="bi bi-arrow-repeat"></i>
                        </a>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- زر الإضافة -->
    <div class="d-flex justify-content-end mb-3">
        <button class="btn btn-primary" onclick="openAddModal()">
            <i class="bi bi-plus-lg me-1"></i>إضافة وجبة جديدة
        </button>
    </div>

    <!-- Mobile Cards -->
    <div class="row g-3 d-md-none">
        <?php if (empty($meals)): ?>
        <div class="col-12">
            <div class="card text-center p-5">
                <i class="bi bi-egg-fried display-1 text-muted mb-3"></i>
                <h6>لا توجد وجبات</h6>
                <p class="text-muted small">قم بإضافة أول وجبة الآن</p>
                <button class="btn btn-primary mx-auto" style="width: fit-content;" onclick="openAddModal()">
                    <i class="bi bi-plus-lg me-1"></i>إضافة
                </button>
            </div>
        </div>
        <?php endif; ?>
        
        <?php foreach ($meals as $m): ?>
        <div class="col-12">
            <div class="card meal-card">
                <div class="card-body p-3">
                    <div class="d-flex gap-3">
                        <!-- صورة الوجبة -->
                        <div class="flex-shrink-0">
                            <?php if ($m['image'] && file_exists("uploads/".$m['image'])): ?>
                                <img src="uploads/<?php echo $m['image']; ?>" width="80" height="80" style="object-fit:cover;border-radius:16px;">
                            <?php else: ?>
                                <div style="width:80px;height:80px;background:#f1f5f9;border-radius:16px;display:flex;align-items:center;justify-content:center;">
                                    <i class="bi bi-image text-muted fs-2"></i>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- معلومات الوجبة -->
                        <div class="flex-grow-1">
                            <div class="d-flex justify-content-between align-items-start">
                                <h6 class="mb-1"><?php echo e($m['name']); ?></h6>
                                <span class="badge bg-<?php echo $m['is_active'] ? 'success' : 'secondary'; ?>">
                                    <?php echo $m['is_active'] ? 'نشط' : 'غير نشط'; ?>
                                </span>
                            </div>
                            <small class="text-muted d-block mb-1">
                                <i class="bi bi-tag me-1"></i><?php echo e($m['category_name'] ?? 'غير مصنف'); ?>
                            </small>
                            
                            <?php if ($m['has_portions'] && !empty($m['portions'])): ?>
                                <div class="mb-1">
                                    <?php foreach ($m['portions'] as $p): ?>
                                        <span class="portion-badge"><?php echo e($p['name']); ?>: <?php echo number_format($p['price'],2); ?></span>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <strong class="text-primary fs-5"><?php echo number_format($m['price'],2); ?> ريال</strong>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- أزرار الإجراءات -->
                    <div class="d-flex gap-2 mt-3">
                        <form method="POST" class="flex-grow-1">
                            <input type="hidden" name="id" value="<?php echo $m['id']; ?>">
                            <button type="submit" name="toggle" class="btn btn-sm w-100 <?php echo $m['is_active'] ? 'btn-warning' : 'btn-success'; ?>">
                                <i class="bi bi-<?php echo $m['is_active'] ? 'pause' : 'play'; ?> me-1"></i>
                                <?php echo $m['is_active'] ? 'تعطيل' : 'تفعيل'; ?>
                            </button>
                        </form>
                        <button class="btn btn-sm btn-warning" onclick="editMeal(<?php echo $m['id']; ?>)">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <form method="POST" class="d-inline" onsubmit="return confirm('تأكيد حذف الوجبة؟')">
                            <input type="hidden" name="id" value="<?php echo $m['id']; ?>">
                            <button type="submit" name="delete" class="btn btn-sm btn-danger">
                                <i class="bi bi-trash"></i>
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Desktop Table -->
    <div class="card d-none d-md-block">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th>الصورة</th>
                        <th>الاسم</th>
                        <th>التصنيف</th>
                        <th>السعر/الأقسام</th>
                        <th>الحالة</th>
                        <th>تاريخ الإضافة</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($meals)): ?>
                    <tr>
                        <td colspan="7" class="text-center py-5">
                            <i class="bi bi-egg-fried display-4 text-muted d-block mb-3"></i>
                            <h6>لا توجد وجبات</h6>
                            <button class="btn btn-primary mt-2" onclick="openAddModal()">
                                <i class="bi bi-plus-lg me-1"></i>إضافة وجبة
                            </button>
                        </td>
                    </tr>
                    <?php endif; ?>
                    
                    <?php foreach ($meals as $m): ?>
                    <tr>
                        <td>
                            <?php if ($m['image'] && file_exists("uploads/".$m['image'])): ?>
                                <img src="uploads/<?php echo $m['image']; ?>" width="50" height="50" style="object-fit:cover;border-radius:12px;">
                            <?php else: ?>
                                <div style="width:50px;height:50px;background:#f1f5f9;border-radius:12px;display:flex;align-items:center;justify-content:center;">
                                    <i class="bi bi-image text-muted"></i>
                                </div>
                            <?php endif; ?>
                        </td>
                        <td><strong><?php echo e($m['name']); ?></strong></td>
                        <td><?php echo e($m['category_name'] ?? '-'); ?></td>
                        <td>
                            <?php if ($m['has_portions'] && !empty($m['portions'])): ?>
                                <?php foreach ($m['portions'] as $p): ?>
                                    <span class="portion-badge"><?php echo e($p['name']); ?>: <?php echo number_format($p['price'],2); ?></span><br>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <?php echo number_format($m['price'],2); ?> ريال
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="badge bg-<?php echo $m['is_active'] ? 'success' : 'secondary'; ?>">
                                <?php echo $m['is_active'] ? 'نشط' : 'غير نشط'; ?>
                            </span>
                        </td>
                        <td><?php echo date('Y-m-d', strtotime($m['created_at'] ?? 'now')); ?></td>
                        <td>
                            <div class="btn-group">
                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="id" value="<?php echo $m['id']; ?>">
                                    <button type="submit" name="toggle" class="btn btn-sm <?php echo $m['is_active'] ? 'btn-warning' : 'btn-success'; ?> btn-icon" title="<?php echo $m['is_active'] ? 'تعطيل' : 'تفعيل'; ?>">
                                        <i class="bi bi-<?php echo $m['is_active'] ? 'pause' : 'play'; ?>"></i>
                                    </button>
                                </form>
                                <button class="btn btn-sm btn-warning btn-icon" onclick="editMeal(<?php echo $m['id']; ?>)" title="تعديل">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <form method="POST" class="d-inline" onsubmit="return confirm('تأكيد حذف الوجبة؟')">
                                    <input type="hidden" name="id" value="<?php echo $m['id']; ?>">
                                    <button type="submit" name="delete" class="btn btn-sm btn-danger btn-icon" title="حذف">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- مودال إضافة وجبة مع نظام الأقسام -->
<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">إضافة وجبة جديدة</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" enctype="multipart/form-data" id="addForm">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-2">
                            <label class="form-label small">اسم الوجبة</label>
                            <input type="text" class="form-control" name="name" required>
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small">التصنيف</label>
                            <select class="form-select" name="category" required>
                                <option value="">اختر التصنيف</option>
                                <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>"><?php echo e($cat['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mb-2">
                        <label class="form-label small">صورة الوجبة</label>
                        <input type="file" class="form-control" name="image" accept="image/*">
                    </div>
                    
                    <!-- نظام الأقسام -->
                    <div class="mb-2">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="add_has_portions" name="has_portions">
                            <label class="form-check-label fw-bold" for="add_has_portions">
                                تفعيل نظام الأقسام (ربع، نصف، كامل)
                            </label>
                        </div>
                    </div>
                    
                    <!-- حقل السعر العادي (يظهر عندما لا يكون نظام الأقسام مفعلاً) -->
                    <div id="add_price_field" class="mb-2">
                        <label class="form-label small">السعر</label>
                        <input type="number" step="0.01" class="form-control" name="price" placeholder="السعر">
                    </div>
                    
                    <!-- أقسام الوجبة (تظهر عند تفعيل نظام الأقسام) -->
                    <div id="add_portions_section" style="display: none;">
                        <div class="portions-section">
                            <div class="portions-title">
                                <i class="bi bi-grid-3x3-gap-fill"></i>
                                أقسام الوجبة
                            </div>
                            <div id="add_portions_container"></div>
                            <button type="button" class="btn btn-sm btn-outline-primary mt-2" onclick="addPortion('add')">
                                <i class="bi bi-plus-circle me-1"></i>إضافة قسم
                            </button>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" name="add" class="btn btn-primary">إضافة</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- مودال تعديل وجبة مع نظام الأقسام -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">تعديل الوجبة</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" enctype="multipart/form-data" id="editForm">
                <input type="hidden" name="id" id="edit_id">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-2">
                            <label class="form-label small">اسم الوجبة</label>
                            <input type="text" class="form-control" name="name" id="edit_name" required>
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small">التصنيف</label>
                            <select class="form-select" name="category" id="edit_category" required>
                                <option value="">اختر التصنيف</option>
                                <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>"><?php echo e($cat['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <!-- عرض الصورة الحالية -->
                    <div id="edit_current_image_container" class="mb-2 text-center" style="display: none;">
                        <img id="edit_current_image" src="" style="max-width: 100px; max-height: 100px; border-radius: 10px;">
                        <p class="small text-muted mt-1">الصورة الحالية</p>
                    </div>
                    
                    <div class="mb-2">
                        <label class="form-label small">تغيير الصورة</label>
                        <input type="file" class="form-control" name="image" accept="image/*">
                        <small class="text-muted">اتركه فارغاً للاحتفاظ بالصورة الحالية</small>
                    </div>
                    
                    <!-- نظام الأقسام -->
                    <div class="mb-2">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="edit_has_portions" name="has_portions">
                            <label class="form-check-label fw-bold" for="edit_has_portions">
                                تفعيل نظام الأقسام (ربع، نصف، كامل)
                            </label>
                        </div>
                    </div>
                    
                    <!-- حقل السعر العادي (يظهر عندما لا يكون نظام الأقسام مفعلاً) -->
                    <div id="edit_price_field" class="mb-2">
                        <label class="form-label small">السعر</label>
                        <input type="number" step="0.01" class="form-control" name="price" id="edit_price" placeholder="السعر">
                    </div>
                    
                    <!-- أقسام الوجبة (تظهر عند تفعيل نظام الأقسام) -->
                    <div id="edit_portions_section" style="display: none;">
                        <div class="portions-section">
                            <div class="portions-title">
                                <i class="bi bi-grid-3x3-gap-fill"></i>
                                أقسام الوجبة
                            </div>
                            <div id="edit_portions_container"></div>
                            <button type="button" class="btn btn-sm btn-outline-primary mt-2" onclick="addPortion('edit')">
                                <i class="bi bi-plus-circle me-1"></i>إضافة قسم
                            </button>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" name="edit" class="btn btn-primary">حفظ التغييرات</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// ============================================
// نظام الأقسام
// ============================================

let portionCount = { add: 1, edit: 1 };

// إضافة قسم جديد
function addPortion(type) {
    const container = document.getElementById(type + '_portions_container');
    const count = portionCount[type]++;
    
    const div = document.createElement('div');
    div.className = 'portion-item row g-2';
    div.id = type + '_portion_' + count;
    div.innerHTML = `
        <div class="col-md-5">
            <input type="text" class="form-control form-control-sm" name="portion_name[]" placeholder="اسم القسم (مثال: ربع)">
        </div>
        <div class="col-md-5">
            <div class="input-group input-group-sm">
                <input type="number" step="0.01" class="form-control" name="portion_price[]" placeholder="السعر" min="0">
                <span class="input-group-text">ريال</span>
            </div>
        </div>
        <div class="col-md-2">
            <button type="button" class="btn btn-sm btn-danger w-100" onclick="removePortion('${type}', ${count})">
                <i class="bi bi-trash"></i>
            </button>
        </div>
    `;
    container.appendChild(div);
}

// حذف قسم
function removePortion(type, id) {
    const element = document.getElementById(type + '_portion_' + id);
    if (element) {
        element.remove();
    }
}

// تحميل أقسام وجبة للتعديل
function loadPortions(portions, type) {
    const container = document.getElementById(type + '_portions_container');
    container.innerHTML = '';
    portionCount[type] = 0;
    
    if (portions && portions.length > 0) {
        portions.forEach(portion => {
            const count = portionCount[type]++;
            const div = document.createElement('div');
            div.className = 'portion-item row g-2';
            div.id = type + '_portion_' + count;
            div.innerHTML = `
                <div class="col-md-5">
                    <input type="text" class="form-control form-control-sm" name="portion_name[]" value="${portion.name}" placeholder="اسم القسم">
                </div>
                <div class="col-md-5">
                    <div class="input-group input-group-sm">
                        <input type="number" step="0.01" class="form-control" name="portion_price[]" value="${portion.price}" placeholder="السعر" min="0">
                        <span class="input-group-text">ريال</span>
                    </div>
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-sm btn-danger w-100" onclick="removePortion('${type}', ${count})">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            `;
            container.appendChild(div);
        });
    } else {
        // إضافة قسم افتراضي واحد
        addPortion(type);
    }
}

// ============================================
// التحكم في إظهار/إخفاء حقول الأقسام
// ============================================

document.getElementById('add_has_portions')?.addEventListener('change', function() {
    const priceField = document.getElementById('add_price_field');
    const portionsSection = document.getElementById('add_portions_section');
    
    if (this.checked) {
        priceField.style.display = 'none';
        portionsSection.style.display = 'block';
        document.querySelector('[name="price"]').required = false;
        
        // إضافة قسم افتراضي إذا لم يكن موجوداً
        if (document.getElementById('add_portions_container').children.length === 0) {
            addPortion('add');
        }
    } else {
        priceField.style.display = 'block';
        portionsSection.style.display = 'none';
        document.querySelector('[name="price"]').required = true;
    }
});

document.getElementById('edit_has_portions')?.addEventListener('change', function() {
    const priceField = document.getElementById('edit_price_field');
    const portionsSection = document.getElementById('edit_portions_section');
    
    if (this.checked) {
        priceField.style.display = 'none';
        portionsSection.style.display = 'block';
        document.getElementById('edit_price').required = false;
    } else {
        priceField.style.display = 'block';
        portionsSection.style.display = 'none';
        document.getElementById('edit_price').required = true;
    }
});

// ============================================
// فتح المودالات
// ============================================

function openAddModal() {
    // إعادة تعيين النموذج
    document.getElementById('addForm').reset();
    document.getElementById('add_portions_container').innerHTML = '';
    document.getElementById('add_portions_section').style.display = 'none';
    document.getElementById('add_price_field').style.display = 'block';
    document.getElementById('add_has_portions').checked = false;
    portionCount.add = 1;
    
    new bootstrap.Modal(document.getElementById('addModal')).show();
}

function editMeal(id) {
    fetch('meals.php?get_meal=' + id)
        .then(response => response.json())
        .then(data => {
            document.getElementById('edit_id').value = data.id;
            document.getElementById('edit_name').value = data.name;
            document.getElementById('edit_category').value = data.category_id;
            document.getElementById('edit_price').value = data.price;
            document.getElementById('edit_has_portions').checked = data.has_portions == 1;
            
            // عرض الصورة الحالية
            if (data.image) {
                document.getElementById('edit_current_image').src = 'uploads/' + data.image;
                document.getElementById('edit_current_image_container').style.display = 'block';
            } else {
                document.getElementById('edit_current_image_container').style.display = 'none';
            }
            
            // إظهار/إخفاء الأقسام حسب الحالة
            if (data.has_portions == 1) {
                document.getElementById('edit_price_field').style.display = 'none';
                document.getElementById('edit_portions_section').style.display = 'block';
                document.getElementById('edit_price').required = false;
                loadPortions(data.portions || [], 'edit');
            } else {
                document.getElementById('edit_price_field').style.display = 'block';
                document.getElementById('edit_portions_section').style.display = 'none';
                document.getElementById('edit_price').required = true;
            }
            
            new bootstrap.Modal(document.getElementById('editModal')).show();
        })
        .catch(error => {
            console.error('Error:', error);
            alert('حدث خطأ في تحميل بيانات الوجبة');
        });
}

// ============================================
// إصلاح القائمة الجانبية
// ============================================

document.addEventListener('DOMContentLoaded', function() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    const menuToggle = document.getElementById('menuToggle');
    const sidebarClose = document.getElementById('sidebarClose');
    
    console.log('Sidebar elements:', {sidebar, overlay, menuToggle, sidebarClose});
    
    function openSidebar() {
        if (sidebar) {
            sidebar.classList.add('show');
            console.log('Sidebar opened');
        }
        if (overlay) overlay.classList.add('show');
        document.body.style.overflow = 'hidden';
    }
    
    function closeSidebar() {
        if (sidebar) {
            sidebar.classList.remove('show');
            console.log('Sidebar closed');
        }
        if (overlay) overlay.classList.remove('show');
        document.body.style.overflow = '';
    }
    
    if (menuToggle) {
        menuToggle.addEventListener('click', openSidebar);
        console.log('Menu toggle listener added');
    } else {
        console.error('Menu toggle not found');
    }
    
    if (sidebarClose) {
        sidebarClose.addEventListener('click', closeSidebar);
    }
    
    if (overlay) {
        overlay.addEventListener('click', closeSidebar);
    }
    
    // إغلاق القائمة عند تغيير حجم النافذة
    window.addEventListener('resize', function() {
        if (window.innerWidth > 768) {
            closeSidebar();
        }
    });
});
</script>

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