<?php
// api/ingredients/read.php
error_reporting(0);
ini_set('display_errors', 0);

// Start output buffering
ob_start();

header('Content-Type: application/json; charset=utf-8');

try {
    // Clear any previous output
    if (ob_get_length()) ob_clean();
    
    // Include files
    require_once __DIR__ . '/../../includes/config.php';
    require_once __DIR__ . '/../../includes/database.php';
    
    // Get database connection
    $pdo = Database::getInstance()->getConnection();
    
    // Get specific ingredient if ID is provided
    $ingredientId = isset($_GET['id']) ? intval($_GET['id']) : null;
    
    if ($ingredientId) {
        // Get single ingredient
        $sql = "SELECT 
                    id,
                    name,
                    unit,
                    price,
                    category,
                    supplier_info,
                    user_id,
                    created_at,
                    updated_at,
                    previous_price,
                    price_updated_at as last_updated
                FROM ingredients 
                WHERE id = ?";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$ingredientId]);
        $ingredient = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$ingredient) {
            throw new Exception('Ingredient not found', 404);
        }
        
        $ingredients = [$ingredient];
    } else {
        // Get all ingredients
        $sql = "SELECT 
                    id,
                    name,
                    unit,
                    price,
                    category,
                    supplier_info,
                    user_id,
                    created_at,
                    updated_at,
                    previous_price,
                    price_updated_at as last_updated
                FROM ingredients 
                ORDER BY name ASC";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $ingredients = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    // Format the data
    $formattedIngredients = [];
    foreach ($ingredients as $ingredient) {
        $currentPrice = floatval($ingredient['price'] ?? 0);
        $previousPrice = isset($ingredient['previous_price']) ? floatval($ingredient['previous_price']) : null;
        
        // Calculate percentage change
        $changePercentage = null;
        if ($previousPrice !== null && $previousPrice > 0 && $currentPrice > 0) {
            $changePercentage = round((($currentPrice - $previousPrice) / $previousPrice) * 100, 2);
        }
        
        $formatted = [
            'id' => intval($ingredient['id']),
            'name' => $ingredient['name'] ?? '',
            'unit' => $ingredient['unit'] ?? '',
            'price' => $currentPrice,
            'category' => $ingredient['category'] ?? null,
            'supplier_info' => $ingredient['supplier_info'] ?? null,
            'previous_price' => $previousPrice,
            'last_updated' => $ingredient['last_updated'] ?? null,
            'change_percentage' => $changePercentage,
            'created_at' => $ingredient['created_at'] ?? null,
            'updated_at' => $ingredient['updated_at'] ?? null
        ];
        
        // Format last_updated for display
        if (!empty($formatted['last_updated'])) {
            try {
                $date = new DateTime($formatted['last_updated']);
                $now = new DateTime();
                $diff = $now->diff($date);
                
                if ($diff->days == 0) {
                    $formatted['last_updated_formatted'] = 'Today';
                } elseif ($diff->days == 1) {
                    $formatted['last_updated_formatted'] = 'Yesterday';
                } elseif ($diff->days < 7) {
                    $formatted['last_updated_formatted'] = $diff->days . ' days ago';
                } else {
                    $formatted['last_updated_formatted'] = $date->format('d M Y');
                }
            } catch (Exception $e) {
                $formatted['last_updated_formatted'] = 'Invalid date';
            }
        } else {
            $formatted['last_updated_formatted'] = 'Never';
        }
        
        $formattedIngredients[] = $formatted;
    }
    
    // Clear output buffer
    while (ob_get_level()) {
        ob_end_clean();
    }
    
    // Send success response
    echo json_encode([
        'success' => true,
        'data' => $ingredientId ? $formattedIngredients[0] : $formattedIngredients,
        'count' => count($formattedIngredients)
    ], JSON_PRETTY_PRINT);
    
    exit();
    
} catch (Exception $e) {
    // Clean all output buffers
    while (ob_get_level()) {
        ob_end_clean();
    }
    
    // Send error response
    http_response_code($e->getCode() ?: 500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'error' => $e->getMessage()
    ], JSON_PRETTY_PRINT);
    
    exit();
}