<?php
$pageTitle = 'API Keys';
require_once __DIR__ . '/includes/header.php';

// Get all API keys with server access count
try {
    $db = getDB();
    $stmt = $db->query("
        SELECT 
            a.*,
            COUNT(DISTINCT asa.server_id) as server_count
        FROM api_keys a
        LEFT JOIN api_server_access asa ON a.id = asa.api_key_id
        GROUP BY a.id
        ORDER BY a.created_at DESC
    ");
    $apiKeys = $stmt->fetchAll();
    
    // Get all servers for assignment
    $servers = $db->query("SELECT id, server_name, country, status FROM vpn_servers ORDER BY server_name")->fetchAll();
    
} catch (PDOException $e) {
    logActivity("API keys page error: " . $e->getMessage(), 'error');
    $apiKeys = [];
    $servers = [];
}

$csrfToken = generateCSRFToken();
?>

<div class="page-actions">
    <button class="btn btn-primary" onclick="showGenerateModal()">
        🔑 Generate New API Key
    </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>API Keys (<?= count($apiKeys) ?>)</h2>
    </div>
    <div class="card-body">
        <?php if (empty($apiKeys)): ?>
            <div class="empty-state">
                <div class="empty-icon">🔑</div>
                <h3>No API keys yet</h3>
                <p>Generate your first API key to connect Android apps</p>
                <button class="btn btn-primary" onclick="showGenerateModal()">Generate API Key</button>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>App Name</th>
                            <th>API Key</th>
                            <th>Usage Limit</th>
                            <th>Used Count</th>
                            <th>Servers</th>
                            <th>Status</th>
                            <th>Created</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($apiKeys as $api): ?>
                            <tr>
                                <td><?= $api['id'] ?></td>
                                <td><strong><?= esc($api['app_name']) ?></strong></td>
                                <td>
                                    <div class="api-key-display">
                                        <code class="api-key-text" id="key-<?= $api['id'] ?>">
                                            <?= esc(substr($api['api_key'], 0, 32)) ?>...
                                        </code>
                                        <button class="btn btn-xs btn-outline" onclick="copyApiKey('<?= esc($api['api_key']) ?>')">
                                            📋
                                        </button>
                                    </div>
                                </td>
                                <td>
                                    <?php if ($api['usage_limit']): ?>
                                        <?= number_format($api['usage_limit']) ?>/day
                                    <?php else: ?>
                                        <span class="badge badge-success">Unlimited</span>
                                    <?php endif; ?>
                                </td>
                                <td><?= number_format($api['used_count']) ?></td>
                                <td>
                                    <span class="badge badge-info"><?= $api['server_count'] ?> servers</span>
                                </td>
                                <td>
                                    <span class="badge badge-<?= $api['status'] === 'active' ? 'success' : 'secondary' ?>">
                                        <?= esc($api['status']) ?>
                                    </span>
                                </td>
                                <td><?= date('M d, Y', strtotime($api['created_at'])) ?></td>
                                <td>
                                    <div class="action-buttons">
                                        <button class="btn btn-sm btn-info" onclick="manageServers(<?= $api['id'] ?>)">
                                            🌐 Servers
                                        </button>
                                        <button class="btn btn-sm btn-warning" onclick="toggleAPIStatus(<?= $api['id'] ?>, '<?= $api['status'] ?>')">
                                            <?= $api['status'] === 'active' ? '⏸️' : '▶️' ?>
                                        </button>
                                        <button class="btn btn-sm btn-danger" onclick="deleteAPI(<?= $api['id'] ?>)">
                                            🗑️
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Generate API Key Modal -->
<div id="generateModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2>Generate New API Key</h2>
            <button class="modal-close" onclick="closeGenerateModal()">&times;</button>
        </div>
        <form action="handlers/manage-api.php" method="POST">
            <input type="hidden" name="csrf_token" value="<?= esc($csrfToken) ?>">
            <input type="hidden" name="action" value="generate">
            
            <div class="modal-body">
                <div class="form-group">
                    <label for="app_name">App Name *</label>
                    <input type="text" id="app_name" name="app_name" required 
                           placeholder="e.g., Free VPN App">
                </div>
                
                <div class="form-group">
                    <label for="usage_limit">Daily Usage Limit</label>
                    <input type="number" id="usage_limit" name="usage_limit" 
                           placeholder="Leave empty for unlimited" min="1">
                    <small class="text-muted">Number of API requests allowed per day (empty = unlimited)</small>
                </div>
            </div>
            
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeGenerateModal()">Cancel</button>
                <button type="submit" class="btn btn-primary">Generate API Key</button>
            </div>
        </form>
    </div>
</div>

<!-- Manage Servers Modal -->
<div id="serversModal" class="modal">
    <div class="modal-content modal-large">
        <div class="modal-header">
            <h2>Assign Servers to API</h2>
            <button class="modal-close" onclick="closeServersModal()">&times;</button>
        </div>
        <form action="handlers/manage-api.php" method="POST" id="serversForm">
            <input type="hidden" name="csrf_token" value="<?= esc($csrfToken) ?>">
            <input type="hidden" name="action" value="assign_servers">
            <input type="hidden" name="api_id" id="assign_api_id">
            
            <div class="modal-body">
                <div id="serversList">
                    <?php foreach ($servers as $server): ?>
                        <div class="checkbox-item">
                            <label>
                                <input type="checkbox" name="servers[]" value="<?= $server['id'] ?>">
                                <span class="checkbox-label">
                                    <strong><?= esc($server['server_name']) ?></strong>
                                    <span class="text-muted">(<?= esc($server['country']) ?>)</span>
                                    <?php if ($server['status'] === 'inactive'): ?>
                                        <span class="badge badge-secondary">Inactive</span>
                                    <?php endif; ?>
                                </span>
                            </label>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeServersModal()">Cancel</button>
                <button type="submit" class="btn btn-primary">Save Server Access</button>
            </div>
        </form>
    </div>
</div>

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

function closeGenerateModal() {
    document.getElementById('generateModal').style.display = 'none';
}

function copyApiKey(key) {
    navigator.clipboard.writeText(key).then(() => {
        alert('API key copied to clipboard!');
    });
}

function manageServers(apiId) {
    document.getElementById('assign_api_id').value = apiId;
    
    // Load currently assigned servers
    fetch(`handlers/get-api-servers.php?id=${apiId}`)
        .then(res => res.json())
        .then(data => {
            // Uncheck all first
            document.querySelectorAll('input[name="servers[]"]').forEach(cb => {
                cb.checked = false;
            });
            
            // Check assigned servers
            if (data.success && data.servers) {
                data.servers.forEach(serverId => {
                    const checkbox = document.querySelector(`input[name="servers[]"][value="${serverId}"]`);
                    if (checkbox) checkbox.checked = true;
                });
            }
            
            document.getElementById('serversModal').style.display = 'flex';
        });
}

function closeServersModal() {
    document.getElementById('serversModal').style.display = 'none';
}

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

function deleteAPI(apiId) {
    if (confirm('Are you sure you want to delete this API key? All connected apps will stop working.')) {
        window.location.href = `handlers/delete-api.php?id=${apiId}&csrf_token=<?= esc($csrfToken) ?>`;
    }
}

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

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