<?php
/**
 * Admin Ingredients API
 * CRUD operations for ingredients and stock management
 * 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_ingredients':
            getIngredients();
            break;
        case 'get_ingredient':
            getIngredient();
            break;
        case 'create_ingredient':
            createIngredient();
            break;
        case 'update_ingredient':
            updateIngredient();
            break;
        case 'update_stock':
            updateStock();
            break;
        case 'delete_ingredient':
            deleteIngredient();
            break;
        case 'get_low_stock':
            getLowStockItems();
            break;
        case 'get_stock_summary':
            getStockSummary();
            break;
        default:
            sendResponse(false, 'Invalid action', null);
    }
} catch (Exception $e) {
    http_response_code(500);
    sendResponse(false, $e->getMessage(), null);
}

// Get all ingredients with stock status
function getIngredients() {
    global $conn;
    
    $status = isset($_GET['status']) ? $_GET['status'] : 'active';
    
    $sql = "
        SELECT 
            id,
            name,
            description,
            unit,
            current_stock,
            minimum_stock,
            unit_cost,
            supplier,
            status,
            CASE 
                WHEN current_stock <= minimum_stock THEN 'low'
                WHEN current_stock > (minimum_stock * 2) THEN 'adequate'
                ELSE 'normal'
            END as stock_status,
            (current_stock * unit_cost) as total_value,
            last_updated
        FROM ingredients
        " . ($status ? "WHERE status = ?" : "") . "
        ORDER BY name ASC
    ";
    
    $stmt = $conn->prepare($sql);
    
    if ($status) {
        $stmt->bind_param('s', $status);
    }
    
    $stmt->execute();
    $result = $stmt->get_result();
    
    $ingredients = [];
    while ($row = $result->fetch_assoc()) {
        $ingredients[] = $row;
    }
    
    $stmt->close();
    
    sendResponse(true, 'Ingredients retrieved successfully', $ingredients);
}

// Get single ingredient
function getIngredient() {
    global $conn;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['id'])) {
        sendResponse(false, 'Ingredient ID required', null);
    }
    
    $id = (int)$input['id'];
    
    $sql = "SELECT * FROM ingredients WHERE id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        sendResponse(false, 'Ingredient not found', null);
    }
    
    $ingredient = $result->fetch_assoc();
    $stmt->close();
    
    sendResponse(true, 'Ingredient retrieved successfully', $ingredient);
}

// Create ingredient
function createIngredient() {
    global $conn;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['name']) || !isset($input['unit']) || !isset($input['unit_cost'])) {
        sendResponse(false, 'Name, unit, and unit cost are required', null);
    }
    
    $name = htmlspecialchars($input['name']);
    $description = isset($input['description']) ? htmlspecialchars($input['description']) : '';
    $unit = htmlspecialchars($input['unit']);
    $current_stock = isset($input['current_stock']) ? (float)$input['current_stock'] : 0;
    $minimum_stock = isset($input['minimum_stock']) ? (float)$input['minimum_stock'] : 0;
    $unit_cost = (float)$input['unit_cost'];
    $supplier = isset($input['supplier']) ? htmlspecialchars($input['supplier']) : '';
    $status = isset($input['status']) ? htmlspecialchars($input['status']) : 'active';
    
    // Check if ingredient already exists
    $check = $conn->query("SELECT id FROM ingredients WHERE name = '$name'");
    if ($check->num_rows > 0) {
        sendResponse(false, 'Ingredient with this name already exists', null);
    }
    
    $sql = "
        INSERT INTO ingredients (
            name, description, unit, current_stock, minimum_stock,
            unit_cost, supplier, status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param(
        'sssdddss',
        $name, $description, $unit, $current_stock, $minimum_stock,
        $unit_cost, $supplier, $status
    );
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to create ingredient: ' . $stmt->error);
    }
    
    $ingredient_id = $stmt->insert_id;
    $stmt->close();
    
    sendResponse(true, 'Ingredient created successfully', ['id' => $ingredient_id, 'name' => $name]);
}

// Update ingredient details
function updateIngredient() {
    global $conn;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['id'])) {
        sendResponse(false, 'Ingredient ID required', null);
    }
    
    $id = (int)$input['id'];
    
    $updates = [];
    $params = [];
    $types = '';
    
    if (isset($input['name'])) {
        $updates[] = 'name = ?';
        $params[] = htmlspecialchars($input['name']);
        $types .= 's';
    }
    if (isset($input['description'])) {
        $updates[] = 'description = ?';
        $params[] = htmlspecialchars($input['description']);
        $types .= 's';
    }
    if (isset($input['unit'])) {
        $updates[] = 'unit = ?';
        $params[] = htmlspecialchars($input['unit']);
        $types .= 's';
    }
    if (isset($input['minimum_stock'])) {
        $updates[] = 'minimum_stock = ?';
        $params[] = (float)$input['minimum_stock'];
        $types .= 'd';
    }
    if (isset($input['unit_cost'])) {
        $updates[] = 'unit_cost = ?';
        $params[] = (float)$input['unit_cost'];
        $types .= 'd';
    }
    if (isset($input['supplier'])) {
        $updates[] = 'supplier = ?';
        $params[] = htmlspecialchars($input['supplier']);
        $types .= 's';
    }
    if (isset($input['status'])) {
        $updates[] = 'status = ?';
        $params[] = htmlspecialchars($input['status']);
        $types .= 's';
    }
    
    if (empty($updates)) {
        sendResponse(false, 'Nothing to update', null);
    }
    
    $params[] = $id;
    $types .= 'i';
    
    $sql = "UPDATE ingredients SET " . implode(', ', $updates) . " WHERE id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update ingredient: ' . $stmt->error);
    }
    
    $stmt->close();
    
    sendResponse(true, 'Ingredient updated successfully', ['id' => $id]);
}

// Update stock level
function updateStock() {
    global $conn;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['id']) || !isset($input['quantity']) || !isset($input['action'])) {
        sendResponse(false, 'ID, quantity, and action (add/subtract) required', null);
    }
    
    $id = (int)$input['id'];
    $quantity = (float)$input['quantity'];
    $action = htmlspecialchars($input['action']); // 'add' or 'subtract'
    $notes = isset($input['notes']) ? htmlspecialchars($input['notes']) : '';
    
    // Get current stock
    $result = $conn->query("SELECT current_stock FROM ingredients WHERE id = $id");
    
    if ($result->num_rows === 0) {
        sendResponse(false, 'Ingredient not found', null);
    }
    
    $ingredient = $result->fetch_assoc();
    $current_stock = $ingredient['current_stock'];
    
    // Calculate new stock
    if ($action === 'add') {
        $new_stock = $current_stock + $quantity;
    } elseif ($action === 'subtract') {
        $new_stock = $current_stock - $quantity;
        if ($new_stock < 0) {
            sendResponse(false, 'Insufficient stock available', null);
        }
    } else {
        sendResponse(false, 'Invalid action. Use "add" or "subtract"', null);
    }
    
    // Update stock
    $sql = "UPDATE ingredients SET current_stock = ? WHERE id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('di', $new_stock, $id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update stock: ' . $stmt->error);
    }
    
    $stmt->close();
    
    sendResponse(true, 'Stock updated successfully', [
        'id' => $id,
        'old_stock' => $current_stock,
        'new_stock' => $new_stock,
        'quantity_changed' => $quantity,
        'action' => $action
    ]);
}

// Delete ingredient
function deleteIngredient() {
    global $conn;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['id'])) {
        sendResponse(false, 'Ingredient ID required', null);
    }
    
    $id = (int)$input['id'];
    
    // Check if ingredient is used in any recipes
    $check = $conn->query("SELECT COUNT(*) as count FROM recipe_ingredients WHERE ingredient_id = $id");
    $result = $check->fetch_assoc();
    
    if ($result['count'] > 0) {
        sendResponse(false, 'Cannot delete ingredient that is used in recipes. Deactivate instead.', null);
    }
    
    $sql = "DELETE FROM ingredients WHERE id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to delete ingredient: ' . $stmt->error);
    }
    
    $stmt->close();
    
    sendResponse(true, 'Ingredient deleted successfully', ['id' => $id]);
}

// Get low stock items
function getLowStockItems() {
    global $conn;
    
    $sql = "
        SELECT 
            id,
            name,
            current_stock,
            minimum_stock,
            unit,
            unit_cost,
            supplier,
            (minimum_stock - current_stock) as shortage_amount
        FROM ingredients
        WHERE current_stock <= minimum_stock
        AND status = 'active'
        ORDER BY shortage_amount DESC
    ";
    
    $result = $conn->query($sql);
    
    if (!$result) {
        throw new Exception('Query failed: ' . $conn->error);
    }
    
    $items = [];
    while ($row = $result->fetch_assoc()) {
        $items[] = $row;
    }
    
    sendResponse(true, 'Low stock items retrieved', [
        'count' => count($items),
        'items' => $items
    ]);
}

// Get stock summary
function getStockSummary() {
    global $conn;
    
    $sql = "
        SELECT 
            COUNT(*) as total_items,
            SUM(current_stock) as total_quantity,
            SUM(current_stock * unit_cost) as total_value,
            SUM(CASE WHEN current_stock <= minimum_stock THEN 1 ELSE 0 END) as low_stock_count,
            SUM(CASE WHEN status = 'discontinued' THEN 1 ELSE 0 END) as discontinued_count
        FROM ingredients
    ";
    
    $result = $conn->query($sql);
    $summary = $result->fetch_assoc();
    
    sendResponse(true, 'Stock summary retrieved', $summary);
}

$conn->close();
?>
