<?php
/**
 * Kitchen Get Order Details API
 * Fetches details of a specific order including all items
 */

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

$input = json_decode(file_get_contents('php://input'), true);

if (!$input || !isset($input['order_id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request. Missing order_id.']);
    exit;
}

$order_id = (int)$input['order_id'];
$include_all_items = isset($input['include_all_items']) ? (bool)$input['include_all_items'] : false;

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)";
    $capacityExpr = "COALESCE(ot.base_capacity, rt.base_capacity)";
    $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";

    // Get order details
    $order_sql = "
        SELECT 
            o.id,
            o.order_number,
            o.table_id,
            $tableExpr AS table_number,
            $sectionExpr AS section,
            $floorExpr AS floor_level,
            $capacityExpr AS capacity,
            o.server_id,
            s.name as server_name,
            o.total_amount,
            o.status,
            o.special_requests,
            o.notes,
            o.created_at
        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 = $order_id
    ";
    
    $order_result = $conn->query($order_sql);
    
    if (!$order_result || $order_result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Order not found']);
        exit;
    }
    
    $order_data = $order_result->fetch_assoc();
    
    // Get order items - filter based on context
    // When include_all_items is true (for billing), return all items
    // Otherwise, return only items that need kitchen preparation (pending/preparing)
    if ($include_all_items) {
        // For billing and server review - show ALL items
        $items_sql = "
            SELECT 
                oi.id,
                oi.item_id,
                oi.item_name,
                oi.quantity,
                oi.unit_price,
                oi.total_price,
                oi.status,
                oi.is_reorder,
                oi.special_instructions,
                oi.created_at,
                mi.image_path
            FROM dine_in_order_items oi
            LEFT JOIN menu_items mi ON oi.item_id = mi.id
            WHERE oi.dine_in_order_id = $order_id
            ORDER BY oi.created_at ASC
        ";
    } else {
        // For kitchen view - show only items that need preparation (not ready/served from previous cycles)
        $items_sql = "
            SELECT 
                oi.id,
                oi.item_id,
                oi.item_name,
                oi.quantity,
                oi.unit_price,
                oi.total_price,
                oi.status,
                oi.is_reorder,
                oi.special_instructions,
                oi.created_at,
                mi.image_path
            FROM dine_in_order_items oi
            LEFT JOIN menu_items mi ON oi.item_id = mi.id
            WHERE oi.dine_in_order_id = $order_id AND oi.status IN ('pending', 'preparing')
            ORDER BY oi.created_at ASC
        ";
    }
    
    $items_result = $conn->query($items_sql);
    
    if (!$items_result) {
        throw new Exception('Failed to fetch items: ' . $conn->error);
    }
    
    $items = [];
    while ($row = $items_result->fetch_assoc()) {
        $items[] = [
            'id' => (int)$row['id'],
            'item_id' => (int)$row['item_id'],
            'item_name' => $row['item_name'],
            'quantity' => (int)$row['quantity'],
            'unit_price' => (float)$row['unit_price'],
            'total_price' => (float)$row['total_price'],
            'status' => $row['status'],
            'is_reorder' => (bool)$row['is_reorder'],
            'special_instructions' => $row['special_instructions'],
            'created_at' => $row['created_at'],
            'image_path' => $row['image_path']
        ];
    }

    // Get latest KOT for this order (if available)
    $kot_sql = "
        SELECT id, ticket_number, status, priority, generated_at, acknowledged_at, started_at, completed_at
        FROM kot_tickets
        WHERE order_id = ?
        ORDER BY id DESC
        LIMIT 1
    ";
    $kot_stmt = $conn->prepare($kot_sql);
    $kot_data = null;
    if ($kot_stmt) {
        $kot_stmt->bind_param('i', $order_id);
        $kot_stmt->execute();
        $kot_result = $kot_stmt->get_result();
        if ($kot_result && $kot_result->num_rows > 0) {
            $kot = $kot_result->fetch_assoc();
            $kot_data = [
                'id' => (int)$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'],
                'print_url' => '../backend/print_kot.php?kot_id=' . (int)$kot['id']
            ];
        }
        $kot_stmt->close();
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Order details fetched successfully',
        'order' => [
            'id' => (int)$order_data['id'],
            'order_number' => $order_data['order_number'],
            'table_id' => (int)$order_data['table_id'],
            'table_number' => $order_data['table_number'],
            'section' => $order_data['section'],
            'floor' => $order_data['floor_level'],
            'capacity' => (int)$order_data['capacity'],
            'server_id' => (int)$order_data['server_id'],
            'server_name' => $order_data['server_name'],
            'total_amount' => (float)$order_data['total_amount'],
            'status' => $order_data['status'],
            'special_requests' => $order_data['special_requests'],
            'notes' => $order_data['notes'],
            'created_at' => $order_data['created_at'],
            'kot' => $kot_data
        ],
        'items' => $items,
        'item_count' => count($items)
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
