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

// Get database connection
$pdo = getDBConnection();

// Get filter parameters
$searchUser = $_GET['search'] ?? '';
$activeOnly = isset($_GET['active_only']) ? filter_var($_GET['active_only'], FILTER_VALIDATE_BOOLEAN) : false;

// Build query
$sql = "SELECT s.*, u.user_name, u.email, u.user_level 
        FROM user_sessions s
        JOIN users u ON s.user_id = u.id
        WHERE 1=1";

$params = [];

if (!empty($searchUser)) {
    $sql .= " AND (u.user_name LIKE ? OR u.email LIKE ?)";
    $searchParam = "%$searchUser%";
    $params[] = $searchParam;
    $params[] = $searchParam;
}

if ($activeOnly) {
    $sql .= " AND s.expires_at > NOW()";
}

$sql .= " ORDER BY s.created_at DESC LIMIT 100";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$sessions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get statistics
$totalStmt = $pdo->query("SELECT COUNT(*) FROM user_sessions");
$totalSessions = $totalStmt->fetchColumn();

$activeStmt = $pdo->query("SELECT COUNT(*) FROM user_sessions WHERE expires_at > NOW()");
$activeSessions = $activeStmt->fetchColumn();

$expiredStmt = $pdo->query("SELECT COUNT(*) FROM user_sessions WHERE expires_at <= NOW()");
$expiredSessions = $expiredStmt->fetchColumn();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Session Management - Admin Panel</title>
    <link rel="stylesheet" href="assets/style.css">
    <style>
        .session-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .session-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        
        .session-user {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .session-status {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .status-active {
            background: #d4edda;
            color: #155724;
        }
        
        .status-expired {
            background: #f8d7da;
            color: #721c24;
        }
        
        .session-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 10px;
        }
        
        .info-item {
            display: flex;
            flex-direction: column;
        }
        
        .info-label {
            font-size: 12px;
            color: #666;
            margin-bottom: 4px;
        }
        
        .info-value {
            font-size: 14px;
            color: #333;
            word-break: break-all;
        }
        
        .token-display {
            font-family: 'Courier New', monospace;
            font-size: 11px;
            background: #f5f5f5;
            padding: 4px 8px;
            border-radius: 4px;
        }
        
        .action-btn {
            padding: 6px 12px;
            font-size: 13px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .btn-terminate {
            background: #dc3545;
            color: white;
        }
        
        .btn-terminate:hover {
            background: #c82333;
        }
        
        .filter-section {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            align-items: center;
        }
        
        .checkbox-label {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="container">
        <div class="page-header">
            <h1>Session Management</h1>
            <p>Monitor and manage user sessions</p>
        </div>
        
        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon" style="background: #4CAF50;">📊</div>
                <div class="stat-content">
                    <div class="stat-value"><?= $totalSessions ?></div>
                    <div class="stat-label">Total Sessions</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: #2196F3;">🟢</div>
                <div class="stat-content">
                    <div class="stat-value"><?= $activeSessions ?></div>
                    <div class="stat-label">Active Sessions</div>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: #f44336;">⏱️</div>
                <div class="stat-content">
                    <div class="stat-value"><?= $expiredSessions ?></div>
                    <div class="stat-label">Expired Sessions</div>
                </div>
            </div>
        </div>
        
        <!-- Filters -->
        <div class="content-card">
            <form method="GET" class="filter-section">
                <input type="text" 
                       name="search" 
                       placeholder="Search by username or email..." 
                       value="<?= htmlspecialchars($searchUser) ?>"
                       class="form-input"
                       style="flex: 1;">
                
                <label class="checkbox-label">
                    <input type="checkbox" 
                           name="active_only" 
                           value="1" 
                           <?= $activeOnly ? 'checked' : '' ?>
                           onchange="this.form.submit()">
                    Active Only
                </label>
                
                <button type="submit" class="btn btn-primary">Filter</button>
                <a href="sessions.php" class="btn btn-secondary">Clear</a>
            </form>
        </div>
        
        <!-- Sessions List -->
        <div class="content-card" style="padding: 20px;">
            <h3 style="margin-bottom: 20px;">Sessions (<?= count($sessions) ?>)</h3>
            
            <?php if (empty($sessions)): ?>
                <p style="text-align: center; padding: 40px; color: #666;">
                    No sessions found matching your criteria.
                </p>
            <?php else: ?>
                <?php foreach ($sessions as $session): 
                    $isActive = strtotime($session['expires_at']) > time();
                    $isExpiringSoon = strtotime($session['expires_at']) < strtotime('+7 days');
                ?>
                    <div class="session-card">
                        <div class="session-header">
                            <div class="session-user">
                                <strong><?= htmlspecialchars($session['user_name']) ?></strong>
                                <span style="color: #666;"><?= htmlspecialchars($session['email']) ?></span>
                                <span class="user-level-badge level-<?= strtolower($session['user_level']) ?>">
                                    <?= ucfirst($session['user_level']) ?>
                                </span>
                            </div>
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <span class="session-status status-<?= $isActive ? 'active' : 'expired' ?>">
                                    <?= $isActive ? '🟢 Active' : '🔴 Expired' ?>
                                </span>
                                <?php if ($isActive): ?>
                                    <button class="action-btn btn-terminate" 
                                            onclick="terminateSession('<?= $session['id'] ?>', '<?= htmlspecialchars($session['user_name']) ?>')">
                                        Terminate
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="session-info">
                            <div class="info-item">
                                <span class="info-label">Session Token</span>
                                <span class="info-value token-display"><?= substr($session['token'], 0, 30) ?>...</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Device Info</span>
                                <span class="info-value"><?= htmlspecialchars($session['device_info']) ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">IP Address</span>
                                <span class="info-value"><?= htmlspecialchars($session['ip_address']) ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Created</span>
                                <span class="info-value"><?= date('M d, Y H:i', strtotime($session['created_at'])) ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Expires</span>
                                <span class="info-value" style="color: <?= $isExpiringSoon && $isActive ? '#f39c12' : 'inherit' ?>">
                                    <?= date('M d, Y H:i', strtotime($session['expires_at'])) ?>
                                    <?php if ($isExpiringSoon && $isActive): ?>
                                        <span style="font-size: 11px;">(Soon)</span>
                                    <?php endif; ?>
                                </span>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
    
    <script>
        function terminateSession(sessionId, username) {
            if (!confirm(`Are you sure you want to terminate the session for ${username}?`)) {
                return;
            }
            
            fetch('api/sessions.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'terminate',
                    session_id: sessionId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Session terminated successfully');
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Failed to terminate session');
            });
        }
        
        // Auto-refresh active sessions every 60 seconds
        setTimeout(() => {
            if (<?= $activeOnly ? 'true' : 'false' ?>) {
                location.reload();
            }
        }, 60000);
    </script>
</body>
</html>
