<?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';
require_once 'ingredient_unit_helper.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 {
    $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();

    $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
        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()) {
        $availability = calculateIngredientAvailability(
            $ing['current_stock'],
            $ing['ingredient_unit'],
            $ing['quantity_required'],
            $ing['unit']
        );

        $ing['quantity_required_in_stock_unit'] = $availability['required_quantity_in_stock_unit'];
        $ing['is_available'] = $availability['in_stock'];
        $ing['stock_status'] = $availability['in_stock']
            ? 'Available'
            : ((float)$ing['current_stock'] > 0 ? 'Partial Stock' : 'Out of Stock');
        $ing['shortage_amount'] = $availability['shortage_amount'];
        $ing['units_convertible'] = $availability['units_convertible'];

        $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['ingredient_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();
