<?php
// load_products.php - Optimized product loader with caching
session_start();
require_once 'config.php';

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

// Get parameters
$category = isset($_GET['category']) && $_GET['category'] !== 'all' ? (int)$_GET['category'] : null;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Build query
$query = "SELECT m.*, c.name as category_name 
          FROM meals m 
          LEFT JOIN categories c ON m.category_id = c.id 
          WHERE m.is_active = 1";

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

if ($category) {
    $query .= " AND m.category_id = ?";
    $params[] = $category;
    $types .= "i";
}

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

$query .= " ORDER BY m.featured DESC, m.created_at DESC LIMIT ? OFFSET ?";
$params[] = $limit;
$params[] = $offset;
$types .= "ii";

// Prepare and execute
$stmt = mysqli_prepare($conn, $query);
if (!empty($params)) {
    mysqli_stmt_bind_param($stmt, $types, ...$params);
}
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

// Output products
if (mysqli_num_rows($result) > 0) {
    while ($product = mysqli_fetch_assoc($result)) {
        $has_portions = $product['has_portions'] ?? false;
        $image_path = !empty($product['image']) ? 'uploads/meals/' . $product['image'] : 'assets/img/default-meal.jpg';
        $price = number_format($product['price']);
        $name = htmlspecialchars($product['name']);
        $category_name = htmlspecialchars($product['category_name'] ?? '');
        ?>
        <div class="product-card" data-product-id="<?= $product['id'] ?>">
            <img src="<?= $image_path ?>" alt="<?= $name ?>" class="product-image" loading="lazy">
            <div class="product-content">
                <h3 class="product-title"><?= $name ?></h3>
                <div class="product-category"><?= $category_name ?></div>
                <div class="product-footer">
                    <span class="product-price"><?= $price ?> ريال</span>
                    <?php if ($has_portions): ?>
                    <button class="add-to-cart" onclick="openPortionModal(<?= $product['id'] ?>, '<?= addslashes($name) ?>', this)">
                        <i class="bi bi-cart-plus"></i> أضف
                    </button>
                    <?php else: ?>
                    <button class="add-to-cart" onclick="addToCart(<?= $product['id'] ?>, 1, null, <?= $product['price'] ?>, this)">
                        <i class="bi bi-cart-plus"></i> أضف
                    </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php
    }
} else {
    echo '<div class="empty-state"><i class="bi bi-search"></i><p>لا توجد منتجات</p></div>';
}
?>