<?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 {
    // Get order details
    $order_sql = "
        SELECT 
            o.id,
            o.order_number,
            o.table_id,
            rt.table_number,
            rt.section,
            rt.floor_level,
            rt.base_capacity 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
        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 
                id,
                item_id,
                item_name,
                quantity,
                unit_price,
                total_price,
                status,
                is_reorder,
                special_instructions,
                created_at
            FROM dine_in_order_items
            WHERE dine_in_order_id = $order_id
            ORDER BY created_at ASC
        ";
    } else {
        // For kitchen view - show only items that need preparation (not ready/served from previous cycles)
        $items_sql = "
            SELECT 
                id,
                item_id,
                item_name,
                quantity,
                unit_price,
                total_price,
                status,
                is_reorder,
                special_instructions,
                created_at
            FROM dine_in_order_items
            WHERE dine_in_order_id = $order_id AND status IN ('pending', 'preparing')
            ORDER BY 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']
        ];
    }
    
    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']
        ],
        'items' => $items,
        'item_count' => count($items)
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
