<?php
require __DIR__ . '/../../../../vendor/autoload.php';

use Ratchet\Client\Connector;
use React\EventLoop\Factory as LoopFactory;

$loop = LoopFactory::create();
$connector = new Connector($loop);

echo "Connecting to ws://localhost:8082...\n";

$connector('ws://localhost:8082')
    ->then(function(Ratchet\Client\WebSocket $conn) use ($loop) {
        echo "Connected! Sending test message...\n";

        $conn->on('message', function($msg) use ($conn) {
            echo "Received: {$msg}\n";
        });

        $conn->on('close', function($code = null, $reason = null) use ($loop) {
            echo "Connection closed ({$code}): {$reason}\n";
            $loop->stop();
        });

        // Send a ping or simple JSON
        $payload = json_encode([ 'type' => 'ping', 'ts' => time() ]);
        $conn->send($payload);

        // Close after short delay
        $loop->addTimer(2.0, function() use ($conn) { $conn->close(); });
    }, function(Exception $e) use ($loop) {
        echo "Could not connect: {$e->getMessage()}\n";
        $loop->stop();
    });

$loop->run();

