<?php
/**
 * Kitchen Get Recipe API
 * Retrieves full recipe details for a menu 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['menu_item_id']) && !isset($input['recipe_id'])) {
    sendResponse(false, 'Menu item ID or recipe ID required', null);
}

try {
    $menu_item_id = isset($input['menu_item_id']) ? (int)$input['menu_item_id'] : null;
    $recipe_id = isset($input['recipe_id']) ? (int)$input['recipe_id'] : null;
    
    // Get recipe (by item or direct ID)
    if ($menu_item_id) {
        $recipe_sql = "SELECT * FROM recipes WHERE menu_item_id = ?";
        $stmt = $conn->prepare($recipe_sql);
        if (!$stmt) {
            throw new Exception('Prepare failed: ' . $conn->error);
        }
        $stmt->bind_param('i', $menu_item_id);
    } else {
        $recipe_sql = "SELECT * FROM recipes WHERE id = ?";
        $stmt = $conn->prepare($recipe_sql);
        if (!$stmt) {
            throw new Exception('Prepare failed: ' . $conn->error);
        }
        $stmt->bind_param('i', $recipe_id);
    }
    
    if (!$stmt->execute()) {
        throw new Exception('Execute failed: ' . $stmt->error);
    }
    $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 menu item details
    $item_sql = "SELECT id, item_name, description, price, image_path FROM menu_items WHERE id = ?";
    $stmt = $conn->prepare($item_sql);
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $conn->error);
    }
    $stmt->bind_param('i', $recipe['menu_item_id']);
    if (!$stmt->execute()) {
        throw new Exception('Execute failed: ' . $stmt->error);
    }
    $item = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if (!$item) {
        throw new Exception('Menu item not found for this recipe');
    }
    
    // Get all ingredients with detailed info
    $ing_sql = "
        SELECT 
            ri.id as requirement_id,
            ri.ingredient_id,
            ri.quantity_required,
            ri.unit as required_unit,
            ri.notes as ingredient_notes,
            i.id,
            i.name,
            i.description,
            i.unit as ingredient_unit,
            i.current_stock,
            i.minimum_stock,
            i.unit_cost,
            (i.current_stock >= ri.quantity_required) as in_stock,
            CASE 
                WHEN i.current_stock >= ri.quantity_required THEN '✓ Available'
                WHEN i.current_stock > 0 THEN '⚠ Partial'
                ELSE '✗ Out of Stock'
            END as availability_status
        FROM recipe_ingredients ri
        JOIN ingredients i ON ri.ingredient_id = i.id
        WHERE ri.recipe_id = ?
        ORDER BY ri.id ASC
    ";
    
    $stmt = $conn->prepare($ing_sql);
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $conn->error);
    }
    $stmt->bind_param('i', $recipe['id']);
    if (!$stmt->execute()) {
        throw new Exception('Execute failed: ' . $stmt->error);
    }
    $ing_result = $stmt->get_result();
    
    $ingredients = [];
    $ingredient_cost = 0;
    $all_in_stock = true;
    
    while ($ing = $ing_result->fetch_assoc()) {
        $cost_per_requirement = $ing['quantity_required'] * $ing['unit_cost'];
        $ing['cost'] = $cost_per_requirement;
        $ingredient_cost += $cost_per_requirement;
        
        if (!$ing['in_stock']) {
            $all_in_stock = false;
        }
        
        $ingredients[] = $ing;
    }
    $stmt->close();
    
    // Get difficulty level badge
    $difficulty_colors = [
        'easy' => '#4caf50',
        'medium' => '#ff9800',
        'hard' => '#f44336'
    ];
    
    sendResponse(true, 'Recipe retrieved successfully', [
        'item' => [
            'id' => $item['id'],
            'name' => $item['item_name'],
            'description' => $item['description'],
            'price' => $item['price'],
            'image' => $item['image_path']
        ],
        'recipe' => [
            'id' => $recipe['id'],
            'name' => $recipe['name'],
            'description' => $recipe['description'],
            'preparation_time' => $recipe['preparation_time'],
            'difficulty_level' => $recipe['difficulty_level'],
            'difficulty_color' => $difficulty_colors[$recipe['difficulty_level']] ?? '#2196f3',
            'yield_quantity' => $recipe['yield_quantity'],
            'yield_unit' => $recipe['yield_unit'],
            'chef_notes' => $recipe['chef_notes'],
            'status' => $recipe['status']
        ],
        'ingredients' => $ingredients,
        'summary' => [
            'total_ingredients' => count($ingredients),
            'all_in_stock' => (bool)$all_in_stock,
            'estimated_ingredient_cost' => round($ingredient_cost, 2),
            'margin' => round($item['item_price'] - $ingredient_cost, 2)
        ]
    ]);

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

$conn->close();
?>
