<?php
$sessionToken = $_GET['token'] ?? '';
if (!$sessionToken) {
    header('Location: /atasteofafricanmarketplace/dashboard/user/appointments.php');
    exit;
}

$page_title = 'Video Session | Herbal Wellness Care';
$page_description = 'Secure video consultation session';
$page_content = function () use ($sessionToken) { ?>

<style>
body {
    margin: 0;
    padding: 0;
    overflow: hidden;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.video-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    background: linear-gradient(135deg, #0b3d2e 0%, #064e3b 50%, #0b3d2e 100%);
    display: flex;
    flex-direction: column;
}

.video-header {
    background: linear-gradient(135deg, rgba(16, 185, 129, 0.95), rgba(5, 150, 105, 0.95));
    backdrop-filter: blur(10px);
    padding: 20px 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
    z-index: 100;
}

.session-info {
    display: flex;
    align-items: center;
    gap: 20px;
}

.session-title {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.session-title h1 {
    margin: 0;
    font-size: 24px;
    font-weight: 700;
    color: white;
    display: flex;
    align-items: center;
    gap: 10px;
}

.session-title .status {
    font-size: 13px;
    color: rgba(255, 255, 255, 0.9);
    display: flex;
    align-items: center;
    gap: 8px;
}

.status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #22c55e;
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
}

.timer {
    background: rgba(255, 255, 255, 0.2);
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 16px;
    font-weight: 600;
    color: white;
}

.video-main {
    flex: 1;
    display: flex;
    overflow: hidden;
    position: relative;
}

.video-area {
    flex: 1;
    position: relative;
    background: #000;
    display: flex;
    align-items: center;
    justify-content: center;
}

#remote-video {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.video-placeholder {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    color: white;
}

.video-placeholder i {
    font-size: 80px;
    color: rgba(255, 255, 255, 0.3);
    margin-bottom: 20px;
}

.video-placeholder p {
    font-size: 18px;
    color: rgba(255, 255, 255, 0.7);
    margin: 0;
}

#local-video {
    position: absolute;
    bottom: 24px;
    right: 24px;
    width: 280px;
    height: 210px;
    border-radius: 16px;
    border: 3px solid rgba(16, 185, 129, 0.6);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
    object-fit: cover;
    background: #1f2937;
    z-index: 10;
}

.local-video-label {
    position: absolute;
    bottom: 32px;
    right: 32px;
    background: rgba(16, 185, 129, 0.9);
    padding: 6px 12px;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 600;
    color: white;
    z-index: 11;
    pointer-events: none;
}

.controls-bar {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 24px;
    background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
    display: flex;
    justify-content: center;
    gap: 16px;
    z-index: 20;
}

.control-btn {
    min-width: 120px;
    height: 56px;
    border-radius: 28px;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    font-size: 15px;
    font-weight: 600;
    padding: 0 24px;
    transition: all 0.3s;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.control-btn i {
    font-size: 20px;
}

.control-btn:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4);
}

.control-btn.video {
    background: linear-gradient(135deg, #10b981, #059669);
    color: white;
}

.control-btn.video.off {
    background: #ef4444;
}

.control-btn.audio {
    background: linear-gradient(135deg, #10b981, #059669);
    color: white;
}

.control-btn.audio.off {
    background: #ef4444;
}

.control-btn.chat {
    background: linear-gradient(135deg, #3b82f6, #2563eb);
    color: white;
}

.control-btn.end {
    background: linear-gradient(135deg, #ef4444, #dc2626);
    color: white;
    min-width: 140px;
    height: 64px;
    font-size: 16px;
}

.chat-sidebar {
    width: 380px;
    background: white;
    display: flex;
    flex-direction: column;
    box-shadow: -4px 0 20px rgba(0, 0, 0, 0.2);
    transform: translateX(100%);
    transition: transform 0.3s;
    position: relative;
    z-index: 50;
}

.chat-sidebar.open {
    transform: translateX(0);
}

.chat-header {
    padding: 20px 24px;
    background: linear-gradient(135deg, #10b981, #059669);
    color: white;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.chat-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 10px;
}

.close-chat {
    background: rgba(255, 255, 255, 0.2);
    border: none;
    color: white;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
}

.close-chat:hover {
    background: rgba(255, 255, 255, 0.3);
}

.chat-messages {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 12px;
    background: #f9fafb;
}

.chat-welcome {
    text-align: center;
    padding: 40px 20px;
    color: #64748b;
}

.chat-welcome i {
    font-size: 48px;
    color: #10b981;
    margin-bottom: 12px;
}

.chat-welcome p {
    margin: 0;
    font-size: 14px;
}

.message {
    display: flex;
    margin-bottom: 12px;
}

.message.own {
    justify-content: flex-end;
}

.message-content {
    max-width: 75%;
    padding: 12px 16px;
    border-radius: 12px;
    word-wrap: break-word;
}

.message.own .message-content {
    background: linear-gradient(135deg, #10b981, #059669);
    color: white;
    border-bottom-right-radius: 4px;
}

.message:not(.own) .message-content {
    background: white;
    color: #1f2937;
    border-bottom-left-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-sender {
    font-size: 11px;
    font-weight: 600;
    margin-bottom: 4px;
    opacity: 0.8;
}

.message-text {
    font-size: 14px;
    line-height: 1.5;
}

.chat-input {
    padding: 20px;
    background: white;
    border-top: 1px solid #e5e7eb;
}

.chat-input-wrapper {
    display: flex;
    gap: 12px;
    align-items: center;
}

#message-input {
    flex: 1;
    padding: 12px 16px;
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    font-size: 14px;
    transition: all 0.3s;
}

#message-input:focus {
    outline: none;
    border-color: #10b981;
}

#send-message {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    border: none;
    background: linear-gradient(135deg, #10b981, #059669);
    color: white;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    transition: all 0.3s;
}

#send-message:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

.connection-status {
    position: absolute;
    top: 24px;
    left: 24px;
    background: rgba(0, 0, 0, 0.7);
    backdrop-filter: blur(10px);
    padding: 10px 16px;
    border-radius: 12px;
    color: white;
    font-size: 13px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 8px;
    z-index: 10;
}

.connection-status i {
    color: #22c55e;
}
</style>

<div class="video-container">
    <!-- Header -->
    <div class="video-header">
        <div class="session-info">
            <div class="session-title">
                <h1>
                    <i class="fas fa-video"></i>
                    Wellness Consultation
                </h1>
                <div class="status">
                    <span class="status-dot"></span>
                    <span id="session-status">Connected</span>
                </div>
            </div>
        </div>
        <div class="timer" id="session-timer">00:00</div>
    </div>

    <!-- Main Video Area -->
    <div class="video-main">
        <div class="video-area">
            <video id="remote-video" autoplay playsinline></video>
            <div class="video-placeholder" id="video-placeholder">
                <i class="fas fa-user-circle"></i>
                <p>Waiting for participant...</p>
            </div>
            
            <div class="connection-status" id="connection-status">
                <i class="fas fa-signal"></i>
                <span>Excellent Connection</span>
            </div>
            
            <video id="local-video" autoplay playsinline muted></video>
            <div class="local-video-label">You</div>
            
            <!-- Control Bar -->
            <div class="controls-bar">
                <button id="toggle-video" class="control-btn video" title="Toggle Video">
                    <i class="fas fa-video"></i>
                    <span>Video</span>
                </button>
                <button id="toggle-audio" class="control-btn audio" title="Toggle Audio">
                    <i class="fas fa-microphone"></i>
                    <span>Microphone</span>
                </button>
                <button id="toggle-chat" class="control-btn chat" title="Toggle Chat">
                    <i class="fas fa-comment"></i>
                    <span>Chat</span>
                </button>
                <button id="end-session" class="control-btn end" title="End Session">
                    <i class="fas fa-phone-slash"></i>
                    <span>End Call</span>
                </button>
            </div>
        </div>

        <!-- Chat Sidebar -->
        <div class="chat-sidebar" id="chat-sidebar">
            <div class="chat-header">
                <h3>
                    <i class="fas fa-comments"></i>
                    Chat
                </h3>
                <button class="close-chat" id="close-chat">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div class="chat-messages" id="chat-messages">
                <div class="chat-welcome">
                    <i class="fas fa-comments"></i>
                    <p>Start a conversation during your session</p>
                </div>
            </div>
            
            <div class="chat-input">
                <div class="chat-input-wrapper">
                    <input type="text" id="message-input" placeholder="Type a message...">
                    <button id="send-message" title="Send Message">
                        <i class="fas fa-paper-plane"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
class VideoSession {
    constructor(sessionToken) {
        this.sessionToken = sessionToken;
        this.sessionId = null;
        this.localStream = null;
        this.peerConnection = null;
        this.isVideoEnabled = true;
        this.isAudioEnabled = true;
        this.isChatOpen = false;
        this.sessionStartTime = Date.now();
        
        this.init();
    }
    
    async init() {
        try {
            // Initialize session
            await this.initializeSession();
            
            // Setup media
            await this.setupMedia();
            
            // Setup chat
            this.setupChat();
            
            // Setup controls
            this.setupControls();
            
            // Start timer
            this.startTimer();
            
            document.getElementById('session-status').textContent = 'Session Active';
            document.getElementById('connection-status').innerHTML = '<i class="fas fa-signal"></i><span>Excellent Connection</span>';
        } catch (error) {
            console.error('Session initialization failed:', error);
            document.getElementById('session-status').textContent = 'Connection failed';
            document.getElementById('connection-status').innerHTML = '<i class="fas fa-exclamation-triangle"></i><span>Connection Failed</span>';
        }
    }
    
    async initializeSession() {
        this.sessionId = 1; // Mock session ID
        console.log('Session initialized with token:', this.sessionToken);
    }
    
    startTimer() {
        setInterval(() => {
            const elapsed = Date.now() - this.sessionStartTime;
            const minutes = Math.floor(elapsed / 60000);
            const seconds = Math.floor((elapsed % 60000) / 1000);
            document.getElementById('session-timer').textContent = 
                `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
        }, 1000);
    }
    
    async setupMedia() {
        try {
            this.localStream = await navigator.mediaDevices.getUserMedia({
                video: { width: 1280, height: 720 },
                audio: { echoCancellation: true, noiseSuppression: true }
            });
            
            const localVideo = document.getElementById('local-video');
            localVideo.srcObject = this.localStream;
            
            // Hide placeholder when video starts
            setTimeout(() => {
                document.getElementById('video-placeholder').style.display = 'none';
            }, 1000);
            
            this.simulateRemoteVideo();
        } catch (error) {
            console.error('Media setup failed:', error);
            alert('Camera/microphone access is required for video sessions. Please allow access and refresh the page.');
        }
    }
    
    simulateRemoteVideo() {
        const remoteVideo = document.getElementById('remote-video');
        const canvas = document.createElement('canvas');
        canvas.width = 1280;
        canvas.height = 720;
        const ctx = canvas.getContext('2d');
        
        const animate = () => {
            // Create gradient background
            const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
            gradient.addColorStop(0, '#0b3d2e');
            gradient.addColorStop(0.5, '#064e3b');
            gradient.addColorStop(1, '#0b3d2e');
            ctx.fillStyle = gradient;
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // Add pulsing circle
            const pulse = Math.sin(Date.now() / 1000) * 20 + 100;
            ctx.beginPath();
            ctx.arc(canvas.width / 2, canvas.height / 2 - 60, pulse, 0, Math.PI * 2);
            ctx.fillStyle = 'rgba(16, 185, 129, 0.2)';
            ctx.fill();
            
            // Add icon
            ctx.fillStyle = '#10b981';
            ctx.font = 'bold 120px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('👤', canvas.width / 2, canvas.height / 2);
            
            // Add text
            ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';
            ctx.font = 'bold 32px Arial';
            ctx.fillText('Waiting for participant...', canvas.width / 2, canvas.height / 2 + 100);
            
            ctx.font = '20px Arial';
            ctx.fillStyle = 'rgba(255, 255, 255, 0.6)';
            ctx.fillText('Demo Mode - In production, WebRTC will connect participants', canvas.width / 2, canvas.height / 2 + 140);
            
            requestAnimationFrame(animate);
        };
        animate();
        
        const stream = canvas.captureStream(30);
        remoteVideo.srcObject = stream;
    }
    
    setupChat() {
        const messageInput = document.getElementById('message-input');
        const sendButton = document.getElementById('send-message');
        
        const sendMessage = async () => {
            const content = messageInput.value.trim();
            if (!content) return;
            
            try {
                const response = await fetch('/atasteofafricanmarketplace/api/video/chat.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'include',
                    body: JSON.stringify({
                        session_id: this.sessionId,
                        content: content,
                        message_type: 'text'
                    })
                });
                
                if (response.ok) {
                    messageInput.value = '';
                    this.addMessageToChat('You', content, true);
                }
            } catch (error) {
                console.error('Failed to send message:', error);
                // Still add message locally for demo
                messageInput.value = '';
                this.addMessageToChat('You', content, true);
            }
        };
        
        sendButton.addEventListener('click', sendMessage);
        messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') sendMessage();
        });
    }
    
    addMessageToChat(sender, content, isOwn = false) {
        const messagesContainer = document.getElementById('chat-messages');
        
        // Remove welcome message if exists
        const welcome = messagesContainer.querySelector('.chat-welcome');
        if (welcome) welcome.remove();
        
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${isOwn ? 'own' : ''}`;
        
        messageDiv.innerHTML = `
            <div class="message-content">
                <div class="message-sender">${sender}</div>
                <div class="message-text">${this.escapeHtml(content)}</div>
            </div>
        `;
        
        messagesContainer.appendChild(messageDiv);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }
    
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    setupControls() {
        // Toggle video
        document.getElementById('toggle-video').addEventListener('click', () => {
            this.isVideoEnabled = !this.isVideoEnabled;
            const btn = document.getElementById('toggle-video');
            
            if (this.localStream) {
                this.localStream.getVideoTracks().forEach(track => {
                    track.enabled = this.isVideoEnabled;
                });
            }
            
            if (this.isVideoEnabled) {
                btn.classList.remove('off');
                btn.innerHTML = '<i class="fas fa-video"></i><span>Video</span>';
            } else {
                btn.classList.add('off');
                btn.innerHTML = '<i class="fas fa-video-slash"></i><span>Video Off</span>';
            }
        });
        
        // Toggle audio
        document.getElementById('toggle-audio').addEventListener('click', () => {
            this.isAudioEnabled = !this.isAudioEnabled;
            const btn = document.getElementById('toggle-audio');
            
            if (this.localStream) {
                this.localStream.getAudioTracks().forEach(track => {
                    track.enabled = this.isAudioEnabled;
                });
            }
            
            if (this.isAudioEnabled) {
                btn.classList.remove('off');
                btn.innerHTML = '<i class="fas fa-microphone"></i><span>Microphone</span>';
            } else {
                btn.classList.add('off');
                btn.innerHTML = '<i class="fas fa-microphone-slash"></i><span>Muted</span>';
            }
        });
        
        // Toggle chat
        document.getElementById('toggle-chat').addEventListener('click', () => {
            this.isChatOpen = !this.isChatOpen;
            const sidebar = document.getElementById('chat-sidebar');
            
            if (this.isChatOpen) {
                sidebar.classList.add('open');
            } else {
                sidebar.classList.remove('open');
            }
        });
        
        document.getElementById('close-chat').addEventListener('click', () => {
            this.isChatOpen = false;
            document.getElementById('chat-sidebar').classList.remove('open');
        });
        
        // End session
        document.getElementById('end-session').addEventListener('click', () => {
            if (confirm('Are you sure you want to end this session?')) {
                this.endSession();
            }
        });
    }
    
    endSession() {
        if (this.localStream) {
            this.localStream.getTracks().forEach(track => track.stop());
        }
        
        // Redirect back to dashboard
        const userType = window.location.pathname.includes('/coach/') ? 'coach' : 'user';
        window.location.href = `/atasteofafricanmarketplace/dashboard/${userType}/`;
    }
}

// Initialize video session
const session = new VideoSession('<?= htmlspecialchars($sessionToken) ?>');
</script>

<?php };
include __DIR__ . '/partials/layout.php';
?>