<?php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/database.php';

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

$user_id = $_GET['user_id'] ?? null;

if (!$user_id) {
    http_response_code(400);
    echo json_encode(['error' => 'User ID is required']);
    exit;
}

try {
    $db = Database::getInstance();
    $pdo = $db->getConnection();
    
    $stmt = $pdo->prepare("
        SELECT 
            m.*,
            COUNT(mc.id) as costing_count
        FROM meals m
        LEFT JOIN meal_costings mc ON m.id = mc.meal_id
        WHERE m.created_by = ?
        GROUP BY m.id
        ORDER BY m.created_at DESC
    ");
    $stmt->execute([$user_id]);
    $meals = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode($meals);
    
} catch (Exception $e) {
    http_response_code(500);
    error_log("get_meals.php error: " . $e->getMessage());
    echo json_encode(['error' => 'Failed to load meals: ' . $e->getMessage()]);
}
?>