<?php
require_once __DIR__ . '/session.php';

$user = getCurrentUser();
if ($user) {
    try {
        // Find which channel and peer they were in to clean up files too
        $stmt = db()->prepare("SELECT channel_id, peer_id FROM voice_sessions WHERE user_id = ?");
        $stmt->execute([$user['id']]);
        $sess = $stmt->fetch();
        
        if ($sess) {
            $room = $sess['channel_id'];
            $peerId = $sess['peer_id'];
            
            // Clean up file-based participants
            $p_file = __DIR__ . "/../data/" . $room . ".participants.json";
            if (file_exists($p_file)) {
                $raw = @file_get_contents($p_file);
                if ($raw) {
                    $ps = json_decode($raw, true);
                    if (is_array($ps)) {
                        $found = false;
                        if (isset($ps[$peerId])) {
                            unset($ps[$peerId]);
                            $found = true;
                        }
                        // Also cleanup by user_id just in case
                        foreach ($ps as $id => $p) {
                            if (($p['user_id'] ?? 0) == $user['id']) {
                                unset($ps[$id]);
                                $found = true;
                            }
                        }
                        if ($found) {
                            file_put_contents($p_file, json_encode($ps), LOCK_EX);
                        }
                    }
                }
            }
        }
        
        // Clean up DB session
        db()->prepare("DELETE FROM voice_sessions WHERE user_id = ?")->execute([$user['id']]);
    } catch (Exception $e) {
        // Ignore errors during logout cleanup
    }
}

session_destroy();
header('Location: login.php');
exit;
