<?php
/**
 * Get Login Activity API
 * Endpoint: /admin/adminapi/get_login_activity.php
 * 
 * Returns:
 * - Active sessions (currently logged in devices with IP)
 * - Recent login/password change history from log file
 * 
 * Query params:
 *   ?type=active   - Get active sessions only
 *   ?type=history  - Get login history only
 *   ?type=all      - Get both (default)
 *   ?limit=50      - Number of history entries (default 50)
 */

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/activity_logger.php';

header('Content-Type: application/json');

// Require valid auth token
$adminId = requireAuth();

$type = $_GET['type'] ?? 'all';
$limit = isset($_GET['limit']) ? min(200, max(10, (int)$_GET['limit'])) : 50;

$response = ['success' => true];

// Active sessions
if ($type === 'active' || $type === 'all') {
    $sessions = getActiveLoginSessions();
    
    $formattedSessions = [];
    foreach ($sessions as $session) {
        $formattedSessions[] = [
            'admin_id' => $session['admin_id'],
            'ip_address' => $session['ip_address'],
            'phone_model' => $session['device_name'] ?? '',
            'device' => !empty($session['device_name']) ? $session['device_name'] : parseUserAgent($session['user_agent']),
            'user_agent' => $session['user_agent'],
            'login_time' => $session['created_at'],
            'last_activity' => $session['last_activity']
        ];
    }
    
    $response['active_sessions'] = $formattedSessions;
    $response['total_active'] = count($formattedSessions);
}

// Login history from log file
if ($type === 'history' || $type === 'all') {
    $logFile = getAdminActivityLogPath();
    
    if (file_exists($logFile)) {
        $content = file_get_contents($logFile);
        
        // Parse log entries into structured format
        $separator = str_repeat('-', 80);
        $entries = explode($separator, $content);
        $entries = array_filter($entries, function($e) { return trim($e) !== ''; });
        
        // Take last N entries, reverse for newest first
        $entries = array_slice($entries, -$limit);
        $entries = array_reverse($entries);
        
        $history = [];
        foreach ($entries as $entry) {
            $parsed = [];
            $lines = explode("\n", trim($entry));
            foreach ($lines as $line) {
                $line = trim($line);
                if (empty($line)) continue;
                
                $colonPos = strpos($line, ':');
                if ($colonPos !== false) {
                    $key = strtolower(trim(substr($line, 0, $colonPos)));
                    $value = trim(substr($line, $colonPos + 1));
                    $parsed[$key] = $value;
                }
            }
            
            if (!empty($parsed)) {
                $history[] = $parsed;
            }
        }
        
        $response['history'] = $history;
        $response['history_count'] = count($history);
    } else {
        $response['history'] = [];
        $response['history_count'] = 0;
    }
}

echo json_encode($response);
