<?php
/**
 * Kitchen Get Pending Orders API
 * Fetches all active kitchen orders, including ready orders awaiting server pickup
 */

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

// This is a public API for kitchen staff (can be accessed with kitchen_id, or admin authentication)
// For now, we'll allow basic authentication

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";

    $completed_today_sql = "
        SELECT COUNT(*) AS completed_count
        FROM dine_in_orders o
        WHERE DATE(o.created_at) = CURDATE()
          AND EXISTS (
              SELECT 1
              FROM dine_in_order_items oi
              WHERE oi.dine_in_order_id = o.id
                AND oi.status IN ('ready', 'served')
          )
          AND NOT EXISTS (
              SELECT 1
              FROM dine_in_order_items oi
              WHERE oi.dine_in_order_id = o.id
                AND oi.status IN ('pending', 'preparing')
          )
    ";
    $completed_today_result = $conn->query($completed_today_sql);
    $completed_today_count = 0;
    if ($completed_today_result) {
        $completed_today_row = $completed_today_result->fetch_assoc();
        $completed_today_count = (int)($completed_today_row['completed_count'] ?? 0);
    }

    // Get all orders that are still relevant to kitchen flow.
    // Confirmed/preparing orders show kitchen-active rows.
    // Ready orders show the ready rows that are awaiting server pickup.
    $sql = "
        SELECT 
            o.id,
            o.order_number,
            o.table_id,
            $tableExpr AS table_number,
            $sectionExpr AS section,
            $floorExpr AS floor_level,
            o.server_id,
            s.name as server_name,
            o.total_amount,
            o.status,
            o.special_requests,
            o.created_at,
            kt.id as kot_id,
            kt.ticket_number as kot_ticket_number,
            kt.priority as kot_priority,
            kt.status as kot_status,
            kt.generated_at as kot_generated_at
        FROM dine_in_orders o
        LEFT JOIN restaurant_tables rt ON o.table_id = rt.id
        $onlineJoin
        LEFT JOIN (
            SELECT t1.*
            FROM kot_tickets t1
            INNER JOIN (
                SELECT order_id, MAX(id) AS latest_id
                FROM kot_tickets
                GROUP BY order_id
            ) t2 ON t1.id = t2.latest_id
        ) kt ON kt.order_id = o.id
        LEFT JOIN servers s ON o.server_id = s.id
        WHERE o.status IN ('confirmed', 'preparing', 'ready')
            AND EXISTS (
                SELECT 1
                FROM dine_in_order_items oi
                WHERE oi.dine_in_order_id = o.id
                  AND (
                    oi.status IN ('pending', 'preparing')
                    OR (o.status = 'ready' AND oi.status = 'ready')
                  )
            )
        ORDER BY o.created_at ASC
    ";
    
    $result = $conn->query($sql);
    
    if (!$result) {
        throw new Exception('Database query failed: ' . $conn->error);
    }
    
    $orders = [];
    while ($row = $result->fetch_assoc()) {
        $order_id = (int)$row['id'];
        $items = [];
        $item_status_filter = $row['status'] === 'ready'
            ? "oi.status = 'ready'"
            : "oi.status IN ('pending', 'preparing')";

        $items_sql = "
            SELECT 
                oi.id,
                oi.item_id,
                oi.item_name,
                oi.quantity,
                oi.status,
                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 = ? AND $item_status_filter
            ORDER BY oi.created_at ASC, oi.id ASC
        ";
        $items_stmt = $conn->prepare($items_sql);

        if ($items_stmt) {
            $items_stmt->bind_param('i', $order_id);
            $items_stmt->execute();
            $items_result = $items_stmt->get_result();

            while ($item = $items_result->fetch_assoc()) {
                $items[] = [
                    'id' => (int)$item['id'],
                    'item_id' => (int)$item['item_id'],
                    'item_name' => $item['item_name'],
                    'quantity' => (int)$item['quantity'],
                    'status' => $item['status'],
                    'image_path' => $item['image_path']
                ];
            }

            $items_stmt->close();
        }

        $orders[] = [
            'id' => $order_id,
            'order_number' => $row['order_number'],
            'table_id' => (int)$row['table_id'],
            'table_number' => $row['table_number'],
            'section' => $row['section'],
            'floor' => $row['floor_level'],
            'server_id' => (int)$row['server_id'],
            'server_name' => $row['server_name'],
            'total_amount' => (float)$row['total_amount'],
            'status' => $row['status'],
            'special_requests' => $row['special_requests'],
            'kot_id' => !empty($row['kot_id']) ? (int)$row['kot_id'] : null,
            'kot_ticket_number' => $row['kot_ticket_number'] ?? null,
            'kot_priority' => $row['kot_priority'] ?? null,
            'kot_status' => $row['kot_status'] ?? null,
            'kot_generated_at' => $row['kot_generated_at'] ?? null,
            'item_count' => count($items),
            'items_summary' => implode(', ', array_map(function ($item) {
                return $item['item_name'] . ' (x' . $item['quantity'] . ')';
            }, $items)),
            'items' => $items,
            'created_at' => $row['created_at']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Orders fetched successfully',
        'data' => $orders,
        'count' => count($orders),
        'completed_count' => $completed_today_count
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
