<?php
/**
 * Two-Factor Authentication (Email)
 */

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

/**
 * Helper function to generate code and send 2FA email
 */
function admilogu_send_2fa_email($user)
{
    $code = sprintf("%06d", wp_rand(1, 999999));
    set_transient('admilogu_2fa_code_' . $user->ID, wp_hash($code), 600); // 10 mins
    
    // Send email
    /* translators: 1: Blog name */
    $subject = sprintf(__('[%1$s] Your Two-Factor Authentication Code', 'admin-login-guard-branding'), wp_specialchars_decode(get_option('blogname'), ENT_QUOTES));
    
    $site_url = get_bloginfo('url');
    $logo_url = admilogu_URL . 'assets/images/admin-login-guard-branding-logo.png';
    
    $message = sprintf('
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body style="margin: 0; padding: 0; background-color: #faf9f7;">
      <div style="background-color: #faf9f7; margin: 0; padding: 50px 20px; font-family: \'Verdana\', Geneva, sans-serif; -webkit-font-smoothing: antialiased;">
        <table border="0" cellpadding="0" cellspacing="0" width="100%%" style="max-width: 520px; margin: 0 auto;">
          <tr>
            <td>
              <!-- Main Card -->
              <div style="background-color: #ffffff; border: 1px solid #f0f0f0; border-radius: 12px; padding: 45px 40px; box-shadow: 0 4px 24px rgba(0,0,0,0.03);">
                
                <!-- Logo Area -->
                <div style="text-align: center; margin-bottom: 30px;">
                  <img src="%4$s" alt="Admin Login Guard" style="height: 40px; width: auto; max-width: 100%%; display: inline-block;" />
                </div>
                
                <!-- Content -->
                <div style="font-size: 16px; color: #444444; line-height: 1.6; font-weight: 400;">
                  <p style="margin: 0 0 16px 0;">Hi %1$s,</p>
                  <p style="margin: 0 0 24px 0;">This is your one-time verification code to securely access the admin area.</p>
                  
                  <div style="background: linear-gradient(135deg, #6167F8, #9965FF); color: #ffffff; text-align: center; padding: 18px 24px; font-size: 32px; font-weight: 700; letter-spacing: 8px; border-radius: 8px; margin: 0 0 24px 0;">
                    %2$s
                  </div>
                  
                  <p style="margin: 0 0 16px 0;">This code is only active for the next 10 minutes. Once the code expires you will have to resubmit a request for a new code.</p>
                  <p style="margin: 0 0 0 0;">If you did not attempt to log in, please reset your password immediately.</p>
                </div>
              </div>
              
              <!-- Footer -->
              <div style="text-align: center; margin-top: 40px; font-size: 14px; color: #888888;">
                <p style="margin: 0 0 35px 0;">For any further questions, please contact the site administrator.</p>
                
                <div style="font-weight: 700; letter-spacing: 1.5px; text-transform: uppercase; margin-bottom: 12px; font-size: 13px;">
                  <a href="https://codeandcore.com" style="color: #999999; text-decoration: none;">POWERED BY CODE AND CORE</a>
                </div>
                <div style="font-size: 13px; color: #aaaaaa;">
                  Secured by Admin Login Guard & Branding
                </div>
              </div>
              
            </td>
          </tr>
        </table>
      </div>
    </body>
    </html>
    ', $user->display_name, $code, $site_url, $logo_url);
    
    $headers = array('Content-Type: text/html; charset=UTF-8');
    wp_mail($user->user_email, $subject, $message, $headers);
}

/**
 * Intercept Login Process
 * 
 * Runs after WP validates the password. Logs the user back out, sets a pending token,
 * and redirects to the 2FA form.
 */
function admilogu_intercept_login_for_2fa($user_login, $user)
{
    if (!get_option('admilogu_enable_2fa', 0)) {
        return;
    }

    // Check if user has 2FA enabled
    $user_2fa_enabled = get_user_meta($user->ID, 'admilogu_2fa_enabled', true);
    
    // Default to ON if it has never been set
    if ($user_2fa_enabled === '') {
        $user_2fa_enabled = '1';
    }

    // If not enabled for this user, let them pass normally
    if (!$user_2fa_enabled || $user_2fa_enabled === '0') {
        return;
    }

    // They need 2FA. Generate code and send email.
    admilogu_send_2fa_email($user);

    // Logout the user (since wp_login fires after auth cookie is set)
    wp_logout();

    // Set a temporary cookie to identify them for the 2FA step
    $temp_token = wp_generate_password(32, false);
    set_transient('admilogu_2fa_pending_' . $temp_token, $user->ID, 600);
    
    setcookie('admilogu_2fa_token', $temp_token, time() + 600, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);

    // Redirect to 2FA form
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $redirect_to = isset($_REQUEST['redirect_to']) ? sanitize_text_field(wp_unslash($_REQUEST['redirect_to'])) : admin_url();
    $login_url = wp_login_url();
    $url = add_query_arg(array('action' => 'admilogu_2fa', 'redirect_to' => urlencode($redirect_to)), $login_url);
    
    wp_safe_redirect($url);
    exit;
}
// Run early (priority 5) to intercept before other plugins redirect
add_action('wp_login', 'admilogu_intercept_login_for_2fa', 5, 2);

/**
 * Render the 2FA Form on the wp-login.php page
 */
function admilogu_render_2fa_form()
{
    $token = isset($_COOKIE['admilogu_2fa_token']) ? sanitize_text_field(wp_unslash($_COOKIE['admilogu_2fa_token'])) : '';
    if (!$token) {
        wp_safe_redirect(wp_login_url());
        exit;
    }

    $uid = get_transient('admilogu_2fa_pending_' . $token);
    if (!$uid) {
        wp_safe_redirect(wp_login_url());
        exit;
    }

    $error = '';
    $form_message = __('Please enter the 6-digit code sent to your email address.', 'admin-login-guard-branding');

    // Handle form submission
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated
    if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!isset($_POST['admilogu_2fa_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['admilogu_2fa_nonce'])), 'admilogu_2fa_action')) {
            $error = __('Invalid security token. Please try again.', 'admin-login-guard-branding');
        } elseif (isset($_POST['admilogu_resend_2fa'])) {
            // Handle Resend action
            $user = get_user_by('id', $uid);
            if ($user) {
                admilogu_send_2fa_email($user);
                $form_message = __('A new code has been sent to your email address.', 'admin-login-guard-branding');
            } else {
                $error = __('User not found. Please try logging in again.', 'admin-login-guard-branding');
            }
        } elseif (isset($_POST['admilogu_2fa_code'])) {
            // Handle Verification action
            $code = sanitize_text_field(wp_unslash($_POST['admilogu_2fa_code']));
            $stored_hash = get_transient('admilogu_2fa_code_' . $uid);

            if ($stored_hash && hash_equals($stored_hash, wp_hash($code))) {
                // Success!
                delete_transient('admilogu_2fa_code_' . $uid);
                delete_transient('admilogu_2fa_pending_' . $token);
                setcookie('admilogu_2fa_token', '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN);

                // Set real auth cookie
                wp_set_auth_cookie($uid, true);

                $user = get_user_by('id', $uid);
                if ($user) {
                    remove_action('wp_login', 'admilogu_intercept_login_for_2fa', 5);
                    do_action('wp_login', $user->user_login, $user);
                }
                
                $redirect_to = isset($_POST['redirect_to']) ? sanitize_text_field(wp_unslash($_POST['redirect_to'])) : admin_url();
                wp_safe_redirect($redirect_to);
                exit;
            } else {
                $error = __('Invalid or expired code. Please check your email and try again.', 'admin-login-guard-branding');
            }
        }
    }

    // Render standard WP login header
    $error_html = $error ? '<div style="background-color: #f44336; color: #ffffff; padding: 12px; border-radius: 4px; border-left: 4px solid #b71c1c; margin-bottom: 20px; font-weight: 500;">' . esc_html($error) . '</div>' : '';
    $message_html = !$error && $form_message ? '<p class="message">' . esc_html($form_message) . '</p>' : '';
    
    login_header(
        __('Two-Factor Authentication', 'admin-login-guard-branding'),
        $error_html . $message_html
    );
    ?>
    <form name="admilogu_2fa_form" id="loginform" action="" method="post">
        <?php wp_nonce_field('admilogu_2fa_action', 'admilogu_2fa_nonce'); ?>
        <p>
            <label for="admilogu_2fa_code"><?php esc_html_e('Authentication Code', 'admin-login-guard-branding'); ?></label>
            <input type="text" name="admilogu_2fa_code" id="admilogu_2fa_code" class="input" value="" size="20" autocomplete="one-time-code" required autofocus />
        </p>
        <?php 
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (isset($_REQUEST['redirect_to'])): ?>
            <input type="hidden" name="redirect_to" value="<?php echo esc_attr(sanitize_text_field(wp_unslash($_REQUEST['redirect_to']))); ?>" />
        <?php endif; ?>
        <p class="submit">
            <input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="<?php esc_attr_e('Verify Code', 'admin-login-guard-branding'); ?>" style="float: right;" />
            <input type="submit" name="admilogu_resend_2fa" id="admilogu_resend_2fa" class="button button-secondary button-large" value="<?php esc_attr_e('Resend Code (60s)', 'admin-login-guard-branding'); ?>" formnovalidate style="float: left;" disabled="disabled" />
        </p>
    </form>
    <p id="nav">
        <a href="<?php echo esc_url(wp_login_url()); ?>"><?php esc_html_e('&larr; Back to Login', 'admin-login-guard-branding'); ?></a>
    </p>
    <script>
        (function() {
            var resendBtn = document.getElementById("admilogu_resend_2fa");
            if (resendBtn) {
                var timeLeft = 60;
                resendBtn.disabled = true;
                
                var timerId = setInterval(function() {
                    timeLeft--;
                    if (timeLeft <= 0) {
                        clearInterval(timerId);
                        resendBtn.disabled = false;
                        resendBtn.value = "<?php esc_attr_e('Resend Code', 'admin-login-guard-branding'); ?>";
                    } else {
                        resendBtn.value = "<?php esc_attr_e('Resend Code', 'admin-login-guard-branding'); ?> (" + timeLeft + "s)";
                    }
                }, 1000);
            }
        })();
    </script>
    <?php
    login_footer();
    exit;
}
add_action('login_form_admilogu_2fa', 'admilogu_render_2fa_form');

/**
 * Add 2FA toggle to User Profile
 */
function admilogu_2fa_user_profile_fields($user)
{
    if (!get_option('admilogu_enable_2fa', 0)) {
        return;
    }
    
    $enabled = get_user_meta($user->ID, 'admilogu_2fa_enabled', true);
    
    // Default to ON if it has never been set
    if ($enabled === '') {
        $enabled = '1';
    }
    ?>
    <h3><?php esc_html_e('Two-Factor Authentication', 'admin-login-guard-branding'); ?></h3>
    <table class="form-table">
        <tr>
            <th><label for="admilogu_2fa_enabled"><?php esc_html_e('Enable Email 2FA', 'admin-login-guard-branding'); ?></label></th>
            <td>
                <input type="checkbox" name="admilogu_2fa_enabled" id="admilogu_2fa_enabled" value="1" <?php checked($enabled, 1); ?> />
                <span class="description"><?php esc_html_e('Require a 6-digit code sent to your email when logging in.', 'admin-login-guard-branding'); ?></span>
            </td>
        </tr>
    </table>
    <?php
}
add_action('show_user_profile', 'admilogu_2fa_user_profile_fields');
add_action('edit_user_profile', 'admilogu_2fa_user_profile_fields');

/**
 * Save User Profile 2FA Setting
 */
function admilogu_save_2fa_user_profile($user_id)
{
    if (!current_user_can('edit_user', $user_id)) {
        return false;
    }
    
    // phpcs:ignore WordPress.Security.NonceVerification.Missing
    if (isset($_POST['admilogu_2fa_enabled'])) {
        update_user_meta($user_id, 'admilogu_2fa_enabled', '1');
    } else {
        // Explicitly save 0 so we know they opted out and don't default it back to ON
        update_user_meta($user_id, 'admilogu_2fa_enabled', '0');
    }
}
add_action('personal_options_update', 'admilogu_save_2fa_user_profile');
add_action('edit_user_profile_update', 'admilogu_save_2fa_user_profile');
