<?php
session_start();
require_once 'config.php';

// Kullanıcı giriş kontrolü
if (!isset($_SESSION['user_id'])) {
    header('Location: /');
    exit;
}

$user_id = $_SESSION['user_id'];

// PDO bağlantısını kontrol et (config.php'de $db olarak tanımlanmış)
if (!isset($db)) {
    die("Veritabanı bağlantısı bulunamadı.");
}

// Aktif sessionları getir
try {
    $stmt = $db->prepare("
        SELECT session_id, ip_address, user_agent, device_info, location_info, 
               login_time, last_activity, is_mobile, login_method, security_level
        FROM user_sessions 
        WHERE user_id = ? AND is_active = TRUE 
        ORDER BY login_time DESC
    ");
    $stmt->execute([$user_id]);
    $sessions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $sessions = [];
    $error = "Veritabanı hatası: " . $e->getMessage();
}

// Debug: Tüm sessionları getir (aktif/pasif)
try {
    $stmt = $db->prepare("
        SELECT session_id, ip_address, user_agent, is_active, login_time, last_activity
        FROM user_sessions 
        WHERE user_id = ? 
        ORDER BY login_time DESC
        LIMIT 10
    ");
    $stmt->execute([$user_id]);
    $all_sessions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $all_sessions = [];
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Session Yönetimi</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .session-card { border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 5px; position: relative; }
        .active { background-color: #e8f5e8; }
        .inactive { background-color: #f5e8e8; }
        .debug { background-color: #f0f0f0; padding: 10px; margin: 20px 0; }
        .terminate-btn { 
            background-color: #dc3545; 
            color: white; 
            border: none; 
            padding: 5px 10px; 
            border-radius: 3px; 
            cursor: pointer; 
            position: absolute; 
            top: 10px; 
            right: 10px; 
        }
        .terminate-btn:hover { background-color: #c82333; }
        .terminate-btn:disabled { background-color: #6c757d; cursor: not-allowed; }
        .current-session { border: 2px solid #007bff; }
        .message { padding: 10px; margin: 10px 0; border-radius: 5px; }
        .success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    </style>
</head>
<body>
    <h1>Session Yönetimi</h1>
    
    <div id="message-container"></div>
    
    <div class="debug">
        <h3>Debug Bilgileri</h3>
        <p><strong>Kullanıcı ID:</strong> <?= htmlspecialchars($user_id) ?></p>
        <p><strong>PHP Session ID:</strong> <?= htmlspecialchars(session_id()) ?></p>
        <p><strong>DB Session ID:</strong> <?= htmlspecialchars($_SESSION['db_session_id'] ?? 'Yok') ?></p>
        <p><strong>Toplam Session Sayısı:</strong> <?= count($all_sessions) ?></p>
        <p><strong>Aktif Session Sayısı:</strong> <?= count($sessions) ?></p>
    </div>

    <?php if (isset($error)): ?>
        <div style="color: red; padding: 10px; background: #ffe6e6;">
            <?= htmlspecialchars($error) ?>
        </div>
    <?php endif; ?>

    <h2>Aktif Sessionlar (<?= count($sessions) ?>)</h2>
    
    <?php if (empty($sessions)): ?>
        <p>Aktif session bulunamadı.</p>
    <?php else: ?>
        <?php foreach ($sessions as $session): ?>
            <?php 
            $is_current = isset($_SESSION['db_session_id']) && $_SESSION['db_session_id'] === $session['session_id'];
            ?>
            <div class="session-card active <?= $is_current ? 'current-session' : '' ?>" id="session-<?= htmlspecialchars($session['session_id']) ?>">
                <?php if (!$is_current): ?>
                    <button class="terminate-btn" onclick="terminateSession('<?= htmlspecialchars($session['session_id']) ?>')">
                        Sonlandır
                    </button>
                <?php else: ?>
                    <span style="position: absolute; top: 10px; right: 10px; background: #007bff; color: white; padding: 5px 10px; border-radius: 3px; font-size: 12px;">
                        Mevcut Oturum
                    </span>
                <?php endif; ?>
                <h3>Session: <?= htmlspecialchars($session['session_id']) ?></h3>
                <p><strong>IP:</strong> <?= htmlspecialchars($session['ip_address']) ?></p>
                <p><strong>Cihaz:</strong> <?= $session['is_mobile'] ? 'Mobil' : 'Masaüstü' ?></p>
                <p><strong>Giriş:</strong> <?= htmlspecialchars($session['login_time']) ?></p>
                <p><strong>Son Aktivite:</strong> <?= htmlspecialchars($session['last_activity']) ?></p>
                <p><strong>Güvenlik:</strong> <?= htmlspecialchars($session['security_level']) ?></p>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>

    <h2>Tüm Sessionlar (Son 10)</h2>
    
    <?php foreach ($all_sessions as $session): ?>
        <div class="session-card <?= $session['is_active'] ? 'active' : 'inactive' ?>">
            <h4><?= htmlspecialchars($session['session_id']) ?> - <?= $session['is_active'] ? 'AKTİF' : 'PASİF' ?></h4>
            <p><strong>IP:</strong> <?= htmlspecialchars($session['ip_address']) ?></p>
            <p><strong>Giriş:</strong> <?= htmlspecialchars($session['login_time']) ?></p>
            <p><strong>Son Aktivite:</strong> <?= htmlspecialchars($session['last_activity']) ?></p>
        </div>
    <?php endforeach; ?>

    <br>
    <a href="/">Ana Sayfa</a> | <a href="/logout.php">Çıkış</a>

    <script>
    function terminateSession(sessionId) {
        if (!confirm('Bu oturumu sonlandırmak istediğinizden emin misiniz?')) {
            return;
        }
        
        const button = document.querySelector(`#session-${sessionId} .terminate-btn`);
        if (button) {
            button.disabled = true;
            button.textContent = 'Sonlandırılıyor...';
        }
        
        fetch('/api/session_management.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `action=terminate_user_session&session_id=${encodeURIComponent(sessionId)}&reason=Kullanıcı tarafından sonlandırıldı`
        })
        .then(response => response.json())
        .then(data => {
            showMessage(data.message, data.success ? 'success' : 'error');
            if (data.success) {
                // Session kartını kaldır
                const sessionCard = document.getElementById(`session-${sessionId}`);
                if (sessionCard) {
                    sessionCard.style.opacity = '0.5';
                    sessionCard.querySelector('.terminate-btn').style.display = 'none';
                    setTimeout(() => {
                        location.reload(); // Sayfayı yenile
                    }, 1000);
                }
            } else {
                // Butonu tekrar aktif et
                if (button) {
                    button.disabled = false;
                    button.textContent = 'Sonlandır';
                }
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showMessage('Bir hata oluştu: ' + error.message, 'error');
            if (button) {
                button.disabled = false;
                button.textContent = 'Sonlandır';
            }
        });
    }
    
    function showMessage(message, type) {
        const container = document.getElementById('message-container');
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}`;
        messageDiv.textContent = message;
        
        container.innerHTML = '';
        container.appendChild(messageDiv);
        
        // 5 saniye sonra mesajı kaldır
        setTimeout(() => {
            messageDiv.remove();
        }, 5000);
    }
    </script>
</body>
</html>