<?php
/**
 * Kitchen Check Ingredients API
 * Verifies if ingredients are available for an order item
 * Phase 4: Kitchen Ingredient Check & Recipe View
 */

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    sendResponse(false, 'Only POST method allowed', null);
}

$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['recipe_id'])) {
    sendResponse(false, 'Recipe ID required', null);
}

$recipe_id = (int)$input['recipe_id'];

try {
    // Get recipe details
    $recipe_sql = "SELECT * FROM recipes WHERE id = ?";
    $stmt = $conn->prepare($recipe_sql);
    $stmt->bind_param('i', $recipe_id);
    $stmt->execute();
    $recipe_result = $stmt->get_result();
    
    if ($recipe_result->num_rows === 0) {
        sendResponse(false, 'Recipe not found', null);
    }
    
    $recipe = $recipe_result->fetch_assoc();
    $stmt->close();
    
    // Get recipe ingredients with stock check
    $ing_sql = "
        SELECT 
            ri.id as requirement_id,
            ri.ingredient_id,
            ri.quantity_required,
            ri.unit,
            i.name,
            i.current_stock,
            i.unit as ingredient_unit,
            i.minimum_stock,
            (i.current_stock >= ri.quantity_required) as is_available,
            CASE 
                WHEN i.current_stock >= ri.quantity_required THEN 'Available'
                WHEN i.current_stock > 0 THEN 'Partial Stock'
                ELSE 'Out of Stock'
            END as stock_status,
            (ri.quantity_required - i.current_stock) as shortage_amount
        FROM recipe_ingredients ri
        JOIN ingredients i ON ri.ingredient_id = i.id
        WHERE ri.recipe_id = ?
        ORDER BY i.name ASC
    ";
    
    $stmt = $conn->prepare($ing_sql);
    $stmt->bind_param('i', $recipe_id);
    $stmt->execute();
    $ing_result = $stmt->get_result();
    
    $ingredients = [];
    $all_available = true;
    $shortage_items = [];
    
    while ($ing = $ing_result->fetch_assoc()) {
        $ingredients[] = $ing;
        
        if (!$ing['is_available']) {
            $all_available = false;
            if ($ing['shortage_amount'] > 0) {
                $shortage_items[] = [
                    'ingredient' => $ing['name'],
                    'required' => $ing['quantity_required'],
                    'available' => $ing['current_stock'],
                    'unit' => $ing['unit'],
                    'shortage' => $ing['shortage_amount']
                ];
            }
        }
    }
    $stmt->close();
    
    sendResponse(true, 'Ingredient availability checked', [
        'recipe' => [
            'id' => $recipe['id'],
            'name' => $recipe['name'],
            'preparation_time' => $recipe['preparation_time']
        ],
        'ingredients' => $ingredients,
        'summary' => [
            'total_ingredients' => count($ingredients),
            'available_ingredients' => count(array_filter($ingredients, fn($x) => $x['is_available'])),
            'all_available' => (bool)$all_available,
            'shortages' => $shortage_items
        ]
    ]);

} catch (Exception $e) {
    http_response_code(500);
    sendResponse(false, $e->getMessage(), null);
}

$conn->close();
?>
