<?php
/**
 * Get KOT Details API
 * Retrieves KOT information with items and ingredients
 * Phase 2: KOT Generation System
 */

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['kot_id']) && !isset($input['order_id'])) {
    sendResponse(false, 'Missing kot_id or order_id', null);
}

$kot_id = isset($input['kot_id']) ? (int)$input['kot_id'] : null;
$order_id = isset($input['order_id']) ? (int)$input['order_id'] : null;

try {
    // Get KOT details
    if ($kot_id) {
        $kot_sql = "SELECT * FROM kot_tickets WHERE id = ?";
        $stmt = $conn->prepare($kot_sql);
        $stmt->bind_param('i', $kot_id);
    } else {
        $kot_sql = "SELECT * FROM kot_tickets WHERE order_id = ?";
        $stmt = $conn->prepare($kot_sql);
        $stmt->bind_param('i', $order_id);
    }
    
    $stmt->execute();
    $kot_result = $stmt->get_result();
    
    if ($kot_result->num_rows === 0) {
        sendResponse(false, 'KOT not found', null);
    }
    
    $kot = $kot_result->fetch_assoc();
    $stmt->close();
    
    $order_id = $kot['order_id'];

    // Get order details
    $order_sql = "
        SELECT 
            o.id,
            o.order_number,
            o.table_id,
            o.server_id,
            o.total_amount,
            o.status,
            o.special_requests,
            rt.table_number,
            rt.section,
            rt.floor_level,
            s.name as server_name
        FROM dine_in_orders o
        LEFT JOIN restaurant_tables rt ON o.table_id = rt.id
        LEFT JOIN servers s ON o.server_id = s.id
        WHERE o.id = ?
    ";
    
    $stmt = $conn->prepare($order_sql);
    $stmt->bind_param('i', $order_id);
    $stmt->execute();
    $order_result = $stmt->get_result();
    $order = $order_result->fetch_assoc();
    $stmt->close();

    // Get order items with recipe and ingredients
    $items_sql = "
        SELECT 
            doi.id as item_id,
            doi.item_id as menu_item_id,
            doi.item_name,
            doi.quantity,
            doi.unit_price,
            doi.total_price,
            doi.status as item_status,
            doi.special_instructions,
            r.id as recipe_id,
            r.preparation_time,
            r.difficulty_level
        FROM dine_in_order_items doi
        LEFT JOIN recipes r ON doi.item_id = r.menu_item_id
        WHERE doi.dine_in_order_id = ?
        ORDER BY doi.created_at ASC
    ";
    
    $stmt = $conn->prepare($items_sql);
    $stmt->bind_param('i', $order_id);
    $stmt->execute();
    $items_result = $stmt->get_result();
    
    $items = [];
    while ($item = $items_result->fetch_assoc()) {
        // Get ingredients for this recipe if exists
        $ingredients = [];
        if ($item['recipe_id']) {
            $ing_sql = "
                SELECT 
                    ri.id,
                    ri.ingredient_id,
                    i.name as ingredient_name,
                    ri.quantity_required,
                    ri.unit,
                    i.current_stock,
                    i.unit as ingredient_unit,
                    (i.current_stock >= ri.quantity_required) as available
                FROM recipe_ingredients ri
                JOIN ingredients i ON ri.ingredient_id = i.id
                WHERE ri.recipe_id = ?
            ";
            
            $ing_stmt = $conn->prepare($ing_sql);
            $ing_stmt->bind_param('i', $item['recipe_id']);
            $ing_stmt->execute();
            $ing_result = $ing_stmt->get_result();
            
            while ($ingredient = $ing_result->fetch_assoc()) {
                $ingredients[] = $ingredient;
            }
            $ing_stmt->close();
        }
        
        $item['ingredients'] = $ingredients;
        $items[] = $item;
    }
    $stmt->close();

    // Calculate order metrics
    $ready_items = 0;
    $total_items = count($items);
    foreach ($items as $item) {
        if ($item['item_status'] === 'ready') {
            $ready_items++;
        }
    }

    sendResponse(true, 'KOT details retrieved successfully', [
        'kot' => [
            'id' => $kot['id'],
            'ticket_number' => $kot['ticket_number'],
            'status' => $kot['status'],
            'priority' => $kot['priority'],
            'generated_at' => $kot['generated_at'],
            'acknowledged_at' => $kot['acknowledged_at'],
            'started_at' => $kot['started_at'],
            'completed_at' => $kot['completed_at']
        ],
        'order' => [
            'id' => $order['id'],
            'order_number' => $order['order_number'],
            'table_number' => $order['table_number'],
            'section' => $order['section'],
            'floor' => $order['floor_level'],
            'server_name' => $order['server_name'],
            'status' => $order['status'],
            'total_amount' => $order['total_amount'],
            'special_requests' => $order['special_requests']
        ],
        'items' => $items,
        'summary' => [
            'total_items' => $total_items,
            'ready_items' => $ready_items,
            'pending_items' => $total_items - $ready_items,
            'completion_percentage' => round(($ready_items / $total_items) * 100, 1)
        ]
    ]);

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

$conn->close();
?>
