sls/resources/views/interview/candidate_room.blade.php
2026-07-21 16:49:58 +05:30

971 lines
45 KiB
PHP

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Live Assessment Room - {{ $interview->candidate_name }} | SingleLogin</title>
@vite(['resources/css/app.css', 'resources/js/app.js'])
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500;600&family=Instrument+Sans:wght@400;500;600;700&family=Outfit:wght@500;600;700&display=swap" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<!-- Monaco Code Editor Loader & PeerJS Realtime WebRTC Call & SweetAlert2 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs/loader.min.js"></script>
<script src="https://unpkg.com/peerjs@1.5.2/dist/peerjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
:root {
--bg-color: #080c14;
--card-bg: #0f172a;
--card-border: rgba(255, 255, 255, 0.15);
--accent-primary: #6366f1;
}
/* Modern Custom Scrollbars */
html, body, *, ::-webkit-scrollbar {
scrollbar-width: thin;
scrollbar-color: rgba(255, 255, 255, 0.4) rgba(15, 23, 42, 0.35);
}
::-webkit-scrollbar {
width: 5px;
height: 5px;
}
::-webkit-scrollbar-track {
background: rgba(15, 23, 42, 0.35);
}
::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.4);
border-radius: 10px;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Instrument Sans', sans-serif;
background-color: var(--bg-color);
color: white;
height: 100vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
.ide-header {
height: 60px;
background: #0d1322;
border-bottom: 1px solid var(--card-border);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 20px;
}
.ide-layout {
display: grid;
grid-template-columns: 1fr 340px;
height: calc(100vh - 60px);
width: 100%;
}
.editor-section {
display: flex;
flex-direction: column;
border-right: 1px solid var(--card-border);
height: 100%;
}
#monaco-editor-container {
flex: 1;
width: 100%;
height: 100%;
}
.terminal-section {
height: 220px;
background: #050811;
border-top: 1px solid var(--card-border);
display: flex;
flex-direction: column;
}
.terminal-header {
height: 36px;
background: #090e1a;
border-bottom: 1px solid rgba(255,255,255,0.08);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 16px;
font-size: 0.75rem;
color: #94a3b8;
font-weight: 600;
}
#terminal-output {
flex: 1;
padding: 12px 16px;
font-family: 'Fira Code', monospace;
font-size: 0.8rem;
color: #34d399;
overflow-y: auto;
white-space: pre-wrap;
}
.proctor-sidebar {
background: #0d1322;
padding: 16px;
display: flex;
flex-direction: column;
gap: 16px;
overflow-y: auto;
}
.webcam-box {
width: 100%;
height: 180px;
min-height: 180px;
flex-shrink: 0;
background: #000;
border-radius: 12px;
border: 2px solid var(--card-border);
overflow: hidden;
position: relative;
}
#webcam {
width: 100%;
height: 100%;
object-fit: cover;
}
.btn-ide {
padding: 8px 16px;
border-radius: 8px;
font-weight: 600;
font-size: 0.8rem;
cursor: pointer;
border: 1px solid var(--card-border);
background: rgba(255,255,255,0.05);
color: white;
transition: all 0.2s ease;
}
.btn-ide-primary {
background: #10b981;
border-color: #10b981;
color: white;
}
.btn-ide-run {
background: #6366f1;
border-color: #6366f1;
color: white;
}
/* Warning Popup Overlay */
#warning-banner {
position: fixed;
top: 70px;
left: 50%;
transform: translateX(-50%);
background: rgba(239, 68, 68, 0.95);
color: white;
padding: 12px 24px;
border-radius: 12px;
font-weight: 700;
font-size: 0.9rem;
box-shadow: 0 10px 30px rgba(239, 68, 68, 0.5);
z-index: 9999;
display: none;
backdrop-filter: blur(10px);
}
</style>
</head>
<body>
<!-- Silent Warning Banner -->
<div id="warning-banner">
🚨 ATTENTION: <span id="warning-text">Please keep your eyes on the screen during the assessment.</span>
</div>
<!-- IDE Header Bar -->
<header class="ide-header">
<div style="display: flex; align-items: center; gap: 12px;">
<div style="font-weight: 700; font-family: 'Outfit', sans-serif; font-size: 1.05rem; color: white;">
Candidate Assessment Room
</div>
<code style="background: rgba(255,255,255,0.06); padding: 4px 10px; border-radius: 6px; color: #38bdf8; font-size: 0.75rem;">
ID: {{ $interview->submission_unique_id }}
</code>
</div>
<div style="display: flex; align-items: center; gap: 14px;">
<button onclick="toggleNotepadModal()" class="btn-ide" style="background: rgba(99,102,241,0.2); border-color: #6366f1;">
📝 Open Notepad
</button>
<button onclick="toggleDrawingModal()" class="btn-ide" style="background: rgba(6,182,212,0.2); border-color: #06b6d4;">
🎨 Open Drawing
</button>
<div style="display: flex; align-items: center; gap: 8px;">
<label style="font-size: 0.75rem; color: #94a3b8; font-weight: 500;">Language:</label>
<select id="language-select" class="btn-ide" style="background: #151b2c;">
<option value="python" {{ strtolower($interview->language) === 'python' ? 'selected' : '' }}>Python 3</option>
<option value="cpp" {{ strtolower($interview->language) === 'cpp' ? 'selected' : '' }}>C++ (GCC)</option>
<option value="c" {{ strtolower($interview->language) === 'c' ? 'selected' : '' }}>C (GCC)</option>
<option value="java" {{ strtolower($interview->language) === 'java' ? 'selected' : '' }}>Java 15</option>
<option value="php" {{ strtolower($interview->language) === 'php' ? 'selected' : '' }}>PHP 8.2 / Laravel</option>
<option value="javascript" {{ strtolower($interview->language) === 'javascript' ? 'selected' : '' }}>JavaScript (Node.js)</option>
</select>
</div>
<button onclick="runCode()" class="btn-ide btn-ide-run">
Run Code
</button>
<button onclick="submitSolution()" class="btn-ide btn-ide-primary">
Submit Final Solution
</button>
<button onclick="candidateLogoutAction()" class="btn-ide" style="background: rgba(239,68,68,0.2); border-color: #ef4444; color: #fca5a5; font-weight: 700;">
🚪 Logout
</button>
</div>
</header>
<!-- Candidate Notepad Modal -->
<div id="notepad-modal" style="position: fixed; top: 70px; right: 360px; width: 420px; height: 350px; background: #0f172a; border: 1.5px solid #6366f1; border-radius: 16px; box-shadow: 0 20px 40px rgba(0,0,0,0.6); display: none; flex-direction: column; z-index: 1000; overflow: hidden;">
<div style="background: #1e293b; padding: 10px 16px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(255,255,255,0.1);">
<div style="font-weight: 700; font-size: 0.85rem; color: white;">📝 Candidate Notepad (Synced)</div>
<button onclick="toggleNotepadModal()" style="background: none; border: none; color: #94a3b8; font-size: 1.2rem; cursor: pointer;">&times;</button>
</div>
<textarea id="notepad-textarea" oninput="saveNotepadContent()" placeholder="Type rough notes, pseudo-code, or thoughts here..." style="flex: 1; width: 100%; padding: 14px; background: #0b0f19; color: #e2e8f0; border: none; outline: none; font-family: 'Fira Code', monospace; font-size: 0.85rem; resize: none;">{{ $interview->candidate_notes }}</textarea>
<div style="padding: 6px 12px; background: #0d1322; font-size: 0.65rem; color: #34d399; text-align: right;">
Auto-saved to interviewer portal
</div>
</div>
<!-- Candidate Canvas Drawing Modal -->
<div id="drawing-modal" style="position: fixed; top: 70px; right: 360px; width: 550px; height: 420px; background: #0f172a; border: 1.5px solid #06b6d4; border-radius: 16px; box-shadow: 0 20px 40px rgba(0,0,0,0.6); display: none; flex-direction: column; z-index: 1000; overflow: hidden;">
<div style="background: #1e293b; padding: 10px 16px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(255,255,255,0.1);">
<div style="font-weight: 700; font-size: 0.85rem; color: white;">🎨 Candidate Live Drawing Board</div>
<div style="display: flex; gap: 8px; align-items: center;">
<input type="color" id="draw-color" value="#38bdf8" style="width: 26px; height: 26px; border: none; border-radius: 50%; cursor: pointer;">
<button onclick="clearCanvasDraw()" class="btn-ide" style="padding: 2px 8px; font-size: 0.7rem;">Clear</button>
<button onclick="toggleDrawingModal()" style="background: none; border: none; color: #94a3b8; font-size: 1.2rem; cursor: pointer;">&times;</button>
</div>
</div>
<div style="flex: 1; background: #050811; position: relative;">
<canvas id="drawing-canvas" width="550" height="340" style="cursor: crosshair; display: block; width: 100%; height: 100%;"></canvas>
</div>
<div style="padding: 6px 12px; background: #0d1322; font-size: 0.65rem; color: #38bdf8; text-align: right;">
🎨 Draw architecture / logic diagrams (Auto-synced to Interviewer)
</div>
</div>
<!-- IDE Room Layout -->
<div class="ide-layout">
<!-- Main Editor & Terminal Area -->
<div class="editor-section">
<div id="monaco-editor-container"></div>
<div class="terminal-section">
<div class="terminal-header">
<span>EXECUTION OUTPUT TERMINAL (STDOUT / STDERR)</span>
<span id="run-status" style="color: #94a3b8;">Ready</span>
</div>
<div id="terminal-output">// Press 'Run Code' to execute candidate solution live...</div>
</div>
</div>
@php
$words = preg_split('/\s+/', trim($interview->candidate_name));
if (count($words) >= 2) {
$candInitials = strtoupper(substr($words[0], 0, 1) . substr(end($words), 0, 1));
} else {
$nameStr = trim($interview->candidate_name);
$candInitials = strtoupper(substr($nameStr, 0, 1) . (strlen($nameStr) > 1 ? substr($nameStr, -1) : ''));
}
@endphp
<!-- Sidebar: Real-Time 2-Way Interview Call & Screen Share -->
<div class="proctor-sidebar">
<!-- Candidate Camera Feed -->
<div class="webcam-box" style="position: relative;">
<video id="webcam" autoplay muted playsinline style="width: 100%; height: 100%; object-fit: cover;"></video>
<div id="webcam-avatar-placeholder" style="position: absolute; inset: 0; display: none; flex-direction: column; align-items: center; justify-content: center; background: #0f172a; color: white; z-index: 5;">
<div style="width: 60px; height: 60px; border-radius: 50%; background: linear-gradient(135deg, #6366f1 0%, #0078d4 100%); display: flex; align-items: center; justify-content: center; font-size: 1.5rem; font-weight: 800; font-family: 'Outfit', sans-serif; box-shadow: 0 0 15px rgba(99,102,241,0.4);">
{{ $candInitials }}
</div>
<div style="font-size: 0.7rem; color: #94a3b8; margin-top: 6px;">Camera Disabled</div>
</div>
<div style="position: absolute; bottom: 8px; left: 8px; background: rgba(0,0,0,0.6); padding: 2px 8px; border-radius: 4px; font-size: 0.65rem; color: #34d399; font-weight: 600; z-index: 10;">
📷 Candidate Camera
</div>
</div>
<!-- Remote Interviewer Video Feed (Live 2-Way Call) -->
<div class="webcam-box" style="position: relative; border-color: #6366f1;">
<video id="interviewer-video" autoplay playsinline style="width: 100%; height: 100%; object-fit: cover; background: #050811;"></video>
<div id="interviewer-video-placeholder" style="position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; background: rgba(15,23,42,0.95); color: #94a3b8; font-size: 0.75rem; text-align: center; padding: 10px; z-index: 5;">
<div id="interviewer-avatar-circle" style="width: 60px; height: 60px; border-radius: 50%; background: linear-gradient(135deg, #38bdf8 0%, #6366f1 100%); display: flex; align-items: center; justify-content: center; font-size: 1.5rem; font-weight: 800; font-family: 'Outfit', sans-serif; color: white; margin-bottom: 6px; box-shadow: 0 0 15px rgba(56,189,248,0.4);">
IV
</div>
<div id="call-status-sub" style="font-size: 0.7rem; color: #e2e8f0; font-weight: 600;">Interviewer Video Feed</div>
<div style="font-size: 0.65rem; color: #38bdf8; margin-top: 2px;">Waiting for panelist to join call...</div>
</div>
<div style="position: absolute; bottom: 8px; left: 8px; background: rgba(99,102,241,0.8); padding: 2px 8px; border-radius: 4px; font-size: 0.65rem; color: white; font-weight: 600; z-index: 10;">
🎙️ Interviewer / Panelist
</div>
</div>
<canvas id="proctor-canvas" style="display: none;" width="320" height="240"></canvas>
<!-- Candidate Profile Info -->
<div style="background: rgba(255,255,255,0.03); border: 1px solid var(--card-border); border-radius: 12px; padding: 14px; font-size: 0.8rem;">
<div style="font-weight: 700; color: white; margin-bottom: 6px;">Candidate Profile</div>
<div style="color: #94a3b8;">Name: <strong style="color: white;">{{ $interview->candidate_name }}</strong></div>
<div style="color: #94a3b8;">Email: <span style="color: white;">{{ $interview->candidate_email }}</span></div>
<div style="color: #94a3b8; margin-top: 6px;">Access Expires: <span style="color: #fca5a5;">{{ $interview->expires_at->format('H:i:s T') }}</span></div>
</div>
<!-- Real-Time Call Controls (Mic, Camera, Screen Sharing) -->
<div style="background: rgba(99,102,241,0.1); border: 1px solid rgba(99,102,241,0.3); border-radius: 14px; padding: 14px;">
<div style="font-size: 0.8rem; font-weight: 700; color: white; margin-bottom: 10px; display: flex; align-items: center; justify-content: space-between;">
<span>📞 Real-Time Interview Call</span>
<span id="call-status-badge" style="font-size: 0.65rem; background: rgba(16,185,129,0.2); color: #34d399; padding: 2px 8px; border-radius: 999px;">READY</span>
</div>
<div style="display: flex; gap: 8px; margin-bottom: 10px;">
<button id="toggle-mic-btn" onclick="toggleMic()" class="btn-ide" style="flex: 1; padding: 8px; font-size: 0.75rem; background: rgba(16,185,129,0.2); border-color: #10b981;">
🎤 Mic On
</button>
<button id="toggle-cam-btn" onclick="toggleCam()" class="btn-ide" style="flex: 1; padding: 8px; font-size: 0.75rem; background: rgba(16,185,129,0.2); border-color: #10b981;">
📷 Cam On
</button>
<button id="leave-call-btn" onclick="candidateLeaveCall()" class="btn-ide" style="padding: 8px; font-size: 0.75rem; background: rgba(239,68,68,0.2); border-color: #ef4444; color: #fca5a5;" title="Leave 2-Way Call">
🚪 Leave Call
</button>
</div>
<button id="share-screen-btn" onclick="startScreenShare()" class="btn-ide btn-ide-run" style="width: 100%; padding: 10px; font-size: 0.8rem; background: linear-gradient(135deg, #6366f1 0%, #0078d4 100%);">
🖥️ Share Screen with Interviewer
</button>
</div>
<!-- 2-Way Real-Time Chat Container with Interviewer/Panelist -->
<div style="background: rgba(15,23,42,0.8); border: 1px solid var(--card-border); border-radius: 14px; padding: 12px; margin-top: 10px;">
<div style="font-size: 0.8rem; font-weight: 700; color: white; margin-bottom: 8px; display: flex; align-items: center; gap: 6px;">
💬 Live Chat with Interviewer
</div>
<div id="candidate-chat-history" style="background: #050811; border: 1px solid var(--card-border); border-radius: 10px; padding: 8px; height: 130px; overflow-y: auto; font-size: 0.72rem; margin-bottom: 8px;">
<div style="color: #94a3b8; font-style: italic; text-align: center; padding-top: 40px;">No messages yet. Send a message below.</div>
</div>
<div style="display: flex; gap: 6px;">
<input type="text" id="candidate-chat-input" placeholder="Type message to panelist..." onkeydown="if(event.key==='Enter') sendCandidateMessage()" class="form-input" style="font-size: 0.75rem; background: #0b0f19; border: 1px solid var(--card-border); padding: 6px 10px; flex: 1;">
<button onclick="sendCandidateMessage()" class="btn-ide" style="padding: 6px 10px; font-size: 0.75rem; background: #6366f1; border: none; font-weight: 600;">
Send
</button>
</div>
</div>
</div>
</div>
<script>
let editor;
let interviewId = {{ $interview->id }};
let mediaRecorder;
let recordedChunks = [];
let previousFrameData = null;
// Default Code Snippets for Languages
const defaultCode = {
python: `# Python 3 Assessment Solution\ndef main():\n print("Hello from SingleLogin Assessment!")\n num = 42\n print(f"Computed Result: {num * 2}")\n\nif __name__ == "__main__":\n main()`,
cpp: `// C++ Assessment Solution\n#include <iostream>\nusing namespace std;\n\nint main() {\n cout << "Hello from SingleLogin Assessment!" << endl;\n return 0;\n}`,
c: `// C Assessment Solution\n#include <stdio.h>\n\nint main() {\n printf("Hello from SingleLogin Assessment!\\n");\n return 0;\n}`,
java: `// Java Assessment Solution\npublic class Solution {\n public static void main(String[] args) {\n System.out.println("Hello from SingleLogin Assessment!");\n }\n}`,
php: `<?php\n// PHP / Laravel Assessment Solution\necho "Hello from SingleLogin Assessment!\\n";\n$data = [1, 2, 3, 4, 5];\necho "Sum: " . array_sum($data);`,
javascript: `// JavaScript (Node.js) Solution\nconsole.log("Hello from SingleLogin Assessment!");\nconst nums = [10, 20, 30];\nconsole.log("Total:", nums.reduce((a, b) => a + b, 0));`
};
// Initialize Monaco Editor
require.config({ paths: { vs: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs' } });
require(['vs/editor/editor.main'], function () {
const initialLang = '{{ strtolower($interview->language) }}';
const initialCode = {!! json_encode($interview->submitted_code) !!} || defaultCode[initialLang] || defaultCode.python;
editor = monaco.editor.create(document.getElementById('monaco-editor-container'), {
value: initialCode,
language: initialLang === 'cpp' ? 'cpp' : (initialLang === 'c' ? 'c' : initialLang),
theme: 'vs-dark',
fontSize: 14,
fontFamily: 'Fira Code, monospace',
automaticLayout: true,
minimap: { enabled: true }
});
// Real-Time Code Sync to Interviewer (Before Submission)
let codeSyncTimeout = null;
editor.onDidChangeModelContent(function () {
clearTimeout(codeSyncTimeout);
codeSyncTimeout = setTimeout(function () {
const code = editor.getValue();
const lang = document.getElementById('language-select').value;
fetch(`{{ route("interview.candidate.sync-code", $interview->id) }}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ code: code, language: lang })
});
}, 600);
});
});
// Handle Language Switch
document.getElementById('language-select').addEventListener('change', function () {
const lang = this.value;
const monacoLang = lang === 'cpp' ? 'cpp' : (lang === 'c' ? 'c' : lang);
monaco.editor.setModelLanguage(editor.getModel(), monacoLang);
if (!editor.getValue() || editor.getValue() === defaultCode[lang]) {
editor.setValue(defaultCode[lang] || '');
}
});
// Execute Code live via Piston API
function runCode() {
document.getElementById('run-status').innerText = 'Running...';
document.getElementById('terminal-output').innerText = 'Executing solution on code engine...';
const lang = document.getElementById('language-select').value;
const code = editor.getValue();
fetch('{{ route("interview.execute") }}', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ language: lang, code: code })
})
.then(r => r.json())
.then(data => {
document.getElementById('run-status').innerText = 'Ready';
if (data.success) {
document.getElementById('terminal-output').innerText = data.output;
} else {
document.getElementById('terminal-output').innerText = 'Error: ' + data.output;
}
})
.catch(err => {
document.getElementById('run-status').innerText = 'Error';
document.getElementById('terminal-output').innerText = 'Failed to reach code runner service.';
});
}
// Submit Solution
function submitSolution() {
const code = editor.getValue();
const lang = document.getElementById('language-select').value;
const output = document.getElementById('terminal-output').innerText;
fetch(`{{ route('interview.submit', $interview->id) }}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ code: code, language: lang, output: output })
})
.then(r => r.json())
.then(data => {
alert('✓ ' + data.message);
});
}
// --- ANTI-CHEAT & PROCTORING ENGINE ---
// 1. Tab Switch Detection
document.addEventListener('visibilitychange', function () {
if (document.hidden) {
logViolation('tab_switch', 'Candidate switched browser tab or minimized window');
}
});
// 2. Window Focus Loss / External Screen Overlap Detection
window.addEventListener('blur', function () {
logViolation('focus_lost', 'Window lost focus (possible external AI overlay or screen overlap)');
});
// 3. Code Copy-Paste Detection
document.addEventListener('paste', function (e) {
logViolation('paste_event', 'Candidate pasted content into editor window');
});
function logViolation(type, details) {
fetch(`{{ route('interview.violation', $interview->id) }}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ type: type, details: details })
});
}
// 4. WebRTC Real-Time 2-Way Interview Call Setup (Dual Signaling: BroadcastChannel + PeerJS)
let localMediaStream = null;
let peerInstance = null;
let candidatePeerConnection = null;
let screenShareStream = null;
let isMicEnabled = true;
let isCamEnabled = true;
let activeCallInstance = null;
const callSigChannel = new BroadcastChannel('webrtc_call_' + interviewId);
callSigChannel.onmessage = async (event) => {
const msg = event.data;
if (!msg) return;
if (msg.type === 'interviewer_joined' || msg.type === 'offer') {
if (msg.offer && msg.sender !== 'candidate') {
await handleInterviewerOffer(msg.offer);
} else if (localMediaStream) {
sendOfferToInterviewer();
}
} else if (msg.type === 'answer' && msg.sender !== 'candidate' && candidatePeerConnection) {
await candidatePeerConnection.setRemoteDescription(new RTCSessionDescription(msg.answer));
} else if (msg.type === 'ice-candidate' && msg.sender !== 'candidate' && candidatePeerConnection && msg.candidate) {
try {
await candidatePeerConnection.addIceCandidate(new RTCIceCandidate(msg.candidate));
} catch(e) {}
} else if (msg.type === 'end_call_all') {
candidateLeaveCall();
}
};
async function createCandidatePeerConnection() {
if (candidatePeerConnection) return candidatePeerConnection;
candidatePeerConnection = new RTCPeerConnection({
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' },
{ urls: 'stun:stun2.l.google.com:19302' }
]
});
if (localMediaStream) {
localMediaStream.getTracks().forEach(track => {
candidatePeerConnection.addTrack(track, localMediaStream);
});
}
candidatePeerConnection.ontrack = (event) => {
const remoteVideo = document.getElementById('interviewer-video');
const placeholder = document.getElementById('interviewer-video-placeholder');
if (remoteVideo && event.streams[0]) {
remoteVideo.srcObject = event.streams[0];
remoteVideo.play().catch(e => console.log(e));
}
if (placeholder) placeholder.style.display = 'none';
document.getElementById('call-status-badge').innerText = 'CONNECTED';
document.getElementById('call-status-badge').style.background = 'rgba(16,185,129,0.3)';
document.getElementById('call-status-badge').style.color = '#34d399';
};
candidatePeerConnection.onicecandidate = (event) => {
if (event.candidate) {
callSigChannel.postMessage({ type: 'ice-candidate', candidate: event.candidate, sender: 'candidate' });
}
};
return candidatePeerConnection;
}
async function sendOfferToInterviewer() {
const pc = await createCandidatePeerConnection();
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
callSigChannel.postMessage({ type: 'offer', offer: offer, sender: 'candidate' });
}
async function handleInterviewerOffer(offer) {
const pc = await createCandidatePeerConnection();
await pc.setRemoteDescription(new RTCSessionDescription(offer));
const answer = await pc.createAnswer();
await pc.setLocalDescription(answer);
callSigChannel.postMessage({ type: 'answer', answer: answer, sender: 'candidate' });
}
function initCandidatePeer() {
if (typeof Peer === 'undefined') return;
const peerId = 'cand_' + interviewId;
if (peerInstance) {
try { peerInstance.destroy(); } catch(e) {}
}
peerInstance = new Peer(peerId, {
config: {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' },
{ urls: 'stun:stun2.l.google.com:19302' }
]
}
});
peerInstance.on('open', id => {
console.log('Candidate WebRTC Peer Registered:', id);
});
peerInstance.on('call', call => {
activeCallInstance = call;
const sendStream = localMediaStream || new MediaStream();
call.answer(sendStream);
call.on('stream', remoteStream => {
const remoteVideo = document.getElementById('interviewer-video');
const placeholder = document.getElementById('interviewer-video-placeholder');
if (remoteVideo) {
remoteVideo.srcObject = remoteStream;
remoteVideo.play().catch(e => console.log(e));
}
if (placeholder) placeholder.style.display = 'none';
document.getElementById('call-status-badge').innerText = 'CONNECTED';
document.getElementById('call-status-badge').style.background = 'rgba(16,185,129,0.3)';
document.getElementById('call-status-badge').style.color = '#34d399';
});
call.on('close', () => {
candidateLeaveCall();
});
});
}
initCandidatePeer();
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(stream => {
localMediaStream = stream;
const vid = document.getElementById('webcam');
if (vid) {
vid.muted = true;
vid.srcObject = stream;
vid.play().catch(e => console.log(e));
}
callSigChannel.postMessage({ type: 'candidate_ready' });
})
.catch(err => {
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
.then(stream => {
localMediaStream = stream;
const vid = document.getElementById('webcam');
if (vid) {
vid.muted = true;
vid.srcObject = stream;
vid.play().catch(e => console.log(e));
}
callSigChannel.postMessage({ type: 'candidate_ready' });
});
});
function candidateLogoutAction() {
if (typeof Swal !== 'undefined') {
Swal.fire({
title: 'Logout of Assessment?',
text: 'Are you sure you want to exit the Candidate Assessment Room?',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#ef4444',
cancelButtonColor: '#475569',
confirmButtonText: 'Yes, Logout'
}).then((result) => {
if (result.isConfirmed) {
window.location.href = "{{ route('interview.candidate.login') }}";
}
});
} else {
if (confirm('Logout of Assessment?')) {
window.location.href = "{{ route('interview.candidate.login') }}";
}
}
}
function candidateLeaveCall() {
if (activeCallInstance) {
try { activeCallInstance.close(); } catch(e) {}
activeCallInstance = null;
}
const remoteVideo = document.getElementById('interviewer-video');
if (remoteVideo) remoteVideo.srcObject = null;
const placeholder = document.getElementById('interviewer-video-placeholder');
if (placeholder) placeholder.style.display = 'flex';
const badge = document.getElementById('call-status-badge');
if (badge) {
badge.innerText = 'DISCONNECTED (LEAVE)';
badge.style.background = 'rgba(239,68,68,0.2)';
badge.style.color = '#fca5a5';
}
}
function toggleMic() {
if (!localMediaStream) return;
const audioTracks = localMediaStream.getAudioTracks();
if (audioTracks.length > 0) {
isMicEnabled = !isMicEnabled;
audioTracks[0].enabled = isMicEnabled;
const btn = document.getElementById('toggle-mic-btn');
btn.innerText = isMicEnabled ? '🎤 Mic On' : '🔇 Mic Muted';
btn.style.background = isMicEnabled ? 'rgba(16,185,129,0.2)' : 'rgba(239,68,68,0.2)';
btn.style.borderColor = isMicEnabled ? '#10b981' : '#ef4444';
}
}
function toggleCam() {
const avatarPlaceholder = document.getElementById('webcam-avatar-placeholder');
if (localMediaStream) {
const videoTracks = localMediaStream.getVideoTracks();
if (videoTracks.length > 0) {
isCamEnabled = !isCamEnabled;
videoTracks[0].enabled = isCamEnabled;
const btn = document.getElementById('toggle-cam-btn');
btn.innerText = isCamEnabled ? '📷 Cam On' : '🚫 Cam Off';
btn.style.background = isCamEnabled ? 'rgba(16,185,129,0.2)' : 'rgba(239,68,68,0.2)';
btn.style.borderColor = isCamEnabled ? '#10b981' : '#ef4444';
if (avatarPlaceholder) avatarPlaceholder.style.display = isCamEnabled ? 'none' : 'flex';
}
} else {
isCamEnabled = !isCamEnabled;
if (avatarPlaceholder) avatarPlaceholder.style.display = isCamEnabled ? 'none' : 'flex';
}
}
function startScreenShare() {
if (!navigator.mediaDevices.getDisplayMedia) {
alert('Screen sharing is not supported on your browser.');
return;
}
navigator.mediaDevices.getDisplayMedia({ video: true, audio: false })
.then(stream => {
screenShareStream = stream;
const btn = document.getElementById('share-screen-btn');
btn.innerText = '🟢 Screen Sharing Active';
btn.style.background = '#10b981';
// Connect screen stream to interviewer screen peer
const screenPeer = new Peer('cand_screen_' + interviewId + '_' + Date.now());
screenPeer.on('open', () => {
screenPeer.call('interviewer_screen_' + interviewId, stream);
});
stream.getVideoTracks()[0].onended = () => {
btn.innerText = '🖥️ Share Screen with Interviewer';
btn.style.background = 'linear-gradient(135deg, #6366f1 0%, #0078d4 100%)';
};
})
.catch(err => console.log('Screen sharing cancelled'));
}
function analyzeCameraFrame() {
const video = document.getElementById('webcam');
const canvas = document.getElementById('proctor-canvas');
if (!video || !canvas || video.readyState !== 4) return;
const ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// Compute brightness / pixel motion difference
let sum = 0;
for (let i = 0; i < imgData.data.length; i += 4) {
sum += (imgData.data[i] + imgData.data[i+1] + imgData.data[i+2]) / 3;
}
const avgBrightness = sum / (imgData.data.length / 4);
if (avgBrightness < 15) {
logViolation('gaze_anomaly', 'Camera lens covered or room completely dark');
}
}
// 5. 2-Way Real-Time Chat Message Polling (No popup alerts!)
function pollCandidateChat() {
fetch(`{{ route('interview.poll', $interview->id) }}`)
.then(r => r.json())
.then(data => {
const chatHistory = document.getElementById('candidate-chat-history');
if (!chatHistory) return;
if (data.call_status === 'ended') {
candidateLeaveCall();
const badge = document.getElementById('call-status-badge');
if (badge) {
badge.innerText = 'CALL ENDED BY HOST';
badge.style.background = 'rgba(239,68,68,0.2)';
badge.style.color = '#fca5a5';
}
}
if (data.warnings && data.warnings.length > 0) {
let html = '';
data.warnings.forEach(w => {
const isInterviewer = w.sent_by !== null;
const senderName = isInterviewer ? (w.sender ? w.sender.name : 'Interviewer / Panelist') : 'You (Candidate)';
const badgeColor = isInterviewer ? '#6366f1' : '#38bdf8';
const bgColor = isInterviewer ? 'rgba(99,102,241,0.1)' : 'rgba(56,189,248,0.1)';
html += `<div style="margin-bottom:8px; background:${bgColor}; padding:8px 10px; border-radius:8px; border-left:3px solid ${badgeColor};">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
<strong style="color:${badgeColor}; font-size:0.75rem;">${senderName}</strong>
<span style="font-size:0.65rem; color:#94a3b8;">${new Date(w.created_at || Date.now()).toLocaleTimeString()}</span>
</div>
<div style="color: #ffffff !important; font-size:0.85rem; font-weight:500; line-height:1.4;">${w.message}</div>
</div>`;
});
chatHistory.innerHTML = html;
chatHistory.scrollTop = chatHistory.scrollHeight;
}
});
}
setInterval(pollCandidateChat, 3000);
pollCandidateChat();
function sendCandidateMessage() {
const input = document.getElementById('candidate-chat-input');
const msg = input.value.trim();
if (!msg) return;
input.value = '';
fetch(`{{ route('interview.candidate.send-message', $interview->id) }}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ message: msg })
})
.then(r => r.json())
.then(res => {
if (res.success) {
pollCandidateChat();
}
});
}
// --- NOTEPAD & CANVAS DRAWING HANDLERS ---
let notesTimeout = null;
function toggleNotepadModal() {
const modal = document.getElementById('notepad-modal');
modal.style.display = (modal.style.display === 'flex') ? 'none' : 'flex';
}
function saveNotepadContent() {
clearTimeout(notesTimeout);
notesTimeout = setTimeout(() => {
const notes = document.getElementById('notepad-textarea').value;
fetch(`{{ route('interview.candidate.notes', $interview->id) }}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ notes: notes })
});
}, 800);
}
// HTML5 Canvas Drawing Logic
let isDrawing = false;
let canvas, ctx;
let drawingSaveTimeout = null;
function toggleDrawingModal() {
const modal = document.getElementById('drawing-modal');
modal.style.display = (modal.style.display === 'flex') ? 'none' : 'flex';
if (modal.style.display === 'flex' && !canvas) {
initCanvasDrawing();
}
}
function initCanvasDrawing() {
canvas = document.getElementById('drawing-canvas');
if (!canvas) return;
ctx = canvas.getContext('2d');
ctx.lineWidth = 3;
ctx.lineCap = 'round';
ctx.strokeStyle = '#38bdf8';
const savedDrawing = {!! json_encode($interview->candidate_drawing) !!};
if (savedDrawing) {
const img = new Image();
img.onload = () => ctx.drawImage(img, 0, 0);
img.src = savedDrawing;
}
canvas.addEventListener('mousedown', startDraw);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDraw);
canvas.addEventListener('mouseleave', stopDraw);
}
function startDraw(e) {
isDrawing = true;
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
}
function draw(e) {
if (!isDrawing) return;
ctx.strokeStyle = document.getElementById('draw-color').value;
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
}
function stopDraw() {
if (isDrawing) {
isDrawing = false;
ctx.closePath();
saveCanvasDrawing();
}
}
function clearCanvasDraw() {
if (ctx && canvas) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
saveCanvasDrawing();
}
}
function saveCanvasDrawing() {
clearTimeout(drawingSaveTimeout);
drawingSaveTimeout = setTimeout(() => {
if (!canvas) return;
const drawingData = canvas.toDataURL();
fetch(`{{ route('interview.candidate.drawing', $interview->id) }}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ drawing: drawingData })
});
}, 1000);
}
</script>
</body>
</html>