<?php

if (!defined('ABSPATH')) {
    exit; // Pas d'accès direct !
}

/**
 * Enregistre une tentative de connexion (réussie ou échouée) en base de données.
 *
 * @param string $username Nom d'utilisateur saisi.
 * @param string $etat     'ok' ou 'failed'.
 */
function hpixl_securicheck_log_connexion(string $username, string $etat): void
{
    global $wpdb;

    $table = $wpdb->prefix . HPIXL_SECURICHECK_TABLE_AUDIT_LOGS_CONNEXIONS;
    if (!hpixl_securicheck_table_exists($table)) return;

    $browser = isset($_SERVER['HTTP_USER_AGENT'])
        ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT']))
        : '';

    $wpdb->insert(
        $table,
        [
            'date'     => wp_date('Y-m-d H:i:s'),
            'username' => sanitize_text_field($username),
            'ip'       => hpixl_securicheck_get_ip(),
            'browser'  => $browser,
            'etat'     => $etat,
        ],
        ['%s', '%s', '%s', '%s', '%s']
    );
}

function hpixl_securicheck_watch_failed_connexions(string $username): void
{
    hpixl_securicheck_log_connexion($username, 'failed');
}

add_action('wp_login_failed', 'hpixl_securicheck_watch_failed_connexions', 10, 1);

function hpixl_securicheck_watch_good_connexions(string $username): void
{
    hpixl_securicheck_log_connexion($username, 'ok');
}

add_action('wp_login', 'hpixl_securicheck_watch_good_connexions', 10, 1);
