<?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;
$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 {
    // Verify that the table assignment belongs to this server and capture
    // the assignment timestamp for reassignment boundary checks.
    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';

    // 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;
    }

    // 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_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()
    ]);
}
