<?php
require_once 'auth/session.php';
header('Content-Type: application/json');

$user = getCurrentUser();
if (!$user) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $channel_id = $_POST['channel_id'] ?? null;

    if ($action === 'join' && $channel_id) {
        $stmt = db()->prepare("INSERT INTO voice_sessions (user_id, channel_id) VALUES (?, ?) ON DUPLICATE KEY UPDATE channel_id = ?");
        $stmt->execute([$user['id'], $channel_id, $channel_id]);
        echo json_encode(['success' => true]);
    } elseif ($action === 'leave') {
        $stmt = db()->prepare("DELETE FROM voice_sessions WHERE user_id = ?");
        $stmt->execute([$user['id']]);
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Invalid action']);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $action = $_GET['action'] ?? '';
    if ($action === 'sessions') {
        $stmt = db()->prepare("
            SELECT vs.channel_id, vs.user_id, u.username, u.display_name, u.avatar_url 
            FROM voice_sessions vs
            JOIN users u ON vs.user_id = u.id
        ");
        $stmt->execute();
        $sessions = $stmt->fetchAll();
        echo json_encode(['success' => true, 'sessions' => $sessions]);
        exit;
    }
}

echo json_encode(['success' => false, 'error' => 'Invalid request']);
