<?php
// api/meals/get_costings.php - Corrected for actual table structure

// Enable full error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

try {
    // Use absolute paths
    $base_path = $_SERVER['DOCUMENT_ROOT'] . '/rcp/includes/';
    $config_path = $base_path . 'config.php';

    if (file_exists($config_path)) {
        require_once $config_path;
    } else {
        throw new Exception('Config file not found');
    }

    require_once $base_path . 'database.php';
    $pdo = Database::getInstance()->getConnection();
    
    // Get user_id from query parameter
    $user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
    
    // Query using the correct column names: created_by and recipe_name
    $query = "
        SELECT 
            id,
            recipe_name as name,  -- Map recipe_name to name
            total_cost,
            cost_per_portion,
            portions,
            created_by,
            category,
            created_at
        FROM recipe_costings 
        WHERE created_by = ?
        ORDER BY recipe_name ASC
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute([$user_id]);
    $costings = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode($costings ?: []);
    
} catch (Throwable $t) {
    error_log("Error in get_costings.php: " . $t->getMessage());
    // Return empty array instead of error
    echo json_encode([]);
}
?>