<?php
/**
 * Send Order to Manager API
 * Allows servers to send completed orders to manager for billing
 */

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'];
$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'];
$table_id = isset($input['table_id']) ? (int)$input['table_id'] : null;
$table_number = isset($input['table_number']) ? $input['table_number'] : '';

try {
    // Verify order ownership
    $verify_sql = "SELECT id, server_id, status, table_id, total_amount FROM dine_in_orders WHERE id = $order_id AND server_id = $server_id";
    $result = $conn->query($verify_sql);
    
    if (!$result || $result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Order not found or not assigned to you']);
        exit;
    }
    
    $order_data = $result->fetch_assoc();
    
    // Update order status to 'ready' to indicate it's ready for billing
    $update_sql = "UPDATE dine_in_orders SET status = 'ready', updated_at = NOW() WHERE id = $order_id";
    
    if (!$conn->query($update_sql)) {
        echo json_encode(['success' => false, 'message' => 'Error updating order status: ' . $conn->error]);
        exit;
    }
    
    // Get all items in the order for reference
    $items_sql = "SELECT id, item_id, item_name, quantity, unit_price, total_price, status FROM dine_in_order_items WHERE dine_in_order_id = $order_id";
    $items_result = $conn->query($items_sql);
    $items = [];
    
    if ($items_result) {
        while ($item = $items_result->fetch_assoc()) {
            $items[] = $item;
        }
    }
    
    // Create a notification entry for the manager (optional - stores in a notifications table if it exists)
    // This is for audit trail and manager notifications
    $notification_sql = "INSERT INTO manager_notifications 
                        (manager_id, order_id, table_id, table_number, server_id, notification_type, status, created_at) 
                        SELECT id, " . $order_id . ", " . $table_id . ", '" . $conn->real_escape_string($table_number) . "', " . $server_id . ", 'order_ready_for_billing', 'unread', NOW()
                        FROM managers LIMIT 1";
    
    // Only execute if the manager_notifications table exists
    $check_table = $conn->query("SHOW TABLES LIKE 'manager_notifications'");
    if ($check_table && $check_table->num_rows > 0) {
        $conn->query($notification_sql);
    }
    
    // Return success response
    echo json_encode([
        'success' => true,
        'message' => 'Order sent to manager for billing',
        'data' => [
            'order_id' => $order_id,
            'table_id' => $table_id,
            'table_number' => $table_number,
            'status' => 'ready',
            'items_count' => count($items),
            'total_amount' => $order_data['total_amount']
        ]
    ]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

$conn->close();
?>
