<?php
// server.php - اجرا: php server.php

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

require 'vendor/autoload.php';

class VoiceRoomServer implements MessageComponentInterface {
    protected $clients;
    protected $users;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
        $this->users = [];
        echo "✅ سرور اتاق صوتی شروع شد (پورت 8080)\n";
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
        echo "🔗 اتصال جدید\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        $data = json_decode($msg, true);
        echo "📨 پیام: " . $data['type'] . "\n";
        
        switch($data['type']) {
            case 'join':
                $this->users[$data['userId']] = [
                    'conn' => $from,
                    'username' => $data['username'],
                    'talking' => false
                ];
                
                // به همه اطلاع بده
                $this->broadcastToOthers($data['userId'], [
                    'type' => 'user_joined',
                    'user' => [
                        'userId' => $data['userId'],
                        'username' => $data['username']
                    ]
                ]);
                
                $this->sendUsersList($from);
                break;
                
            case 'talking':
                if(isset($this->users[$data['userId']])) {
                    $this->users[$data['userId']]['talking'] = true;
                    
                    $this->broadcastToOthers($data['userId'], [
                        'type' => 'talking',
                        'userId' => $data['userId']
                    ]);
                }
                break;
                
            case 'stopped_talking':
                if(isset($this->users[$data['userId']])) {
                    $this->users[$data['userId']]['talking'] = false;
                    
                    $this->broadcastToOthers($data['userId'], [
                        'type' => 'stopped_talking',
                        'userId' => $data['userId']
                    ]);
                }
                break;
                
            case 'chat':
                $this->broadcastToAll([
                    'type' => 'chat',
                    'username' => $data['username'],
                    'message' => $data['message']
                ]);
                break;
                
            case 'get_users':
                $this->sendUsersList($from);
                break;
                
            case 'leave':
                if(isset($this->users[$data['userId']])) {
                    $this->broadcastToOthers($data['userId'], [
                        'type' => 'user_left',
                        'userId' => $data['userId']
                    ]);
                    
                    unset($this->users[$data['userId']]);
                }
                break;
        }
    }

    public function onClose(ConnectionInterface $conn) {
        // پیدا و حذف کاربر
        foreach($this->users as $userId => $user) {
            if($user['conn'] === $conn) {
                $this->broadcastToOthers($userId, [
                    'type' => 'user_left',
                    'userId' => $userId
                ]);
                
                unset($this->users[$userId]);
                break;
            }
        }
        
        $this->clients->detach($conn);
        echo "❌ اتصال بسته شد\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "🚨 خطا: " . $e->getMessage() . "\n";
        $conn->close();
    }
    
    private function sendUsersList($conn) {
        $usersList = [];
        foreach($this->users as $userId => $user) {
            $usersList[] = [
                'userId' => $userId,
                'username' => $user['username']
            ];
        }
        
        $conn->send(json_encode([
            'type' => 'users',
            'users' => $usersList
        ]));
    }
    
    private function broadcastToAll($data) {
        $msg = json_encode($data);
        foreach($this->clients as $client) {
            $client->send($msg);
        }
    }
    
    private function broadcastToOthers($excludeUserId, $data) {
        $msg = json_encode($data);
        foreach($this->users as $userId => $user) {
            if($userId !== $excludeUserId) {
                $user['conn']->send($msg);
            }
        }
    }
}

// اجرای سرور
$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new VoiceRoomServer()
        )
    ),
    8080
);

$server->run();