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

try {
    if (isset($pdo)) {
        // First, let's find what tables exist in the database
        $stmt = $pdo->query("SHOW TABLES");
        $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
        error_log("Available tables: " . implode(', ', $tables));
        
        $ingredients = [];
        $ingredientTable = null;
        
        // Look for possible ingredient table names
        $possibleTables = ['ingredients', 'ingredient', 'items', 'products', 'inventory'];
        foreach ($possibleTables as $table) {
            if (in_array($table, $tables)) {
                $ingredientTable = $table;
                error_log("Found ingredient table: " . $table);
                break;
            }
        }
        
        if ($ingredientTable) {
            // Get table structure to understand columns
            $stmt = $pdo->query("DESCRIBE $ingredientTable");
            $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $columnMap = [
                'id' => 'id',
                'name' => 'name', 
                'cost' => 'unit_cost',
                'unit' => 'unit_type'
            ];
            
            // Auto-detect column names
            foreach ($columns as $col) {
                $colName = strtolower($col['Field']);
                if (strpos($colName, 'name') !== false) $columnMap['name'] = $col['Field'];
                if (strpos($colName, 'cost') !== false || strpos($colName, 'price') !== false) $columnMap['cost'] = $col['Field'];
                if (strpos($colName, 'unit') !== false || strpos($colName, 'measure') !== false) $columnMap['unit'] = $col['Field'];
            }
            
            $query = "SELECT 
                {$columnMap['id']} as id, 
                {$columnMap['name']} as name, 
                {$columnMap['cost']} as unit_cost, 
                {$columnMap['unit']} as unit_type 
                FROM $ingredientTable 
                ORDER BY {$columnMap['name']}";
                
            error_log("Ingredient query: " . $query);
            
            $stmt = $pdo->query($query);
            $ingredients = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            error_log("Found " . count($ingredients) . " ingredients");
        }
        
        // If no ingredients found, check if we need to create the table
        if (empty($ingredients)) {
            error_log("No ingredients found, creating sample data");
            // Create sample ingredients table if it doesn't exist
            try {
                $pdo->exec("CREATE TABLE IF NOT EXISTS ingredients (
                    id INT PRIMARY KEY AUTO_INCREMENT,
                    name VARCHAR(255) NOT NULL,
                    unit_cost DECIMAL(10,2) NOT NULL,
                    unit_type VARCHAR(50) NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )");
                
                // Insert sample data
                $sampleIngredients = [
                    ['Flour', 15.50, 'kg'],
                    ['Sugar', 12.75, 'kg'],
                    ['Butter', 45.00, 'kg'],
                    ['Eggs', 35.00, 'dozen'],
                    ['Chicken Breast', 85.00, 'kg'],
                    ['Tomatoes', 25.00, 'kg'],
                    ['Olive Oil', 75.00, 'liter'],
                    ['Salt', 8.50, 'kg']
                ];
                
                $stmt = $pdo->prepare("INSERT INTO ingredients (name, unit_cost, unit_type) VALUES (?, ?, ?)");
                foreach ($sampleIngredients as $ingredient) {
                    $stmt->execute($ingredient);
                }
                
                // Now fetch the inserted ingredients
                $stmt = $pdo->query("SELECT * FROM ingredients ORDER BY name");
                $ingredients = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
            } catch (Exception $e) {
                error_log("Error creating ingredients table: " . $e->getMessage());
                // Fallback to hardcoded sample data
                $ingredients = [
                    ['id' => 1, 'name' => 'Flour', 'unit_cost' => 15.50, 'unit_type' => 'kg'],
                    ['id' => 2, 'name' => 'Sugar', 'unit_cost' => 12.75, 'unit_type' => 'kg'],
                    ['id' => 3, 'name' => 'Butter', 'unit_cost' => 45.00, 'unit_type' => 'kg'],
                    ['id' => 4, 'name' => 'Eggs', 'unit_cost' => 35.00, 'unit_type' => 'dozen'],
                    ['id' => 5, 'name' => 'Chicken Breast', 'unit_cost' => 85.00, 'unit_type' => 'kg']
                ];
            }
        }
        
        echo json_encode(['success' => true, 'ingredients' => $ingredients]);
        
    } else {
        echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    }
} catch (PDOException $e) {
    error_log("Ingredients API Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>