<?php
// Permission checking is handled by the permission system in auto-prepend.php

// Check if user is authenticated
if (!defined('AUTH_USER')) {
    header('Location: login.php');
    exit();
}

$is_root = (defined('AUTH_USER') && AUTH_USER === 'root');
?>

<link rel="stylesheet" href="js/xterm/xterm.css" />

<?php if (!empty($message)): ?>
    <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
        <?php echo htmlspecialchars($message); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="alert alert-warning" role="alert">
    <h6 class="alert-heading mb-2"><i class="fa fa-exclamation-triangle"></i> Important Notice</h6>
    <p class="mb-1"><strong>Container modifications will not persist.</strong> Containers may be refreshed at any time, which will reset any changes you make to the container filesystem.</p>
    <p class="mb-0">If you need a customized container with persistent modifications, please contact support to discuss custom container solutions.</p>
</div>

<div class="row">
    <div class="col-md-3">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Container Selection</h5>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label for="containerSelect" class="form-label">Select Container</label>
                    <select class="form-select" id="containerSelect">
                        <option value="">Loading containers...</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label for="userInput" class="form-label">User</label>
                    <input type="text" class="form-control" id="userInput" placeholder="Default: container owner" style="color: #000; background-color: #fff;">
                    <div class="form-text" style="color: #aaa;">Leave empty to use container owner</div>
                </div>
                
                <div class="mb-3">
                    <label for="shellSelect" class="form-label">Shell</label>
                    <select class="form-select" id="shellSelect">
                        <option value="bash" selected>bash</option>
                        <option value="sh">sh</option>
                        <option value="ash">ash (Alpine)</option>
                        <option value="zsh">zsh</option>
                        <option value="fish">fish</option>
                    </select>
                </div>
                
                <button class="btn btn-primary w-100" id="connectBtn" disabled>Connect to Container</button>
            </div>
        </div>
        
        <div class="card mt-3">
            <div class="card-header">
                <h5 class="mb-0">Session Info</h5>
            </div>
            <div class="card-body" id="sessionInfo">
                <p class="text-muted mb-0">No active session</p>
            </div>
        </div>
        
        <div class="card mt-3">
            <div class="card-header">
                <h5 class="mb-0">Terminal Settings</h5>
            </div>
            <div class="card-body">
                <div class="mb-2">
                    <label for="fontSizeRange" class="form-label">Font Size: <span id="fontSizeValue">14</span>px</label>
                    <input type="range" class="form-range" min="10" max="20" value="14" id="fontSizeRange">
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="cursorBlink" checked>
                    <label class="form-check-label" for="cursorBlink">Cursor Blink</label>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-9">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Terminal</h5>
                <div>
                    <span class="badge bg-secondary me-2" id="terminalSize">80x24</span>
                    <button class="btn btn-sm btn-outline-danger" id="disconnectBtn" style="display: none;">Disconnect</button>
                </div>
            </div>
            <div class="card-body p-0" style="background: #000;">
                <div id="terminal-container" style="padding: 5px; height: 600px;">
                    <div id="terminal-placeholder" class="text-muted p-3" style="color: #666;">
                        Select a container and click Connect to start a terminal session.
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="js/xterm/xterm.js"></script>
<script src="js/xterm/addons/xterm-addon-fit.js"></script>
<script src="js/xterm/addons/xterm-addon-web-links.js"></script>

<script>
const nonce = '<?php echo get_csrf_token(); ?>';
let terminal = null;
let fitAddon = null;
let webLinksAddon = null;
let ws = null;
let currentSession = null;
let resizeTimeout = null;

// Load containers on page load
document.addEventListener('DOMContentLoaded', function() {
    loadContainers();
    
    // Enable connect button when container is selected
    document.getElementById('containerSelect').addEventListener('change', function() {
        document.getElementById('connectBtn').disabled = !this.value;
    });
    
    // Connect button click
    document.getElementById('connectBtn').addEventListener('click', connectToContainer);
    
    // Disconnect button click
    document.getElementById('disconnectBtn').addEventListener('click', disconnect);
    
    // Font size adjustment
    document.getElementById('fontSizeRange').addEventListener('input', function(e) {
        const size = e.target.value;
        document.getElementById('fontSizeValue').textContent = size;
        if (terminal) {
            terminal.options.fontSize = parseInt(size);
            fitAddon.fit();
        }
    });
    
    // Cursor blink
    document.getElementById('cursorBlink').addEventListener('change', function(e) {
        if (terminal) {
            terminal.options.cursorBlink = e.target.checked;
        }
    });
    
    // Handle window resize
    window.addEventListener('resize', function() {
        if (resizeTimeout) clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(() => {
            if (terminal && fitAddon) {
                fitAddon.fit();
                sendResize();
            }
        }, 100);
    });
});

function loadContainers() {
    fetch('/api/terminal.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': nonce
        },
        body: JSON.stringify({ action: 'list_containers' })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const select = document.getElementById('containerSelect');
            select.innerHTML = '<option value="">Select a container...</option>';
            
            data.containers.forEach(container => {
                const option = document.createElement('option');
                option.value = container.container_id;
                option.textContent = `${container.container_id} (${container.site_name} - ${container.username})`;
                select.appendChild(option);
            });
        } else {
            showError('Failed to load containers: ' + data.error);
        }
    })
    .catch(error => {
        showError('Error loading containers: ' + error.message);
    });
}

async function connectToContainer() {
    const containerId = document.getElementById('containerSelect').value;
    const user = document.getElementById('userInput').value;
    const shell = document.getElementById('shellSelect').value;
    
    if (!containerId) return;
    
    try {
        // Get auth token for WebSocket
        const authResponse = await fetch('/api/terminal-auth.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': nonce
            }
        });
        
        const authData = await authResponse.json();
        if (!authData.success) {
            showError('Failed to get auth token: ' + authData.error);
            return;
        }
        
        // Remove placeholder
        document.getElementById('terminal-placeholder').style.display = 'none';
        
        // Create terminal
        terminal = new Terminal({
            fontSize: parseInt(document.getElementById('fontSizeRange').value),
            cursorBlink: document.getElementById('cursorBlink').checked,
            theme: {
                background: '#000000',
                foreground: '#ffffff',
                cursor: '#00ff00'
            }
        });
        
        // Add addons
        fitAddon = new FitAddon.FitAddon();
        webLinksAddon = new WebLinksAddon.WebLinksAddon();
        terminal.loadAddon(fitAddon);
        terminal.loadAddon(webLinksAddon);
        
        // Open terminal in container
        terminal.open(document.getElementById('terminal-container'));
        fitAddon.fit();
        
        // Update terminal size display
        updateTerminalSize();
        
        // Create WebSocket connection
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        ws = new WebSocket(`${protocol}//${window.location.host}/terminal-ws`);
        
        ws.onopen = () => {
            console.log('WebSocket connected');
            
            // Send authentication
            ws.send(JSON.stringify({
                type: 'auth',
                token: authData.token
            }));
        };
        
        ws.onmessage = (event) => {
            const message = JSON.parse(event.data);
            
            switch (message.type) {
                case 'authenticated':
                    // Now connect to container
                    ws.send(JSON.stringify({
                        type: 'connect',
                        containerId: containerId,
                        user: user || undefined,
                        shell: shell,
                        cols: terminal.cols,
                        rows: terminal.rows
                    }));
                    break;
                    
                case 'connected':
                    // Update UI
                    document.getElementById('connectBtn').disabled = true;
                    document.getElementById('disconnectBtn').style.display = 'inline-block';
                    document.getElementById('containerSelect').disabled = true;
                    document.getElementById('userInput').disabled = true;
                    document.getElementById('shellSelect').disabled = true;
                    
                    // Update session info
                    document.getElementById('sessionInfo').innerHTML = `
                        <p class="mb-1"><strong>Container:</strong> ${containerId}</p>
                        <p class="mb-1"><strong>User:</strong> ${user || 'container owner'}</p>
                        <p class="mb-1"><strong>Shell:</strong> ${shell}</p>
                        <p class="mb-0 text-success"><strong>Status:</strong> Connected</p>
                    `;
                    
                    terminal.focus();
                    break;
                    
                case 'data':
                    terminal.write(message.data);
                    break;
                    
                case 'exit':
                    terminal.write('\r\n\r\n[Process exited with code ' + message.code + ']\r\n');
                    disconnect();
                    break;
                    
                case 'error':
                    showError(message.message);
                    disconnect();
                    break;
            }
        };
        
        ws.onerror = (error) => {
            console.error('WebSocket error:', error);
            showError('WebSocket connection error');
            disconnect();
        };
        
        ws.onclose = () => {
            console.log('WebSocket disconnected');
            if (terminal) {
                terminal.write('\r\n[Disconnected]\r\n');
            }
        };
        
        // Send terminal input to WebSocket
        terminal.onData((data) => {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({
                    type: 'data',
                    data: data
                }));
            }
        });
        
        // Handle terminal resize
        terminal.onResize((size) => {
            updateTerminalSize();
            sendResize();
        });
        
    } catch (error) {
        showError('Connection error: ' + error.message);
    }
}

function disconnect() {
    if (ws) {
        ws.close();
        ws = null;
    }
    
    if (terminal) {
        terminal.dispose();
        terminal = null;
        fitAddon = null;
        webLinksAddon = null;
    }
    
    // Reset UI
    document.getElementById('connectBtn').disabled = false;
    document.getElementById('disconnectBtn').style.display = 'none';
    document.getElementById('containerSelect').disabled = false;
    document.getElementById('userInput').disabled = false;
    document.getElementById('shellSelect').disabled = false;
    
    // Update session info
    document.getElementById('sessionInfo').innerHTML = '<p class="text-muted mb-0">No active session</p>';
    
    // Show placeholder
    document.getElementById('terminal-placeholder').style.display = 'block';
}

function sendResize() {
    if (ws && ws.readyState === WebSocket.OPEN && terminal) {
        ws.send(JSON.stringify({
            type: 'resize',
            cols: terminal.cols,
            rows: terminal.rows
        }));
    }
}

function updateTerminalSize() {
    if (terminal) {
        document.getElementById('terminalSize').textContent = `${terminal.cols}x${terminal.rows}`;
    }
}

function showError(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'alert alert-danger alert-dismissible fade show';
    alertDiv.setAttribute('role', 'alert');
    alertDiv.innerHTML = `
        ${escapeHtml(message)}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    document.querySelector('.col-md-3').insertBefore(alertDiv, document.querySelector('.card'));
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}
</script>