<?php
require_once __DIR__ . '/config/webrtc_config.php';
webrtc_require_login();

$db = webrtc_db();
ensureWebRtcCallWorkflow($db);

$userId = webrtc_current_user_id();
$role = strtolower((string)webrtc_current_role());
$csrRole = strtolower((string)($_SESSION['csr_role'] ?? ''));

$roomToken = trim((string)($_GET['room'] ?? ''));
if ($roomToken === '') {
    exit('Missing room token.');
}

$stmt = $db->prepare('SELECT cr.*, sr.request_number FROM call_requests cr LEFT JOIN service_requests sr ON sr.id = cr.request_id WHERE cr.room_token = :room LIMIT 1');
$stmt->execute([':room' => $roomToken]);
$call = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$call) {
    http_response_code(404);
    exit('Call room not found.');
}

if (webrtc_is_customer() && (int)($call['customer_id'] ?? 0) !== $userId) {
    http_response_code(403);
    exit('You cannot join this call.');
}

if (webrtc_is_csr() && !in_array($call['status'], ['assigned', 'accepted', 'manager_queue', 'active'], true)) {
    http_response_code(403);
    exit('This call is not active.');
}

$participantType = webrtc_is_customer() ? 'customer' : 'csr';

$configuredSignalUrl = rtrim((string)SIGNALING_SERVER_URL, '/');
$parsedSignal = parse_url($configuredSignalUrl);

if (!empty($parsedSignal['scheme']) && !empty($parsedSignal['host'])) {
    $signalingUrl = $parsedSignal['scheme'] . '://' . $parsedSignal['host'] . (isset($parsedSignal['port']) ? ':' . $parsedSignal['port'] : '');
} else {
    $signalingUrl = $configuredSignalUrl;
}

$signalingSocketPath = SIGNALING_SOCKET_PATH;
$signalingHealthUrl = SIGNALING_HEALTH_URL;
$apiBase = 'api/webrtc';

/*
|--------------------------------------------------------------------------
| Back button URL
|--------------------------------------------------------------------------
| Customer goes back to the customer dashboard.
| CSR roles go back to their proper call queue.
*/
if (webrtc_is_customer()) {
    $backUrl = 'customer/dashboard.php';
    $backLabel = 'Back to Dashboard';
} else {
    if (in_array($csrRole, ['csr_manager', 'manager'], true) || $role === 'admin') {
        $backUrl = 'csr_manager/calls.php';
        $backLabel = 'Back to Manager Queue';
    } elseif (in_array($csrRole, ['team_leader', 'csr_team_leader', 'leader'], true)) {
        $backUrl = 'team_leader/calls.php';
        $backLabel = 'Back to Team Queue';
    } else {
        $backUrl = 'csr/calls.php';
        $backLabel = 'Back to Call Queue';
    }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>USHS Web Call</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
body{min-height:100vh;margin:0;background:linear-gradient(135deg,#080240,#093349);color:#fff;font-family:Inter,system-ui,sans-serif;display:flex;align-items:center;justify-content:center;padding:18px}.call-card{width:min(760px,100%);background:linear-gradient(135deg,#17295e,#102448);border:1px solid rgba(56,189,248,.36);border-radius:22px;padding:24px;box-shadow:0 24px 80px rgba(0,0,0,.35)}.call-top{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex-wrap:wrap}.badge-soft{display:inline-flex;gap:6px;align-items:center;border-radius:999px;background:rgba(56,189,248,.16);border:1px solid rgba(56,189,248,.32);color:#dff7ff;padding:7px 11px;font-weight:800}.status{font-size:1.05rem;font-weight:800;margin:18px 0;color:#dff7ff}.controls{display:flex;gap:10px;flex-wrap:wrap}.btn{border-radius:12px;font-weight:900}.btn-primary{background:linear-gradient(135deg,#1d9bf0,#17bdd4);border:0}.btn-danger{background:linear-gradient(135deg,#dc2626,#ef4444);border:0}.btn-secondary{background:rgba(148,163,184,.18);border:1px solid rgba(148,163,184,.35);color:#fff}.btn-secondary:hover{background:rgba(148,163,184,.28);color:#fff}textarea{width:100%;min-height:100px;margin-top:16px;background:rgba(8,20,48,.72);border:1px solid rgba(96,165,250,.34);color:#fff;border-radius:14px;padding:12px}.small{color:#aebbd4}.call-tip{margin-top:14px;color:#aebbd4;font-size:.9rem}
</style>
</head>
<body>
<div class="call-card">
  <div class="call-top">
    <span class="badge-soft"><i class="fas fa-phone-volume"></i><?= htmlspecialchars(strtoupper($participantType), ENT_QUOTES, 'UTF-8') ?> WEB CALL</span>
    <a class="btn btn-secondary btn-sm" href="<?= htmlspecialchars($backUrl, ENT_QUOTES, 'UTF-8') ?>"><i class="fas fa-arrow-left me-1"></i><?= htmlspecialchars($backLabel, ENT_QUOTES, 'UTF-8') ?></a>
  </div>

  <h1 class="mt-3 mb-1">Online Call Room</h1>
  <p class="small mb-1">Request: <?= htmlspecialchars($call['request_number'] ?: 'No ticket yet', ENT_QUOTES, 'UTF-8') ?></p>
  <p class="small mb-0">Customer: <?= htmlspecialchars($call['customer_name'] ?? 'Customer', ENT_QUOTES, 'UTF-8') ?></p>

  <div class="status" id="callStatus">Ready. Click Join Call and allow microphone access.</div>
  <audio id="remoteAudio" autoplay playsinline></audio>
  <audio id="localAudio" autoplay muted playsinline></audio>

  <div class="controls">
    <button class="btn btn-primary" id="startBtn"><i class="fas fa-headset me-1"></i>Join Call</button>
    <button class="btn btn-secondary" id="muteBtn" disabled>Mute</button>
    <button class="btn btn-danger" id="endBtn" disabled>End Call</button>
    <?php if (webrtc_is_csr()): ?><a class="btn btn-secondary" href="csr/manual_ticket.php?call_id=<?= (int)$call['id'] ?>"><i class="fas fa-file-circle-plus me-1"></i>Create Manual Ticket</a><?php endif; ?>
  </div>

  <div class="call-tip">Tip: If the call is done, click <strong>End Call</strong> first so the call log saves, then click <strong>Back</strong>.</div>

  <?php if (webrtc_is_csr()): ?>
  <form id="notesForm"><textarea id="callNotes" placeholder="Call notes / follow-up summary..."></textarea><div class="controls mt-2"><button class="btn btn-primary" type="submit">Save Notes</button></div></form>
  <?php endif; ?>
</div>

<script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script>
<script>
window.USHS_CALL={roomToken:<?= json_encode($roomToken) ?>,userId:<?= json_encode($userId) ?>,participantType:<?= json_encode($participantType) ?>,signalingUrl:<?= json_encode($signalingUrl) ?>,signalingPath:<?= json_encode($signalingSocketPath) ?>,signalingHealthUrl:<?= json_encode($signalingHealthUrl) ?>,apiBase:<?= json_encode($apiBase) ?>};
</script>
<script src="assets/js/webrtc-client.js"></script>
</body>
</html>
