<?php
/**
 * Server Get Table Orders API
 * Fetches existing orders for a table to allow servers to add more items
 */

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 = $_SESSION['server_id'];
$table_id = isset($_GET['table_id']) ? (int)$_GET['table_id'] : null;
$customer_id = isset($_GET['customer_id']) ? (int)$_GET['customer_id'] : null;
$requested_assignment_id = isset($_GET['assignment_id']) ? (int)$_GET['assignment_id'] : null;
$table_source = isset($_GET['table_source']) ? strtolower(trim($_GET['table_source'])) : 'restaurant';
$is_online_source = ($table_source === 'online');
$use_strict_assignment = ($requested_assignment_id && $requested_assignment_id > 0);

if (!$table_id) {
    echo json_encode([
        'success' => false,
        'message' => 'Table ID is required'
    ]);
    exit;
}

try {
    $order_source_table = 'restaurant';
    $order_source_table_id = $table_id;
    $order_source_assignment_id = 0;

    // Verify that the table assignment belongs to this server and capture
    // the assignment timestamp for reassignment boundary checks.
    if ($is_online_source) {
        if ($requested_assignment_id && $requested_assignment_id > 0) {
            $stmt = $conn->prepare("
                SELECT otb.id, otb.allocated_at AS assigned_at
                FROM online_table_bookings otb
                WHERE otb.id = ?
                  AND otb.online_table_id = ?
                  AND otb.assigned_server_id = ?
                  AND otb.allocation_status = 'allocated'
                LIMIT 1
            ");
            $stmt->bind_param('iii', $requested_assignment_id, $table_id, $server_id);
        } else {
            $stmt = $conn->prepare("
                SELECT otb.id, otb.allocated_at AS assigned_at
                FROM online_table_bookings otb
                WHERE otb.online_table_id = ?
                  AND otb.assigned_server_id = ?
                  AND otb.allocation_status = 'allocated'
                ORDER BY otb.allocated_at DESC
                LIMIT 1
            ");
            $stmt->bind_param('ii', $table_id, $server_id);
        }
    } else {
        if ($requested_assignment_id && $requested_assignment_id > 0) {
            $stmt = $conn->prepare("
                SELECT ta.id, ta.assigned_at
                FROM table_assignments ta
                WHERE ta.id = ? AND ta.table_id = ? AND ta.server_id = ? AND ta.status = 'assigned'
                LIMIT 1
            ");
            $stmt->bind_param('iii', $requested_assignment_id, $table_id, $server_id);
        } else {
            $stmt = $conn->prepare("
                SELECT ta.id, ta.assigned_at
                FROM table_assignments ta
                WHERE ta.table_id = ? AND ta.server_id = ? AND ta.status = 'assigned'
                ORDER BY ta.assigned_at DESC
                LIMIT 1
            ");
            $stmt->bind_param('ii', $table_id, $server_id);
        }
    }
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Table not assigned to this server'
        ]);
        exit;
    }

    $assignment = $result->fetch_assoc();
    $assignment_id = (int)$assignment['id'];
    $assigned_at = $assignment['assigned_at'] ?: '1970-01-01 00:00:00';
    $order_source_table = $is_online_source ? 'online' : 'restaurant';
    $order_source_table_id = $table_id;
    $order_source_assignment_id = $assignment_id;

    // Prefer explicit assignment binding when available.
    $has_assignment_id_col = false;
    $assignment_col_check = $conn->query("SHOW COLUMNS FROM dine_in_orders LIKE 'assignment_id'");
    if ($assignment_col_check && $assignment_col_check->num_rows > 0) {
        $has_assignment_id_col = true;
    }
    $has_source_cols = false;
    $source_col_check = $conn->query("SHOW COLUMNS FROM dine_in_orders LIKE 'source_table_id'");
    $source_assign_col_check = $conn->query("SHOW COLUMNS FROM dine_in_orders LIKE 'source_assignment_id'");
    $source_type_col_check = $conn->query("SHOW COLUMNS FROM dine_in_orders LIKE 'table_source'");
    if ($source_col_check && $source_col_check->num_rows > 0 &&
        $source_assign_col_check && $source_assign_col_check->num_rows > 0 &&
        $source_type_col_check && $source_type_col_check->num_rows > 0) {
        $has_source_cols = true;
    }

    // Get the latest ACTIVE order that belongs to this server and was created
    // after the current assignment time. This prevents showing orders from:
    // 1) a previous server assigned to this table
    // 2) an older assignment cycle for the same server
    // If customer_id is provided, filter to only orders for that customer
    if ($has_source_cols) {
        if ($customer_id) {
            $stmt = $conn->prepare("
                SELECT id, status FROM dine_in_orders
                WHERE server_id = ?
                  AND table_source = ?
                  AND source_table_id = ?
                  AND source_assignment_id = ?
                  AND customer_id = ?
                  AND status IN ('pending', 'confirmed', 'preparing', 'ready', 'completed')
                ORDER BY created_at DESC LIMIT 1
            ");
            $stmt->bind_param('isiii', $server_id, $order_source_table, $order_source_table_id, $order_source_assignment_id, $customer_id);
        } else {
            $stmt = $conn->prepare("
                SELECT id, status FROM dine_in_orders
                WHERE server_id = ?
                  AND table_source = ?
                  AND source_table_id = ?
                  AND source_assignment_id = ?
                  AND status IN ('pending', 'confirmed', 'preparing', 'ready', 'completed')
                ORDER BY created_at DESC LIMIT 1
            ");
            $stmt->bind_param('isii', $server_id, $order_source_table, $order_source_table_id, $order_source_assignment_id);
        }
    } else if ($has_assignment_id_col) {
        // Primary path: assignment_id is authoritative.
        if ($use_strict_assignment) {
            if ($customer_id) {
                $stmt = $conn->prepare("
                    SELECT id, status FROM dine_in_orders 
                    WHERE table_id = ?
                      AND server_id = ?
                      AND customer_id = ?
                      AND assignment_id = ?
                      AND status IN ('pending', 'confirmed', 'preparing', 'ready', 'completed')
                    ORDER BY created_at DESC LIMIT 1
                ");
                $stmt->bind_param('iiii', $table_id, $server_id, $customer_id, $assignment_id);
            } else {
                $stmt = $conn->prepare("
                    SELECT id, status FROM dine_in_orders 
                    WHERE table_id = ?
                      AND server_id = ?
                      AND assignment_id = ?
                      AND status IN ('pending', 'confirmed', 'preparing', 'ready', 'completed')
                    ORDER BY created_at DESC LIMIT 1
                ");
                $stmt->bind_param('iii', $table_id, $server_id, $assignment_id);
            }
        } else if ($customer_id) {
            // Legacy fallback: older rows with NULL assignment_id still use assigned_at boundary.
            $stmt = $conn->prepare("
                SELECT id, status FROM dine_in_orders 
                WHERE table_id = ?
                  AND server_id = ?
                  AND customer_id = ?
                  AND status IN ('pending', 'confirmed', 'preparing', 'ready', 'completed')
                  AND (
                        assignment_id = ?
                        OR (assignment_id IS NULL AND created_at >= ?)
                  )
                ORDER BY created_at DESC LIMIT 1
            ");
            $stmt->bind_param('iiisis', $table_id, $server_id, $customer_id, $assignment_id, $assigned_at);
        } else {
            $stmt = $conn->prepare("
                SELECT id, status FROM dine_in_orders 
                WHERE table_id = ?
                  AND server_id = ?
                  AND status IN ('pending', 'confirmed', 'preparing', 'ready', 'completed')
                  AND (
                        assignment_id = ?
                        OR (assignment_id IS NULL AND created_at >= ?)
                  )
                ORDER BY created_at DESC LIMIT 1
            ");
            $stmt->bind_param('iiis', $table_id, $server_id, $assignment_id, $assigned_at);
        }
    } else {
        // Legacy path for databases not yet migrated.
        if ($customer_id) {
            $stmt = $conn->prepare("
                SELECT id, status FROM dine_in_orders 
                WHERE table_id = ?
                  AND server_id = ?
                  AND customer_id = ?
                  AND created_at >= ?
                  AND status IN ('pending', 'confirmed', 'preparing', 'ready', 'completed')
                ORDER BY created_at DESC LIMIT 1
            ");
            $stmt->bind_param('iiis', $table_id, $server_id, $customer_id, $assigned_at);
        } else {
            $stmt = $conn->prepare("
                SELECT id, status FROM dine_in_orders 
                WHERE table_id = ?
                  AND server_id = ?
                  AND created_at >= ?
                  AND status IN ('pending', 'confirmed', 'preparing', 'ready', 'completed')
                ORDER BY created_at DESC LIMIT 1
            ");
            $stmt->bind_param('iis', $table_id, $server_id, $assigned_at);
        }
    }
    $stmt->execute();
    $orderResult = $stmt->get_result();
    
    if ($orderResult->num_rows === 0) {
        // No active order exists
        echo json_encode([
            'success' => true,
            'has_existing_order' => false,
            'order_id' => null,
            'items' => [],
            'order_status' => null
        ]);
        exit;
    }
    
    $order = $orderResult->fetch_assoc();
    $order_id = $order['id'];
    
    // Get all items in the existing order with their status
    // Include is_reorder flag so frontend can properly distinguish reordered items from served items
    $stmt = $conn->prepare("
        SELECT id, item_id, item_name, quantity, unit_price, status, is_reorder 
        FROM dine_in_order_items 
        WHERE dine_in_order_id = ?
        ORDER BY id ASC
    ");
    $stmt->bind_param('i', $order_id);
    $stmt->execute();
    $itemsResult = $stmt->get_result();
    
    $items = [];
    while ($item = $itemsResult->fetch_assoc()) {
        $items[] = [
            'row_id' => (int)$item['id'],  // Add the database row ID for specific tracking
            'id' => (int)$item['item_id'],
            'quantity' => (int)$item['quantity'],
            'name' => $item['item_name'],  // Include item name from database
            'unit_price' => (float)$item['unit_price'],  // Preserve historical price even if menu changes
            'status' => $item['status'],  // Include item status from database
            'is_reorder' => (bool)$item['is_reorder'],  // Flag to indicate reordered items
            'served' => ($item['status'] === 'served' ? true : false)  // Convert status to served boolean
        ];
    }
    
    echo json_encode([
        'success' => true,
        'has_existing_order' => true,
        'order_id' => (int)$order_id,
        'order_status' => $order['status'],
        'items' => $items
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
