<?php
require_once '../inc/config.php';
require_once '../inc/functions.php';

// Oturum kontrolü
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$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; ?> - <?php echo SITE_NAME; ?></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">
    <style>
        .session-card {
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 15px;
            background: #fff;
            transition: all 0.3s ease;
        }
        
        .session-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .session-card.current {
            border-color: #28a745;
            background: linear-gradient(135deg, #f8fff9 0%, #e8f5e8 100%);
        }
        
        .session-card.suspicious {
            border-color: #dc3545;
            background: linear-gradient(135deg, #fff8f8 0%, #ffe8e8 100%);
        }
        
        .device-icon {
            font-size: 2rem;
            margin-right: 15px;
        }
        
        .device-icon.mobile {
            color: #17a2b8;
        }
        
        .device-icon.desktop {
            color: #6c757d;
        }
        
        .session-info {
            flex: 1;
        }
        
        .session-meta {
            font-size: 0.9rem;
            color: #6c757d;
        }
        
        .activity-timeline {
            position: relative;
            padding-left: 30px;
        }
        
        .activity-timeline::before {
            content: '';
            position: absolute;
            left: 15px;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e9ecef;
        }
        
        .activity-item {
            position: relative;
            padding: 15px 0;
            border-bottom: 1px solid #f8f9fa;
        }
        
        .activity-item::before {
            content: '';
            position: absolute;
            left: -23px;
            top: 20px;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #007bff;
        }
        
        .activity-item.login::before {
            background: #28a745;
        }
        
        .activity-item.logout::before {
            background: #dc3545;
        }
        
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
        }
        
        .stats-number {
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .filter-tabs {
            border-bottom: 2px solid #e9ecef;
            margin-bottom: 20px;
        }
        
        .filter-tab {
            padding: 10px 20px;
            border: none;
            background: none;
            color: #6c757d;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            transition: all 0.3s ease;
        }
        
        .filter-tab.active {
            color: #007bff;
            border-bottom-color: #007bff;
        }
        
        .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;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 p-0">
                <?php include 'sidebar.php'; ?>
            </div>
            
            <!-- Ana İçerik -->
            <div class="col-md-9 col-lg-10 p-4">
                <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>
                    <button class="btn btn-outline-primary" onclick="refreshSessions()">
                        <i class="fas fa-sync-alt me-1"></i>Yenile
                    </button>
                </div>
                
                <!-- İstatistikler -->
                <div class="row mb-4">
                    <div class="col-md-4">
                        <div class="stats-card">
                            <div class="stats-number" id="totalSessions">-</div>
                            <div>Aktif Oturum</div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="stats-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                            <div class="stats-number" id="currentDevice">-</div>
                            <div>Mevcut Cihaz</div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="stats-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                            <div class="stats-number" id="lastActivity">-</div>
                            <div>Son Aktivite</div>
                        </div>
                    </div>
                </div>
                
                <!-- Filtre Sekmeleri -->
                <div class="filter-tabs">
                    <button class="filter-tab active" data-tab="sessions" onclick="switchTab('sessions')">
                        <i class="fas fa-desktop me-1"></i>Aktif Oturumlar
                    </button>
                    <button class="filter-tab" data-tab="activity" onclick="switchTab('activity')">
                        <i class="fas fa-history me-1"></i>Oturum Geçmişi
                    </button>
                </div>
                
                <!-- Aktif Oturumlar -->
                <div id="sessionsTab" class="tab-content">
                    <div class="row">
                        <div class="col-12">
                            <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>
                        </div>
                    </div>
                </div>
                
                <!-- Oturum Geçmişi -->
                <div id="activityTab" class="tab-content" style="display: none;">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-history me-2"></i>Son Aktiviteler</h5>
                        </div>
                        <div class="card-body">
                            <div id="activityContainer">
                                <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>
            </div>
        </div>
    </div>
    
    <!-- Oturum Sonlandırma Modal -->
    <div class="modal fade" id="terminateModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Oturumu Sonlandır</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>Bu oturumu sonlandırmak istediğinizden emin misiniz?</p>
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Bu işlem geri alınamaz ve ilgili cihazdan çıkış yapılacaktır.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                    <button type="button" class="btn btn-danger" onclick="confirmTerminate()">Sonlandır</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentSessionToTerminate = null;
        
        // Sayfa yüklendiğinde
        document.addEventListener('DOMContentLoaded', function() {
            loadSessions();
        });
        
        // Sekme değiştirme
        function switchTab(tab) {
            // Sekme butonlarını güncelle
            document.querySelectorAll('.filter-tab').forEach(btn => {
                btn.classList.remove('active');
            });
            document.querySelector(`[data-tab="${tab}"]`).classList.add('active');
            
            // İçerikleri göster/gizle
            document.querySelectorAll('.tab-content').forEach(content => {
                content.style.display = 'none';
            });
            
            if (tab === 'sessions') {
                document.getElementById('sessionsTab').style.display = 'block';
                loadSessions();
            } else if (tab === 'activity') {
                document.getElementById('activityTab').style.display = 'block';
                loadActivity();
            }
        }
        
        // Oturumları yükle
        function loadSessions() {
            fetch('../api/session_management.php?action=get_my_sessions')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displaySessions(data.sessions);
                        updateStats(data.sessions);
                    } 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">Aktif oturum bulunamadı</h5>
                    </div>
                `;
                return;
            }
            
            let html = '';
            sessions.forEach(session => {
                const deviceIcon = session.is_mobile ? 'fa-mobile-alt mobile' : 'fa-desktop desktop';
                const deviceName = session.is_mobile ? 'Mobil Cihaz' : 'Masaüstü';
                const currentBadge = session.is_current ? '<span class="badge bg-success ms-2">Mevcut Oturum</span>' : '';
                const terminateButton = session.is_current ? '' : `
                    <button class="btn btn-outline-danger btn-sm" onclick="terminateSession('${session.session_id}')">
                        <i class="fas fa-sign-out-alt me-1"></i>Sonlandır
                    </button>
                `;
                
                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_current ? 'current' : ''}">
                        <div class="d-flex align-items-center">
                            <div class="device-icon ${session.is_mobile ? 'mobile' : 'desktop'}">
                                <i class="fas ${deviceIcon}"></i>
                            </div>
                            <div class="session-info">
                                <h6 class="mb-1">
                                    ${deviceName}
                                    ${currentBadge}
                                    <span class="security-badge security-${session.security_level}">
                                        ${session.security_level.toUpperCase()}
                                    </span>
                                </h6>
                                <div class="session-meta">
                                    <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><i class="fas fa-clock me-1"></i>Giriş: ${formatDateTime(session.login_time)}</div>
                                    <div><i class="fas fa-history me-1"></i>Son Aktivite: ${formatDateTime(session.last_activity)}</div>
                                </div>
                            </div>
                            <div class="session-actions">
                                ${terminateButton}
                            </div>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }
        
        // İstatistikleri güncelle
        function updateStats(sessions) {
            document.getElementById('totalSessions').textContent = sessions.length;
            
            const currentSession = sessions.find(s => s.is_current);
            if (currentSession) {
                document.getElementById('currentDevice').textContent = currentSession.is_mobile ? 'Mobil' : 'Masaüstü';
                document.getElementById('lastActivity').textContent = formatTimeAgo(currentSession.last_activity);
            }
        }
        
        // Aktiviteleri yükle
        function loadActivity() {
            fetch('../api/session_management.php?action=get_my_session_activity&limit=50')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayActivity(data.activities);
                    } else {
                        showError('Aktiviteler yüklenemedi: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Hata:', error);
                    showError('Bir hata oluştu');
                });
        }
        
        // Aktiviteleri görüntüle
        function displayActivity(activities) {
            const container = document.getElementById('activityContainer');
            
            if (activities.length === 0) {
                container.innerHTML = `
                    <div class="text-center py-5">
                        <i class="fas fa-history fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">Aktivite geçmişi bulunamadı</h5>
                    </div>
                `;
                return;
            }
            
            let html = '<div class="activity-timeline">';
            activities.forEach(activity => {
                const activityIcon = getActivityIcon(activity.activity_type);
                const activityText = getActivityText(activity.activity_type);
                
                html += `
                    <div class="activity-item ${activity.activity_type}">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <h6 class="mb-1">
                                    <i class="${activityIcon} me-2"></i>${activityText}
                                </h6>
                                <div class="text-muted small">
                                    ${activity.page_url ? `<div>Sayfa: ${activity.page_url}</div>` : ''}
                                    <div>IP: ${activity.ip_address}</div>
                                </div>
                            </div>
                            <small class="text-muted">${formatDateTime(activity.activity_time)}</small>
                        </div>
                    </div>
                `;
            });
            html += '</div>';
            
            container.innerHTML = html;
        }
        
        // Oturum sonlandırma
        function terminateSession(sessionId) {
            currentSessionToTerminate = sessionId;
            new bootstrap.Modal(document.getElementById('terminateModal')).show();
        }
        
        function confirmTerminate() {
            if (!currentSessionToTerminate) return;
            
            const formData = new FormData();
            formData.append('action', 'terminate_my_session');
            formData.append('session_id', currentSessionToTerminate);
            
            fetch('../api/session_management.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccess(data.message);
                    loadSessions();
                } else {
                    showError(data.message);
                }
                bootstrap.Modal.getInstance(document.getElementById('terminateModal')).hide();
                currentSessionToTerminate = null;
            })
            .catch(error => {
                console.error('Hata:', error);
                showError('Bir hata oluştu');
            });
        }
        
        // Yenile
        function refreshSessions() {
            const activeTab = document.querySelector('.filter-tab.active').dataset.tab;
            if (activeTab === 'sessions') {
                loadSessions();
            } else {
                loadActivity();
            }
        }
        
        // Yardımcı fonksiyonlar
        function getActivityIcon(type) {
            const icons = {
                'login': 'fas fa-sign-in-alt text-success',
                'logout': 'fas fa-sign-out-alt text-danger',
                'page_view': 'fas fa-eye text-info',
                'bet_placed': 'fas fa-dice text-warning',
                'deposit': 'fas fa-plus-circle text-success',
                'withdrawal': 'fas fa-minus-circle text-danger',
                'profile_update': 'fas fa-user-edit text-primary',
                'password_change': 'fas fa-key text-warning'
            };
            return icons[type] || 'fas fa-circle text-muted';
        }
        
        function getActivityText(type) {
            const texts = {
                'login': 'Giriş Yapıldı',
                'logout': 'Çıkış Yapıldı',
                'page_view': 'Sayfa Görüntülendi',
                'bet_placed': 'Bahis Yapıldı',
                'deposit': 'Para Yatırıldı',
                'withdrawal': 'Para Çekildi',
                'profile_update': 'Profil Güncellendi',
                'password_change': 'Şifre Değiştirildi'
            };
            return texts[type] || 'Bilinmeyen Aktivite';
        }
        
        function formatDateTime(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('tr-TR');
        }
        
        function formatTimeAgo(dateString) {
            const date = new Date(dateString);
            const now = new Date();
            const diff = Math.floor((now - date) / 1000);
            
            if (diff < 60) return 'Az önce';
            if (diff < 3600) return Math.floor(diff / 60) + ' dk önce';
            if (diff < 86400) return Math.floor(diff / 3600) + ' sa önce';
            return Math.floor(diff / 86400) + ' gün önce';
        }
        
        function showSuccess(message) {
            // Toast bildirimi göster
            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) {
            // Toast bildirimi göster
            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);
        }
    </script>
</body>
</html>