<?php
namespace BLR\Backline\Modules\Users;

if (!defined('ABSPATH')) {
    exit;
}

final class Activity {
    public const USER_META_LAST_LOGIN = 'blr_ba_last_login';

    public static function boot(): void {
        add_action('wp_login', [self::class, 'record_login'], 10, 2);
    }

    /**
     * Records the user's most recent successful WordPress login.
     *
     * This intentionally listens to the core wp_login hook instead of only the
     * Backline frontend login form so the Users page reflects successful logins
     * through wp-login.php, wp-admin, and Backline's own login screen.
     */
    public static function record_login(string $user_login, \WP_User $user): void {
        unset($user_login);

        $user_id = (int) $user->ID;
        if ($user_id <= 0) {
            return;
        }

        update_user_meta($user_id, self::USER_META_LAST_LOGIN, time());
    }

    public static function last_login_timestamp(int $user_id): int {
        return absint(get_user_meta($user_id, self::USER_META_LAST_LOGIN, true));
    }

    public static function last_login_label(int $user_id): string {
        $timestamp = self::last_login_timestamp($user_id);
        if ($timestamp <= 0) {
            return '';
        }

        return wp_date(get_option('date_format') . ' ' . get_option('time_format'), $timestamp);
    }
}
