<?php
/**
 * VMPFence Login Security Features
 * Implements functional hooks for Login Security settings (Phase 1)
 *
 * @package VMPFence
 * @since 2.1.0
 */

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

/**
 * Class VMPFence_Login_Security_Features
 * Handles Login Security feature implementations
 */
class VMPFence_Login_Security_Features {

    /**
     * Initialize the class
     */
    public static function init() {
        // Phase 1: Show Last Login Column
        self::init_last_login_column();

        // Phase 1: Track login times
        add_action('wp_login', array(__CLASS__, 'track_last_login'), 10, 2);

        // Phase 1: Delete on Deactivation
        // The actual deletion logic in cleanup_data() is called from vmpfence_deactivate()
        // when vmpfence_delete_on_deactivate setting is enabled
    }

    /**
     * Initialize Last Login Column feature
     * Note: This is checked once during plugin load. Changes require page reload.
     */
    private static function init_last_login_column() {
        // Check if feature is enabled (default: true)
        $enabled = VMPFence_Config::get('vmpfence_show_last_login_column', true);

        if ($enabled) {
            // Add column to users table
            add_filter('manage_users_columns', array(__CLASS__, 'add_last_login_column'));
            add_filter('manage_users_custom_column', array(__CLASS__, 'show_last_login_column'), 10, 3);

            // Make column sortable
            add_filter('manage_users_sortable_columns', array(__CLASS__, 'make_last_login_sortable'));
            add_action('pre_get_users', array(__CLASS__, 'sort_by_last_login'));
        }
    }

    /**
     * Add Last Login column to users table
     *
     * @param array $columns Existing columns
     * @return array Modified columns
     */
    public static function add_last_login_column($columns) {
        // Insert after 'posts' column
        $new_columns = array();
        
        foreach ($columns as $key => $value) {
            $new_columns[$key] = $value;
            
            if ($key === 'posts') {
                $new_columns['vmpfence_last_login'] = __('Last Login', 'vmpfence-security');
            }
        }

        // If 'posts' column doesn't exist, add at the end
        if (!isset($new_columns['vmpfence_last_login'])) {
            $new_columns['vmpfence_last_login'] = __('Last Login', 'vmpfence-security');
        }

        return $new_columns;
    }

    /**
     * Display Last Login column content
     *
     * @param string $value Column value
     * @param string $column_name Column name
     * @param int $user_id User ID
     * @return string Column content
     */
    public static function show_last_login_column($value, $column_name, $user_id) {
        if ($column_name === 'vmpfence_last_login') {
            $last_login = get_user_meta($user_id, 'vmpfence_last_login', true);

            if (!empty($last_login)) {
                // Format timestamp
                $timestamp = is_numeric($last_login) ? intval($last_login) : strtotime($last_login);
                
                // Show relative time (e.g., "2 hours ago")
                $time_diff = human_time_diff($timestamp, current_time('timestamp'));
                $formatted_date = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $timestamp);

                return sprintf(
                    '<span title="%s">%s ago</span>',
                    esc_attr($formatted_date),
                    esc_html($time_diff)
                );
            } else {
                return '<span class="vmpfence-never-logged-in">Never</span>';
            }
        }

        return $value;
    }

    /**
     * Make Last Login column sortable
     *
     * @param array $columns Sortable columns
     * @return array Modified sortable columns
     */
    public static function make_last_login_sortable($columns) {
        $columns['vmpfence_last_login'] = 'vmpfence_last_login';
        return $columns;
    }

    /**
     * Sort users by last login
     *
     * @param WP_User_Query $query User query object
     */
    public static function sort_by_last_login($query) {
        if (!is_admin()) {
            return;
        }

        $orderby = $query->get('orderby');

        if ($orderby === 'vmpfence_last_login') {
            $query->set('meta_key', 'vmpfence_last_login');
            $query->set('orderby', 'meta_value_num');
        }
    }

    /**
     * Track user login time
     *
     * @param string $user_login Username
     * @param WP_User $user User object
     */
    public static function track_last_login($user_login, $user) {
        // Store current timestamp
        update_user_meta($user->ID, 'vmpfence_last_login', current_time('timestamp'));
    }

    /**
     * Get delete on deactivate setting
     * This is called from vmpfence_deactivate() hook
     *
     * @return bool Whether to delete data on deactivation
     */
    public static function should_delete_on_deactivate() {
        return (bool) VMPFence_Config::get('vmpfence_delete_on_deactivate', false);
    }

    /**
     * Clean up login security data
     * Called from vmpfence_deactivate() hook if delete_on_deactivate is enabled
     */
    public static function cleanup_data() {
        global $wpdb;

        // Delete all vmpfence_show_last_login_column and vmpfence_delete_on_deactivate from config
        VMPFence_Config::delete('vmpfence_show_last_login_column');
        VMPFence_Config::delete('vmpfence_delete_on_deactivate');

        // Delete last login user meta
        $wpdb->query("DELETE FROM {$wpdb->usermeta} WHERE meta_key = 'vmpfence_last_login'");

        // Future phases will add more cleanup here (2FA settings, reCAPTCHA keys, etc.)
    }
}

// Initialize the features
VMPFence_Login_Security_Features::init();
