<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/database.php';
require_once __DIR__ . '/../includes/app_helpers.php';

/*
 * WebRTC signaling configuration.
 * Your cPanel Node.js app is mounted at https://ushs.space/webrtc.
 * Socket.IO must use the mounted path /webrtc/socket.io.
 */
defined('SIGNALING_SERVER_URL') || define('SIGNALING_SERVER_URL', 'https://ushs.space');
defined('SIGNALING_SOCKET_PATH') || define('SIGNALING_SOCKET_PATH', '/webrtc/socket.io');
defined('SIGNALING_HEALTH_URL') || define('SIGNALING_HEALTH_URL', 'https://ushs.space/webrtc/');

function webrtc_db(): PDO {
    return (new Database())->getConnection();
}

function webrtc_json(array $data, int $status = 200): void {
    http_response_code($status);
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

function webrtc_current_user_id(): int {
    return (int)($_SESSION['customer_id'] ?? $_SESSION['csr_id'] ?? $_SESSION['admin_id'] ?? 0);
}

function webrtc_current_role(): string {
    if (isset($_SESSION['customer_id'])) return 'customer';
    if (isset($_SESSION['csr_id'])) return 'csr';
    if (isset($_SESSION['admin_id'])) return 'admin';
    return '';
}

function webrtc_is_csr(): bool { return isset($_SESSION['csr_id']) || isset($_SESSION['admin_id']); }
function webrtc_is_customer(): bool { return isset($_SESSION['customer_id']); }

function webrtc_require_login(): void {
    if (!webrtc_current_user_id()) {
        http_response_code(401);
        exit('Unauthorized');
    }
}

function webrtc_room_token(): string { return bin2hex(random_bytes(32)); }

function webrtc_customer_can_access_request(PDO $db, int $requestId, int $customerId): bool {
    if ($requestId <= 0 || $customerId <= 0) return false;
    $stmt = $db->prepare('SELECT id FROM service_requests WHERE id = :id AND customer_id = :customer_id LIMIT 1');
    $stmt->execute([':id'=>$requestId, ':customer_id'=>$customerId]);
    return (bool)$stmt->fetchColumn();
}
