<?php
// test_columns.php - Place this in the api/ingredients/ directory
header('Content-Type: application/json');

try {
    echo json_encode(['step' => '1', 'status' => 'Starting test']);
    
    // Check paths
    $configPath = __DIR__ . '/../../includes/config.php';
    $databasePath = __DIR__ . '/../../includes/database.php';
    
    echo json_encode([
        'step' => '2', 
        'status' => 'Checking paths',
        'config_path' => $configPath,
        'config_exists' => file_exists($configPath),
        'database_exists' => file_exists($databasePath)
    ]);
    
    if (!file_exists($configPath)) {
        throw new Exception('Config file not found');
    }
    
    if (!file_exists($databasePath)) {
        throw new Exception('Database file not found');
    }
    
    require_once $configPath;
    echo json_encode(['step' => '3', 'status' => 'Config loaded']);
    
    require_once $databasePath;
    echo json_encode(['step' => '4', 'status' => 'Database loaded']);
    
    $pdo = Database::getInstance()->getConnection();
    echo json_encode(['step' => '5', 'status' => 'Database connected']);
    
    // List all tables
    $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
    echo json_encode(['step' => '6', 'status' => 'Tables listed', 'tables' => $tables]);
    
    // Check ingredients table structure
    if (in_array('ingredients', $tables)) {
        $columns = $pdo->query("DESCRIBE ingredients")->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['step' => '7', 'status' => 'Ingredients columns', 'columns' => $columns]);
        
        // Show sample data
        $sample = $pdo->query("SELECT * FROM ingredients LIMIT 3")->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['step' => '8', 'status' => 'Sample data', 'sample' => $sample]);
    } else {
        echo json_encode(['step' => '7', 'status' => 'Ingredients table not found']);
    }
    
    // Check price history table
    if (in_array('ingredient_price_history', $tables)) {
        $historyColumns = $pdo->query("DESCRIBE ingredient_price_history")->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['step' => '9', 'status' => 'Price history columns', 'columns' => $historyColumns]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'error' => $e->getMessage(),
        'file' => $e->getFile(),
        'line' => $e->getLine(),
        'trace' => $e->getTraceAsString()
    ]);
}