<?php
header('Content-Type: application/json');
require_once '../config.php';

// Check admin authentication
requireAdminAuth();

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

try {
    switch ($action) {
        case 'terminate':
            $sessionId = $input['session_id'] ?? 0;
            
            if (!$sessionId) {
                echo json_encode(['success' => false, 'message' => 'Session ID is required']);
                exit;
            }
            
            // Get session info before deleting
            $stmt = $pdo->prepare("
                SELECT s.*, u.user_name, u.email 
                FROM user_sessions s 
                JOIN users u ON s.user_id = u.id 
                WHERE s.id = ?
            ");
            $stmt->execute([$sessionId]);
            $session = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$session) {
                echo json_encode(['success' => false, 'message' => 'Session not found']);
                exit;
            }
            
            // Delete the session
            $stmt = $pdo->prepare("DELETE FROM user_sessions WHERE id = ?");
            $stmt->execute([$sessionId]);
            
            // Log the action
            $adminInfo = getCurrentAdmin();
            logAdminActivity(
                $adminInfo['id'],
                'terminate_session',
                "Terminated session for user: {$session['user_name']} ({$session['email']}), Device: {$session['device_info']}"
            );
            
            echo json_encode(['success' => true, 'message' => 'Session terminated successfully']);
            break;
            
        case 'cleanup':
            // Delete all expired sessions
            $stmt = $pdo->prepare("DELETE FROM user_sessions WHERE expires_at < NOW()");
            $stmt->execute();
            $deletedCount = $stmt->rowCount();
            
            // Log the action
            $adminInfo = getCurrentAdmin();
            logAdminActivity(
                $adminInfo['id'],
                'cleanup_sessions',
                "Cleaned up $deletedCount expired session(s)"
            );
            
            echo json_encode([
                'success' => true, 
                'message' => "Cleaned up $deletedCount expired session(s)",
                'deleted_count' => $deletedCount
            ]);
            break;
            
        case 'terminate_user_sessions':
            $userId = $input['user_id'] ?? 0;
            
            if (!$userId) {
                echo json_encode(['success' => false, 'message' => 'User ID is required']);
                exit;
            }
            
            // Get user info
            $stmt = $pdo->prepare("SELECT user_name, email FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$user) {
                echo json_encode(['success' => false, 'message' => 'User not found']);
                exit;
            }
            
            // Delete all sessions for this user
            $stmt = $pdo->prepare("DELETE FROM user_sessions WHERE user_id = ?");
            $stmt->execute([$userId]);
            $deletedCount = $stmt->rowCount();
            
            // Log the action
            $adminInfo = getCurrentAdmin();
            logAdminActivity(
                $adminInfo['id'],
                'terminate_user_sessions',
                "Terminated all sessions ($deletedCount) for user: {$user['user_name']} ({$user['email']})"
            );
            
            echo json_encode([
                'success' => true, 
                'message' => "Terminated $deletedCount session(s) for user {$user['user_name']}",
                'deleted_count' => $deletedCount
            ]);
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
    
} catch (PDOException $e) {
    error_log("Session API error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error occurred']);
}
