<?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';
    }
}

$manualTicketBase = 'csr/manual_ticket.php';
if (webrtc_is_csr()) {
    if (in_array($csrRole, ['csr_manager', 'manager'], true) || $role === 'admin') {
        $manualTicketBase = 'csr_manager/manual_ticket.php';
    } elseif (in_array($csrRole, ['team_leader', 'csr_team_leader', 'leader'], true)) {
        $manualTicketBase = 'team_leader/manual_ticket.php';
    }
}
$manualTicketUrl = $manualTicketBase . '?call_id=' . (int)$call['id'] . '&source=webrtc_call';
?>
<!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}

.recording-pill{display:inline-flex;align-items:center;gap:8px;border-radius:999px;background:rgba(244,63,94,.12);border:1px solid rgba(244,63,94,.32);color:#fecaca;padding:7px 10px;font-weight:900;font-size:.85rem;margin-top:10px}.recording-pill.idle{background:rgba(148,163,184,.12);border-color:rgba(148,163,184,.32);color:#d7e7ff}.recording-dot{width:9px;height:9px;border-radius:999px;background:#ef4444;box-shadow:0 0 0 rgba(239,68,68,.75);animation:recordPulse 1.3s infinite}@keyframes recordPulse{0%{box-shadow:0 0 0 0 rgba(239,68,68,.75)}70%{box-shadow:0 0 0 9px rgba(239,68,68,0)}100%{box-shadow:0 0 0 0 rgba(239,68,68,0)}}.manual-ticket-overlay{position:fixed;inset:0;background:rgba(2,6,23,.76);z-index:7000;display:none;align-items:stretch;justify-content:flex-end;padding:14px}.manual-ticket-drawer{width:min(1080px,100%);height:100%;background:linear-gradient(135deg,#17295e,#102448);border:1px solid rgba(56,189,248,.42);border-radius:18px;box-shadow:0 24px 90px rgba(0,0,0,.58);display:flex;flex-direction:column;overflow:hidden}.manual-ticket-drawer__head{padding:12px 14px;border-bottom:1px solid rgba(96,165,250,.26);display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap}.manual-ticket-drawer__head h3{font-size:1rem;font-weight:900;margin:0}.manual-ticket-drawer__actions{display:flex;gap:8px;flex-wrap:wrap}.manual-ticket-frame{border:0;width:100%;height:100%;background:#fff}.manual-ticket-drawer__note{font-size:.82rem;color:#aebbd4;margin:0}.call-room-audio{position:absolute;width:1px;height:1px;opacity:.01;pointer-events:none}

</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" class="call-room-audio" autoplay playsinline></audio>
  <audio id="localAudio" class="call-room-audio" autoplay muted playsinline></audio>

  <?php if (webrtc_is_csr()): ?>
  <div class="recording-pill idle" id="recordingStatus"><i class="fas fa-circle-info"></i> Recording is off. Click Start Recording after the call connects.</div>
  <?php endif; ?>

  <div class="controls">
    <button class="btn btn-primary" id="startBtn"><i class="fas fa-headset me-1"></i>Join Call</button>
    <?php if (webrtc_is_csr()): ?>
    <button class="btn btn-secondary" id="recordStartBtn" disabled><i class="fas fa-record-vinyl me-1"></i>Start Recording</button>
    <button class="btn btn-secondary" id="recordStopBtn" disabled style="display:none;"><i class="fas fa-stop-circle me-1"></i>Stop Recording</button>
    <?php endif; ?>
    <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()): ?><button class="btn btn-secondary" type="button" onclick="openManualTicketPanel()"><i class="fas fa-file-circle-plus me-1"></i>Create Manual Ticket</button><?php endif; ?>
  </div>

  <div class="call-tip">Tip: Click <strong>Start Recording</strong> only after the call connects. Use <strong>Create Manual Ticket</strong> to open the form in a side panel without ending the call.</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>

<?php if (webrtc_is_csr()): ?>
<div class="manual-ticket-overlay" id="manualTicketOverlay">
  <div class="manual-ticket-drawer">
    <div class="manual-ticket-drawer__head">
      <div>
        <h3><i class="fas fa-file-circle-plus me-2"></i>Create Manual Ticket During Call</h3>
        <p class="manual-ticket-drawer__note">The WebRTC call and recording stay active while this form is open.</p>
      </div>
      <div class="manual-ticket-drawer__actions">
        <a class="btn btn-secondary btn-sm" target="_blank" rel="noopener" href="<?= htmlspecialchars($manualTicketUrl, ENT_QUOTES, 'UTF-8') ?>"><i class="fas fa-up-right-from-square me-1"></i>Open New Tab</a>
        <button class="btn btn-secondary btn-sm" type="button" onclick="closeManualTicketPanel()"><i class="fas fa-times me-1"></i>Close</button>
      </div>
    </div>
    <iframe id="manualTicketFrame" class="manual-ticket-frame" title="Create Manual Ticket"></iframe>
  </div>
</div>
<?php endif; ?>

<script src="/webrtc/socket.io/socket.io.js"></script>
<script>
if (typeof io === 'undefined') {
    document.write('<script src="https://cdn.socket.io/4.7.5/socket.io.min.js"><\/script>');
}
</script>
<script>
window.USHS_CALL={callId:<?= (int)$call['id'] ?>,roomToken:<?= json_encode($roomToken) ?>,userId:<?= json_encode($userId) ?>,participantType:<?= json_encode($participantType) ?>,isCsr:<?= webrtc_is_csr() ? 'true' : 'false' ?>,signalingUrl:<?= json_encode($signalingUrl) ?>,signalingPath:<?= json_encode($signalingSocketPath) ?>,signalingHealthUrl:<?= json_encode($signalingHealthUrl) ?>,apiBase:<?= json_encode($apiBase) ?>,manualTicketUrl:<?= json_encode($manualTicketUrl) ?>};
</script>

<?php if (webrtc_is_csr()): ?>
<script>
function openManualTicketPanel() {
    var overlay = document.getElementById('manualTicketOverlay');
    var frame = document.getElementById('manualTicketFrame');
    if (!overlay || !frame || !window.USHS_CALL) return;
    if (!frame.getAttribute('src')) {
        frame.setAttribute('src', window.USHS_CALL.manualTicketUrl || 'csr/manual_ticket.php');
    }
    overlay.style.display = 'flex';
}
function closeManualTicketPanel() {
    var overlay = document.getElementById('manualTicketOverlay');
    if (overlay) overlay.style.display = 'none';
}
</script>
<?php endif; ?>
<script src="assets/js/webrtc-client.js"></script>
</body>
</html>
