<?php
// websocket/server.php
require_once '../vendor/autoload.php'; // Установите Ratchet: composer require ratchet/pawl

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;

class ChatServer implements MessageComponentInterface {
    protected $clients;
    protected $chatRooms;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
        $this->chatRooms = [];
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
        echo "Новое подключение: {$conn->resourceId}\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        $data = json_decode($msg, true);
        
        switch ($data['type']) {
            case 'join':
                $this->joinRoom($from, $data['chatId'], $data['userId']);
                break;
            case 'message':
                $this->broadcastMessage($data);
                break;
        }
    }

    private function joinRoom($conn, $chatId, $userId) {
        if (!isset($this->chatRooms[$chatId])) {
            $this->chatRooms[$chatId] = [];
        }
        $this->chatRooms[$chatId][$conn->resourceId] = $conn;
        $conn->chatId = $chatId;
        $conn->userId = $userId;
    }

    private function broadcastMessage($data) {
        $chatId = $data['chatId'];
        if (isset($this->chatRooms[$chatId])) {
            foreach ($this->chatRooms[$chatId] as $client) {
                $client->send(json_encode([
                    'type' => 'newMessage',
                    'message' => $data['message'],
                    'username' => $data['username'],
                    'timestamp' => date('Y-m-d H:i:s')
                ]));
            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
        if (isset($conn->chatId) && isset($this->chatRooms[$conn->chatId][$conn->resourceId])) {
            unset($this->chatRooms[$conn->chatId][$conn->resourceId]);
        }
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "Ошибка: {$e->getMessage()}\n";
        $conn->close();
    }
}

// Запуск сервера
$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new ChatServer()
        )
    ),
    8080
);

echo "WebSocket сервер запущен на порту 8080\n";
$server->run();
?>