<?php
require_once __DIR__ . '/../../includes/config.php';
header('Content-Type: application/json');

try {
    if (isset($pdo)) {
        // Get user_id from session or use default
        session_start();
        $user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 1;
        
        // Get ingredients from database
        $query = "SELECT id, name, price as unit_cost, unit as unit_type 
                  FROM ingredients 
                  WHERE user_id = ? 
                  ORDER BY name";
        $stmt = $pdo->prepare($query);
        $stmt->execute([$user_id]);
        $ingredients = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // If no ingredients found, return empty array
        echo json_encode(['success' => true, 'ingredients' => $ingredients]);
        
    } else {
        echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>