<?php

namespace app\ws;

use think\facade\Db;

require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/./include/config.php';

echo WS_URL;
Db::setConfig([
    // 默認數據連接標識
    'default'     => 'mysql',
    // 數據庫連接信息
    'connections' => [
        'mysql' => [
            // 數據庫類型
            'type'     => 'mysql',
            // 主機地址
            'hostname' => '127.0.0.1',
            // 用户名
            'username' => 'shop_h888_fun',
            'password' => 'h52DHfyG5rXkXTfJ',
            // 數據庫名
            'database' => 'shop_h888_fun',
            // 數據庫編碼默認採用utf8
            'charset'  => 'utf8mb4',
            // 數據庫表前綴
            'prefix'   => 'ecs_',
            // 數據庫調試模式
            'debug'    => true,
        ],
    ],
]);

$redis = new \Redis();

$redis->connect('127.0.0.1', 6379);

// $server = new \Swoole\Websocket\Server('0.0.0.0', 9501);
$server = new \Swoole\Websocket\Server("0.0.0.0", 8443, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);

$server->set([
    'daemonize' => false, //守護進程化。
    //配置SSL證書和密鑰路徑
    'ssl_cert_file' => "/www/server/panel/vhost/cert/".WS_URL."/fullchain.pem",
    'ssl_key_file'  => "/www/server/panel/vhost/cert/".WS_URL."/privkey.pem"
]);

     // 定義路由映射表
$routes = [
    'init' => 'app\\ws\\handleInit',
    'use' => 'app\\ws\\handleUse',
];

$server->on('start', function ($server) {
    echo "Websocket Server is started at ws://0.0.0.0:9501\n";
});

$server->on('open', function ($server, $req) {
    echo "connection open: {$req->fd}\n";
});

$server->on('message', function ($server, $frame) use (&$routes) {
    echo "received message: {$frame->data}\n";
    // $server->push($frame->fd, json_encode(['hello', 'world']));
    $message = json_decode($frame->data, true);
    if (isset($message['action']) && isset($routes[$message['action']])) {
        $action = $message['action'];
        $payload = $message['payload'];

        $handler = $routes[$action];

        $handler($server, $frame->fd, $payload);
    } else {
        // 處理未知路由或錯誤情況
        $server->push($frame->fd, json_encode(['error' => 'Invalid action']));
    }
});

$server->on('close', function ($server, $fd) use ($redis){
    $conns = $redis->keys('sn:*');

    foreach ($conns as $connKey) {
        $bonus_sn = str_replace('sn:', '', $connKey);
        $redis->sRem($connKey, $fd);
        echo "Client #$fd left sn: $bonus_sn \n";
    }    
});

function handleInit($server, $fd, $payload)
{
    // 將$payload 存入redis
    global $redis;
    $redis->sAdd('sn:' . $payload, $fd);
}

function handleUse($server, $fd, $payload)
{
    global $redis;

    // 從 Redis 中獲取該序號所有連接
    $connections = $redis->sMembers('sn:' . $payload);

    // 廣播消息到房間中的所有連接
    foreach ($connections as $fd) {
        $server->push($fd, json_encode(['action' => 'use', 'sn' => $payload]));
    }
}
$server->start();
