<?php
// /telefonia/api/wsproxy.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');

$url = 'wss://voice.zenvia.com:8089/ws';

// Se for uma requisição de upgrade (WebSocket)
if (isset($_SERVER['HTTP_UPGRADE']) && $_SERVER['HTTP_UPGRADE'] == 'websocket') {
    // Passar para o WebSocket real
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Upgrade: websocket',
        'Connection: Upgrade',
        'Sec-WebSocket-Key: ' . $_SERVER['HTTP_SEC_WEBSOCKET_KEY'],
        'Sec-WebSocket-Version: ' . $_SERVER['HTTP_SEC_WEBSOCKET_VERSION']
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    
    $response = curl_exec($ch);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $headers = substr($response, 0, $header_size);
    
    foreach (explode("\r\n", $headers) as $header) {
        if (!empty($header)) {
            header($header);
        }
    }
    
    echo substr($response, $header_size);
    curl_close($ch);
    exit;
}

echo json_encode(['error' => 'WebSocket upgrade required']);
?>