<!DOCTYPE html>
<html dir="rtl" lang="ar">

<head>
    <meta charset="UTF-8">
    <meta name="theme-color" content="#ff0000">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blacklist | إدارة التراخيص</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-python.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-lua.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <style>
        :root {
            --primary-color: #ff0000;
            --secondary-color: #000000;
            --text-color: #ffffff;
            --card-bg: #000000;
            --hover-color: #cc0000;
            --border-color: #3d3d3d;
            --success-color: #4CAF50;
            --warning-color: #FFC107;
            --danger-color: #dc3545;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Cairo', sans-serif;
        }

        body {
            background-color: var(--secondary-color);
            color: var(--text-color);
            min-height: 100vh;
        }

        /* Notification System */
        .notification-container {
            position: fixed;
            top: 32px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 2000;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .notification {
            background: var(--card-bg);
            color: var(--text-color);
            padding: 1rem 1.5rem;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
            gap: 1rem;
            border: 1px solid var(--border-color);
            min-width: 300px;
            max-width: 500px;
            transform: translateY(-100%);
            opacity: 0;
            transition: all 0.3s ease;
        }

        .notification.show {
            transform: translateY(0);
            opacity: 1;
        }

        .notification.success {
            border-right: 4px solid var(--success-color);
        }

        .notification.error {
            border-right: 4px solid var(--danger-color);
        }

        .notification.warning {
            border-right: 4px solid var(--warning-color);
        }

        .notification-icon {
            font-size: 1.2rem;
        }

        .notification.success .notification-icon {
            color: var(--success-color);
        }

        .notification.error .notification-icon {
            color: var(--danger-color);
        }

        .notification.warning .notification-icon {
            color: var(--warning-color);
        }

        .notification-content {
            flex: 1;
        }

        .notification-close {
            cursor: pointer;
            padding: 0.5rem;
            color: var(--text-color);
            opacity: 0.7;
            transition: opacity 0.3s ease;
        }

        .notification-close:hover {
            opacity: 1;
        }

        /* Confirmation Dialog */
        .confirmation-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 3000;
            opacity: 0;
            transition: opacity 0.3s ease;
            backdrop-filter: blur(4px);
        }

        .confirmation-overlay.show {
            opacity: 1;
        }

        .confirmation-dialog {
            background: var(--card-bg);
            border-radius: 12px;
            padding: 2rem;
            max-width: 400px;
            width: 90%;
            border: 1px solid var(--border-color);
            transform: translateY(20px);
            opacity: 0;
            transition: all 0.3s ease;
        }

        .confirmation-overlay.show .confirmation-dialog {
            transform: translateY(0);
            opacity: 1;
        }

        .confirmation-title {
            font-size: 1.2rem;
            font-weight: bold;
            margin-bottom: 1rem;
            color: var(--text-color);
        }

        .confirmation-message {
            margin-bottom: 1.5rem;
            color: var(--text-color);
        }

        .confirmation-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
        }

        .btn-confirm {
            background: var(--primary-color);
            border: 2px solid var(--primary-color);
            color: var(--text-color);
            transition: all 0.3s ease;
        }

        .btn-confirm:hover {
            background: var(--hover-color);
            border-color: var(--hover-color);
            transform: translateY(-2px);
        }

        .btn-cancel {
            background: transparent;
            border: 2px solid var(--border-color);
            color: var(--text-color);
            transition: all 0.3s ease;
        }

        .btn-cancel:hover {
            background: var(--primary-color);
            border-color: var(--primary-color);
            transform: translateY(-2px);
        }

        .sidebar {
            width: 280px;
            background-color: var(--card-bg);
            padding: 2rem;
            position: fixed;
            height: 100vh;
            right: 0;
            border-left: 1px solid var(--border-color);
        }

        .logo-container {
            text-align: center;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid var(--border-color);
        }

        .logo {
            font-size: 1.5rem;
            font-weight: bold;
            color: var(--primary-color);
        }

        .menu-list {
            list-style: none;
        }

        .menu-item {
            padding: 1rem;
            margin-bottom: 0.5rem;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 1rem;
            color: var(--text-color);
            text-decoration: none;
        }

        .menu-item:hover {
            color: var(--primary-color);
            transform: translateY(-5px);
        }

        .menu-item.active {
            background: var(--primary-color);
        }

        .menu-item.active:hover {
            color: var(--text-color);
        }

        .menu-item i {
            font-size: 1.2rem;
        }

        /* Adjust main content margin */
        .main-content {
            margin-right: 280px;
            padding: 2rem;
        }

        .dashboard-container {
            display: flex;
            min-height: 100vh;
        }

        .main-content {
            flex: 1;
            margin-right: 280px;
            padding: 2rem;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: var(--card-bg);
            padding: 1.5rem;
            border-radius: 12px;
            border: 1px solid var(--border-color);
            transition: transform 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            border-color: var(--primary-color);
        }

        .stat-icon {
            font-size: 2rem;
            margin-bottom: 1rem;
            color: var(--primary-color);
        }

        .stat-value {
            font-size: 1.8rem;
            font-weight: bold;
            margin-bottom: 0.5rem;
        }

        .stat-label {
            color: #888;
            font-size: 0.9rem;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
        }

        .section-title {
            font-size: 1.5rem;
            font-weight: bold;
        }

        .filters-container {
            margin-bottom: 2rem;
        }

        .search-container {
            display: flex;
            gap: 1rem;
            margin-bottom: 1rem;
            align-items: center; /* Align items vertically */
        }

        /* Updated search input styles */
        #searchInput {
            flex: 1;
            height: 49px; /* Match button height */
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            border: 1px solid var(--border-color);
            background: var(--secondary-color);
            color: var(--text-color);
            font-size: 1rem; /* Slightly smaller font */
        }

        /* Updated select styles to match button */
        #typeFilter,
        #statusFilter {
            height: 49px; /* Match button height */
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            border: 1px solid var(--border-color);
            background: var(--secondary-color);
            color: var(--text-color);
            cursor: pointer;
            font-weight: 600;
            width: 166px; /* Fixed width for consistency */
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: var(--primary-color);
            border: 2px solid var(--primary-color);
            color: var(--text-color);
        }

        .btn-primary:hover {
            background: var(--hover-color);
            border: 2px solid var(--hover-color);
            transform: translateY(-2px);
        }

        .btn-secondary {
    background: var(--secondary-color);
    border: 2px solid var(--border-color);  /* Changed from dynamic border to fixed 2px */
    color: var(--text-color);
    transition: all 0.3s ease;
}

.btn-secondary:hover {
    background: var(--primary-color);
    border-color: var(--primary-color);    /* Changed to border-color instead of border */
    transform: translateY(-2px);
}

        .table-container {
            background: var(--card-bg);
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th,
        td {
            padding: 1rem;
            text-align: right;
            border-bottom: 1px solid var(--border-color);
        }

        th {
            font-weight: 600;
            color: var(--primary-color);
        }

        tr:hover {
            background: rgba(255, 255, 255, 0.05);
        }

        .badge {
            padding: 0.25rem 0.75rem;
            border-radius: 50px;
            font-size: 0.85rem;
        }

        .badge-success {
            background: var(--success-color);
            color: white;
        }

        .badge-warning {
            background: var(--warning-color);
            color: black;
        }

        .badge-danger {
            background: var(--danger-color);
            color: white;
        }

        .badge-production {
            background: #543A14;
            color: white;
        }

        .badge-personal {
            background: #0A3981;
            color: white;
        }

        .badge-subscription {
            background: #004225;
            color: white;
        }

        .action-btn {
            padding: 0.5rem;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            color: var(--text-color);
            background: transparent;
            transition: all 0.3s ease;
        }

        .action-btn:hover {
            color: var(--primary-color);
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            z-index: 1000;
            justify-content: center;
            align-items: center;
            opacity: 0;
            transition: opacity 0.3s ease;
            backdrop-filter: blur(4px);
        }

        .modal.show {
            opacity: 1;
        }

        .modal-content {
            background: var(--card-bg);
            padding: 2rem;
            border-radius: 12px;
            width: 90%;
            max-width: 500px;
            border: 1px solid var(--border-color);
            transform: translateY(20px);
            opacity: 0;
            transition: all 0.3s ease;
        }

        .modal.show .modal-content {
            transform: translateY(0);
            opacity: 1;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            color: var(--text-color);
        }

        .form-input {
            width: 100%;
            padding: 0.75rem;
            border-radius: 8px;
            border: 1px solid var(--border-color);
            background: var(--secondary-color);
            color: var(--text-color);
        }

        .form-input:focus {
            border-color: var(--primary-color);
            outline: none;
        }

        .form-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            margin-top: 2rem;
        }

        .key-cell {
            filter: blur(3px);
            transition: filter 0.3s ease;
            cursor: pointer;
            user-select: none;
        }

        .key-cell:hover {
            filter: blur(0);
        }

        .modal-content {
            position: relative;
        }

        .form-input.error {
            border-color: var(--danger-color);
        }

        .form-input.error:focus {
            box-shadow: 0 0 0 2px rgba(220, 53, 69, 0.25);
        }

        /* Loading spinner animation */
        @keyframes spin {
            from {
                transform: rotate(0deg);
            }

            to {
                transform: rotate(360deg);
            }
        }

        .fa-spinner {
            animation: spin 1s linear infinite;
        }

        /* Modal transition animations */
        .modal {
            transition: opacity 0.3s ease;
        }

        .modal-content {
            transition: transform 0.3s ease, opacity 0.3s ease;
        }

        /* Enhanced form styles */
        .form-group {
            position: relative;
        }

        .form-input:disabled {
            background-color: rgba(255, 255, 255, 0.1);
            cursor: not-allowed;
        }

        .form-input::placeholder {
            color: rgba(255, 255, 255, 0.5);
        }

        /* Button loading state */
        .btn:disabled {
            opacity: 0.7;
            cursor: not-allowed;
        }

        /* Add to your existing CSS */
.code-container {
    padding: 2rem;
}

.language-selector {
    display: flex;
    gap: 1rem;
    margin-bottom: 2rem;
    flex-wrap: wrap;
}

.language-btn {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    color: var(--text-color);
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    transition: all 0.3s ease;
}

.language-btn:hover,
.language-btn.active {
    background: var(--primary-color);
    border-color: var(--primary-color);
}

.code-block {
    background: var(--code-bg);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    overflow: hidden;
    display: none;
}

.code-block.active {
    display: block;
}

.code-header {
    background: var(--card-bg);
    padding: 1rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid var(--border-color);
}

.code-title {
    font-size: 1.1rem;
    font-weight: bold;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.copy-btn {
    background: transparent;
    border: none;
    color: var(--text-color);
    cursor: pointer;
    padding: 0.5rem;
    border-radius: 4px;
    transition: all 0.3s ease;
}

.copy-btn:hover {
    background: var(--primary-color);
}

.code-content {
    padding: 1.5rem;
    background: var(--code-bg);
}

/* Prism.js customization */
pre[class*="language-"] {
    margin: 0;
    background: var(--code-bg) !important;
    font-size: 0.9rem;
    line-height: 1.5;
}

code[class*="language-"] {
    background: none !important;
    text-shadow: none !important;
    padding: 0 !important;
}

/* Remove Prism.js toolbar */
div.code-toolbar > .toolbar {
    display: none;
}

.menu-item.active {
    background: var(--primary-color) !important;
    color: var(--text-color) !important;
}

.menu-item.active:hover {
    color: var(--text-color) !important;
    transform: translateY(-5px);
}
    </style>
</head>

<body>


    <div class="dashboard-container">
        <aside class="sidebar">
            <div class="logo-container">
                <div class="logo">إدارة التراخيص</div>
            </div>
            <ul class="menu-list">
                <div class="menu-item" data-section="key-management" onclick="handleMenuClick(this)">
                    <i class="fas fa-key"></i>
                    <span>إدارة التراخيص</span>
                </div>
                <a href="/login" class="menu-item">
                    <i class="fas fa-home"></i>
                    <span>الرئيسية</span>
                </a>
                <a href="/team-panel" class="menu-item">
                    <i class="fas fa-users"></i>
                    <span>غرفة العمليات</span>
                </a>
                <a href="/dashboard" class="menu-item">
                    <i class="fas fa-tachometer-alt"></i>
                    <span>لوحة التحكم</span>
                </a>
                <a href="/discord-bots" class="menu-item">
                    <i class="fab fa-discord"></i>
                    <span>التطبيقات</span>
                </a>
                <div class="menu-item" data-section="code-checker" onclick="handleMenuClick(this)">
                    <i class="fas fa-code"></i>
                    <span>الأكواد</span>
                </div>
            </ul>
        </aside>

        <div class="notification-container"></div>

        <div class="confirmation-overlay">
            <div class="confirmation-dialog">
                <div class="confirmation-title"></div>
                <div class="confirmation-message"></div>
                <div class="confirmation-actions">
                    <button class="btn btn-confirm"></button>
                    <button class="btn btn-cancel">إلغاء</button>
                </div>
            </div>
        </div>

        <main class="main-content">
            <!-- Stats Section -->
            <div class="stats-grid">
                <div class="stat-card">
                    <i class="fas fa-key stat-icon"></i>
                    <div class="stat-value" id="totalKeys">0</div>
                    <div class="stat-label">إجمالي التراخيص</div>
                </div>
                <div class="stat-card">
                    <i class="fas fa-check-circle stat-icon"></i>
                    <div class="stat-value" id="activeKeys">0</div>
                    <div class="stat-label">التراخيص النشطة</div>
                </div>
                <div class="stat-card">
                    <i class="fas fa-clock stat-icon"></i>
                    <div class="stat-value" id="tempKeys">0</div>
                    <div class="stat-label">التراخيص المؤقتة</div>
                </div>
                <div class="stat-card">
                    <i class="fas fa-user-lock stat-icon"></i>
                    <div class="stat-value" id="personalKeys">0</div>
                    <div class="stat-label">التراخيص الشخصية</div>
                </div>
            </div>

            <!-- Keys Management Section -->
            <div class="section-header">
                <h2 class="section-title">إدارة التراخيص</h2>
                <div class="action-buttons">
                    <button class="btn btn-primary" onclick="openModal('generateKeyModal')">
                        <i class="fas fa-plus"></i>
                        إنشاء ترخيص جديد
                    </button>
                </div>
            </div>

            <!-- Add this after the section-header div -->
<div class="filters-container" style="margin-bottom: 2rem;">
    <div class="search-container" style="display: flex; gap: 1rem; margin-bottom: 1rem;">
        <div style="flex: 1;">
            <input type="text" id="searchInput" class="form-input" placeholder="البحث بواسطة معرف العميل أو الترخيص...">
        </div>
        <div style="display: flex; gap: 0.5rem;">
            <select id="typeFilter" class="form-input" style="width: auto;">
                <option value="">جميع الأنواع</option>
                <option value="production">تجاري</option>
                <option value="personal">شخصي</option>
                <option value="subscription">اشتراك</option>
            </select>
            <select id="statusFilter" class="form-input" style="width: auto;">
                <option value="">جميع الحالات</option>
                <option value="active">نشط</option>
                <option value="inactive">معطل</option>
                <option value="expired">منتهي</option>
            </select>
        </div>
    </div>
</div>

            <!-- Keys Table -->
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>الترخيص</th>
                            <th>النوع</th>
                            <th>الحالة</th>
                            <th>تاريخ الإنشاء</th>
                            <th>تاريخ الانتهاء</th>
                            <th>العميل</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody id="keysTableBody">
                        <!-- Will be filled with JavaScript -->
                    </tbody>
                </table>
            </div>
        </main>
    </div>

    <!-- Generate Key Modal -->
    <div id="generateKeyModal" class="modal">
        <div class="modal-content">
            <h2 style="margin-bottom: 1.5rem; color: var(--text-color);">إنشاء ترخيص جديد</h2>
            <form id="generateKeyForm">
                <div class="form-group">
                    <label class="form-label">نوع الترخيص</label>
                    <select name="keyType" class="form-input" required>
                        <option value="production">تجاري</option>
                        <option value="personal">شخصي</option>
                        <option value="subscription">اشتراك</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">مدة الصلاحية</label>
                    <input type="number" name="duration" class="form-input" min="1" placeholder="بالأيام">
                </div>
                <div class="form-group">
                    <label class="form-label">معرف العميل</label>
                    <input type="text" name="userId" class="form-input" required>
                </div>
                <div class="form-group" id="ipAddressGroup" style="display: none;">
                    <label class="form-label">عنوان IP <small style="color: #888;">اختياري</small></label>
                    <input type="text" name="ipAddress" class="form-input" pattern="^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$">
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">إنشاء</button>
                    <button type="button" class="btn btn-secondary" onclick="closeModal('generateKeyModal')">إلغاء</button>
                </div>                
            </form>
        </div>
    </div>

    <script>
        function handleMenuClick(element) {
    // Remove active class from all menu items
    document.querySelectorAll('.menu-item').forEach(item => {
        item.classList.remove('active');
    });
    
    // Add active class to clicked item
    element.classList.add('active');
    
    // Handle specific sections
    const section = element.dataset.section;
    if(section === 'key-management') {
        // Your key management display logic
        showKeyManagement();
    } else if(section === 'code-checker') {
        // Your code checker display logic
        showCodeChecker();
    }
}

// Initial active state based on current section
document.addEventListener('DOMContentLoaded', () => {
    // Set active state based on current section
    const currentSection = window.location.pathname === '/key-management' ? 'key-management' : 'code-checker';
    const activeElement = document.querySelector(`[data-section="${currentSection}"]`);
    if(activeElement) {
        activeElement.classList.add('active');
    }
});
    </script>

    <script>
        // Store code examples
const codeExamples = {
    javascript: `const config = {
  licenseKey: "D0D8-C4A2-C2ED-C0A1-133F-F87E-1B85-2BB0-355A-7D6C-C90E-E91B"
};

/* ------------- LICENSE CHECKER ------------- */
(async () => {
  try {
      // Check if axios is installed
      try {
          require('axios');
      } catch {
          console.error('❌ Fatal Error: axios is not installed. Run: npm install axios');
          process.exit(1);
      }

      const axios = require('axios');
      const { WebhookClient } = require('discord.js');

      // Configuration checks
      if (!config.licenseKey) {
          const error = '❌ No license key found in config!';
          await sendWebhook('error', error);
          console.error(error);
          process.exit(1);
      }

      // Hardcoded webhook
      const webhook = new WebhookClient({ url: 'https://discord.com/api/webhooks/1323279551182274642/suiJBIAhNAIMVXWKKE6sscLzFByUBWKs6dEsF4v9A-UBL3Yz2yy8ErguA9ChTP70mnbh' });

      // Function to send webhook notifications
      async function sendWebhook(type, message, details = {}) {
          const colors = {
              success: 0x00FF00,
              error: 0xFF0000,
              warning: 0xFFA500
          };

          try {
              await webhook.send({
                  embeds: [{
                      title: '🔑 License System',
                      description: message,
                      color: colors[type] || colors.info,
                      fields: Object.entries(details).map(([name, value]) => ({
                          name, value: String(value), inline: true
                      })),
                      timestamp: new Date()
                  }]
              });
          } catch (error) {
              console.error('Failed to send webhook:', error);
          }
      }

      // Function to validate license
      async function validateLicense() {
          try {
              // Get machine's IP
              const ipResponse = await axios.get('https://api.ipify.org?format=json');
              const currentIp = ipResponse.data.ip;

              // Validate license
              const response = await axios.post('https://blacklist.im/api/keys/validate', {
                  keyString: config.licenseKey,
                  ip: currentIp,
                  timestamp: Date.now()
              });

              if (!response.data.valid) {
                  const error = \`❌ Invalid License: \${response.data.message}\`;
                  await sendWebhook('error', error, {
                      'License Key': \`\${config.licenseKey.slice(0, 4)}...\${config.licenseKey.slice(-4)}\`,
                      'Error': response.data.message
                  });
                  console.error(error);
                  process.exit(1);
              }

              // Check IP restriction
              if (response.data.ipLocked && response.data.ipAddress !== currentIp) {
                  const error = '❌ IP Address Mismatch: Bot running from unauthorized IP';
                  await sendWebhook('error', error, {
                      'Expected IP': response.data.ipAddress,
                      'Current IP': currentIp
                  });
                  console.error(error);
                  process.exit(1);
              }

              // License is valid
              await sendWebhook('success', '✅ License validated successfully', {
                  'Type': response.data.keyType,
                  'Expires': response.data.expiresAt ? new Date(response.data.expiresAt).toLocaleDateString() : 'Never'
              });
              console.log('✅ License check passed');

              return true;
          } catch (error) {
              const errorMessage = '❌ License validation failed';
              await sendWebhook('error', errorMessage, {
                  'Error': error.response?.data?.message || error.message
              });
              console.error(errorMessage, error);
              process.exit(1);
          }
      }

      // Initial validation
      await validateLicense();

      // Set up periodic validation (every 12 hours)
      setInterval(validateLicense, 12 * 60 * 60 * 1000);

  } catch (error) {
      console.error('❌ Fatal error in license system:', error);
      process.exit(1);
  }
})();
/* ------------- END LICENSE CHECKER ------------- */`,

    python: String.raw`import asyncio
import sys
import requests
from discord_webhook import DiscordWebhook, DiscordEmbed
from datetime import datetime

# Configuration
config = {
    "licenseKey": "D0D8-C4A2-C2ED-C0A1-133F-F87E-1B85-2BB0-355A-7D6C-C90E-E91B"
}

# Hardcoded webhook URL
WEBHOOK_URL = "https://discord.com/api/webhooks/1323279551182274642/suiJBIAhNAIMVXWKKE6sscLzFByUBWKs6dEsF4v9A-UBL3Yz2yy8ErguA9ChTP70mnbh"

# Color mappings for webhook messages
COLORS = {
    "success": 0x00FF00,
    "error": 0xFF0000,
    "warning": 0xFFA500
}

async def send_webhook(type_: str, message: str, details: dict = None):
    """Send a notification to Discord webhook."""
    if details is None:
        details = {}
    
    try:
        webhook = DiscordWebhook(url=WEBHOOK_URL)
        embed = DiscordEmbed(
            title="🔑 License System",
            description=message,
            color=COLORS.get(type_, COLORS["warning"])
        )
        
        # Add fields from details
        for name, value in details.items():
            embed.add_embed_field(name=str(name), value=str(value), inline=True)
        
        embed.set_timestamp()
        webhook.add_embed(embed)
        webhook.execute()
    except Exception as error:
        print(f"Failed to send webhook: {error}")

async def validate_license():
    """Validate the license key."""
    try:
        # Get machine's IP
        ip_response = requests.get("https://api.ipify.org?format=json")
        current_ip = ip_response.json()["ip"]
        
        # Validate license
        response = requests.post("https://blacklist.im/api/keys/validate", json={
            "keyString": config["licenseKey"],
            "ip": current_ip,
            "timestamp": int(datetime.now().timestamp() * 1000)
        })
        response_data = response.json()
        
        if not response_data.get("valid"):
            error_msg = f"❌ Invalid License: {response_data.get('message')}"
            await send_webhook("error", error_msg, {
                "License Key": f"{config['licenseKey'][:4]}...{config['licenseKey'][-4:]}",
                "Error": response_data.get("message")
            })
            print(error_msg)
            sys.exit(1)
            
        # Check IP restriction
        if response_data.get("ipLocked") and response_data.get("ipAddress") != current_ip:
            error_msg = "❌ IP Address Mismatch: Bot running from unauthorized IP"
            await send_webhook("error", error_msg, {
                "Expected IP": response_data.get("ipAddress"),
                "Current IP": current_ip
            })
            print(error_msg)
            sys.exit(1)
            
        # License is valid
        expires_at = response_data.get("expiresAt")
        expires_str = datetime.fromtimestamp(expires_at/1000).strftime("%m/%d/%Y") if expires_at else "Never"
        
        await send_webhook("success", "✅ License validated successfully", {
            "Type": response_data.get("keyType"),
            "Expires": expires_str
        })
        print("✅ License check passed")
        return True
        
    except Exception as error:
        error_msg = "❌ License validation failed"
        error_detail = error.response.json().get("message") if hasattr(error, "response") else str(error)
        await send_webhook("error", error_msg, {
            "Error": error_detail
        })
        print(f"{error_msg}: {error}")
        sys.exit(1)

async def main():
    """Main function to run the license checker."""
    try:
        # Check if required packages are installed
        try:
            import requests
            import discord_webhook
        except ImportError as e:
            print(f"❌ Fatal Error: {str(e).split()[-1]} is not installed. Run: pip install {str(e).split()[-1]}")
            sys.exit(1)
            
        # Configuration checks
        if not config.get("licenseKey"):
            error_msg = "❌ No license key found in config!"
            await send_webhook("error", error_msg)
            print(error_msg)
            sys.exit(1)
            
        # Initial validation
        await validate_license()
        
        # Set up periodic validation (every 12 hours)
        while True:
            await asyncio.sleep(12 * 60 * 60)  # 12 hours in seconds
            await validate_license()
            
    except Exception as error:
        print(f"❌ Fatal error in license system: {error}")
        sys.exit(1)

if __name__ == "__main__":
    # Run the async main function
    asyncio.run(main())`,

    lua: String.raw`-- Required dependencies
local http = require("socket.http")
local ltn12 = require("ltn12")
local json = require("cjson")
local discordia = require('discordia')

-- Configuration
local config = {
    licenseKey = "D0D8-C4A2-C2ED-C0A1-133F-F87E-1B85-2BB0-355A-7D6C-C90E-E91B"
}

-- Hardcoded webhook
local WEBHOOK_URL = "https://discord.com/api/webhooks/1323279551182274642/suiJBIAhNAIMVXWKKE6sscLzFByUBWKs6dEsF4v9A-UBL3Yz2yy8ErguA9ChTP70mnbh"

-- Color mappings for webhook messages
local COLORS = {
    success = 0x00FF00,
    error = 0xFF0000,
    warning = 0xFFA500
}

-- Function to send HTTP requests
local function makeRequest(url, method, data)
    local response = {}
    local headers = {
        ["Content-Type"] = "application/json"
    }
    
    local requestBody = data and json.encode(data) or nil
    
    local _, code, _, _ = http.request{
        url = url,
        method = method,
        headers = headers,
        source = requestBody and ltn12.source.string(requestBody) or nil,
        sink = ltn12.sink.table(response)
    }
    
    if code ~= 200 then
        error("HTTP request failed with code: " .. code)
    end
    
    return json.decode(table.concat(response))
end

-- Function to send webhook notifications
local function sendWebhook(type, message, details)
    details = details or {}
    
    local embedFields = {}
    for name, value in pairs(details) do
        table.insert(embedFields, {
            name = tostring(name),
            value = tostring(value),
            inline = true
        })
    end
    
    local embed = {
        title = "🔑 License System",
        description = message,
        color = COLORS[type] or COLORS.warning,
        fields = embedFields,
        timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ")
    }
    
    local webhookData = {
        embeds = {embed}
    }
    
    local success, err = pcall(function()
        makeRequest(WEBHOOK_URL, "POST", webhookData)
    end)
    
    if not success then
        print("Failed to send webhook:", err)
    end
end

-- Function to validate license
local function validateLicense()
    local success, result = pcall(function()
        -- Get machine's IP
        local ipResponse = makeRequest("https://api.ipify.org?format=json", "GET")
        local currentIp = ipResponse.ip
        
        -- Validate license
        local response = makeRequest("https://blacklist.im/api/keys/validate", "POST", {
            keyString = config.licenseKey,
            ip = currentIp,
            timestamp = os.time() * 1000 -- Convert to milliseconds
        })
        
        if not response.valid then
            local error = string.format("❌ Invalid License: %s", response.message)
            sendWebhook("error", error, {
                ["License Key"] = string.format("%s...%s", 
                    string.sub(config.licenseKey, 1, 4),
                    string.sub(config.licenseKey, -4)
                ),
                ["Error"] = response.message
            })
            print(error)
            os.exit(1)
        end
        
        -- Check IP restriction
        if response.ipLocked and response.ipAddress ~= currentIp then
            local error = "❌ IP Address Mismatch: Bot running from unauthorized IP"
            sendWebhook("error", error, {
                ["Expected IP"] = response.ipAddress,
                ["Current IP"] = currentIp
            })
            print(error)
            os.exit(1)
        end
        
        -- License is valid
        local expiresStr = response.expiresAt and 
            os.date("%m/%d/%Y", response.expiresAt / 1000) or "Never"
            
        sendWebhook("success", "✅ License validated successfully", {
            ["Type"] = response.keyType,
            ["Expires"] = expiresStr
        })
        print("✅ License check passed")
        
        return true
    end)
    
    if not success then
        local errorMessage = "❌ License validation failed"
        local errorDetail = type(result) == "table" and 
            result.response and 
            result.response.message or 
            tostring(result)
            
        sendWebhook("error", errorMessage, {
            ["Error"] = errorDetail
        })
        print(string.format("%s: %s", errorMessage, errorDetail))
        os.exit(1)
    end
end

-- Main execution
local function main()
    -- Check if required packages are available
    local required_packages = {"socket.http", "ltn12", "cjson", "discordia"}
    for _, package in ipairs(required_packages) do
        if not pcall(require, package) then
            print(string.format("❌ Fatal Error: %s is not installed", package))
            os.exit(1)
        end
    end
    
    -- Configuration checks
    if not config.licenseKey then
        local error = "❌ No license key found in config!"
        sendWebhook("error", error)
        print(error)
        os.exit(1)
    end
    
    -- Initial validation
    validateLicense()
    
    -- Set up periodic validation (every 12 hours)
    while true do
        os.execute("sleep " .. (12 * 60 * 60)) -- Sleep for 12 hours
        validateLicense()
    end
end

-- Error handling wrapper
local success, err = pcall(main)
if not success then
    print(string.format("❌ Fatal error in license system: %s", tostring(err)))
    os.exit(1)
end`
};
    </script>

    <script>
        // Add this in the DOMContentLoaded event listener or after all your other scripts
document.addEventListener('DOMContentLoaded', () => {
    // Existing initialization
    loadKeys();

    // Add click handler for the key management menu item
    document.querySelector('[data-section="key-management"]').addEventListener('click', function() {
        const mainContent = document.querySelector('.main-content');
        mainContent.innerHTML = `
            <!-- Stats Section -->
            <div class="stats-grid">
                <div class="stat-card">
                    <i class="fas fa-key stat-icon"></i>
                    <div class="stat-value" id="totalKeys">0</div>
                    <div class="stat-label">إجمالي التراخيص</div>
                </div>
                <div class="stat-card">
                    <i class="fas fa-check-circle stat-icon"></i>
                    <div class="stat-value" id="activeKeys">0</div>
                    <div class="stat-label">التراخيص النشطة</div>
                </div>
                <div class="stat-card">
                    <i class="fas fa-clock stat-icon"></i>
                    <div class="stat-value" id="tempKeys">0</div>
                    <div class="stat-label">التراخيص المؤقتة</div>
                </div>
                <div class="stat-card">
                    <i class="fas fa-user-lock stat-icon"></i>
                    <div class="stat-value" id="personalKeys">0</div>
                    <div class="stat-label">التراخيص الشخصية</div>
                </div>
            </div>

            <!-- Keys Management Section -->
            <div class="section-header">
                <h2 class="section-title">إدارة التراخيص</h2>
                <div class="action-buttons">
                    <button class="btn btn-primary" onclick="openModal('generateKeyModal')">
                        <i class="fas fa-plus"></i>
                        إنشاء ترخيص جديد
                    </button>
                </div>
            </div>

            <!-- Filters Section -->
            <div class="filters-container">
                <div class="search-container">
                    <div style="flex: 1;">
                        <input type="text" id="searchInput" class="form-input" placeholder="البحث بواسطة معرف العميل أو الترخيص...">
                    </div>
                    <div style="display: flex; gap: 0.5rem;">
                        <select id="typeFilter" class="form-input" style="width: auto;">
                            <option value="">جميع الأنواع</option>
                            <option value="production">تجاري</option>
                            <option value="personal">شخصي</option>
                            <option value="subscription">اشتراك</option>
                        </select>
                        <select id="statusFilter" class="form-input" style="width: auto;">
                            <option value="">جميع الحالات</option>
                            <option value="active">نشط</option>
                            <option value="inactive">معطل</option>
                            <option value="expired">منتهي</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- Keys Table -->
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>الترخيص</th>
                            <th>النوع</th>
                            <th>الحالة</th>
                            <th>تاريخ الإنشاء</th>
                            <th>تاريخ الانتهاء</th>
                            <th>العميل</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody id="keysTableBody">
                        <!-- Will be filled with JavaScript -->
                    </tbody>
                </table>
            </div>
        `;

        // Reinitialize the necessary event listeners
        const searchInput = document.getElementById('searchInput');
        const typeFilter = document.getElementById('typeFilter');
        const statusFilter = document.getElementById('statusFilter');

        searchInput.addEventListener('input', () => {
            applyFiltersAndRender();
        });

        typeFilter.addEventListener('change', () => {
            applyFiltersAndRender();
        });

        statusFilter.addEventListener('change', () => {
            applyFiltersAndRender();
        });

        // Load the keys data
        loadKeys();
    });
});
    </script>

    <script>
        // Find your existing click handler for 'code-checker' menu item and modify it:
document.querySelector('[data-section="code-checker"]').addEventListener('click', function() {
    // Clear main content
    const mainContent = document.querySelector('.main-content');
    mainContent.innerHTML = `
        <div class="code-container">
            <div class="language-selector">
                <button class="language-btn active" data-target="javascript">
                    <i class="fas fa-code"></i>
                    جافا سكربت
                </button>
                <button class="language-btn" data-target="python">
                    <i class="fab fa-python"></i>
                    بايثون
                </button>
                <button class="language-btn" data-target="lua">
                    <i class="fas fa-moon"></i>
                    لوا
                </button>
            </div>

            <div class="code-block active" id="javascript">
                <div class="code-header">
                    <div class="code-title">
                        <i class="fas fa-code"></i>
                        جافا سكربت
                    </div>
                    <button class="copy-btn" onclick="copyCode('javascript')">
                        <i class="fas fa-copy"></i>
                    </button>
                </div>
                <div class="code-content">
                    <pre><code class="language-javascript">${codeExamples.javascript}</code></pre>
                </div>
            </div>

            <div class="code-block" id="python">
                <div class="code-header">
                    <div class="code-title">
                        <i class="fab fa-python"></i>
                        بايثون
                    </div>
                    <button class="copy-btn" onclick="copyCode('python')">
                        <i class="fas fa-copy"></i>
                    </button>
                </div>
                <div class="code-content">
                    <pre><code class="language-python">${codeExamples.python}</code></pre>
                </div>
            </div>

            <div class="code-block" id="lua">
                <div class="code-header">
                    <div class="code-title">
                        <i class="fas fa-moon"></i>
                        لوا
                    </div>
                    <button class="copy-btn" onclick="copyCode('lua')">
                        <i class="fas fa-copy"></i>
                    </button>
                </div>
                <div class="code-content">
                    <pre><code class="language-lua">${codeExamples.lua}</code></pre>
                </div>
            </div>
        </div>
    `;

    // Add click handlers for language buttons
    document.querySelectorAll('.language-btn').forEach(button => {
        button.addEventListener('click', () => {
            // Update active button
            document.querySelectorAll('.language-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            button.classList.add('active');

            // Update active code block
            const target = button.dataset.target;
            document.querySelectorAll('.code-block').forEach(block => {
                block.classList.remove('active');
            });
            document.getElementById(target).classList.add('active');
        });
    });

    // Highlight code (required for Prism.js to work)
    Prism.highlightAll();
});

// Add copy code function
function copyCode(language) {
    const codeBlock = document.querySelector(`#${language} .code-content code`);
    navigator.clipboard.writeText(codeBlock.textContent)
        .then(() => {
            const copyBtn = document.querySelector(`#${language} .copy-btn i`);
            copyBtn.className = 'fas fa-check';
            setTimeout(() => {
                copyBtn.className = 'fas fa-copy';
            }, 2000);
        })
        .catch(err => {
            console.error('Failed to copy code:', err);
        });
}
    </script>

    <script>

        function openModal(modalId) {
            modalSystem.openModal(modalId);

            // Add specific modal initialization logic
            if (modalId === 'generateKeyModal') {
                // Reset form fields
                const form = document.getElementById('generateKeyForm');
                form.setAttribute('novalidate', 'true');
                if (form) {
                    form.reset();

                    // Reset any custom field visibility
                    const ipGroup = document.getElementById('ipAddressGroup');
                    if (ipGroup) {
                        ipGroup.style.display = 'none';
                    }

                    // Reset any validation states
                    const inputs = form.querySelectorAll('input, select');
                    inputs.forEach(input => {
                        input.classList.remove('error');
                        const errorMessage = input.parentElement.querySelector('.error-message');
                        if (errorMessage) {
                            errorMessage.remove();
                        }
                    });
                }
            }
        }

        function closeModal(modalId) {
            modalSystem.closeModal(modalId);

            // Cleanup any modal-specific states
            const modal = document.getElementById(modalId);
            if (modal) {
                // Remove any error states
                const inputs = modal.querySelectorAll('input, select');
                inputs.forEach(input => {
                    input.classList.remove('error');
                    const errorMessage = input.parentElement.querySelector('.error-message');
                    if (errorMessage) {
                        errorMessage.remove();
                    }
                });

                // Reset any custom states
                if (modalId === 'generateKeyModal') {
                    const form = document.getElementById('generateKeyForm');
                    if (form) {
                        form.reset();
                    }
                }
            }
        }

        async function loadKeys() {
            const tbody = document.getElementById('keysTableBody');
            tbody.innerHTML = '<tr><td colspan="7" style="text-align: center;">جاري التحميل...</td></tr>';

            try {
                const response = await fetch('/api/keys');
                const data = await response.json();

                // Update stats
                document.getElementById('totalKeys').textContent = data.stats.total;
                document.getElementById('activeKeys').textContent = data.stats.active;
                document.getElementById('tempKeys').textContent = data.stats.temporary;
                document.getElementById('personalKeys').textContent = data.stats.personal;

                // Update table
                if (data.keys.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="7" style="text-align: center;">لا توجد تراخيص</td></tr>';
                    return;
                }

                tbody.innerHTML = data.keys.map(key => `
    <tr>
        <td class="key-cell" onclick="copyToClipboard('${key.keyString}')" title="انقر للنسخ">${key.keyString}</td>
        <td>
            <span class="badge ${getBadgeClass(key.keyType)}">
                ${getKeyTypeText(key.keyType)}
            </span>
        </td>
        <td>
            <span class="badge ${getStatusBadgeClass(key.status)}">
                ${getStatusText(key.status)}
            </span>
        </td>
        <td>${new Date(key.createdAt).toLocaleDateString('ar')}</td>
        <td>${key.expiresAt ? new Date(key.expiresAt).toLocaleDateString('ar') : '-'}</td>
        <td>
            ${key.discordUser ? `
                <div class="user-info" style="display: flex; align-items: center; gap: 0.5rem">
                    <img src="https://cdn.discordapp.com/avatars/${key.discordUser.id}/${key.discordUser.avatar}.png" 
                         alt="${key.discordUser.username}"
                         style="width: 24px; height: 24px; border-radius: 50%; object-fit: cover;">
                    <span>${key.discordUser.username}</span>
                </div>
            ` : '-'}
        </td>
        <td>
            ${key.status === 'inactive'
                        ? `<button class="action-btn" onclick="reactivateKey('${key._id}')" title="تفعيل">
                    <i class="fas fa-check-circle"></i>
                   </button>`
                        : `<button class="action-btn" onclick="deactivateKey('${key._id}')" title="تعطيل">
                    <i class="fas fa-ban"></i>
                   </button>`
                    }
            <button class="action-btn" onclick="deleteKey('${key._id}')" title="حذف">
                <i class="fas fa-trash"></i>
            </button>
        </td>
    </tr>
`).join('');
            } catch (error) {
                console.error('Error loading keys:', error);
                tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: var(--danger-color);">حدث خطأ أثناء تحميل التراخيص</td></tr>';
            }
        }

        // Copy to clipboard function
        async function copyToClipboard(text) {
            try {
                await navigator.clipboard.writeText(text);
                notificationSystem.show('تم نسخ الترخيص إلى الحافظة', 'success');
            } catch (err) {
                notificationSystem.show('فشل نسخ الترخيص', 'error');
                console.error('Failed to copy:', err);
            }
        }

        // Utility Functions
        function getBadgeClass(keyType) {
            switch (keyType) {
                case 'production': return 'badge-production';
                case 'personal': return 'badge-personal';
                case 'subscription': return 'badge-subscription';
                default: return 'badge-secondary';
            }
        }

        function getKeyTypeText(keyType) {
            switch (keyType) {
                case 'production': return 'تجاري';
                case 'personal': return 'شخصي';
                case 'subscription': return 'اشتراك';
                default: return 'غير معروف';
            }
        }

        function getStatusBadgeClass(status) {
            switch (status) {
                case 'active': return 'badge-success';
                case 'expired': return 'badge-danger';
                case 'inactive': return 'badge-warning';
                default: return 'badge-secondary';
            }
        }

        function getStatusText(status) {
            switch (status) {
                case 'active': return 'نشط';
                case 'expired': return 'منتهي';
                case 'inactive': return 'معطل';
                default: return 'غير معروف';
            }
        }

        // Notification System
        const notificationSystem = {
            container: document.querySelector('.notification-container'),

            show(message, type = 'success') {
                const notification = document.createElement('div');
                notification.className = `notification ${type}`;

                let icon;
                switch (type) {
                    case 'success':
                        icon = 'check-circle';
                        break;
                    case 'error':
                        icon = 'times-circle';
                        break;
                    case 'warning':
                        icon = 'exclamation-circle';
                        break;
                    default:
                        icon = 'info-circle';
                }

                notification.innerHTML = `
                    <i class="fas fa-${icon} notification-icon"></i>
                    <div class="notification-content">${message}</div>
                    <div class="notification-close">
                        <i class="fas fa-times"></i>
                    </div>
                `;

                this.container.appendChild(notification);

                // Trigger animation
                setTimeout(() => notification.classList.add('show'), 10);

                // Auto remove after 5 seconds
                const timeout = setTimeout(() => this.hide(notification), 5000);

                // Close button handler
                notification.querySelector('.notification-close').addEventListener('click', () => {
                    clearTimeout(timeout);
                    this.hide(notification);
                });
            },

            hide(notification) {
                notification.classList.remove('show');
                setTimeout(() => notification.remove(), 300);
            }
        };

        // Confirmation System
        const confirmationSystem = {
            overlay: document.querySelector('.confirmation-overlay'),
            dialog: document.querySelector('.confirmation-dialog'),
            confirmButton: document.querySelector('.btn-confirm'),
            cancelButton: document.querySelector('.btn-cancel'),

            async show(options = {}) {
                const {
                    title = 'تأكيد',
                    message = 'هل أنت متأكد من هذا الإجراء؟',
                    confirmText = 'تأكيد',
                    confirmClass = 'btn-confirm'
                } = options;

                this.dialog.querySelector('.confirmation-title').textContent = title;
                this.dialog.querySelector('.confirmation-message').textContent = message;
                this.confirmButton.textContent = confirmText;
                this.confirmButton.className = `btn ${confirmClass}`;

                this.overlay.style.display = 'flex';
                setTimeout(() => this.overlay.classList.add('show'), 10);

                return new Promise((resolve) => {
                    const handleConfirm = () => {
                        this.hide();
                        resolve(true);
                        cleanup();
                    };

                    const handleCancel = () => {
                        this.hide();
                        resolve(false);
                        cleanup();
                    };

                    const cleanup = () => {
                        this.confirmButton.removeEventListener('click', handleConfirm);
                        this.cancelButton.removeEventListener('click', handleCancel);
                    };

                    this.confirmButton.addEventListener('click', handleConfirm);
                    this.cancelButton.addEventListener('click', handleCancel);
                });
            },

            hide() {
                this.overlay.classList.remove('show');
                setTimeout(() => this.overlay.style.display = 'none', 300);
            }
        };

        // Key Management Functions
        async function deactivateKey(keyId) {
            const confirmed = await confirmationSystem.show({
                title: 'تعطيل الترخيص',
                message: 'هل أنت متأكد من تعطيل هذا الترخيص؟',
                confirmText: 'تعطيل',
                confirmClass: 'btn-confirm'
            });

            if (!confirmed) return;

            try {
                const response = await fetch(`/api/keys/${keyId}/deactivate`, {
                    method: 'PUT'
                });

                if (response.ok) {
                    loadKeys();
                    notificationSystem.show('تم تعطيل الترخيص بنجاح', 'success');
                } else {
                    throw new Error('Failed to deactivate key');
                }
            } catch (error) {
                console.error('Error:', error);
                notificationSystem.show('حدث خطأ أثناء تعطيل الترخيص', 'error');
            }
        }

        async function reactivateKey(keyId) {
            const confirmed = await confirmationSystem.show({
                title: 'تفعيل الترخيص',
                message: 'هل أنت متأكد من إعادة تفعيل هذا الترخيص؟',
                confirmText: 'تفعيل',
                confirmClass: 'btn-confirm'
            });

            if (!confirmed) return;

            try {
                const response = await fetch(`/api/keys/${keyId}/reactivate`, {
                    method: 'PUT'
                });

                if (response.ok) {
                    loadKeys();
                    notificationSystem.show('تم تفعيل الترخيص بنجاح', 'success');
                } else {
                    throw new Error('Failed to reactivate key');
                }
            } catch (error) {
                console.error('Error:', error);
                notificationSystem.show('حدث خطأ أثناء تفعيل الترخيص', 'error');
            }
        }

        async function deleteKey(keyId) {
            const confirmed = await confirmationSystem.show({
                title: 'حذف الترخيص',
                message: 'هل أنت متأكد من حذف هذا الترخيص؟ لا يمكن التراجع عن هذا الإجراء.',
                confirmText: 'حذف',
                confirmClass: 'btn-confirm'
            });

            if (!confirmed) return;

            try {
                const response = await fetch(`/api/keys/${keyId}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    loadKeys();
                    notificationSystem.show('تم حذف الترخيص بنجاح', 'success');
                } else {
                    throw new Error('Failed to delete key');
                }
            } catch (error) {
                console.error('Error:', error);
                notificationSystem.show('حدث خطأ أثناء حذف الترخيص', 'error');
            }
        }

        // Initialize dashboard
        document.addEventListener('DOMContentLoaded', () => {
            loadKeys();
        });

        // Modal Management System
        class ModalSystem {
            constructor() {
                this.activeModal = null;
                this.setupGlobalListeners();
            }

            setupGlobalListeners() {
                // Close modal on escape key
                document.addEventListener('keydown', (e) => {
                    if (e.key === 'Escape' && this.activeModal) {
                        this.closeModal(this.activeModal.id);
                    }
                });

                // Close modal when clicking outside
                document.addEventListener('click', (e) => {
                    if (this.activeModal && e.target.classList.contains('modal')) {
                        this.closeModal(this.activeModal.id);
                    }
                });
            }

            openModal(modalId) {
                const modal = document.getElementById(modalId);
                if (!modal) return;

                // Store reference to active modal
                this.activeModal = modal;

                // Display modal
                modal.style.display = 'flex';

                // Add show class after a brief delay for animation
                requestAnimationFrame(() => {
                    modal.classList.add('show');
                    const modalContent = modal.querySelector('.modal-content');
                    if (modalContent) {
                        modalContent.classList.add('show');
                    }
                });

                // Prevent body scrolling
                document.body.style.overflow = 'hidden';

                // Focus first input if exists
                const firstInput = modal.querySelector('input, select, textarea');
                if (firstInput) {
                    firstInput.focus();
                }

                // Reset form if exists
                const form = modal.querySelector('form');
                if (form) {
                    form.reset();
                }

                // Trigger custom event
                modal.dispatchEvent(new CustomEvent('modal:opened'));
            }

            closeModal(modalId) {
                const modal = document.getElementById(modalId);
                if (!modal) return;

                // Remove show classes
                modal.classList.remove('show');
                const modalContent = modal.querySelector('.modal-content');
                if (modalContent) {
                    modalContent.classList.remove('show');
                }

                // Hide modal after animation
                setTimeout(() => {
                    modal.style.display = 'none';
                    // Reset active modal if this was the active one
                    if (this.activeModal === modal) {
                        this.activeModal = null;
                    }
                }, 300); // Match your CSS transition duration

                // Restore body scrolling
                document.body.style.overflow = '';

                // Trigger custom event
                modal.dispatchEvent(new CustomEvent('modal:closed'));
            }

            updateModal(modalId, options = {}) {
                const modal = document.getElementById(modalId);
                if (!modal) return;

                const {
                    title,
                    content,
                    onConfirm,
                    onCancel,
                    confirmText,
                    cancelText
                } = options;

                // Update title if provided
                if (title) {
                    const titleElement = modal.querySelector('.modal-title');
                    if (titleElement) titleElement.textContent = title;
                }

                // Update content if provided
                if (content) {
                    const contentElement = modal.querySelector('.modal-body');
                    if (contentElement) contentElement.innerHTML = content;
                }

                // Update button text if provided
                if (confirmText) {
                    const confirmButton = modal.querySelector('.btn-confirm');
                    if (confirmButton) confirmButton.textContent = confirmText;
                }

                if (cancelText) {
                    const cancelButton = modal.querySelector('.btn-cancel');
                    if (cancelButton) cancelButton.textContent = cancelText;
                }

                // Update event handlers if provided
                if (onConfirm || onCancel) {
                    const form = modal.querySelector('form');
                    if (form) {
                        form.onsubmit = onConfirm ? (e) => {
                            e.preventDefault();
                            onConfirm(e);
                        } : null;
                    }
                }
            }
        }

        // Initialize modal system
        const modalSystem = new ModalSystem();

        // Export for use in other modules
        window.modalSystem = modalSystem;

    </script>

    <script>
        // Initialize form validation when the document loads
        document.addEventListener('DOMContentLoaded', function () {
            // Get form element and disable default validation
            const form = document.getElementById('generateKeyForm');
            form.setAttribute('novalidate', 'true');

            // Helper function to show field errors
            function showFieldError(field, message) {
                field.classList.add('error');
                const errorDiv = document.createElement('div');
                errorDiv.className = 'error-message';
                errorDiv.style.color = 'var(--danger-color)';
                errorDiv.style.fontSize = '0.8rem';
                errorDiv.style.marginTop = '0.25rem';
                errorDiv.textContent = message;
                field.parentElement.appendChild(errorDiv);
            }

            // Helper function to validate IP address
            function isValidIpAddress(ip) {
                const ipRegex = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/;
                if (!ipRegex.test(ip)) return false;

                const parts = ip.split('.');
                return parts.every(part => {
                    const num = parseInt(part, 10);
                    return num >= 0 && num <= 255;
                });
            }

            // Add change event listener for key type selection
            const keyTypeSelect = form.querySelector('select[name="keyType"]');
            keyTypeSelect.addEventListener('change', function () {
                const ipGroup = document.getElementById('ipAddressGroup');
                const userIdGroup = form.querySelector('.form-group:has(input[name="userId"])');

                // Show/hide IP address field based on key type
                ipGroup.style.display = this.value === 'personal' ? 'block' : 'none';

                // Always show user ID field
                userIdGroup.style.display = 'block';
                const userIdInput = form.querySelector('input[name="userId"]');
                userIdInput.removeAttribute('required');

                // Update label to show required status
                const userIdLabel = userIdGroup.querySelector('.form-label');
                userIdLabel.innerHTML = 'معرف العميل';
            });

            // Form submission handler
            form.addEventListener('submit', async (e) => {
                e.preventDefault();

                // Clear previous errors
                const inputs = form.querySelectorAll('input, select');
                inputs.forEach(input => {
                    input.classList.remove('error');
                    const errorMessage = input.parentElement.querySelector('.error-message');
                    if (errorMessage) errorMessage.remove();
                });

                // Validate
                let hasError = false;
                const keyType = form.elements.keyType.value;
                const userId = form.elements.userId.value.trim();

                // Validate user ID for all key types
                if (!userId) {
                    showFieldError(form.elements.userId, 'معرف العميل مطلوب');
                    hasError = true;
                }

                // Validate subscription requirements
                if (keyType === 'subscription') {
                    if (!form.elements.duration.value) {
                        showFieldError(form.elements.duration, 'مدة الصلاحية مطلوبة لتراخيص الاشتراك');
                        hasError = true;
                    }
                }

                // Validate personal type requirements
                if (keyType === 'personal') {
                    const ipAddress = form.elements.ipAddress.value;
                    if (ipAddress && !isValidIpAddress(ipAddress)) {
                        showFieldError(form.elements.ipAddress, 'عنوان IP غير صالح');
                        hasError = true;
                    }
                }

                if (hasError) return;

                // Submit form
                const submitButton = form.querySelector('button[type="submit"]');
                const formData = new FormData(form);

                try {
                    submitButton.disabled = true;
                    submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> جاري الإنشاء...';

                    const response = await fetch('/api/keys/generate', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            keyType: formData.get('keyType'),
                            duration: formData.get('duration'),
                            userId: formData.get('userId'),
                            ipAddress: formData.get('ipAddress')
                        })
                    });

                    if (!response.ok) {
                        const errorData = await response.json();
                        throw new Error(errorData.message || 'Failed to generate key');
                    }

                    closeModal('generateKeyModal');
                    loadKeys();
                    form.reset();
                    notificationSystem.show('تم إنشاء الترخيص بنجاح', 'success');

                } catch (error) {
                    console.error('Error:', error);
                    notificationSystem.show(error.message || 'حدث خطأ أثناء إنشاء الترخيص', 'error');
                } finally {
                    submitButton.disabled = false;
                    submitButton.innerHTML = 'إنشاء';
                }
            });
        });
    </script>

    <script>
        // Add this after your existing script

let keysData = []; // Store the original data

// Update the loadKeys function to store the data
async function loadKeys() {
    const tbody = document.getElementById('keysTableBody');
    tbody.innerHTML = '<tr><td colspan="7" style="text-align: center;">جاري التحميل...</td></tr>';

    try {
        const response = await fetch('/api/keys');
        const data = await response.json();

        // Store the keys data
        keysData = data.keys;

        // Update stats
        document.getElementById('totalKeys').textContent = data.stats.total;
        document.getElementById('activeKeys').textContent = data.stats.active;
        document.getElementById('tempKeys').textContent = data.stats.temporary;
        document.getElementById('personalKeys').textContent = data.stats.personal;

        // Apply current filters and render
        applyFiltersAndRender();
    } catch (error) {
        console.error('Error loading keys:', error);
        tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: var(--danger-color);">حدث خطأ أثناء تحميل التراخيص</td></tr>';
    }
}

// Function to apply filters and render the table
function applyFiltersAndRender() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase().trim();
    const typeFilter = document.getElementById('typeFilter').value;
    const statusFilter = document.getElementById('statusFilter').value;

    // Debug logging
    console.log('Current search term:', searchTerm);
    console.log('Current type filter:', typeFilter);
    console.log('Current status filter:', statusFilter);
    console.log('Total keys before filtering:', keysData.length);

    // Filter the data
    let filteredData = [...keysData]; // Create a copy of the original data

    // Apply search filter if there's a search term
    if (searchTerm) {
        filteredData = filteredData.filter(key => {
            const keyString = (key.keyString || '').toLowerCase();
            const username = key.discordUser?.username?.toLowerCase() || '';
            const userId = key.discordUser?.id?.toString().toLowerCase() || '';

            // Debug logging for each key
            console.log('Checking key:', {
                keyString,
                username,
                userId,
                searchTerm,
                matches: {
                    keyMatch: keyString.includes(searchTerm),
                    usernameMatch: username.includes(searchTerm),
                    userIdMatch: userId.includes(searchTerm)
                }
            });

            return keyString.includes(searchTerm) ||
                   username.includes(searchTerm) ||
                   userId.includes(searchTerm);
        });
    }

    // Debug logging after search filter
    console.log('Keys after search filter:', filteredData.length);

    // Apply type filter
    if (typeFilter) {
        filteredData = filteredData.filter(key => key.keyType === typeFilter);
        console.log('Keys after type filter:', filteredData.length);
    }

    // Apply status filter
    if (statusFilter) {
        filteredData = filteredData.filter(key => key.status === statusFilter);
        console.log('Keys after status filter:', filteredData.length);
    }

    // Render the filtered data
    const tbody = document.getElementById('keysTableBody');
    
    if (filteredData.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" style="text-align: center;">لا توجد نتائج</td></tr>';
        return;
    }

    tbody.innerHTML = filteredData.map(key => `
        <tr>
            <td class="key-cell" onclick="copyToClipboard('${key.keyString}')" title="انقر للنسخ">${key.keyString}</td>
            <td>
                <span class="badge ${getBadgeClass(key.keyType)}">
                    ${getKeyTypeText(key.keyType)}
                </span>
            </td>
            <td>
                <span class="badge ${getStatusBadgeClass(key.status)}">
                    ${getStatusText(key.status)}
                </span>
            </td>
            <td>${new Date(key.createdAt).toLocaleDateString('ar')}</td>
            <td>${key.expiresAt ? new Date(key.expiresAt).toLocaleDateString('ar') : '-'}</td>
            <td>
                ${key.discordUser ? `
                    <div class="user-info" style="display: flex; align-items: center; gap: 0.5rem">
                        <img src="https://cdn.discordapp.com/avatars/${key.discordUser.id}/${key.discordUser.avatar}.png" 
                             alt="${key.discordUser.username}"
                             style="width: 24px; height: 24px; border-radius: 50%; object-fit: cover;">
                        <span>${key.discordUser.username}</span>
                    </div>
                ` : '-'}
            </td>
            <td>
                ${key.status === 'inactive'
                    ? `<button class="action-btn" onclick="reactivateKey('${key._id}')" title="تفعيل">
                        <i class="fas fa-check-circle"></i>
                       </button>`
                    : `<button class="action-btn" onclick="deactivateKey('${key._id}')" title="تعطيل">
                        <i class="fas fa-ban"></i>
                       </button>`
                }
                <button class="action-btn" onclick="deleteKey('${key._id}')" title="حذف">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');

    // Debug logging for final render
    console.log('Final rendered keys:', filteredData.length);
}

// Make sure to properly bind the event listener
document.addEventListener('DOMContentLoaded', () => {
    const searchInput = document.getElementById('searchInput');
    const typeFilter = document.getElementById('typeFilter');
    const statusFilter = document.getElementById('statusFilter');

    // Use 'input' event for real-time search
    searchInput.addEventListener('input', () => {
        console.log('Search input event triggered');
        applyFiltersAndRender();
    });

    // Add change event listeners for filters
    typeFilter.addEventListener('change', () => {
        console.log('Type filter changed');
        applyFiltersAndRender();
    });

    statusFilter.addEventListener('change', () => {
        console.log('Status filter changed');
        applyFiltersAndRender();
    });

    // Initial load
    loadKeys();
});
    </script>
</body>

</html>