<?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';
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['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 {
    $hasDisplayTable = false;
    $hasSourceCols = false;
    $col = $conn->query("SHOW COLUMNS FROM dine_in_orders LIKE 'display_table_number'");
    if ($col && $col->num_rows > 0) $hasDisplayTable = true;
    $col1 = $conn->query("SHOW COLUMNS FROM dine_in_orders LIKE 'table_source'");
    $col2 = $conn->query("SHOW COLUMNS FROM dine_in_orders LIKE 'source_table_id'");
    if ($col1 && $col1->num_rows > 0 && $col2 && $col2->num_rows > 0) $hasSourceCols = true;

    $tableExpr = $hasDisplayTable
        ? "COALESCE(o.display_table_number, ot.table_number, rt.table_number)"
        : "COALESCE(ot.table_number, rt.table_number)";
    $sectionExpr = "COALESCE(ot.section, rt.section)";
    $floorExpr = "COALESCE(ot.floor_level, rt.floor_level)";
    $onlineJoin = $hasSourceCols
        ? "LEFT JOIN online_tables ot ON o.table_source = 'online' AND o.source_table_id = ot.id"
        : "LEFT JOIN online_tables ot ON 1 = 0";

    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'];

    $order_sql = "
        SELECT
            o.id,
            o.order_number,
            o.table_id,
            o.server_id,
            o.total_amount,
            o.status,
            o.special_requests,
            $tableExpr AS table_number,
            $sectionExpr AS section,
            $floorExpr AS floor_level,
            s.name as server_name
        FROM dine_in_orders o
        LEFT JOIN restaurant_tables rt ON o.table_id = rt.id
        $onlineJoin
        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();

    $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()) {
        $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
                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()) {
                $availability = calculateIngredientAvailability(
                    $ingredient['current_stock'],
                    $ingredient['ingredient_unit'],
                    $ingredient['quantity_required'],
                    $ingredient['unit']
                );
                $ingredient['available'] = $availability['in_stock'];
                $ingredient['quantity_required_in_stock_unit'] = $availability['required_quantity_in_stock_unit'];
                $ingredient['shortage_amount'] = $availability['shortage_amount'];
                $ingredients[] = $ingredient;
            }
            $ing_stmt->close();
        }

        $item['ingredients'] = $ingredients;
        $items[] = $item;
    }
    $stmt->close();

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