<?php
// game.php - Trang quản lý game
require_once 'conn.php';

// Kiểm tra admin login (giả sử session đã có)
if (!is_admin_logged_in()) {
    // Nếu chưa login, redirect hoặc hiển thị form login đơn giản
    ?>
    <!DOCTYPE html>
    <html lang="vi">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Đăng nhập Admin - Quản lý Game</title>
    </head>
    <body style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; display: flex; align-items: center; justify-content: center;">
        <div style="background: white; padding: 40px; border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); max-width: 400px; width: 90%;">
            <div style="text-align: center; margin-bottom: 30px;">
                <div style="width: 60px; height: 60px; background: linear-gradient(135deg, #4361ee, #3a0ca3); border-radius: 12px; display: inline-flex; align-items: center; justify-content: center; color: white; font-size: 1.5rem; margin-bottom: 15px;">
                    <i class="fas fa-key"></i>
                </div>
                <h2 style="color: #333; margin-bottom: 10px;">Admin Login</h2>
                <p style="color: #666;">Vui lòng đăng nhập để tiếp tục</p>
            </div>
            
            <form method="POST" action="">
                <div style="margin-bottom: 20px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #495057;">Username</label>
                    <input type="text" name="username" style="width: 100%; padding: 12px 15px; border: 2px solid #e2e8f0; border-radius: 8px; font-size: 1rem;" placeholder="Nhập username" required>
                </div>
                
                <div style="margin-bottom: 25px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #495057;">Password</label>
                    <input type="password" name="password" style="width: 100%; padding: 12px 15px; border: 2px solid #e2e8f0; border-radius: 8px; font-size: 1rem;" placeholder="Nhập password" required>
                </div>
                
                <button type="submit" name="login" style="width: 100%; padding: 14px; background: linear-gradient(135deg, #4361ee, #3a0ca3); color: white; border: none; border-radius: 8px; font-size: 1rem; font-weight: 600; cursor: pointer; transition: all 0.3s;">
                    Đăng nhập
                </button>
            </form>
            
            <?php
            // Simple login (for demo - in production use proper authentication)
            if (isset($_POST['login'])) {
                $username = $_POST['username'] ?? '';
                $password = $_POST['password'] ?? '';
                
                // Simple admin check (replace with proper authentication)
                if ($username === 'aypt09' && $password === '261129') {
                    $_SESSION['user_id'] = 1;
                    $_SESSION['user_level'] = 1;
                    $_SESSION['username'] = 'Admin';
                    echo '<script>window.location.href = "game.php";</script>';
                    exit;
                } else {
                    echo '<div style="margin-top: 20px; padding: 12px; background: linear-gradient(135deg, #fee2e2, #fecaca); color: #991b1b; border-radius: 8px; text-align: center;">
                            Sai username hoặc password!
                          </div>';
                }
            }
            ?>
            
            <div style="text-align: center; margin-top: 20px; color: #666; font-size: 0.9rem;">
                <p>Dev : @aypt09</p>
            </div>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// Process actions
$action = $_GET['action'] ?? '';
$id = $_GET['id'] ?? 0;

$message = '';
$message_type = '';

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_game'])) {
        $result = add_game($_POST);
        $message = $result['message'];
        $message_type = $result['success'] ? 'success' : 'error';
        
        // Reload to show new game
        if ($result['success']) {
            echo '<script>setTimeout(function() { window.location.href = "game.php"; }, 1500);</script>';
        }
        
    } elseif (isset($_POST['update_game'])) {
        $result = update_game($_POST['id'], $_POST);
        $message = $result['message'];
        $message_type = $result['success'] ? 'success' : 'error';
        
        // Reload to show updated game
        if ($result['success']) {
            echo '<script>setTimeout(function() { window.location.href = "game.php"; }, 1500);</script>';
        }
        
    } elseif (isset($_POST['delete_game_confirm'])) {
        // Delete game from POST form
        $result = delete_game($_POST['game_id']);
        $message = $result['message'];
        $message_type = $result['success'] ? 'success' : 'error';
        
        // Reload to remove deleted game
        if ($result['success']) {
            echo '<script>setTimeout(function() { window.location.href = "game.php"; }, 1500);</script>';
        }
    }
}

// Handle GET actions for delete
if ($action === 'delete' && $id) {
    // Show delete confirmation modal
    $delete_game_id = $id;
    echo '<script>showDeleteConfirm(' . $id . ');</script>';
    
} elseif ($action === 'toggle_status' && $id) {
    $result = toggle_game_status($id);
    $message = $result['message'];
    $message_type = $result['success'] ? 'success' : 'error';
    
    // Reload to show updated status
    if ($result['success']) {
        echo '<script>setTimeout(function() { window.location.href = "game.php"; }, 1500);</script>';
    }
}

// Get all games
$games = get_all_games();
$total_games = count($games);
$active_games = count(array_filter($games, function($g) { return $g['status'] == 1; }));
$inactive_games = $total_games - $active_games;

// Get game for editing
$edit_game = null;
if ($action === 'edit' && $id) {
    $edit_game = get_game_by_id($id);
}

// Search functionality
$search_keyword = $_GET['search'] ?? '';
if ($search_keyword) {
    $games = search_games($search_keyword);
}

// Handle logout
if (isset($_GET['logout'])) {
    session_destroy();
    echo '<script>window.location.href = "game.php";</script>';
    exit;
}
?>

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quản lý Game - Hệ thống Key</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script>
        // Show message from PHP
        <?php if ($message): ?>
        window.onload = function() {
            showToast('<?= addslashes($message) ?>', '<?= $message_type ?>');
        };
        <?php endif; ?>
        
        // Function to show delete confirmation
        function showDeleteConfirm(gameId) {
            showConfirm('Bạn có chắc muốn xóa game này? Hành động này không thể hoàn tác!', 
                function() {
                    // Submit delete form
                    document.getElementById('deleteFormId').value = gameId;
                    document.getElementById('deleteForm').submit();
                }
            );
        }
    </script>
</head>
<body>
    <!-- Delete Form (hidden) -->
    <form id="deleteForm" method="POST" action="" style="display: none;">
        <input type="hidden" name="delete_game_confirm" value="1">
        <input type="hidden" name="game_id" id="deleteFormId" value="">
    </form>
    
    <div class="container">
        <!-- Header -->
        <div class="header">
            <div class="logo">
                <div class="logo-icon">
                    <i class="fas fa-gamepad"></i>
                </div>
                <div class="logo-text">
                    <h1>Quản lý Game</h1>
                    <p>Hệ thống phân quyền và quản lý game</p>
                </div>
            </div>
            <div>
                <span style="color: #666; margin-right: 15px;">Xin chào, <?= htmlspecialchars($_SESSION['username'] ?? 'Admin') ?></span>
                <a href="?logout" class="btn btn-danger btn-sm">
                    <i class="fas fa-sign-out-alt"></i> Đăng xuất
                </a>
            </div>
        </div>

        <!-- Stats -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon total">
                    <i class="fas fa-gamepad"></i>
                </div>
                <div class="stat-value"><?= $total_games ?></div>
                <div class="stat-label">Tổng số Game</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon active">
                    <i class="fas fa-check-circle"></i>
                </div>
                <div class="stat-value"><?= $active_games ?></div>
                <div class="stat-label">Game Active</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon inactive">
                    <i class="fas fa-pause-circle"></i>
                </div>
                <div class="stat-value"><?= $inactive_games ?></div>
                <div class="stat-label">Game Inactive</div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="card">
            <div class="card-header">
                <h3><?= $edit_game ? 'Chỉnh sửa Game' : 'Thêm Game mới' ?></h3>
            </div>
            <div class="card-body">
                <form method="POST" action="" onsubmit="return validateGameForm()">
                    <?php if ($edit_game): ?>
                        <input type="hidden" name="id" value="<?= $edit_game['id'] ?>">
                    <?php endif; ?>
                    
                    <div class="form-group">
                        <label class="form-label">Game Code <span style="color: red">*</span></label>
                        <input type="text" 
                               name="game_code" 
                               id="game_code"
                               class="form-control" 
                               value="<?= htmlspecialchars($edit_game['game_code'] ?? '') ?>"
                               placeholder="VD: PUBG, KENTOS, MYSTIC"
                               <?= $edit_game ? 'readonly' : '' ?>
                               required>
                        <div class="form-text">
                            Mã duy nhất để nhận diện game. Chỉ chứa chữ và số.
                            <?= $edit_game ? '(Không thể thay đổi sau khi tạo)' : '' ?>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Tên Game <span style="color: red">*</span></label>
                        <input type="text" 
                               name="game_name" 
                               id="game_name"
                               class="form-control" 
                               value="<?= htmlspecialchars($edit_game['game_name'] ?? '') ?>"
                               placeholder="VD: PUBG Mobile, Kentos Cheat"
                               required>
                        <div class="form-text">Tên hiển thị của game</div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Level được phép truy cập <span style="color: red">*</span></label>
                        <input type="text" 
                               name="allowed_levels" 
                               id="allowed_levels"
                               class="form-control" 
                               value="<?= htmlspecialchars($edit_game['allowed_levels'] ?? '1') ?>"
                               placeholder="VD: 1,2,3"
                               required>
                        <div class="form-text">Nhập các Level được phép truy cập game, cách nhau bằng dấu phẩy</div>
                        
                        <!-- Quick Level Selector -->
                        <div class="level-selector">
                            <button type="button" class="level-btn" data-level="1">Level 1 (Admin)</button>
                            <button type="button" class="level-btn" data-level="2">Level 2 (Reseller)</button>
                            <button type="button" class="level-btn" data-level="3">Level 3 (VIP)</button>
                            <button type="button" class="level-btn" data-level="4">Level 4 (Premium)</button>
                            <button type="button" class="level-btn" data-level="5">Level 5 (User)</button>
                        </div>
                        
                        <div style="display: flex; gap: 10px; margin-top: 10px;">
                            <button type="button" class="btn btn-sm btn-primary" onclick="selectAllLevels()">
                                <i class="fas fa-check-double"></i> Chọn tất cả
                            </button>
                            <button type="button" class="btn btn-sm btn-secondary" onclick="clearLevels()">
                                <i class="fas fa-times"></i> Xóa tất cả
                            </button>
                        </div>
                        
                        <!-- Common Combinations -->
                        <div style="margin-top: 15px;">
                            <small style="display: block; margin-bottom: 5px; color: #666;">Gợi ý:</small>
                            <div style="display: flex; gap: 5px; flex-wrap: wrap;">
                                <button type="button" class="btn btn-xs btn-outline-primary" onclick="setLevels('1,2,3,4,5')">Tất cả Level</button>
                                <button type="button" class="btn btn-xs btn-outline-primary" onclick="setLevels('1,2,3')">Admin + Reseller + VIP</button>
                                <button type="button" class="btn btn-xs btn-outline-primary" onclick="setLevels('1,2')">Admin + Reseller</button>
                                <button type="button" class="btn btn-xs btn-outline-primary" onclick="setLevels('1,3,4')">Admin + VIP + Premium</button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Trạng thái</label>
                        <div class="form-check">
                            <input type="checkbox" 
                                   name="status" 
                                   id="status"
                                   class="form-check-input" 
                                   value="1"
                                   <?= (!isset($edit_game) || $edit_game['status'] == 1) ? 'checked' : '' ?>>
                            <label class="form-check-label" for="status">Active (Hiển thị và cho phép tạo key)</label>
                        </div>
                        <div class="form-text">Bỏ chọn để ẩn game khỏi danh sách tạo key</div>
                    </div>
                    
                    <div style="display: flex; gap: 10px; margin-top: 25px;">
                        <?php if ($edit_game): ?>
                            <button type="submit" name="update_game" class="btn btn-primary">
                                <i class="fas fa-save"></i> Cập nhật Game
                            </button>
                            <a href="game.php" class="btn btn-secondary">
                                <i class="fas fa-times"></i> Hủy
                            </a>
                        <?php else: ?>
                            <button type="submit" name="add_game" class="btn btn-primary">
                                <i class="fas fa-plus-circle"></i> Thêm Game mới
                            </button>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>

        <!-- Game List -->
        <div class="card">
            <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
                <h3>Danh sách Game (<?= $total_games ?>)</h3>
                <div style="display: flex; gap: 10px;">
                    <!-- Search Form -->
                    <form method="GET" action="" style="display: flex; gap: 5px;">
                        <input type="text" 
                               name="search" 
                               class="form-control" 
                               placeholder="Tìm kiếm game..."
                               value="<?= htmlspecialchars($search_keyword) ?>"
                               style="width: 200px;">
                        <button type="submit" class="btn btn-primary btn-sm">
                            <i class="fas fa-search"></i>
                        </button>
                        <?php if ($search_keyword): ?>
                            <a href="game.php" class="btn btn-secondary btn-sm">
                                <i class="fas fa-times"></i>
                            </a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Game Code</th>
                                <th>Tên Game</th>
                                <th>Phân quyền Level</th>
                                <th>Trạng thái</th>
                                <th>Ngày tạo</th>
                                <th>Hành động</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($games)): ?>
                                <tr>
                                    <td colspan="7" style="text-align: center; padding: 40px; color: #666;">
                                        <i class="fas fa-gamepad" style="font-size: 3rem; color: #ddd; margin-bottom: 15px; display: block;"></i>
                                        <p>Chưa có game nào. Hãy thêm game đầu tiên!</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($games as $index => $game): ?>
                                <tr>
                                    <td><?= $index + 1 ?></td>
                                    <td><strong><?= htmlspecialchars($game['game_code']) ?></strong></td>
                                    <td><?= htmlspecialchars($game['game_name']) ?></td>
                                    <td>
                                        <?php 
                                        $levels = explode(',', $game['allowed_levels']);
                                        foreach ($levels as $level): 
                                            $level = trim($level);
                                            $colors = ['', 'danger', 'success', 'info', 'warning', 'primary'];
                                            $color = $colors[$level] ?? 'secondary';
                                        ?>
                                            <span class="badge" style="background: <?= $color === 'danger' ? '#f72585' : 
                                                                                   ($color === 'success' ? '#4cc9f0' : 
                                                                                   ($color === 'info' ? '#7209b7' : 
                                                                                   ($color === 'warning' ? '#f8961e' : '#4361ee'))) ?>; 
                                                   margin: 2px;">
                                                Level <?= $level ?>
                                            </span>
                                        <?php endforeach; ?>
                                    </td>
                                    <td>
                                        <?php if ($game['status'] == 1): ?>
                                            <span class="badge" style="background: linear-gradient(135deg, #4cc9f0, #4361ee);">
                                                <i class="fas fa-check-circle"></i> Active
                                            </span>
                                        <?php else: ?>
                                            <span class="badge" style="background: linear-gradient(135deg, #f8961e, #f3722c);">
                                                <i class="fas fa-times-circle"></i> Inactive
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= date('d/m/Y', strtotime($game['created_at'])) ?></td>
                                    <td>
                                        <div style="display: flex; gap: 5px;">
                                            <a href="?action=edit&id=<?= $game['id'] ?>" class="btn btn-sm btn-warning">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            
                                            <button onclick="toggleStatus(<?= $game['id'] ?>)" 
                                                    class="btn btn-sm <?= $game['status'] == 1 ? 'btn-danger' : 'btn-success' ?>">
                                                <i class="fas fa-<?= $game['status'] == 1 ? 'toggle-on' : 'toggle-off' ?>"></i>
                                            </button>
                                            
                                            <button onclick="showDeleteConfirm(<?= $game['id'] ?>)" 
                                                    class="btn btn-sm btn-danger">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Footer -->
        <div style="text-align: center; padding: 20px; color: white; margin-top: 30px;">
            <p>© <?= date('Y') ?> Hệ thống Quản lý Game. Phiên bản 1.0</p>
            <p style="font-size: 0.9rem; opacity: 0.8;">Kết nối database: <?= DB_HOST ?> | Database: <?= DB_NAME ?></p>
        </div>
    </div>

    <script>
    // Toggle game status
    function toggleStatus(gameId) {
        showConfirm('Bạn có chắc muốn thay đổi trạng thái game này?', 
            function() {
                showLoading('Đang xử lý...');
                window.location.href = 'game.php?action=toggle_status&id=' + gameId;
            }
        );
    }
    
    // Delete game
    function confirmDelete(gameId) {
        showConfirm('Bạn có chắc muốn xóa game này? Hành động này không thể hoàn tác!', 
            function() {
                showLoading('Đang xóa...');
                window.location.href = 'game.php?action=delete&id=' + gameId;
            }
        );
    }
    
    // Initialize level buttons
    document.addEventListener('DOMContentLoaded', function() {
        updateLevelButtons();
        
        // Auto-hide messages after 5 seconds
        setTimeout(function() {
            const toasts = document.querySelectorAll('[id^="toast-"]');
            toasts.forEach(toast => {
                toast.style.animation = 'slideOutRight 0.3s';
                setTimeout(() => {
                    if (toast.parentNode) {
                        toast.parentNode.removeChild(toast);
                    }
                }, 300);
            });
        }, 5000);
    });
    
    // Handle URL parameters for delete action
    window.addEventListener('load', function() {
        const urlParams = new URLSearchParams(window.location.search);
        const action = urlParams.get('action');
        const id = urlParams.get('id');
        
        if (action === 'delete' && id) {
            showDeleteConfirm(id);
            
            // Clean URL to prevent re-trigger on refresh
            const cleanUrl = window.location.pathname;
            window.history.replaceState({}, document.title, cleanUrl);
        }
    });
    </script>
</body>
</html>