<?php
include 'config.php';
checkCustomerAuth(false);

header('Content-Type: application/json');

// التحقق من CSRF token
if (!isset($_SERVER['HTTP_X_CSRF_TOKEN']) || !validateCSRFToken($_SERVER['HTTP_X_CSRF_TOKEN'])) {
    echo json_encode(['success' => false, 'error' => 'رمز التحقق غير صالح']);
    exit();
}

// قراءة البيانات المرسلة
$input = json_decode(file_get_contents('php://input'), true);
$offset = isset($input['offset']) ? (int)$input['offset'] : 0;
$category = isset($input['category']) ? sanitizeInput($input['category']) : 'all';
$limit = 12; // عدد الوجبات لكل تحميل

// بناء الاستعلام
$where_clause = "WHERE m.is_active = 1";
$params = [];
$types = "";

if ($category !== 'all') {
    $where_clause .= " AND m.category_id = ?";
    $params[] = (int)$category;
    $types .= "i";
}

try {
    $sql = "
        SELECT m.*, c.name as category_name,
               (SELECT COUNT(*) FROM meal_portions mp WHERE mp.meal_id = m.id AND mp.is_active = 1) as portions_count
        FROM meals m 
        LEFT JOIN categories c ON m.category_id = c.id 
        $where_clause
        ORDER BY m.featured DESC, m.created_at DESC
        LIMIT ? OFFSET ?
    ";
    
    $params[] = $limit;
    $params[] = $offset;
    $types .= "ii";
    
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        if ($params) {
            $stmt->bind_param($types, ...$params);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        
        $html = '';
        $default_image = 'data:image/svg+xml;base64,' . base64_encode('<svg width="400" height="200" xmlns="http://www.w3.org/2000/svg"><rect width="100%" height="100%" fill="#eee"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="#999" font-family="Arial" font-size="14">No Image</text></svg>');
        
        while ($meal = $result->fetch_assoc()) {
            $portions = getMealPortions($conn, $meal['id']);
            $has_portions = $meal['has_portions'] && !empty($portions);
            
            $html .= '
            <div class="col-6 col-md-6 col-lg-4 lazy-load">
                <div class="meal-card">
                    ' . ($has_portions ? '<span class="meal-label portion-label"><i class="bi bi-tags"></i> أقسام متعددة</span>' : '') . '
                    
                    <img src="' . ($meal['image'] ? '../../admin/uploads/'.$meal['image'] : $default_image) . '" 
                         class="meal-image" 
                         alt="' . htmlspecialchars($meal['name']) . '"
                         onerror="this.src=\'' . $default_image . '\'">
                    
                    <div class="meal-content">
                        <h6 class="mb-1 fw-bold text-truncate">' . htmlspecialchars($meal['name']) . '</h6>
                        
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="price-tag">' . number_format($meal['price'], 2) . ' ريال</span>
                            ' . ($has_portions ? '<small class="text-muted"><i class="bi bi-tag"></i> ' . count($portions) . ' خيار</small>' : '') . '
                        </div>
                        
                        <div class="d-grid">
                            <button type="button" 
                                    class="btn add-to-cart-btn portion-btn"
                                    data-meal-id="' . $meal['id'] . '"
                                    data-meal-name="' . htmlspecialchars($meal['name'], ENT_QUOTES, 'UTF-8') . '"
                                    data-meal-image="' . ($meal['image'] ? '../../admin/uploads/'.$meal['image'] : $default_image) . '"
                                    data-meal-price="' . $meal['price'] . '"
                                    data-has-portions="' . ($has_portions ? '1' : '0') . '"
                                    data-portions=\'' . json_encode($portions, JSON_UNESCAPED_UNICODE) . '\'>
                                <i class="bi bi-cart-plus"></i> أضف إلى السلة
                            </button>
                        </div>
                    </div>
                </div>
            </div>';
        }
        
        // التحقق إذا كان هناك المزيد من الوجبات
        $count_sql = "SELECT COUNT(*) as total FROM meals m $where_clause";
        $count_stmt = $conn->prepare($count_sql);
        if ($params) {
            array_pop($params); // إزالة OFFSET
            array_pop($params); // إزالة LIMIT
            $count_stmt->bind_param($types, ...$params);
        }
        $count_stmt->execute();
        $count_result = $count_stmt->get_result();
        $total = $count_result->fetch_assoc()['total'];
        
        $has_more = ($offset + $limit) < $total;
        
        echo json_encode([
            'success' => true,
            'html' => $html,
            'hasMore' => $has_more,
            'offset' => $offset + $limit
        ]);
        
        $stmt->close();
        $count_stmt->close();
        
    } else {
        echo json_encode(['success' => false, 'error' => 'فشل في إعداد الاستعلام']);
    }
    
} catch (Exception $e) {
    error_log("Error in load_more_meals: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'حدث خطأ في الخادم']);
}
?>