<?php
$pageTitle = 'VPN Servers';
require_once __DIR__ . '/includes/header.php';

// Get all servers
try {
    $db = getDB();
    $servers = $db->query("SELECT * FROM vpn_servers ORDER BY created_at DESC")->fetchAll();
} catch (PDOException $e) {
    logActivity("Servers page error: " . $e->getMessage(), 'error');
    $servers = [];
}

$csrfToken = generateCSRFToken();
?>

<div class="page-actions">
    <button class="btn btn-primary" onclick="showUploadModal()">
        ➕ Upload Server Config
    </button>
</div>

<?php if (isset($_GET['success'])): ?>
    <div class="alert alert-success">
        <?= esc($_GET['success']) ?>
    </div>
<?php endif; ?>

<?php if (isset($_GET['error'])): ?>
    <div class="alert alert-error">
        <?= esc($_GET['error']) ?>
    </div>
<?php endif; ?>

<div class="card">
    <div class="card-header">
        <h2>VPN Servers (<?= count($servers) ?>)</h2>
    </div>
    <div class="card-body">
        <?php if (empty($servers)): ?>
            <div class="empty-state">
                <div class="empty-icon">🌐</div>
                <h3>No servers yet</h3>
                <p>Upload your first .ovpn configuration file to get started</p>
                <button class="btn btn-primary" onclick="showUploadModal()">Upload Server</button>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Server Name</th>
                            <th>Country</th>
                            <th>Flag</th>
                            <th>Status</th>
                            <th>Created</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($servers as $server): ?>
                            <tr>
                                <td><?= $server['id'] ?></td>
                                <td><strong><?= esc($server['server_name']) ?></strong></td>
                                <td><?= esc($server['country']) ?></td>
                                <td>
                                    <?php if ($server['flag_url']): ?>
                                        <img src="<?= esc($server['flag_url']) ?>" alt="Flag" class="flag-icon">
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge badge-<?= $server['status'] === 'active' ? 'success' : 'secondary' ?>">
                                        <?= esc($server['status']) ?>
                                    </span>
                                </td>
                                <td><?= date('M d, Y', strtotime($server['created_at'])) ?></td>
                                <td>
                                    <div class="action-buttons">
                                        <button class="btn btn-sm btn-info" onclick="viewConfig(<?= $server['id'] ?>)">
                                            👁️ View
                                        </button>
                                        <button class="btn btn-sm btn-warning" onclick="toggleStatus(<?= $server['id'] ?>, '<?= $server['status'] ?>')">
                                            <?= $server['status'] === 'active' ? '⏸️ Disable' : '▶️ Enable' ?>
                                        </button>
                                        <button class="btn btn-sm btn-danger" onclick="deleteServer(<?= $server['id'] ?>)">
                                            🗑️ Delete
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Upload Modal -->
<div id="uploadModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2>Upload VPN Server Config</h2>
            <button class="modal-close" onclick="closeUploadModal()">&times;</button>
        </div>
        <form action="handlers/upload-server.php" method="POST" enctype="multipart/form-data" id="uploadForm">
            <input type="hidden" name="csrf_token" value="<?= esc($csrfToken) ?>">
            
            <div class="modal-body">
                <div class="form-group">
                    <label for="server_name">Server Name *</label>
                    <input type="text" id="server_name" name="server_name" required 
                           placeholder="e.g., USA Server 1">
                </div>
                
                <div class="form-group">
                    <label for="country">Country *</label>
                    <input type="text" id="country" name="country" required 
                           placeholder="e.g., United States">
                </div>
                
                <div class="form-group">
                    <label for="flag_url">Flag URL (optional)</label>
                    <input type="url" id="flag_url" name="flag_url" 
                           placeholder="https://example.com/flags/us.png">
                    <small class="text-muted">Direct link to country flag image</small>
                </div>
                
                <div class="form-group">
                    <label for="ovpn_file">OpenVPN Config File (.ovpn) *</label>
                    <input type="file" id="ovpn_file" name="ovpn_file" accept=".ovpn" required>
                    <small class="text-muted">Upload your .ovpn configuration file from VPN Gate</small>
                </div>
            </div>
            
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeUploadModal()">Cancel</button>
                <button type="submit" class="btn btn-primary">Upload Server</button>
            </div>
        </form>
    </div>
</div>

<!-- View Config Modal -->
<div id="configModal" class="modal">
    <div class="modal-content modal-large">
        <div class="modal-header">
            <h2>OpenVPN Configuration</h2>
            <button class="modal-close" onclick="closeConfigModal()">&times;</button>
        </div>
        <div class="modal-body">
            <pre id="configContent" class="config-display"></pre>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeConfigModal()">Close</button>
            <button type="button" class="btn btn-primary" onclick="copyConfig()">📋 Copy</button>
        </div>
    </div>
</div>

<script>
function showUploadModal() {
    document.getElementById('uploadModal').style.display = 'flex';
}

function closeUploadModal() {
    document.getElementById('uploadModal').style.display = 'none';
}

function viewConfig(serverId) {
    fetch(`handlers/get-server-config.php?id=${serverId}`)
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                document.getElementById('configContent').textContent = data.config;
                document.getElementById('configModal').style.display = 'flex';
            } else {
                alert('Error: ' + data.message);
            }
        });
}

function closeConfigModal() {
    document.getElementById('configModal').style.display = 'none';
}

function copyConfig() {
    const config = document.getElementById('configContent').textContent;
    navigator.clipboard.writeText(config).then(() => {
        alert('Configuration copied to clipboard!');
    });
}

function toggleStatus(serverId, currentStatus) {
    const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
    if (confirm(`Are you sure you want to ${newStatus === 'active' ? 'enable' : 'disable'} this server?`)) {
        window.location.href = `handlers/toggle-server.php?id=${serverId}&status=${newStatus}&csrf_token=<?= esc($csrfToken) ?>`;
    }
}

function deleteServer(serverId) {
    if (confirm('Are you sure you want to delete this server? This action cannot be undone.')) {
        window.location.href = `handlers/delete-server.php?id=${serverId}&csrf_token=<?= esc($csrfToken) ?>`;
    }
}

// Close modals on outside click
window.onclick = function(event) {
    if (event.target.classList.contains('modal')) {
        event.target.style.display = 'none';
    }
}
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
