<?php
/**
 * Admin Recipes API
 * CRUD operations for recipes and recipe ingredients
 * Phase 3: Recipe & Ingredient Management
 */

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

$action = isset($_GET['action']) ? $_GET['action'] : null;

try {
    switch ($action) {
        case 'get_recipes':
            getRecipes();
            break;
        case 'get_recipe':
            getRecipe();
            break;
        case 'create_recipe':
            createRecipe();
            break;
        case 'update_recipe':
            updateRecipe();
            break;
        case 'delete_recipe':
            deleteRecipe();
            break;
        case 'add_ingredient':
            addRecipeIngredient();
            break;
        case 'remove_ingredient':
            removeRecipeIngredient();
            break;
        case 'get_menu_items':
            getMenuItems();
            break;
        case 'get_ingredients':
            getIngredients();
            break;
        default:
            sendResponse(false, 'Invalid action', null);
    }
} catch (Exception $e) {
    http_response_code(500);
    sendResponse(false, $e->getMessage(), null);
}

// Get all recipes with item count
function getRecipes() {
    global $conn;
    
    $sql = "
        SELECT 
            r.id,
            r.menu_item_id,
            r.name,
            r.description,
            r.preparation_time,
            r.difficulty_level,
            r.status,
            mi.item_name,
            mi.image_path,
            (SELECT COUNT(*) FROM recipe_ingredients WHERE recipe_id = r.id) as ingredient_count
        FROM recipes r
        LEFT JOIN menu_items mi ON r.menu_item_id = mi.id
        ORDER BY r.name ASC
    ";
    
    $result = $conn->query($sql);
    
    if (!$result) {
        throw new Exception('Query failed: ' . $conn->error);
    }
    
    $recipes = [];
    while ($row = $result->fetch_assoc()) {
        $recipes[] = $row;
    }
    
    sendResponse(true, 'Recipes retrieved successfully', $recipes);
}

// Get single recipe with ingredients
function getRecipe() {
    global $conn;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['id'])) {
        sendResponse(false, 'Recipe ID required', null);
    }
    
    $id = (int)$input['id'];
    
    // Get recipe
    $sql = "
        SELECT r.*, m.item_name, m.description, m.price
        FROM recipes r
        LEFT JOIN menu_items m ON r.menu_item_id = m.id
        WHERE r.id = ?
    ";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        sendResponse(false, 'Recipe not found', null);
    }
    
    $recipe = $result->fetch_assoc();
    $stmt->close();
    
    // Get ingredients
    $ing_sql = "
        SELECT 
            ri.id,
            ri.ingredient_id,
            ri.quantity_required,
            ri.unit,
            ri.notes,
            i.name as ingredient_name,
            i.unit as ingredient_unit,
            i.unit_cost
        FROM recipe_ingredients ri
        JOIN ingredients i ON ri.ingredient_id = i.id
        WHERE ri.recipe_id = ?
    ";
    
    $stmt = $conn->prepare($ing_sql);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $ing_result = $stmt->get_result();
    
    $ingredients = [];
    while ($ing = $ing_result->fetch_assoc()) {
        $ingredients[] = $ing;
    }
    $stmt->close();
    
    $recipe['ingredients'] = $ingredients;
    
    sendResponse(true, 'Recipe retrieved successfully', $recipe);
}

// Create recipe
function createRecipe() {
    global $conn;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['menu_item_id']) || !isset($input['name'])) {
        sendResponse(false, 'Menu item ID and recipe name required', null);
    }
    
    $menu_item_id = (int)$input['menu_item_id'];
    $name = htmlspecialchars($input['name']);
    $description = isset($input['description']) ? htmlspecialchars($input['description']) : '';
    $prep_time = isset($input['preparation_time']) ? (int)$input['preparation_time'] : 0;
    $difficulty = isset($input['difficulty_level']) ? htmlspecialchars($input['difficulty_level']) : 'medium';
    $yield_qty = isset($input['yield_quantity']) ? (int)$input['yield_quantity'] : 1;
    $yield_unit = isset($input['yield_unit']) ? htmlspecialchars($input['yield_unit']) : 'portion';
    $notes = isset($input['chef_notes']) ? htmlspecialchars($input['chef_notes']) : '';
    
    // Check if recipe already exists for this menu item
    $check = $conn->query("SELECT id FROM recipes WHERE menu_item_id = $menu_item_id");
    if ($check->num_rows > 0) {
        sendResponse(false, 'Recipe already exists for this menu item', null);
    }
    
    $sql = "
        INSERT INTO recipes (
            menu_item_id, name, description, preparation_time,
            difficulty_level, yield_quantity, yield_unit, chef_notes
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param(
        'issiisis',
        $menu_item_id, $name, $description, $prep_time,
        $difficulty, $yield_qty, $yield_unit, $notes
    );
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to create recipe: ' . $stmt->error);
    }
    
    $recipe_id = $stmt->insert_id;
    $stmt->close();
    
    sendResponse(true, 'Recipe created successfully', ['id' => $recipe_id, 'name' => $name]);
}

// Update recipe
function updateRecipe() {
    global $conn;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['id'])) {
        sendResponse(false, 'Recipe ID required', null);
    }
    
    $id = (int)$input['id'];
    $name = isset($input['name']) ? htmlspecialchars($input['name']) : null;
    $description = isset($input['description']) ? htmlspecialchars($input['description']) : null;
    $prep_time = isset($input['preparation_time']) ? (int)$input['preparation_time'] : null;
    $difficulty = isset($input['difficulty_level']) ? htmlspecialchars($input['difficulty_level']) : null;
    $status = isset($input['status']) ? htmlspecialchars($input['status']) : null;
    
    $updates = [];
    $params = [];
    $types = '';
    
    if ($name !== null) {
        $updates[] = 'name = ?';
        $params[] = $name;
        $types .= 's';
    }
    if ($description !== null) {
        $updates[] = 'description = ?';
        $params[] = $description;
        $types .= 's';
    }
    if ($prep_time !== null) {
        $updates[] = 'preparation_time = ?';
        $params[] = $prep_time;
        $types .= 'i';
    }
    if ($difficulty !== null) {
        $updates[] = 'difficulty_level = ?';
        $params[] = $difficulty;
        $types .= 's';
    }
    if ($status !== null) {
        $updates[] = 'status = ?';
        $params[] = $status;
        $types .= 's';
    }
    
    if (empty($updates)) {
        sendResponse(false, 'Nothing to update', null);
    }
    
    $params[] = $id;
    $types .= 'i';
    
    $sql = "UPDATE recipes SET " . implode(', ', $updates) . " WHERE id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update recipe: ' . $stmt->error);
    }
    
    $stmt->close();
    
    sendResponse(true, 'Recipe updated successfully', ['id' => $id]);
}

// Delete recipe
function deleteRecipe() {
    global $conn;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['id'])) {
        sendResponse(false, 'Recipe ID required', null);
    }
    
    $id = (int)$input['id'];
    
    // This will cascade delete recipe_ingredients due to FK constraint
    $sql = "DELETE FROM recipes WHERE id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to delete recipe: ' . $stmt->error);
    }
    
    $stmt->close();
    
    sendResponse(true, 'Recipe deleted successfully', ['id' => $id]);
}

// Add ingredient to recipe
function addRecipeIngredient() {
    global $conn;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['recipe_id']) || !isset($input['ingredient_id']) || !isset($input['quantity_required'])) {
        sendResponse(false, 'Recipe ID, ingredient ID, and quantity required', null);
    }
    
    $recipe_id = (int)$input['recipe_id'];
    $ingredient_id = (int)$input['ingredient_id'];
    $quantity = (float)$input['quantity_required'];
    $unit = htmlspecialchars($input['unit']);
    $notes = isset($input['notes']) ? htmlspecialchars($input['notes']) : '';
    
    $sql = "
        INSERT INTO recipe_ingredients (
            recipe_id, ingredient_id, quantity_required, unit, notes
        ) VALUES (?, ?, ?, ?, ?)
    ";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('iidss', $recipe_id, $ingredient_id, $quantity, $unit, $notes);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to add ingredient: ' . $stmt->error);
    }
    
    $ing_id = $stmt->insert_id;
    $stmt->close();
    
    sendResponse(true, 'Ingredient added to recipe', ['id' => $ing_id]);
}

// Remove ingredient from recipe
function removeRecipeIngredient() {
    global $conn;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['id'])) {
        sendResponse(false, 'Recipe ingredient ID required', null);
    }
    
    $id = (int)$input['id'];
    
    $sql = "DELETE FROM recipe_ingredients WHERE id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to remove ingredient: ' . $stmt->error);
    }
    
    $stmt->close();
    
    sendResponse(true, 'Ingredient removed from recipe', ['id' => $id]);
}

// Get all menu items for recipe assignment
function getMenuItems() {
    global $conn;
    
    $sql = "
        SELECT 
            mi.id,
            mi.item_name,
            mi.price,
            CASE 
                WHEN r.id IS NOT NULL THEN 'Has Recipe'
                ELSE 'No Recipe'
            END as recipe_status
        FROM menu_items mi
        LEFT JOIN recipes r ON mi.id = r.menu_item_id
        ORDER BY mi.item_name ASC
    ";
    
    $result = $conn->query($sql);
    
    if (!$result) {
        throw new Exception('Query failed: ' . $conn->error);
    }
    
    $items = [];
    while ($row = $result->fetch_assoc()) {
        $items[] = $row;
    }
    
    sendResponse(true, 'Menu items retrieved', $items);
}

// Get all ingredients
function getIngredients() {
    global $conn;
    
    $sql = "
        SELECT 
            id,
            name,
            unit,
            current_stock,
            minimum_stock,
            unit_cost,
            status
        FROM ingredients
        WHERE status = 'active'
        ORDER BY name ASC
    ";
    
    $result = $conn->query($sql);
    
    if (!$result) {
        throw new Exception('Query failed: ' . $conn->error);
    }
    
    $ingredients = [];
    while ($row = $result->fetch_assoc()) {
        $ingredients[] = $row;
    }
    
    sendResponse(true, 'Ingredients retrieved', $ingredients);
}

$conn->close();
?>
