<?php
require_once '../config.php';
require_once '../app/classes/AdminAuth.php';
require_once '../app/classes/ApiKeyManager.php';

$adminAuth = new AdminAuth($conn);

// Check if admin is authenticated
if (!$adminAuth->isAuthenticated()) {
    header('Location: admin_login.php');
    exit();
}

// Initialize API key manager
$apiKeyManager = new ApiKeyManager($conn);

// Handle form submissions
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'generate_key':
                $user_id = intval($_POST['user_id']);
                $name = trim($_POST['key_name']);
                $description = trim($_POST['key_description']);
                $rateLimit = intval($_POST['rate_limit']);
                $permissions = $_POST['permissions'] ?? null;
                
                if (empty($name) || $user_id <= 0) {
                    $message = 'User ID and key name are required';
                    $message_type = 'error';
                } else {
                    $result = $apiKeyManager->generateApiKey($user_id, $name, $description, $permissions, $rateLimit);
                    if ($result['success']) {
                        $message = 'API key generated successfully for user ID: ' . $user_id;
                        $message_type = 'success';
                        $new_api_key = $result['api_key'];
                        $new_api_secret = $result['api_secret'];
                    } else {
                        $message = $result['message'];
                        $message_type = 'error';
                    }
                }
                break;
                
            case 'delete_key':
                $key_id = intval($_POST['key_id']);
                if ($apiKeyManager->deleteApiKey($key_id)) {
                    $message = 'API key deleted successfully';
                    $message_type = 'success';
                } else {
                    $message = 'Failed to delete API key';
                    $message_type = 'error';
                }
                break;
                
            case 'update_key':
                $key_id = intval($_POST['key_id']);
                $name = trim($_POST['key_name']);
                $description = trim($_POST['key_description']);
                $rateLimit = intval($_POST['rate_limit']);
                $is_active = intval($_POST['is_active']);
                $expires_at = $_POST['expires_at'] ?: null;
                
                if ($apiKeyManager->updateApiKey($key_id, $name, $description, null, $rateLimit, $is_active, $expires_at)) {
                    $message = 'API key updated successfully';
                    $message_type = 'success';
                } else {
                    $message = 'Failed to update API key';
                    $message_type = 'error';
                }
                break;
                
            case 'toggle_user_api_access':
                $user_id = intval($_POST['user_id']);
                $enabled = intval($_POST['enabled']);
                if ($apiKeyManager->setUserApiAccess($user_id, $enabled)) {
                    $message = 'User API access ' . ($enabled ? 'enabled' : 'disabled') . ' successfully';
                    $message_type = 'success';
                } else {
                    $message = 'Failed to update user API access';
                    $message_type = 'error';
                }
                break;
        }
    }
}

// Get all API keys
$api_keys = $apiKeyManager->getAllApiKeys(100, 0);

// Get all users for dropdown
$users_result = mysqli_query($conn, "SELECT id, username, role, api_key_enabled FROM agents ORDER BY username");
$users = [];
while ($row = mysqli_fetch_assoc($users_result)) {
    $users[] = $row;
}

// Get API usage statistics
$usage_stats = $apiKeyManager->getApiUsageStats(null, 30);

// Set page variables for header
$page_title = 'API Keys Management';
$page_description = 'Manage API keys and access control for external integrations';
?>

    <meta name="description" content="Admin panel for managing API keys and user access - D-Bundles Stores Admin">
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Admin Dark Theme CSS -->
    <link rel="stylesheet" href="assets/admin-dark-theme.css">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: {
                            50: '#f8fafc',
                            100: '#f1f5f9',
                            200: '#e2e8f0',
                            300: '#cbd5e1',
                            400: '#94a3b8',
                            500: '#64748b',
                            600: '#475569',
                            700: '#334155',
                            800: '#1e293b',
                            900: '#0f172a',
                        },
                        accent: {
                            50: '#eff6ff',
                            100: '#dbeafe',
                            200: '#bfdbfe',
                            300: '#93c5fd',
                            400: '#60a5fa',
                            500: '#3b82f6',
                            600: '#2563eb',
                            700: '#1d4ed8',
                            800: '#1e40af',
                            900: '#1e3a8a',
                        }
                    }
                }
            }
        }
    </script>
</head>
<body class="font-inter">
    <!-- Header -->
    <header class="bg-gradient-to-r from-slate-800 to-slate-900 shadow-lg border-b border-slate-700">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center py-4">
                
            </div>
        </div>
    </header>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Page Header -->
        <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-2xl p-8 mb-8 border border-slate-600 shadow-2xl">
            <h1 class="text-4xl font-bold text-white mb-3 flex items-center">
                <i class="fas fa-key mr-4 text-blue-400"></i>
                <span class="bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">
                    API Keys Management
                </span>
            </h1>
            <p class="text-slate-300 text-lg">Manage API keys and user access for D-Bundles Stores integration</p>
        </div>

        <!-- Success/Error Messages -->
        <?php if (!empty($message)): ?>
        <div class="mb-6 p-4 rounded-xl border flex items-center gap-3 <?= $message_type === 'success' ? 'bg-green-900/20 border-green-500/30 text-green-300' : 'bg-red-900/20 border-red-500/30 text-red-300' ?>">
            <i class="fas fa-<?= $message_type === 'success' ? 'check-circle' : 'exclamation-circle' ?> text-lg"></i>
            <span class="font-medium"><?= htmlspecialchars($message) ?></span>
        </div>
        <?php endif; ?>

        <!-- New API Key Display (if just generated) -->
        <?php if (isset($new_api_key) && isset($new_api_secret)): ?>
        <div class="mb-6 p-6 bg-gradient-to-br from-amber-900/30 to-yellow-900/30 border border-amber-500/30 rounded-xl">
            <h3 class="text-xl font-bold text-amber-300 mb-4 flex items-center">
                <i class="fas fa-key mr-3"></i>New API Key Generated
            </h3>
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-semibold text-amber-200 mb-2">API Key:</label>
                    <div class="flex items-center space-x-3">
                        <input type="text" value="<?= htmlspecialchars($new_api_key) ?>" readonly 
                               class="flex-1 px-4 py-3 border border-amber-500/50 rounded-lg bg-slate-800 text-amber-100 font-mono text-sm">
                        <button onclick="copyToClipboard('<?= htmlspecialchars($new_api_key) ?>')" 
                                class="px-4 py-3 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition-colors">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-semibold text-amber-200 mb-2">API Secret:</label>
                    <div class="flex items-center space-x-3">
                        <input type="text" value="<?= htmlspecialchars($new_api_secret) ?>" readonly 
                               class="flex-1 px-4 py-3 border border-amber-500/50 rounded-lg bg-slate-800 text-amber-100 font-mono text-sm">
                        <button onclick="copyToClipboard('<?= htmlspecialchars($new_api_secret) ?>')" 
                                class="px-4 py-3 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition-colors">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                </div>
            </div>
            <div class="mt-4 p-4 bg-amber-900/20 border border-amber-500/30 rounded-lg">
                <p class="text-sm text-amber-200 flex items-center">
                    <i class="fas fa-exclamation-triangle mr-3 text-amber-400"></i>
                    <strong>Important:</strong> Save the API secret now! It will not be shown again for security reasons.
                </p>
            </div>
        </div>
        <?php endif; ?>

        <!-- Generate New API Key -->
        <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-xl mb-8 border border-slate-600 shadow-lg">
            <div class="px-6 py-4 border-b border-slate-600">
                <h2 class="text-xl font-bold text-white flex items-center">
                    <i class="fas fa-plus-circle mr-3 text-green-400"></i>Generate New API Key
                </h2>
            </div>
            <div class="p-6">
                <form method="POST" class="space-y-6">
                    <input type="hidden" name="action" value="generate_key">
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label for="user_id" class="block text-sm font-semibold text-slate-300 mb-2">User *</label>
                            <select id="user_id" name="user_id" required
                                    class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                                <option value="">Select User</option>
                                <?php foreach ($users as $user): ?>
                                <option value="<?= $user['id'] ?>">
                                    <?= htmlspecialchars($user['username']) ?> (<?= ucfirst($user['role']) ?>)
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label for="rate_limit" class="block text-sm font-semibold text-slate-300 mb-2">Rate Limit (requests/hour)</label>
                            <input type="number" id="rate_limit" name="rate_limit" value="1000" min="1" max="10000"
                                   class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                        </div>
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label for="key_name" class="block text-sm font-semibold text-slate-300 mb-2">Key Name *</label>
                            <input type="text" id="key_name" name="key_name" required
                                   class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                        </div>
                        <div>
                            <label for="expires_at" class="block text-sm font-semibold text-slate-300 mb-2">Expires At (Optional)</label>
                            <input type="datetime-local" id="expires_at" name="expires_at"
                                   class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                        </div>
                    </div>
                    
                    <div>
                        <label for="key_description" class="block text-sm font-semibold text-slate-300 mb-2">Description</label>
                        <textarea id="key_description" name="key_description" rows="3"
                                  class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                                  placeholder="Optional description for this API key..."></textarea>
                    </div>
                    
                    <div class="flex justify-end">
                        <button type="submit" 
                                class="bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-200 hover:shadow-lg hover:-translate-y-0.5 flex items-center">
                            <i class="fas fa-key mr-2"></i>Generate API Key
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- User API Access Management -->
        <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-xl mb-8 border border-slate-600 shadow-lg overflow-hidden">
            <div class="px-6 py-4 border-b border-slate-600">
                <h2 class="text-xl font-bold text-white flex items-center">
                    <i class="fas fa-users mr-3 text-blue-400"></i>User API Access Management
                </h2>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-slate-700">
                        <tr>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">User</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Role</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">API Access</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">API Keys</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-600">
                        <?php foreach ($users as $user): 
                            $user_api_keys = array_filter($api_keys, function($key) use ($user) {
                                return $key['user_id'] == $user['id'];
                            });
                            $active_keys = array_filter($user_api_keys, function($key) {
                                return $key['is_active'];
                            });
                        ?>
                        <tr class="hover:bg-slate-700/50 transition-colors">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm font-semibold text-white"><?= htmlspecialchars($user['username']) ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold bg-blue-500/20 text-blue-400 border border-blue-500/30">
                                    <?= ucfirst($user['role']) ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold <?= $user['api_key_enabled'] ? 'bg-green-500/20 text-green-400 border border-green-500/30' : 'bg-red-500/20 text-red-400 border border-red-500/30' ?>">
                                    <?= $user['api_key_enabled'] ? 'Enabled' : 'Disabled' ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-300">
                                <?= count($active_keys) ?> / <?= count($user_api_keys) ?> active
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <form method="POST" class="inline">
                                    <input type="hidden" name="action" value="toggle_user_api_access">
                                    <input type="hidden" name="user_id" value="<?= $user['id'] ?>">
                                    <input type="hidden" name="enabled" value="<?= $user['api_key_enabled'] ? 0 : 1 ?>">
                                    <button type="submit" class="text-<?= $user['api_key_enabled'] ? 'red' : 'green' ?>-400 hover:text-<?= $user['api_key_enabled'] ? 'red' : 'green' ?>-300 transition-colors font-semibold">
                                        <?= $user['api_key_enabled'] ? 'Disable' : 'Enable' ?> API Access
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- API Keys List -->
        <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-xl mb-8 border border-slate-600 shadow-lg overflow-hidden">
            <div class="px-6 py-4 border-b border-slate-600">
                <h2 class="text-xl font-bold text-white flex items-center">
                    <i class="fas fa-list mr-3 text-purple-400"></i>All API Keys
                </h2>
            </div>
            <div class="overflow-x-auto">
                <?php if (empty($api_keys)): ?>
                <div class="p-8 text-center text-slate-400">
                    <i class="fas fa-key text-5xl mb-4 text-slate-500"></i>
                    <p class="text-lg">No API keys found.</p>
                </div>
                <?php else: ?>
                <table class="w-full">
                    <thead class="bg-slate-700">
                        <tr>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">User</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Name</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">API Key</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Status</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Usage</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Last Used</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-600">
                        <?php foreach ($api_keys as $key): ?>
                        <tr class="hover:bg-slate-700/50 transition-colors">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div>
                                    <div class="text-sm font-semibold text-white"><?= htmlspecialchars($key['username']) ?></div>
                                    <div class="text-sm text-slate-400"><?= ucfirst($key['role']) ?></div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div>
                                    <div class="text-sm font-semibold text-white"><?= htmlspecialchars($key['name']) ?></div>
                                    <?php if ($key['description']): ?>
                                    <div class="text-sm text-slate-400"><?= htmlspecialchars($key['description']) ?></div>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <code class="text-sm bg-slate-700 text-slate-300 px-3 py-1 rounded border border-slate-600"><?= htmlspecialchars($key['api_key_masked']) ?></code>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold <?= $key['is_active'] ? 'bg-green-500/20 text-green-400 border border-green-500/30' : 'bg-red-500/20 text-red-400 border border-red-500/30' ?>">
                                    <?= $key['is_active'] ? 'Active' : 'Inactive' ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-300">
                                <?= number_format($key['usage_count']) ?> requests
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-400">
                                <?= $key['last_used'] ? date('M j, Y g:i A', strtotime($key['last_used'])) : 'Never' ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-3">
                                <button onclick="editApiKey(<?= htmlspecialchars(json_encode($key)) ?>)" 
                                        class="text-blue-400 hover:text-blue-300 transition-colors font-semibold">Edit</button>
                                <form method="POST" class="inline" onsubmit="return confirm('Are you sure you want to delete this API key? This action cannot be undone.')">
                                    <input type="hidden" name="action" value="delete_key">
                                    <input type="hidden" name="key_id" value="<?= $key['id'] ?>">
                                    <button type="submit" class="text-red-400 hover:text-red-300 transition-colors font-semibold">Delete</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>
        </div>

        <!-- API Usage Statistics -->
        <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-xl border border-slate-600 shadow-lg overflow-hidden">
            <div class="px-6 py-4 border-b border-slate-600">
                <h2 class="text-xl font-bold text-white flex items-center">
                    <i class="fas fa-chart-bar mr-3 text-green-400"></i>API Usage Statistics (Last 30 Days)
                </h2>
            </div>
            <div class="p-6">
                <?php if (empty($usage_stats)): ?>
                <div class="text-center text-slate-400">
                    <i class="fas fa-chart-line text-5xl mb-4 text-slate-500"></i>
                    <p class="text-lg">No usage statistics available.</p>
                </div>
                <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-slate-700">
                            <tr>
                                <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Date</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Total Requests</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Successful</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Failed</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-slate-300 uppercase tracking-wider">Avg Response Time</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-600">
                            <?php foreach ($usage_stats as $stat): ?>
                            <tr class="hover:bg-slate-700/50 transition-colors">
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-300">
                                    <?= date('M j, Y', strtotime($stat['date'])) ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-300">
                                    <?= number_format($stat['total_requests']) ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-300">
                                    <?= number_format($stat['successful_requests']) ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-300">
                                    <?= number_format($stat['failed_requests']) ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-300">
                                    <?= $stat['avg_response_time'] ? round($stat['avg_response_time'], 2) . 'ms' : 'N/A' ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Edit API Key Modal -->
    <div id="editModal" class="fixed inset-0 bg-black/50 backdrop-blur-sm hidden z-50">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-gradient-to-br from-slate-800 to-slate-700 rounded-xl shadow-2xl max-w-md w-full border border-slate-600">
                <div class="px-6 py-4 border-b border-slate-600">
                    <h3 class="text-xl font-bold text-white flex items-center">
                        <i class="fas fa-edit mr-3 text-blue-400"></i>Edit API Key
                    </h3>
                </div>
                <form method="POST" id="editForm">
                    <input type="hidden" name="action" value="update_key">
                    <input type="hidden" name="key_id" id="edit_key_id">
                    
                    <div class="p-6 space-y-6">
                        <div>
                            <label for="edit_key_name" class="block text-sm font-semibold text-slate-300 mb-2">Key Name</label>
                            <input type="text" id="edit_key_name" name="key_name" required
                                   class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                        </div>
                        
                        <div>
                            <label for="edit_key_description" class="block text-sm font-semibold text-slate-300 mb-2">Description</label>
                            <textarea id="edit_key_description" name="key_description" rows="3"
                                      class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"></textarea>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label for="edit_rate_limit" class="block text-sm font-semibold text-slate-300 mb-2">Rate Limit</label>
                                <input type="number" id="edit_rate_limit" name="rate_limit" min="1" max="10000"
                                       class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                            </div>
                            
                            <div>
                                <label for="edit_is_active" class="block text-sm font-semibold text-slate-300 mb-2">Status</label>
                                <select id="edit_is_active" name="is_active"
                                        class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                                    <option value="1">Active</option>
                                    <option value="0">Inactive</option>
                                </select>
                            </div>
                        </div>
                        
                        <div>
                            <label for="edit_expires_at" class="block text-sm font-semibold text-slate-300 mb-2">Expires At</label>
                            <input type="datetime-local" id="edit_expires_at" name="expires_at"
                                   class="w-full px-4 py-3 bg-slate-700 border border-slate-600 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors">
                        </div>
                    </div>
                    
                    <div class="px-6 py-4 border-t border-slate-600 flex justify-end space-x-3">
                        <button type="button" onclick="closeEditModal()" 
                                class="px-6 py-3 text-slate-300 bg-slate-700 border border-slate-600 rounded-lg hover:bg-slate-600 transition-colors font-semibold">
                            Cancel
                        </button>
                        <button type="submit" 
                                class="px-6 py-3 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white rounded-lg transition-all duration-200 hover:shadow-lg hover:-translate-y-0.5 font-semibold">
                            Update
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(function() {
                const button = event.target.closest('button');
                const originalHTML = button.innerHTML;
                button.innerHTML = '<i class="fas fa-check"></i>';
                button.classList.add('bg-green-600', 'hover:bg-green-700');
                button.classList.remove('bg-amber-600', 'hover:bg-amber-700');
                
                setTimeout(() => {
                    button.innerHTML = originalHTML;
                    button.classList.remove('bg-green-600', 'hover:bg-green-700');
                    button.classList.add('bg-amber-600', 'hover:bg-amber-700');
                }, 2000);
            });
        }
        
        function editApiKey(key) {
            document.getElementById('edit_key_id').value = key.id;
            document.getElementById('edit_key_name').value = key.name;
            document.getElementById('edit_key_description').value = key.description || '';
            document.getElementById('edit_rate_limit').value = key.rate_limit;
            document.getElementById('edit_is_active').value = key.is_active;
            document.getElementById('edit_expires_at').value = key.expires_at ? key.expires_at.replace(' ', 'T') : '';
            
            document.getElementById('editModal').classList.remove('hidden');
        }
        
        function closeEditModal() {
            document.getElementById('editModal').classList.add('hidden');
        }
        
        // Close modal when clicking outside
        document.getElementById('editModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeEditModal();
            }
        });
    </script>



