<?php
require_once 'config.php';
require_once 'database.php';
require_once 'auth.php';

// Admin kontrolü
if (!isset($_SESSION['admin_logged_in']) || !has_permission('users_manage')) {
    header('Location: index.php');
    exit;
}

$page_title = "Oturum Yönetimi";
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link rel="stylesheet" href="styles.css">
    <style>
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            transition: transform 0.3s ease;
        }
        
        .stats-card:hover {
            transform: translateY(-5px);
        }
        
        .stats-card.danger {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
        }
        
        .stats-card.success {
            background: linear-gradient(135deg, #00b894 0%, #00a085 100%);
        }
        
        .stats-card.warning {
            background: linear-gradient(135deg, #fdcb6e 0%, #e17055 100%);
        }
        
        .stats-number {
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .session-card {
            border: 2px solid #FFD700;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 10px;
            background: #000000;
            color: #ffffff;
            transition: all 0.3s ease;
        }
        
        .session-card:hover {
            box-shadow: 0 4px 15px rgba(255, 215, 0, 0.3);
            border-color: #FFA500;
        }
        
        .session-card.suspicious {
            border-color: #dc3545;
            background: linear-gradient(135deg, #2d0a0a 0%, #4d1a1a 100%);
        }
        
        .session-card .text-muted {
            color: #cccccc !important;
        }
        
        .session-card h6 {
            color: #ffffff;
        }
        
        /* Modal styling */
        .modal-content {
            background-color: #000000;
            color: #ffffff;
            border: 2px solid #FFD700;
        }
        
        .modal-header {
            background-color: #000000;
            color: #ffffff;
            border-bottom: 1px solid #FFD700;
        }
        
        .modal-body {
            background-color: #000000;
            color: #ffffff;
        }
        
        .modal-footer {
            background-color: #000000;
            color: #ffffff;
            border-top: 1px solid #FFD700;
        }
        
        .btn-close {
            filter: invert(1);
        }
        
        .device-icon {
            font-size: 1.5rem;
            margin-right: 10px;
        }
        
        .device-icon.mobile {
            color: #17a2b8;
        }
        
        .device-icon.desktop {
            color: #6c757d;
        }
        
        .security-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .security-low {
            background: #fff3cd;
            color: #856404;
        }
        
        .security-medium {
            background: #d1ecf1;
            color: #0c5460;
        }
        
        .security-high {
            background: #d4edda;
            color: #155724;
        }
        
        .risk-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .risk-low {
            background: #d4edda;
            color: #155724;
        }
        
        .risk-medium {
            background: #fff3cd;
            color: #856404;
        }
        
        .risk-high {
            background: #f8d7da;
            color: #721c24;
        }
        
        .risk-critical {
            background: #dc3545;
            color: white;
        }
        
        .nav-tabs .nav-link {
            border: none;
            color: #6c757d;
            font-weight: 500;
        }
        
        .nav-tabs .nav-link.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
        }
        
        .search-box {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .filter-buttons {
            margin-bottom: 20px;
        }
        
        .filter-btn {
            margin-right: 10px;
            margin-bottom: 10px;
        }
        
        .chart-container {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include 'sidebar.php'; ?>

            <div class="col-md-10 p-4">
                <?php include __DIR__ . '/topbar.php'; ?>
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2><i class="fas fa-shield-alt me-2"></i><?php echo $page_title; ?></h2>
                    <div>
                        <button class="btn btn-outline-primary me-2" onclick="refreshData()">
                            <i class="fas fa-sync-alt me-1"></i>Yenile
                        </button>
                        <button class="btn btn-outline-success" onclick="exportData()">
                            <i class="fas fa-download me-1"></i>Dışa Aktar
                        </button>
                    </div>
                </div>
                
                <!-- İstatistikler -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="stats-card">
                            <div class="stats-number" id="totalActiveSessions">-</div>
                            <div><i class="fas fa-users me-1"></i>Aktif Oturum</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card danger">
                            <div class="stats-number" id="suspiciousSessions">-</div>
                            <div><i class="fas fa-exclamation-triangle me-1"></i>Şüpheli Oturum</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card success">
                            <div class="stats-number" id="mobilePercentage">-%</div>
                            <div><i class="fas fa-mobile-alt me-1"></i>Mobil Kullanım</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card warning">
                            <div class="stats-number" id="avgSessionDuration">- dk</div>
                            <div><i class="fas fa-clock me-1"></i>Ort. Süre</div>
                        </div>
                    </div>
                </div>
                
                <!-- Sekmeler -->
                <ul class="nav nav-tabs mb-4" id="sessionTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="sessions-tab" data-bs-toggle="tab" data-bs-target="#sessions" type="button" role="tab">
                            <i class="fas fa-desktop me-1"></i>Aktif Oturumlar
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="suspicious-tab" data-bs-toggle="tab" data-bs-target="#suspicious" type="button" role="tab">
                            <i class="fas fa-exclamation-triangle me-1"></i>Şüpheli Aktiviteler
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="analytics-tab" data-bs-toggle="tab" data-bs-target="#analytics" type="button" role="tab">
                            <i class="fas fa-chart-bar me-1"></i>Analitik
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="search-tab" data-bs-toggle="tab" data-bs-target="#search" type="button" role="tab">
                            <i class="fas fa-search me-1"></i>Arama
                        </button>
                    </li>
                </ul>
                
                <!-- Sekme İçerikleri -->
                <div class="tab-content" id="sessionTabContent">
                    <!-- Aktif Oturumlar -->
                    <div class="tab-pane fade show active" id="sessions" role="tabpanel">
                        <div class="filter-buttons">
                            <button class="btn btn-outline-primary filter-btn active" data-filter="all" onclick="filterSessions('all')">
                                <i class="fas fa-list me-1"></i>Tümü
                            </button>
                            <button class="btn btn-outline-info filter-btn" data-filter="mobile" onclick="filterSessions('mobile')">
                                <i class="fas fa-mobile-alt me-1"></i>Mobil
                            </button>
                            <button class="btn btn-outline-secondary filter-btn" data-filter="desktop" onclick="filterSessions('desktop')">
                                <i class="fas fa-desktop me-1"></i>Masaüstü
                            </button>
                            <button class="btn btn-outline-danger filter-btn" data-filter="suspicious" onclick="filterSessions('suspicious')">
                                <i class="fas fa-exclamation-triangle me-1"></i>Şüpheli
                            </button>
                        </div>
                        
                        <div class="card">
                            <div class="card-body">
                                <div id="sessionsContainer">
                                    <div class="text-center py-4">
                                        <div class="spinner-border text-primary" role="status">
                                            <span class="visually-hidden">Yükleniyor...</span>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Sayfalama -->
                                <nav aria-label="Oturum sayfalama" id="sessionsPagination" style="display: none;">
                                    <ul class="pagination justify-content-center mt-3">
                                        <!-- Dinamik olarak doldurulacak -->
                                    </ul>
                                </nav>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Şüpheli Aktiviteler -->
                    <div class="tab-pane fade" id="suspicious" role="tabpanel">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0"><i class="fas fa-exclamation-triangle me-2"></i>Şüpheli Oturum Aktiviteleri</h5>
                            </div>
                            <div class="card-body">
                                <div id="suspiciousContainer">
                                    <div class="text-center py-4">
                                        <div class="spinner-border text-primary" role="status">
                                            <span class="visually-hidden">Yükleniyor...</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Analitik -->
                    <div class="tab-pane fade" id="analytics" role="tabpanel">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="chart-container">
                                    <h5><i class="fas fa-chart-line me-2"></i>Oturum Trendi</h5>
                                    <canvas id="sessionTrendChart"></canvas>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="chart-container">
                                    <h5><i class="fas fa-chart-pie me-2"></i>Cihaz Dağılımı</h5>
                                    <canvas id="deviceDistributionChart"></canvas>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="chart-container">
                                    <h5><i class="fas fa-chart-bar me-2"></i>Günlük İstatistikler</h5>
                                    <canvas id="dailyStatsChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Arama -->
                    <div class="tab-pane fade" id="search" role="tabpanel">
                        <div class="search-box">
                            <div class="row">
                                <div class="col-md-4">
                                    <label class="form-label">Arama Türü</label>
                                    <select class="form-select" id="searchType">
                                        <option value="username">Kullanıcı Adı</option>
                                        <option value="email">E-posta</option>
                                        <option value="ip">IP Adresi</option>
                                        <option value="session_id">Oturum ID</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Arama Terimi</label>
                                    <input type="text" class="form-control" id="searchQuery" placeholder="Aranacak terim...">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">&nbsp;</label>
                                    <button class="btn btn-primary w-100" onclick="searchSessions()">
                                        <i class="fas fa-search me-1"></i>Ara
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card">
                            <div class="card-body">
                                <div id="searchResults">
                                    <div class="text-center py-5 text-muted">
                                        <i class="fas fa-search fa-3x mb-3"></i>
                                        <h5>Arama yapmak için yukarıdaki formu kullanın</h5>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Oturum Detayları Modal -->
    <div class="modal fade" id="sessionDetailsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Oturum Detayları</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="sessionDetailsContent">
                    <!-- Dinamik içerik -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Kapat</button>
                    <button type="button" class="btn btn-danger" id="terminateSessionBtn" onclick="terminateSessionFromModal()">
                        <i class="fas fa-sign-out-alt me-1"></i>Oturumu Sonlandır
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Şüpheli Aktivite İnceleme Modal -->
    <div class="modal fade" id="reviewSuspiciousModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Şüpheli Aktivite İncelemesi</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="reviewForm">
                        <input type="hidden" id="suspiciousId">
                        <div class="mb-3">
                            <label class="form-label">Durum</label>
                            <select class="form-select" id="reviewStatus" required>
                                <option value="">Seçiniz</option>
                                <option value="reviewed">İncelendi</option>
                                <option value="false_positive">Yanlış Alarm</option>
                                <option value="confirmed">Doğrulandı</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Alınan Aksiyon</label>
                            <select class="form-select" id="actionTaken">
                                <option value="none">Hiçbiri</option>
                                <option value="warning_sent">Uyarı Gönderildi</option>
                                <option value="session_terminated">Oturum Sonlandırıldı</option>
                                <option value="account_suspended">Hesap Askıya Alındı</option>
                                <option value="account_locked">Hesap Kilitlendi</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">İnceleme Notları</label>
                            <textarea class="form-control" id="reviewNotes" rows="3" placeholder="İnceleme notlarınızı yazın..."></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                    <button type="button" class="btn btn-primary" onclick="submitReview()">
                        <i class="fas fa-save me-1"></i>Kaydet
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    <script>
        let currentFilter = 'all';
        let currentPage = 1;
        let currentSessionId = null;
        let currentSuspiciousId = null;
        
        // Sayfa yüklendiğinde
        document.addEventListener('DOMContentLoaded', function() {
            loadStatistics();
            loadSessions();
            
            // Sekme değişikliklerini dinle
            document.querySelectorAll('[data-bs-toggle="tab"]').forEach(tab => {
                tab.addEventListener('shown.bs.tab', function(e) {
                    const target = e.target.getAttribute('data-bs-target');
                    if (target === '#suspicious') {
                        loadSuspiciousActivities();
                    } else if (target === '#analytics') {
                        loadAnalytics();
                    }
                });
            });
        });
        
        // İstatistikleri yükle
        function loadStatistics() {
            fetch('../api/session_management.php?action=get_session_statistics&days=7')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateStatistics(data);
                    }
                })
                .catch(error => console.error('İstatistik yükleme hatası:', error));
        }
        
        // İstatistikleri güncelle
        function updateStatistics(data) {
            const current = data.current_stats;
            document.getElementById('totalActiveSessions').textContent = current.active_sessions || 0;
            document.getElementById('suspiciousSessions').textContent = data.pending_suspicious || 0;
            
            const mobilePercentage = current.active_sessions > 0 ? 
                Math.round((current.mobile_sessions / current.active_sessions) * 100) : 0;
            document.getElementById('mobilePercentage').textContent = mobilePercentage;
            
            document.getElementById('avgSessionDuration').textContent = 
                Math.round(current.avg_duration || 0);
        }
        
        // Oturumları yükle
        function loadSessions(page = 1, filter = 'all') {
            currentPage = page;
            currentFilter = filter;
            
            fetch(`../api/session_management.php?action=get_all_sessions&page=${page}&limit=20&filter=${filter}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displaySessions(data.sessions);
                        updatePagination(data.pagination);
                    } else {
                        showError('Oturumlar yüklenemedi: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Hata:', error);
                    showError('Bir hata oluştu');
                });
        }
        
        // Oturumları görüntüle
        function displaySessions(sessions) {
            const container = document.getElementById('sessionsContainer');
            
            if (sessions.length === 0) {
                container.innerHTML = `
                    <div class="text-center py-5">
                        <i class="fas fa-desktop fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">Oturum bulunamadı</h5>
                    </div>
                `;
                return;
            }
            
            let html = '';
            sessions.forEach(session => {
                const deviceIcon = session.is_mobile ? 'fa-mobile-alt mobile' : 'fa-desktop desktop';
                const suspiciousBadge = session.is_suspicious ? 
                    '<span class="badge bg-danger ms-2">Şüpheli</span>' : '';
                
                const location = session.location_info ? 
                    `${session.location_info.city || 'Bilinmeyen'}, ${session.location_info.country || 'Bilinmeyen'}` : 
                    'Konum bilgisi yok';
                
                html += `
                    <div class="session-card ${session.is_suspicious ? 'suspicious' : ''}">
                        <div class="row align-items-center">
                            <div class="col-md-1">
                                <div class="device-icon ${session.is_mobile ? 'mobile' : 'desktop'}">
                                    <i class="fas ${deviceIcon}"></i>
                                </div>
                            </div>
                            <div class="col-md-7">
                                <h6 class="mb-1">
                                    ${session.username}
                                    <span class="security-badge security-${session.security_level}">
                                        ${session.security_level.toUpperCase()}
                                    </span>
                                    ${suspiciousBadge}
                                </h6>
                                <div class="text-muted small">
                                    <div><i class="fas fa-envelope me-1"></i>${session.email}</div>
                                    <div><i class="fas fa-map-marker-alt me-1"></i>${location}</div>
                                    <div><i class="fas fa-network-wired me-1"></i>${session.ip_address}</div>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="text-muted small">
                                    <div>Giriş: ${formatDateTime(session.login_time)}</div>
                                    <div>Son: ${formatDateTime(session.last_activity)}</div>
                                </div>
                            </div>
                            <div class="col-md-2 text-end">
                                <button class="btn btn-outline-info btn-sm me-1" onclick="viewSessionDetails('${session.session_id}')">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button class="btn btn-outline-danger btn-sm" onclick="terminateSession('${session.session_id}')">
                                    <i class="fas fa-sign-out-alt"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }
        
        // Sayfalama güncelle
        function updatePagination(pagination) {
            const container = document.getElementById('sessionsPagination');
            const ul = container.querySelector('ul');
            
            if (pagination.total_pages <= 1) {
                container.style.display = 'none';
                return;
            }
            
            container.style.display = 'block';
            
            let html = '';
            
            // Önceki sayfa
            if (pagination.current_page > 1) {
                html += `<li class="page-item">
                    <a class="page-link" href="#" onclick="loadSessions(${pagination.current_page - 1}, '${currentFilter}')">Önceki</a>
                </li>`;
            }
            
            // Sayfa numaraları
            for (let i = 1; i <= pagination.total_pages; i++) {
                if (i === pagination.current_page) {
                    html += `<li class="page-item active">
                        <span class="page-link">${i}</span>
                    </li>`;
                } else {
                    html += `<li class="page-item">
                        <a class="page-link" href="#" onclick="loadSessions(${i}, '${currentFilter}')">${i}</a>
                    </li>`;
                }
            }
            
            // Sonraki sayfa
            if (pagination.current_page < pagination.total_pages) {
                html += `<li class="page-item">
                    <a class="page-link" href="#" onclick="loadSessions(${pagination.current_page + 1}, '${currentFilter}')">Sonraki</a>
                </li>`;
            }
            
            ul.innerHTML = html;
        }
        
        // Filtre değiştir
        function filterSessions(filter) {
            // Filtre butonlarını güncelle
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            document.querySelector(`[data-filter="${filter}"]`).classList.add('active');
            
            loadSessions(1, filter);
        }
        
        // Oturum detaylarını görüntüle
        function viewSessionDetails(sessionId) {
            currentSessionId = sessionId;
            
            fetch(`../api/session_management.php?action=get_session_details&session_id=${sessionId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displaySessionDetails(data);
                        new bootstrap.Modal(document.getElementById('sessionDetailsModal')).show();
                    } else {
                        showError('Oturum detayları yüklenemedi: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Hata:', error);
                    showError('Bir hata oluştu');
                });
        }
        
        // Oturum detaylarını göster
        function displaySessionDetails(data) {
            const session = data.session;
            const activities = data.activities;
            const suspicious = data.suspicious_activities;
            
            const location = session.location_info ? 
                `${session.location_info.city || 'Bilinmeyen'}, ${session.location_info.country || 'Bilinmeyen'}` : 
                'Konum bilgisi yok';
            
            let html = `
                <div class="row">
                    <div class="col-md-6">
                        <h6>Kullanıcı Bilgileri</h6>
                        <table class="table table-sm">
                            <tr><td>Kullanıcı Adı:</td><td>${session.username}</td></tr>
                            <tr><td>E-posta:</td><td>${session.email}</td></tr>
                            <tr><td>Ad Soyad:</td><td>${session.first_name} ${session.last_name}</td></tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6>Oturum Bilgileri</h6>
                        <table class="table table-sm">
                            <tr><td>Oturum ID:</td><td>${session.session_id}</td></tr>
                            <tr><td>IP Adresi:</td><td>${session.ip_address}</td></tr>
                            <tr><td>Konum:</td><td>${location}</td></tr>
                            <tr><td>Cihaz:</td><td>${session.is_mobile ? 'Mobil' : 'Masaüstü'}</td></tr>
                            <tr><td>Güvenlik Seviyesi:</td><td><span class="security-badge security-${session.security_level}">${session.security_level.toUpperCase()}</span></td></tr>
                        </table>
                    </div>
                </div>
            `;
            
            if (suspicious.length > 0) {
                html += `
                    <div class="mt-3">
                        <h6 class="text-danger">Şüpheli Aktiviteler</h6>
                        <div class="alert alert-danger">
                `;
                suspicious.forEach(s => {
                    html += `
                        <div class="mb-2">
                            <strong>${s.suspicion_type}</strong> - 
                            <span class="risk-badge risk-${s.risk_level}">${s.risk_level.toUpperCase()}</span>
                            <br><small>${s.description}</small>
                        </div>
                    `;
                });
                html += '</div></div>';
            }
            
            if (activities.length > 0) {
                html += `
                    <div class="mt-3">
                        <h6>Son Aktiviteler</h6>
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Aktivite</th>
                                        <th>Sayfa</th>
                                        <th>Zaman</th>
                                    </tr>
                                </thead>
                                <tbody>
                `;
                activities.slice(0, 10).forEach(activity => {
                    html += `
                        <tr>
                            <td>${getActivityText(activity.activity_type)}</td>
                            <td>${activity.page_url || '-'}</td>
                            <td>${formatDateTime(activity.activity_time)}</td>
                        </tr>
                    `;
                });
                html += '</tbody></table></div></div>';
            }
            
            document.getElementById('sessionDetailsContent').innerHTML = html;
        }
        
        // Oturum sonlandır
        function terminateSession(sessionId) {
            Swal.fire({
                title: 'Oturum Sonlandır',
                text: 'Bu oturumu sonlandırmak istediğinizden emin misiniz?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Evet, Sonlandır',
                cancelButtonText: 'İptal',
                background: '#222',
                color: '#fff'
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'Sonlandırma Nedeni',
                        input: 'text',
                        inputPlaceholder: 'Sonlandırma nedeni (isteğe bağlı)',
                        showCancelButton: true,
                        confirmButtonText: 'Sonlandır',
                        cancelButtonText: 'İptal',
                        background: '#222',
                        color: '#fff',
                        inputValidator: () => {
                            return false; // Her zaman geçerli, çünkü isteğe bağlı
                        }
                    }).then((reasonResult) => {
                        if (reasonResult.isConfirmed) {
                            const reason = reasonResult.value || 'Admin tarafından sonlandırıldı';
                            
                            const formData = new FormData();
                            formData.append('action', 'terminate_session');
                            formData.append('session_id', sessionId);
                            formData.append('reason', reason);
                            
                            fetch('../api/session_management.php', {
                                method: 'POST',
                                body: formData
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    showSuccess(data.message);
                                    loadSessions(currentPage, currentFilter);
                                    loadStatistics();
                                } else {
                                    showError(data.message);
                                }
                            })
                            .catch(error => {
                                console.error('Hata:', error);
                                showError('Bir hata oluştu');
                            });
                        }
                    });
                }
            });
        }
        
        // Modal'dan oturum sonlandır
        function terminateSessionFromModal() {
            if (currentSessionId) {
                terminateSession(currentSessionId);
                bootstrap.Modal.getInstance(document.getElementById('sessionDetailsModal')).hide();
            }
        }
        
        // Şüpheli aktiviteleri yükle
        function loadSuspiciousActivities() {
            fetch('../api/session_management.php?action=get_suspicious_sessions&page=1&limit=50')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displaySuspiciousActivities(data.suspicious_sessions);
                    } else {
                        showError('Şüpheli aktiviteler yüklenemedi: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Hata:', error);
                    showError('Bir hata oluştu');
                });
        }
        
        // Şüpheli aktiviteleri görüntüle
        function displaySuspiciousActivities(suspicious) {
            const container = document.getElementById('suspiciousContainer');
            
            if (suspicious.length === 0) {
                container.innerHTML = `
                    <div class="text-center py-5">
                        <i class="fas fa-shield-alt fa-3x text-success mb-3"></i>
                        <h5 class="text-success">Şüpheli aktivite bulunamadı</h5>
                    </div>
                `;
                return;
            }
            
            let html = '<div class="table-responsive"><table class="table table-hover">';
            html += `
                <thead>
                    <tr>
                        <th>Kullanıcı</th>
                        <th>Şüphe Türü</th>
                        <th>Risk Seviyesi</th>
                        <th>Durum</th>
                        <th>Tarih</th>
                        <th>İşlemler</th>
                    </tr>
                </thead>
                <tbody>
            `;
            
            suspicious.forEach(s => {
                const statusBadge = getStatusBadge(s.status);
                const riskBadge = `<span class="risk-badge risk-${s.risk_level}">${s.risk_level.toUpperCase()}</span>`;
                
                html += `
                    <tr>
                        <td>
                            <strong>${s.username}</strong><br>
                            <small class="text-muted">${s.email}</small>
                        </td>
                        <td>${getSuspicionTypeText(s.suspicion_type)}</td>
                        <td>${riskBadge}</td>
                        <td>${statusBadge}</td>
                        <td>${formatDateTime(s.created_at)}</td>
                        <td>
                            ${s.status === 'pending' ? 
                                `<button class="btn btn-outline-primary btn-sm" onclick="reviewSuspicious(${s.id})">
                                    <i class="fas fa-eye me-1"></i>İncele
                                </button>` : 
                                '<span class="text-muted">İncelendi</span>'
                            }
                        </td>
                    </tr>
                `;
            });
            
            html += '</tbody></table></div>';
            container.innerHTML = html;
        }
        
        // Şüpheli aktivite inceleme
        function reviewSuspicious(suspiciousId) {
            currentSuspiciousId = suspiciousId;
            new bootstrap.Modal(document.getElementById('reviewSuspiciousModal')).show();
        }
        
        // İnceleme gönder
        function submitReview() {
            const formData = new FormData();
            formData.append('action', 'review_suspicious_session');
            formData.append('suspicious_id', currentSuspiciousId);
            formData.append('status', document.getElementById('reviewStatus').value);
            formData.append('notes', document.getElementById('reviewNotes').value);
            formData.append('action_taken', document.getElementById('actionTaken').value);
            
            fetch('../api/session_management.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccess(data.message);
                    loadSuspiciousActivities();
                    loadStatistics();
                    bootstrap.Modal.getInstance(document.getElementById('reviewSuspiciousModal')).hide();
                    
                    // Formu temizle
                    document.getElementById('reviewForm').reset();
                } else {
                    showError(data.message);
                }
            })
            .catch(error => {
                console.error('Hata:', error);
                showError('Bir hata oluştu');
            });
        }
        
        // Arama yap
        function searchSessions() {
            const query = document.getElementById('searchQuery').value.trim();
            const type = document.getElementById('searchType').value;
            
            if (!query) {
                showError('Arama terimi giriniz');
                return;
            }
            
            fetch(`../api/session_management.php?action=search_sessions&query=${encodeURIComponent(query)}&type=${type}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displaySearchResults(data.sessions);
                    } else {
                        showError('Arama yapılamadı: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Hata:', error);
                    showError('Bir hata oluştu');
                });
        }
        
        // Arama sonuçlarını göster
        function displaySearchResults(sessions) {
            const container = document.getElementById('searchResults');
            
            if (sessions.length === 0) {
                container.innerHTML = `
                    <div class="text-center py-5">
                        <i class="fas fa-search fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">Sonuç bulunamadı</h5>
                    </div>
                `;
                return;
            }
            
            let html = '<div class="table-responsive"><table class="table table-hover">';
            html += `
                <thead>
                    <tr>
                        <th>Kullanıcı</th>
                        <th>IP Adresi</th>
                        <th>Durum</th>
                        <th>Son Aktivite</th>
                        <th>İşlemler</th>
                    </tr>
                </thead>
                <tbody>
            `;
            
            sessions.forEach(session => {
                const statusBadge = session.is_active ? 
                    '<span class="badge bg-success">Aktif</span>' : 
                    '<span class="badge bg-secondary">Pasif</span>';
                
                html += `
                    <tr>
                        <td>
                            <strong>${session.username}</strong><br>
                            <small class="text-muted">${session.email}</small>
                        </td>
                        <td>${session.ip_address}</td>
                        <td>${statusBadge}</td>
                        <td>${formatDateTime(session.last_activity)}</td>
                        <td>
                            <button class="btn btn-outline-info btn-sm" onclick="viewSessionDetails('${session.session_id}')">
                                <i class="fas fa-eye"></i>
                            </button>
                            ${session.is_active ? 
                                `<button class="btn btn-outline-danger btn-sm ms-1" onclick="terminateSession('${session.session_id}')">
                                    <i class="fas fa-sign-out-alt"></i>
                                </button>` : ''
                            }
                        </td>
                    </tr>
                `;
            });
            
            html += '</tbody></table></div>';
            container.innerHTML = html;
        }
        
        // Analitik yükle
        function loadAnalytics() {
            fetch('../api/session_management.php?action=get_session_statistics&days=30')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        createCharts(data);
                    }
                })
                .catch(error => console.error('Analitik yükleme hatası:', error));
        }
        
        // Grafikleri oluştur
        function createCharts(data) {
            // Oturum trendi grafiği
            const trendCtx = document.getElementById('sessionTrendChart').getContext('2d');
            new Chart(trendCtx, {
                type: 'line',
                data: {
                    labels: data.historical_stats.map(s => s.date_recorded).reverse(),
                    datasets: [{
                        label: 'Aktif Oturumlar',
                        data: data.historical_stats.map(s => s.total_active_sessions).reverse(),
                        borderColor: '#007bff',
                        backgroundColor: 'rgba(0, 123, 255, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
            
            // Cihaz dağılımı grafiği
            const deviceCtx = document.getElementById('deviceDistributionChart').getContext('2d');
            const current = data.current_stats;
            new Chart(deviceCtx, {
                type: 'doughnut',
                data: {
                    labels: ['Mobil', 'Masaüstü'],
                    datasets: [{
                        data: [current.mobile_sessions, current.desktop_sessions],
                        backgroundColor: ['#17a2b8', '#6c757d']
                    }]
                },
                options: {
                    responsive: true
                }
            });
            
            // Günlük istatistikler grafiği
            const dailyCtx = document.getElementById('dailyStatsChart').getContext('2d');
            new Chart(dailyCtx, {
                type: 'bar',
                data: {
                    labels: data.historical_stats.map(s => s.date_recorded).reverse(),
                    datasets: [{
                        label: 'Yeni Oturumlar',
                        data: data.historical_stats.map(s => s.total_new_sessions).reverse(),
                        backgroundColor: '#28a745'
                    }, {
                        label: 'Sonlandırılan Oturumlar',
                        data: data.historical_stats.map(s => s.total_terminated_sessions).reverse(),
                        backgroundColor: '#dc3545'
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }
        
        // Veri yenile
        function refreshData() {
            loadStatistics();
            loadSessions(currentPage, currentFilter);
            
            // Aktif sekmeye göre veri yenile
            const activeTab = document.querySelector('.nav-link.active').getAttribute('data-bs-target');
            if (activeTab === '#suspicious') {
                loadSuspiciousActivities();
            } else if (activeTab === '#analytics') {
                loadAnalytics();
            }
        }
        
        // Veri dışa aktar
        function exportData() {
            // Bu fonksiyon CSV veya Excel formatında veri dışa aktarma işlemi yapabilir
            showInfo('Dışa aktarma özelliği yakında eklenecek');
        }
        
        // Yardımcı fonksiyonlar
        function getActivityText(type) {
            const texts = {
                'login': 'Giriş',
                'logout': 'Çıkış',
                'page_view': 'Sayfa Görüntüleme',
                'bet_placed': 'Bahis',
                'deposit': 'Para Yatırma',
                'withdrawal': 'Para Çekme',
                'profile_update': 'Profil Güncelleme',
                'password_change': 'Şifre Değişikliği'
            };
            return texts[type] || type;
        }
        
        function getSuspicionTypeText(type) {
            const texts = {
                'multiple_locations': 'Çoklu Konum',
                'unusual_device': 'Alışılmadık Cihaz',
                'rapid_login_attempts': 'Hızlı Giriş Denemeleri',
                'suspicious_ip': 'Şüpheli IP',
                'unusual_activity_pattern': 'Alışılmadık Aktivite'
            };
            return texts[type] || type;
        }
        
        function getStatusBadge(status) {
            const badges = {
                'pending': '<span class="badge bg-warning">Beklemede</span>',
                'reviewed': '<span class="badge bg-info">İncelendi</span>',
                'false_positive': '<span class="badge bg-success">Yanlış Alarm</span>',
                'confirmed': '<span class="badge bg-danger">Doğrulandı</span>'
            };
            return badges[status] || status;
        }
        
        function formatDateTime(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('tr-TR');
        }
        
        function showSuccess(message) {
            const toast = document.createElement('div');
            toast.className = 'toast align-items-center text-white bg-success border-0 position-fixed top-0 end-0 m-3';
            toast.style.zIndex = '9999';
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">${message}</div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            `;
            document.body.appendChild(toast);
            new bootstrap.Toast(toast).show();
            setTimeout(() => toast.remove(), 5000);
        }
        
        function showError(message) {
            const toast = document.createElement('div');
            toast.className = 'toast align-items-center text-white bg-danger border-0 position-fixed top-0 end-0 m-3';
            toast.style.zIndex = '9999';
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">${message}</div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            `;
            document.body.appendChild(toast);
            new bootstrap.Toast(toast).show();
            setTimeout(() => toast.remove(), 5000);
        }
        
        function showInfo(message) {
            const toast = document.createElement('div');
            toast.className = 'toast align-items-center text-white bg-info border-0 position-fixed top-0 end-0 m-3';
            toast.style.zIndex = '9999';
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">${message}</div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            `;
            document.body.appendChild(toast);
            new bootstrap.Toast(toast).show();
            setTimeout(() => toast.remove(), 5000);
        }
        
        // Enter tuşu ile arama
        document.getElementById('searchQuery').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchSessions();
            }
        });
    </script>
</body>
</html>