<?php
// WebRTC signaling — room create, signal relay, poll
require_auth();
$u = current_user();
$method = $_SERVER['REQUEST_METHOD'];
$d = input();

if ($method === 'GET') {
    $code = v_str($d, 'room', 32);
    if (!$code) json_error('room required', 422);
    if (!hv4_table_exists('webrtc_rooms')) json_ok(['room' => null, 'signals' => []]);
    $row = db()->prepare('SELECT * FROM webrtc_rooms WHERE room_code=? AND status="open" LIMIT 1');
    $row->execute([$code]);
    $room = $row->fetch() ?: null;
    $since = (int)($d['since'] ?? 0);
    $sigs = [];
    if ($room && hv4_table_exists('webrtc_signals')) {
        $s = db()->prepare('SELECT * FROM webrtc_signals WHERE room_code=? AND id>? AND sender_id!=? ORDER BY id ASC LIMIT 20');
        $s->execute([$code, $since, $u['id']]);
        $sigs = $s->fetchAll();
    }
    json_ok(['room' => $room, 'signals' => $sigs]);
}

csrf_check();

if ($method === 'POST') {
    $action = v_str($d, 'action', 40);

    if ($action === 'create') {
        if (!hv4_table_exists('webrtc_rooms')) json_error('Run migration 009', 503);
        $code  = strtoupper(substr(bin2hex(random_bytes(4)), 0, 8));
        $title = v_str($d, 'title', 120) ?: 'Team Call';
        db()->prepare('INSERT INTO webrtc_rooms (room_code, title, host_user_id, status, created_at) VALUES (?,?,?,"open",NOW())')
           ->execute([$code, $title, $u['id']]);
        json_ok(['room_code' => $code, 'title' => $title], 'Room created');
    }

    if ($action === 'signal') {
        $code   = v_str($d, 'room_code', 32);
        $signal = (string)($d['signal'] ?? '');
        if (!$code || !$signal) json_error('room_code and signal required', 422);
        if (!hv4_table_exists('webrtc_signals')) json_error('Run migration 009', 503);
        db()->prepare('INSERT INTO webrtc_signals (room_code, sender_id, signal, created_at) VALUES (?,?,?,NOW())')
           ->execute([$code, $u['id'], $signal]);
        // Clean up old signals (keep last 100 per room)
        db()->prepare('DELETE FROM webrtc_signals WHERE room_code=? AND id NOT IN (SELECT id FROM (SELECT id FROM webrtc_signals WHERE room_code=? ORDER BY id DESC LIMIT 100) t)')
           ->execute([$code, $code]);
        json_ok([], 'Signal relayed');
    }

    if ($action === 'join') {
        $code = v_str($d, 'room_code', 32);
        hv4_emit_event('call.joined', ['room' => $code, 'user' => $u['name']], 'webrtc', 0);
        json_ok(['joined' => true]);
    }

    json_error('Unknown action', 422);
}

if ($method === 'PUT') {
    $action = v_str($d, 'action', 40);
    if ($action === 'end') {
        $code = v_str($d, 'room_code', 32);
        db()->prepare('UPDATE webrtc_rooms SET status="ended" WHERE room_code=?')->execute([$code]);
        json_ok([], 'Call ended');
    }
    json_error('Unknown action', 422);
}

json_error('Method not allowed', 405);
