<?php
/**
 * ajax_load_meals.php - تحميل المزيد من الوجبات (Infinite Scroll)
 */

include 'config.php';
checkAdminAuth();

header('Content-Type: text/html; charset=utf-8');

$page = intval($_GET['page'] ?? 1);
$limit = 20;
$offset = ($page - 1) * $limit;

$category = intval($_GET['category'] ?? 0);
$status = $_GET['status'] ?? 'all';
$portions = $_GET['portions'] ?? 'all';
$search = $_GET['search'] ?? '';

$where = ["1=1"];
$params = [];
$types = "";

if ($category > 0) {
    $where[] = "m.category_id = ?";
    $params[] = $category;
    $types .= "i";
}

if ($status === 'active') {
    $where[] = "m.is_active = 1";
} elseif ($status === 'inactive') {
    $where[] = "m.is_active = 0";
}

if ($portions === 'has_portions') {
    $where[] = "m.has_portions = 1";
} elseif ($portions === 'no_portions') {
    $where[] = "m.has_portions = 0";
}

if (!empty($search)) {
    $where[] = "(m.name LIKE ? OR m.description LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= "ss";
}

$where_sql = implode(" AND ", $where);

$sql = "SELECT m.*, c.name as category_name,
               (SELECT JSON_ARRAYAGG(JSON_OBJECT('name', mp.name, 'price', mp.price)) 
                FROM meal_portions mp WHERE mp.meal_id = m.id) as portions_json
        FROM meals m
        LEFT JOIN categories c ON m.category_id = c.id
        WHERE $where_sql
        ORDER BY m.created_at DESC
        LIMIT ? OFFSET ?";

$params[] = $limit;
$params[] = $offset;
$types .= "ii";

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$meals = $stmt->get_result();

while ($meal = $meals->fetch_assoc()):
    $portions = json_decode($meal['portions_json'], true) ?: [];
?>
<div class="meal-card" data-id="<?php echo $meal['id']; ?>">
    <div class="meal-image-container">
        <?php if ($meal['image'] && file_exists("uploads/" . $meal['image'])): ?>
            <img src="uploads/<?php echo $meal['image']; ?>" 
                 alt="<?php echo htmlspecialchars($meal['name']); ?>" 
                 class="meal-image"
                 loading="lazy">
        <?php else: ?>
            <div class="meal-image-placeholder">
                <i class="bi bi-image"></i>
            </div>
        <?php endif; ?>
        
        <div class="meal-badge">
            <span class="<?php echo $meal['is_active'] ? 'active' : 'inactive'; ?>">
                <?php echo $meal['is_active'] ? 'نشط' : 'غير نشط'; ?>
            </span>
        </div>
    </div>
    
    <div class="meal-content">
        <div class="meal-header">
            <h3 class="meal-name"><?php echo htmlspecialchars($meal['name']); ?></h3>
        </div>
        
        <div class="meal-category">
            <i class="bi bi-tag"></i> <?php echo htmlspecialchars($meal['category_name'] ?? 'غير مصنف'); ?>
        </div>
        
        <?php if (!empty($meal['description'])): ?>
        <p class="meal-description"><?php echo htmlspecialchars($meal['description']); ?></p>
        <?php endif; ?>
        
        <div class="meal-price-row">
            <div class="meal-price">
                <?php if (!empty($portions)): ?>
                    <?php 
                    $prices = array_column($portions, 'price');
                    $min_price = min($prices);
                    $max_price = max($prices);
                    ?>
                    <?php if ($min_price == $max_price): ?>
                        <?php echo number_format($min_price, 0); ?>
                    <?php else: ?>
                        <?php echo number_format($min_price, 0); ?> - <?php echo number_format($max_price, 0); ?>
                    <?php endif; ?>
                    <small>ريال</small>
                <?php else: ?>
                    <?php echo number_format($meal['price'], 0); ?> <small>ريال</small>
                <?php endif; ?>
            </div>
            
            <?php if (!empty($portions)): ?>
            <div class="meal-portions-badge">
                <i class="bi bi-grid"></i> <?php echo count($portions); ?>
            </div>
            <?php endif; ?>
        </div>
        
        <div class="meal-actions">
            <button class="meal-action edit" onclick="openEditMealModal(<?php echo $meal['id']; ?>)">
                <i class="bi bi-pencil"></i>
            </button>
            <button class="meal-action delete" onclick="deleteMeal(<?php echo $meal['id']; ?>, '<?php echo htmlspecialchars(addslashes($meal['name'])); ?>')">
                <i class="bi bi-trash"></i>
            </button>
        </div>
    </div>
</div>
<?php endwhile; ?>