<?php
require_once '../includes/init.php';

// Set content type to JSON
header('Content-Type: application/json');

if (!isAuthenticated()) {
    jsonResponse(false, 'Not authenticated');
    exit;
}

$db = getDB();
$currentUserId = $_SESSION['user_id'];

// Get admin settings for auto-logout (key-value format)
$stmt = $db->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('auto_logout_enabled', 'auto_logout_minutes')");
$stmt->execute();
$settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

// Default settings if not found
$autoLogoutEnabled = ($settings['auto_logout_enabled'] ?? '1') === '1';
$autoLogoutMinutes = intval($settings['auto_logout_minutes'] ?? '5');

// Check if auto-logout is enabled by admin
if (!$autoLogoutEnabled) {
    jsonResponse(true, 'Auto-logout disabled by admin', [
        'auto_logout_enabled' => false,
        'current_user_status' => 'online',
        'last_activity' => date('Y-m-d H:i:s')
    ]);
    exit;
}

// ALWAYS update current user's last activity when API is called
$stmt = $db->prepare("UPDATE users SET last_activity = NOW() WHERE id = ?");
$stmt->execute([$currentUserId]);

// Get current user data for auto-logout check
$stmt = $db->prepare("SELECT last_activity, status, failed_login_attempts, last_failed_login FROM users WHERE id = ?");
$stmt->execute([$currentUserId]);
$user = $stmt->fetch();

if (!$user) {
    jsonResponse(false, 'User not found');
    exit;
}

// Calculate inactivity
$lastActivity = new DateTime($user['last_activity']);
$now = new DateTime();
$interval = $now->diff($lastActivity);

// Check for too many failed login attempts
$maxFailedAttempts = 5;
$lockoutMinutes = 30;
if ($user['failed_login_attempts'] >= $maxFailedAttempts) {
    $lastFailedTime = new DateTime($user['last_failed_login']);
    $lockoutEnd = (clone $lastFailedTime)->add(new DateInterval("PT{$lockoutMinutes}M"));
    
    if ($now < $lockoutEnd) {
        jsonResponse(false, 'Account locked due to too many failed login attempts', [
            'locked' => true,
            'failed_attempts' => $user['failed_login_attempts'],
            'lockout_until' => $lockoutEnd->format('Y-m-d H:i:s'),
            'remaining_minutes' => $now->diff($lockoutEnd)->i
        ]);
        exit;
    }
}

// Auto-logout after configured minutes of inactivity
if ($interval->i >= $autoLogoutMinutes) {
    // Update last seen and status to offline
    $stmt = $db->prepare("UPDATE users SET last_seen = NOW(), status = 'offline' WHERE id = ?");
    $stmt->execute([$currentUserId]);
    
    // Invalidate all user sessions
    $stmt = $db->prepare("UPDATE sessions SET is_valid = 0 WHERE user_id = ?");
    $stmt->execute([$currentUserId]);
    
    // Destroy current session
    session_destroy();
    
    jsonResponse(false, 'Auto-logged out due to inactivity', [
        'logged_out' => true,
        'last_seen' => date('Y-m-d H:i:s'),
        'inactive_minutes' => $interval->i,
        'auto_logout_minutes' => $autoLogoutMinutes,
        'message' => 'You have been logged out due to inactivity. Please login again.',
        'redirect_to' => 'login.php'
    ]);
    exit;
}

// Update user status based on activity
if ($interval->i < 2) {
    $status = 'online';
} elseif ($interval->i < 5) {
    $status = 'away';
} else {
    $status = 'offline';
}

$stmt = $db->prepare("UPDATE users SET status = ? WHERE id = ?");
$stmt->execute([$status, $currentUserId]);

// Handle specific requests
$userId = intval($_GET['user'] ?? 0);
if ($userId) {
    $stmt = $db->prepare("
        SELECT id, unique_id, name, status, last_seen, last_activity,
               CASE 
                   WHEN TIMESTAMPDIFF(MINUTE, last_activity, NOW()) < 2 THEN 'online'
                   WHEN TIMESTAMPDIFF(MINUTE, last_activity, NOW()) < 5 THEN 'away'
                   ELSE 'offline'
               END as current_status
        FROM users 
        WHERE id = ? AND status = 'approved'
    ");
    $stmt->execute([$userId]);
    $userStatus = $stmt->fetch();
    
    if ($userStatus) {
        jsonResponse(true, 'User status retrieved', [
            'id' => $userStatus['id'],
            'unique_id' => $userStatus['unique_id'],
            'name' => $userStatus['name'],
            'status' => $userStatus['current_status'],
            'last_seen' => $userStatus['last_seen'],
            'last_activity' => $userStatus['last_activity']
        ]);
    } else {
        jsonResponse(false, 'User not found');
    }
    exit;
}

// Get all users' status
$stmt = $db->prepare("
    SELECT id, unique_id, name, status, last_seen, last_activity,
           CASE 
               WHEN TIMESTAMPDIFF(MINUTE, last_activity, NOW()) < 2 THEN 'online'
               WHEN TIMESTAMPDIFF(MINUTE, last_activity, NOW()) < 5 THEN 'away'
               ELSE 'offline'
           END as current_status
    FROM users 
    WHERE id != ? AND status = 'approved'
    ORDER BY last_activity DESC
");
$stmt->execute([$currentUserId]);
$allUsers = $stmt->fetchAll();

// Return current user status
jsonResponse(true, 'Status updated', [
    'current_user_status' => $status,
    'last_activity' => date('Y-m-d H:i:s'),
    'inactive_minutes' => $interval->i,
    'auto_logout_minutes' => $autoLogoutMinutes,
    'auto_logout_enabled' => $autoLogoutEnabled,
    'failed_attempts' => $user['failed_login_attempts'] ?? 0,
    'users' => $allUsers
]);
?>
