<?php
/**
 * Name: Last Login Column
 * Description: Track and display when users last logged in with column in users table to identify inactive accounts, monitor user activity, and audit patterns
 * Category: User Management
 * Icon: -
  * UseCases: [
 *   {
 *     "title": "Track User Activity",
 *     "description": "See when each user last logged in to identify inactive accounts or monitor user engagement patterns."
 *   },
 *   {
 *     "title": "Security Monitoring",
 *     "description": "Quickly spot suspicious login activity or identify accounts that may have been compromised by unusual login times."
 *   }
 * ]
 * Added: 2025-06-28
 * Tags: login, users, tracking, admin, columns, last-login
 * WhereToFind: {
 *   "location": "Users List",
 *   "url": "users.php",
 *   "instructions": "'Last Login' column appears showing login timestamps",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardLastLoginColumn {
    
    public function __construct() {
        add_action('wp_login', [$this, 'update_last_login'], 10, 2);
        add_filter('manage_users_columns', [$this, 'add_column']);
        add_filter('manage_users_custom_column', [$this, 'show_column'], 10, 3);
        add_filter('manage_users_sortable_columns', [$this, 'sortable_column']);
    }
    
    public function update_last_login($user_login, $user) {
        update_user_meta($user->ID, 'last_login', current_time('mysql'));
    }
    
    public function add_column($columns) {
        $columns['last_login'] = esc_html__('Last Login', 'wpswitchboard');
        return $columns;
    }

    public function show_column($value, $column_name, $user_id) {
        if ($column_name === 'last_login') {
            $last_login = get_user_meta($user_id, 'last_login', true);
            if ($last_login) {
                /* translators: %s: human-readable time difference */
                return sprintf(esc_html__('%s ago', 'wpswitchboard'), human_time_diff(strtotime($last_login), current_time('timestamp')));
            }
            return esc_html__('Never', 'wpswitchboard');
        }
        return $value;
    }
    
    public function sortable_column($columns) {
        $columns['last_login'] = 'last_login';
        return $columns;
    }

    /**
     * Register data locations for cleanup system
     */
    public function register_data_locations() {
        return [
            'options' => [],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [
                'last_login',
            ],
        ];
    }
}

$switchboard_instance = new SwitchboardLastLoginColumn();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
