<?php
// conn.php - Database connection file
session_start();

// Database configuration - THAY ĐỔI THÔNG TIN NÀY
define('DB_HOST', 'localhost');
define('DB_USER', 'sql_aypt09_com');          // Username MySQL của bạn
define('DB_PASS', 'sql_aypt09_com');              // Password 
define('DB_NAME', 'sql_aypt09_com');    // Tên database của bạn
define('DB_PORT', '3306');          // Port MySQL
define('DB_CHARSET', 'utf8mb4');    // Character set

// Create connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT);

// Check connection
if ($conn->connect_error) {
    die("<h2 style='color:red'>Lỗi kết nối database:</h2> 
         <p>" . $conn->connect_error . "</p>
         <p>Vui lòng kiểm tra file conn.php và thông tin database</p>");
}

// Set charset
$conn->set_charset(DB_CHARSET);

// Function to escape input
function escape($string) {
    global $conn;
    return $conn->real_escape_string($string);
}

// Function to check if table exists
function table_exists($table_name) {
    global $conn;
    $result = $conn->query("SHOW TABLES LIKE '$table_name'");
    return $result->num_rows > 0;
}

// Function to create game_permissions table if not exists
function create_game_table() {
    global $conn;
    
    $sql = "CREATE TABLE IF NOT EXISTS `game_permissions` (
        `id` INT(11) NOT NULL AUTO_INCREMENT,
        `game_code` VARCHAR(50) NOT NULL,
        `game_name` VARCHAR(100) NOT NULL,
        `allowed_levels` VARCHAR(255) NOT NULL DEFAULT '1',
        `status` TINYINT(1) DEFAULT 1,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`),
        UNIQUE KEY `game_code` (`game_code`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    
    if ($conn->query($sql) === TRUE) {
        return true;
    } else {
        die("Lỗi tạo bảng: " . $conn->error);
    }
}

// Auto-create table on first run
if (!table_exists('game_permissions')) {
    create_game_table();
}

// Check session for admin login
function is_admin_logged_in() {
    return isset($_SESSION['user_id']) && isset($_SESSION['user_level']) && $_SESSION['user_level'] == 1;
}

// Redirect if not admin
function require_admin() {
    if (!is_admin_logged_in()) {
        header('Location: login.php');
        exit();
    }
}

// Get all games
function get_all_games() {
    global $conn;
    $sql = "SELECT * FROM game_permissions ORDER BY game_name ASC";
    $result = $conn->query($sql);
    
    $games = [];
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $games[] = $row;
        }
    }
    return $games;
}

// Get single game by ID
function get_game_by_id($id) {
    global $conn;
    $id = escape($id);
    $sql = "SELECT * FROM game_permissions WHERE id = '$id'";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
        return $result->fetch_assoc();
    }
    return null;
}

// Check if game code exists
function game_code_exists($game_code, $exclude_id = null) {
    global $conn;
    $game_code = escape($game_code);
    $sql = "SELECT id FROM game_permissions WHERE game_code = '$game_code'";
    
    if ($exclude_id) {
        $exclude_id = escape($exclude_id);
        $sql .= " AND id != '$exclude_id'";
    }
    
    $result = $conn->query($sql);
    return $result->num_rows > 0;
}

// Add new game
function add_game($data) {
    global $conn;
    
    $game_code = escape(strtoupper(trim($data['game_code'])));
    $game_name = escape(trim($data['game_name']));
    $allowed_levels = escape(trim($data['allowed_levels']));
    $status = isset($data['status']) ? 1 : 0;
    
    // Validate input
    if (empty($game_code) || empty($game_name) || empty($allowed_levels)) {
        return ['success' => false, 'message' => 'Vui lòng điền đầy đủ thông tin'];
    }
    
    if (!preg_match('/^[A-Z0-9]+$/i', $game_code)) {
        return ['success' => false, 'message' => 'Game Code chỉ được chứa chữ và số'];
    }
    
    if (!preg_match('/^[0-9,]+$/', $allowed_levels)) {
        return ['success' => false, 'message' => 'Allowed Levels chỉ được chứa số và dấu phẩy'];
    }
    
    // Check if game code exists
    if (game_code_exists($game_code)) {
        return ['success' => false, 'message' => 'Game Code đã tồn tại'];
    }
    
    // Clean levels
    $levels = explode(',', $allowed_levels);
    $levels = array_map('trim', $levels);
    $levels = array_filter($levels);
    $levels = array_unique($levels);
    sort($levels);
    $clean_levels = implode(',', $levels);
    
    // Insert game
    $sql = "INSERT INTO game_permissions (game_code, game_name, allowed_levels, status) 
            VALUES ('$game_code', '$game_name', '$clean_levels', '$status')";
    
    if ($conn->query($sql) === TRUE) {
        return ['success' => true, 'message' => 'Thêm game thành công!', 'id' => $conn->insert_id];
    } else {
        return ['success' => false, 'message' => 'Lỗi database: ' . $conn->error];
    }
}

// Update game
function update_game($id, $data) {
    global $conn;
    
    $id = escape($id);
    $game_code = escape(strtoupper(trim($data['game_code'])));
    $game_name = escape(trim($data['game_name']));
    $allowed_levels = escape(trim($data['allowed_levels']));
    $status = isset($data['status']) ? 1 : 0;
    
    // Validate input
    if (empty($game_code) || empty($game_name) || empty($allowed_levels)) {
        return ['success' => false, 'message' => 'Vui lòng điền đầy đủ thông tin'];
    }
    
    if (!preg_match('/^[A-Z0-9]+$/i', $game_code)) {
        return ['success' => false, 'message' => 'Game Code chỉ được chứa chữ và số'];
    }
    
    if (!preg_match('/^[0-9,]+$/', $allowed_levels)) {
        return ['success' => false, 'message' => 'Allowed Levels chỉ được chứa số và dấu phẩy'];
    }
    
    // Check if game code exists (excluding current game)
    if (game_code_exists($game_code, $id)) {
        return ['success' => false, 'message' => 'Game Code đã tồn tại'];
    }
    
    // Check if game exists
    $existing_game = get_game_by_id($id);
    if (!$existing_game) {
        return ['success' => false, 'message' => 'Game không tồn tại'];
    }
    
    // Clean levels
    $levels = explode(',', $allowed_levels);
    $levels = array_map('trim', $levels);
    $levels = array_filter($levels);
    $levels = array_unique($levels);
    sort($levels);
    $clean_levels = implode(',', $levels);
    
    // Update game
    $sql = "UPDATE game_permissions 
            SET game_name = '$game_name', 
                allowed_levels = '$clean_levels', 
                status = '$status' 
            WHERE id = '$id'";
    
    if ($conn->query($sql) === TRUE) {
        return ['success' => true, 'message' => 'Cập nhật game thành công!'];
    } else {
        return ['success' => false, 'message' => 'Lỗi database: ' . $conn->error];
    }
}

// Delete game
function delete_game($id) {
    global $conn;
    
    $id = escape($id);
    
    // Check if game has associated keys
    $game = get_game_by_id($id);
    if ($game) {
        $sql = "SELECT COUNT(*) as count FROM keys_code WHERE game = '{$game['game_code']}'";
        $result = $conn->query($sql);
        $row = $result->fetch_assoc();
        
        if ($row['count'] > 0) {
            return ['success' => false, 'message' => 'Không thể xóa game vì có ' . $row['count'] . ' key đang sử dụng'];
        }
    }
    
    $sql = "DELETE FROM game_permissions WHERE id = '$id'";
    
    if ($conn->query($sql) === TRUE) {
        return ['success' => true, 'message' => 'Xóa game thành công!'];
    } else {
        return ['success' => false, 'message' => 'Lỗi database: ' . $conn->error];
    }
}

// Toggle game status
function toggle_game_status($id) {
    global $conn;
    
    $id = escape($id);
    $game = get_game_by_id($id);
    
    if (!$game) {
        return ['success' => false, 'message' => 'Game không tồn tại'];
    }
    
    $new_status = $game['status'] == 1 ? 0 : 1;
    $sql = "UPDATE game_permissions SET status = '$new_status' WHERE id = '$id'";
    
    if ($conn->query($sql) === TRUE) {
        return [
            'success' => true, 
            'message' => 'Cập nhật trạng thái thành công!',
            'new_status' => $new_status
        ];
    } else {
        return ['success' => false, 'message' => 'Lỗi database: ' . $conn->error];
    }
}

// Search games
function search_games($keyword) {
    global $conn;
    $keyword = escape($keyword);
    
    $sql = "SELECT * FROM game_permissions 
            WHERE game_code LIKE '%$keyword%' 
               OR game_name LIKE '%$keyword%'
               OR allowed_levels LIKE '%$keyword%'
            ORDER BY game_name ASC";
    
    $result = $conn->query($sql);
    $games = [];
    
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $games[] = $row;
        }
    }
    return $games;
}

// Close connection function
function close_connection() {
    global $conn;
    if ($conn) {
        $conn->close();
    }
}

// Register shutdown function to close connection
register_shutdown_function('close_connection');
?>

<!-- CSS Styles -->
<style>
:root {
    --primary-color: #4361ee;
    --secondary-color: #3a0ca3;
    --success-color: #4cc9f0;
    --danger-color: #f72585;
    --warning-color: #f8961e;
    --light-color: #f8f9fa;
    --dark-color: #212529;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;
    padding: 20px;
}

.container {
    max-width: 1200px;
    margin: 0 auto;
}

/* Header */
.header {
    background: white;
    border-radius: 15px;
    padding: 25px 30px;
    margin-bottom: 30px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.logo {
    display: flex;
    align-items: center;
    gap: 15px;
}

.logo-icon {
    width: 50px;
    height: 50px;
    background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 1.5rem;
}

.logo-text h1 {
    font-size: 1.8rem;
    font-weight: 700;
    color: var(--dark-color);
    margin-bottom: 5px;
}

.logo-text p {
    color: #6c757d;
    font-size: 0.9rem;
}

/* Cards */
.card {
    background: white;
    border-radius: 15px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
    margin-bottom: 25px;
    overflow: hidden;
}

.card-header {
    background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
    color: white;
    padding: 20px 25px;
    border-bottom: 1px solid rgba(255,255,255,0.1);
}

.card-header h3 {
    margin: 0;
    font-size: 1.4rem;
    font-weight: 600;
}

.card-body {
    padding: 25px;
}

/* Stats Cards */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.stat-card {
    background: white;
    border-radius: 15px;
    padding: 25px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.08);
    transition: transform 0.3s;
}

.stat-card:hover {
    transform: translateY(-5px);
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.8rem;
    margin-bottom: 20px;
}

.stat-icon.total { background: linear-gradient(135deg, #4361ee, #3a0ca3); color: white; }
.stat-icon.active { background: linear-gradient(135deg, #4cc9f0, #4361ee); color: white; }
.stat-icon.inactive { background: linear-gradient(135deg, #f8961e, #f3722c); color: white; }

.stat-value {
    font-size: 2.2rem;
    font-weight: 700;
    color: var(--dark-color);
    line-height: 1;
}

.stat-label {
    font-size: 0.9rem;
    color: #6c757d;
    text-transform: uppercase;
    letter-spacing: 1px;
    margin-top: 10px;
}

/* Form Styles */
.form-group {
    margin-bottom: 20px;
}

.form-label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #495057;
}

.form-control {
    width: 100%;
    padding: 12px 15px;
    border: 2px solid #e2e8f0;
    border-radius: 10px;
    font-size: 1rem;
    transition: all 0.3s;
}

.form-control:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
    outline: none;
}

.form-text {
    font-size: 0.85rem;
    color: #6c757d;
    margin-top: 5px;
}

.form-check {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
}

.form-check-input {
    width: 20px;
    height: 20px;
}

.form-check-label {
    font-weight: 500;
}

/* Button Styles */
.btn {
    padding: 12px 25px;
    border: none;
    border-radius: 10px;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.btn-primary {
    background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
    color: white;
}

.btn-primary:hover {
    background: linear-gradient(135deg, var(--secondary-color), var(--primary-color));
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(67, 97, 238, 0.3);
}

.btn-success {
    background: linear-gradient(135deg, #4cc9f0, #4361ee);
    color: white;
}

.btn-danger {
    background: linear-gradient(135deg, #f72585, #7209b7);
    color: white;
}

.btn-warning {
    background: linear-gradient(135deg, #f8961e, #f3722c);
    color: white;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-sm {
    padding: 8px 15px;
    font-size: 0.9rem;
}

/* Table Styles */
.table-responsive {
    overflow-x: auto;
}

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

.table th {
    background: #f8f9fa;
    padding: 15px;
    text-align: left;
    font-weight: 600;
    color: #495057;
    border-bottom: 2px solid #e2e8f0;
    text-transform: uppercase;
    font-size: 0.85rem;
    letter-spacing: 0.5px;
}

.table td {
    padding: 15px;
    border-bottom: 1px solid #e2e8f0;
    vertical-align: middle;
}

.table tr:hover {
    background: #f8f9fa;
}

/* Badges */
.badge {
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 0.85rem;
    font-weight: 600;
    display: inline-block;
}

.badge-primary {
    background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
    color: white;
}

.badge-success {
    background: linear-gradient(135deg, #4cc9f0, #4361ee);
    color: white;
}

.badge-danger {
    background: linear-gradient(135deg, #f72585, #7209b7);
    color: white;
}

.badge-warning {
    background: linear-gradient(135deg, #f8961e, #f3722c);
    color: white;
}

.badge-info {
    background: linear-gradient(135deg, #7209b7, #3a0ca3);
    color: white;
}

/* Level Badges */
.level-badge {
    font-size: 0.75rem;
    padding: 4px 8px;
    margin: 2px;
    border-radius: 4px;
    display: inline-block;
}

/* Alert Messages */
.alert {
    padding: 15px 20px;
    border-radius: 10px;
    margin-bottom: 20px;
    border: none;
}

.alert-success {
    background: linear-gradient(135deg, #d1fae5, #a7f3d0);
    color: #065f46;
}

.alert-danger {
    background: linear-gradient(135deg, #fee2e2, #fecaca);
    color: #991b1b;
}

.alert-warning {
    background: linear-gradient(135deg, #fef3c7, #fde68a);
    color: #92400e;
}

/* Level Selection */
.level-selector {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 20px;
}

.level-btn {
    padding: 10px 20px;
    border: 2px solid #e2e8f0;
    border-radius: 8px;
    background: white;
    cursor: pointer;
    transition: all 0.3s;
    font-weight: 500;
}

.level-btn.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}

.level-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 3px 10px rgba(0,0,0,0.1);
}

/* Modal Styles */
.modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 1000;
    align-items: center;
    justify-content: center;
}

.modal.show {
    display: flex;
}

.modal-content {
    background: white;
    border-radius: 15px;
    width: 90%;
    max-width: 500px;
    box-shadow: 0 20px 60px rgba(0,0,0,0.3);
    animation: modalSlideIn 0.3s;
}

@keyframes modalSlideIn {
    from {
        opacity: 0;
        transform: translateY(-50px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.modal-header {
    background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
    color: white;
    padding: 20px 25px;
    border-radius: 15px 15px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-title {
    margin: 0;
    font-size: 1.3rem;
    font-weight: 600;
}

.modal-close {
    background: none;
    border: none;
    color: white;
    font-size: 1.5rem;
    cursor: pointer;
    line-height: 1;
}

.modal-body {
    padding: 25px;
}

.modal-footer {
    padding: 20px 25px;
    border-top: 1px solid #e2e8f0;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

/* Responsive */
@media (max-width: 768px) {
    .header {
        flex-direction: column;
        text-align: center;
        gap: 20px;
    }
    
    .stats-grid {
        grid-template-columns: 1fr;
    }
    
    .table {
        font-size: 0.9rem;
    }
    
    .table th,
    .table td {
        padding: 10px;
    }
    
    .btn {
        padding: 10px 20px;
    }
}

/* Animation for toasts */
@keyframes slideInRight {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

@keyframes slideOutRight {
    from {
        transform: translateX(0);
        opacity: 1;
    }
    to {
        transform: translateX(100%);
        opacity: 0;
    }
}

/* Loading spinner */
.spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid var(--primary-color);
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin: 0 auto;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
</style>

<!-- JavaScript Functions -->
<script>
// Toast notification system
function showToast(message, type = 'info', duration = 3000) {
    const toastId = 'toast-' + Date.now();
    const toastContainer = document.getElementById('toast-container') || createToastContainer();
    
    const toast = document.createElement('div');
    toast.id = toastId;
    toast.className = `toast alert-${type}`;
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        border-radius: 10px;
        color: white;
        z-index: 9999;
        animation: slideInRight 0.3s;
        max-width: 350px;
        box-shadow: 0 5px 15px rgba(0,0,0,0.2);
    `;
    
    // Set background based on type
    const bgColors = {
        'success': 'linear-gradient(135deg, #4cc9f0, #4361ee)',
        'error': 'linear-gradient(135deg, #f72585, #7209b7)',
        'warning': 'linear-gradient(135deg, #f8961e, #f3722c)',
        'info': 'linear-gradient(135deg, #4361ee, #3a0ca3)'
    };
    
    toast.style.background = bgColors[type] || bgColors.info;
    toast.innerHTML = `
        <div style="display: flex; align-items: center; gap: 10px;">
            <i class="fas fa-${getToastIcon(type)}"></i>
            <span>${message}</span>
        </div>
    `;
    
    toastContainer.appendChild(toast);
    
    // Auto remove after duration
    setTimeout(() => {
        toast.style.animation = 'slideOutRight 0.3s';
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 300);
    }, duration);
    
    // Click to dismiss
    toast.addEventListener('click', () => {
        toast.style.animation = 'slideOutRight 0.3s';
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 300);
    });
    
    return toastId;
}

function getToastIcon(type) {
    const icons = {
        'success': 'check-circle',
        'error': 'exclamation-circle',
        'warning': 'exclamation-triangle',
        'info': 'info-circle'
    };
    return icons[type] || 'info-circle';
}

function createToastContainer() {
    const container = document.createElement('div');
    container.id = 'toast-container';
    document.body.appendChild(container);
    return container;
}

// Confirm dialog
function showConfirm(message, confirmCallback, cancelCallback) {
    const modalId = 'confirm-modal-' + Date.now();
    
    const modal = document.createElement('div');
    modal.id = modalId;
    modal.className = 'modal';
    modal.innerHTML = `
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Xác nhận</h3>
                <button class="modal-close" onclick="closeModal('${modalId}')">&times;</button>
            </div>
            <div class="modal-body">
                <div style="text-align: center; padding: 20px;">
                    <i class="fas fa-question-circle" style="font-size: 3rem; color: #4361ee; margin-bottom: 20px;"></i>
                    <p style="font-size: 1.1rem; margin-bottom: 20px;">${message}</p>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeModal('${modalId}'); ${cancelCallback ? cancelCallback : ''}">Hủy</button>
                <button class="btn btn-danger" onclick="closeModal('${modalId}'); ${confirmCallback}">Xác nhận</button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // Show modal
    setTimeout(() => {
        modal.classList.add('show');
    }, 10);
    
    // Close on background click
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            closeModal(modalId);
            if (cancelCallback) {
                cancelCallback();
            }
        }
    });
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.remove('show');
        setTimeout(() => {
            if (modal.parentNode) {
                modal.parentNode.removeChild(modal);
            }
        }, 300);
    }
}

// Loading overlay
function showLoading(message = 'Đang xử lý...') {
    let loader = document.getElementById('global-loader');
    if (!loader) {
        loader = document.createElement('div');
        loader.id = 'global-loader';
        loader.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            z-index: 9998;
            backdrop-filter: blur(5px);
        `;
        loader.innerHTML = `
            <div class="spinner"></div>
            <p style="margin-top: 20px; font-size: 1.1rem; color: #333; font-weight: 500;">${message}</p>
        `;
        document.body.appendChild(loader);
    }
    loader.style.display = 'flex';
}

function hideLoading() {
    const loader = document.getElementById('global-loader');
    if (loader) {
        loader.style.display = 'none';
    }
}

// Form validation
function validateGameForm() {
    const gameCode = document.getElementById('game_code').value.trim();
    const gameName = document.getElementById('game_name').value.trim();
    const allowedLevels = document.getElementById('allowed_levels').value.trim();
    
    if (!gameCode || !gameName || !allowedLevels) {
        showToast('Vui lòng điền đầy đủ thông tin bắt buộc', 'warning');
        return false;
    }
    
    if (!/^[A-Z0-9]+$/i.test(gameCode)) {
        showToast('Game Code chỉ được chứa chữ và số', 'warning');
        return false;
    }
    
    if (!/^[0-9,]+$/.test(allowedLevels)) {
        showToast('Allowed Levels chỉ được chứa số và dấu phẩy', 'warning');
        return false;
    }
    
    return true;
}

// Level selector functions
function addLevel(level) {
    const input = document.getElementById('allowed_levels');
    let levels = input.value.split(',').map(l => l.trim()).filter(l => l);
    
    if (!levels.includes(level.toString())) {
        levels.push(level.toString());
        levels.sort((a, b) => a - b);
        input.value = levels.join(',');
        updateLevelButtons();
    }
}

function removeLevel(level) {
    const input = document.getElementById('allowed_levels');
    let levels = input.value.split(',').map(l => l.trim()).filter(l => l);
    levels = levels.filter(l => l !== level.toString());
    input.value = levels.join(',');
    updateLevelButtons();
}

function selectAllLevels() {
    document.getElementById('allowed_levels').value = '1,2,3,4,5';
    updateLevelButtons();
}

function clearLevels() {
    document.getElementById('allowed_levels').value = '';
    updateLevelButtons();
}

function updateLevelButtons() {
    const input = document.getElementById('allowed_levels');
    const levels = input.value.split(',').map(l => l.trim()).filter(l => l);
    
    // Remove all active classes
    document.querySelectorAll('.level-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    // Add active class to selected levels
    levels.forEach(level => {
        const btn = document.querySelector(`.level-btn[data-level="${level}"]`);
        if (btn) {
            btn.classList.add('active');
        }
    });
}

// Common level combinations
function setLevels(levels) {
    document.getElementById('allowed_levels').value = levels;
    updateLevelButtons();
}

// Initialize level buttons
document.addEventListener('DOMContentLoaded', function() {
    // Initialize level buttons
    const levelButtons = document.querySelectorAll('.level-btn');
    levelButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            const level = this.getAttribute('data-level');
            if (this.classList.contains('active')) {
                removeLevel(level);
            } else {
                addLevel(level);
            }
        });
    });
    
    // Initialize form level input
    const levelInput = document.getElementById('allowed_levels');
    if (levelInput) {
        updateLevelButtons();
        levelInput.addEventListener('input', updateLevelButtons);
    }
});
</script>