<?php
/**
 * Server Get Ready Orders API
 * Fetches orders that are ready for pickup for the current server
 */

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

// Check server authentication
if (!isset($_SESSION['server_id'])) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access'
    ]);
    exit;
}

$server_id = (int)$_SESSION['server_id'];

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

    // Create notification table if it doesn't exist
    $check_notif = "CREATE TABLE IF NOT EXISTS order_notifications (
        id INT PRIMARY KEY AUTO_INCREMENT,
        order_id INT NOT NULL,
        server_id INT NOT NULL,
        item_id INT NULL,
        notification_type VARCHAR(50) DEFAULT 'ready',
        message TEXT,
        is_read INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        KEY idx_server_read (server_id, is_read),
        KEY idx_order (order_id)
    )";
    @$conn->query($check_notif);

    
    // Get all ready orders for this server
    $sql = "SELECT 
            o.id,
            o.order_number,
            o.table_id,
            $tableExpr AS table_number,
            $sectionExpr AS section,
            o.total_amount,
            o.status,
            o.created_at
        FROM dine_in_orders o
        LEFT JOIN restaurant_tables rt ON o.table_id = rt.id
        $onlineJoin
        WHERE o.server_id = $server_id 
            AND EXISTS (
                SELECT 1 FROM dine_in_order_items WHERE dine_in_order_id = o.id AND status = 'ready'
            )
        ORDER BY o.created_at DESC";
    
    $result = $conn->query($sql);
    
    if (!$result) {
        throw new Exception('Query failed: ' . $conn->error);
    }
    
    $ready_orders = [];
    while ($row = $result->fetch_assoc()) {
        // Get item count and summary for this order
        $item_sql = "SELECT 
                        COUNT(*) as item_count,
                        GROUP_CONCAT(CONCAT(item_name, ' (x', quantity, ')') SEPARATOR ', ') as items_summary,
                        COALESCE(SUM(total_price), 0) as total_price
                    FROM dine_in_order_items 
                    WHERE dine_in_order_id = " . (int)$row['id'] . " AND status = 'ready'";
        
        $item_result = $conn->query($item_sql);
        if (!$item_result) {
            continue; // Skip this order if query fails
        }
        
        $item_data = $item_result->fetch_assoc();
        
        $ready_orders[] = [
            'id' => (int)$row['id'],
            'order_number' => $row['order_number'],
            'table_id' => (int)$row['table_id'],
            'table_number' => $row['table_number'] ?? 'N/A',
            'section' => $row['section'] ?? 'N/A',
            'total_amount' => (float)($item_data['total_price'] ?? 0),
            'item_count' => (int)($item_data['item_count'] ?? 0),
            'items_summary' => $item_data['items_summary'] ?? '',
            'created_at' => $row['created_at']
        ];
    }
    
    // Get unread notifications count
    $unread_count = 0;
    $notif_sql = "SELECT COUNT(*) as unread FROM order_notifications 
                  WHERE server_id = $server_id AND is_read = 0 
                  AND notification_type IN ('ready', 'item_ready')";
    
    $notif_result = $conn->query($notif_sql);
    if ($notif_result) {
        $notif_data = $notif_result->fetch_assoc();
        $unread_count = (int)($notif_data['unread'] ?? 0);
    }
    
    echo json_encode([
        'success' => true,
        'data' => $ready_orders,
        'count' => count($ready_orders),
        'unread_notifications' => $unread_count
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    error_log('Ready orders error: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error loading ready orders: ' . $e->getMessage()
    ]);
}
?>
