<?php

/**
 * Template for the login form
 *
 * This template handles the rendering of the login form with proper
 * security measures and error handling.
 *
 * @package Attributes\Front
 * @since   1.1.0
 */

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

// Ensure $args is set
if (!isset($args)) {
    $args = [];
}

// Start session if not already started
if (!session_id()) {
    session_start();
}

// Get user settings to determine registration method for consistent labeling
$user_settings = get_option('attrua_pro_user_settings', array());
$registration_method = $user_settings['registration_method'] ?? 'both';

// Determine appropriate label and placeholder based on registration method
$field_label = '';
$field_placeholder = '';
$input_type = 'text';

switch ($registration_method) {
    case 'username':
        $field_label = __('Username', 'attributes-user-access');
        $field_placeholder = __('Enter your username', 'attributes-user-access');
        break;

    case 'email':
        $field_label = __('Email Address', 'attributes-user-access');
        $field_placeholder = __('Enter your email address', 'attributes-user-access');
        $input_type = 'email';
        break;

    case 'both':
    default:
        $field_label = __('Username or Email', 'attributes-user-access');
        $field_placeholder = __('Enter your username or email address', 'attributes-user-access');
        break;
}

// Allow override from shortcode attributes only when registration method is "both"
// When a specific method is set (username/email), respect the registration method setting
if (!empty($args['label_username']) && $registration_method === 'both') {
    $field_label = $args['label_username'];
}

// Get the redirect URL
$redirect_to = !empty($args['redirect']) ? $args['redirect'] : '';

// Get potential error message
$error_message = isset($error_message) ? $error_message : '';
?>

<div class="attrua-form-wrapper">
    <!-- Error Messages Container -->
    <?php if (!empty($error_message)): ?>
        <div class="attrua-message-container error visible">
            <div class="attrua-message">
                <?php echo wp_kses_post($error_message); ?>
            </div>
        </div>
    <?php endif; ?>

    <!-- Login Form -->
    <form id="<?php echo esc_attr($args['form_id']); ?>"
        class="attrua-login-form"
        method="post"
        action="">

        <?php wp_nonce_field('attrua_login', 'attrua_login_nonce'); ?>
        <input type="hidden" name="attrua_login_submit" value="1">

        <!-- Username/Email Field -->
        <div class="attrua-form-row">
            <label for="attrua_username">
                <?php echo esc_html($field_label); ?>
                <span class="required">*</span>
            </label>
            <input type="<?php echo esc_attr($input_type); ?>"
                name="log"
                id="attrua_username"
                class="attrua-input"
                value="<?php echo esc_attr($args['value_username']); ?>"
                required
                autocomplete="<?php echo esc_attr($registration_method === 'email' ? 'email' : 'username'); ?>"
                placeholder="<?php echo esc_attr($field_placeholder); ?>">
            <div class="attrua-field-error"></div>
        </div>

        <!-- Password Field -->
        <div class="attrua-form-row">
            <label for="attrua_password">
                <?php echo esc_html($args['label_password']); ?>
                <span class="required">*</span>
            </label>
            <div class="attrua-password-field">
                <input type="password"
                    name="pwd"
                    id="attrua_password"
                    class="attrua-input"
                    required
                    autocomplete="current-password">
                <button type="button"
                    class="attrua-toggle-password"
                    aria-label="<?php esc_attr_e('Toggle password visibility', 'attributes-user-access'); ?>">
                    <span class="ti ti-eye"></span>
                </button>
            </div>
            <div class="attrua-field-error"></div>
        </div>

        <!-- Remember Me -->
        <?php if ($args['remember']): ?>
            <div class="attrua-form-row">
                <label class="attrua-checkbox-label">
                    <input type="checkbox"
                        name="rememberme"
                        id="attrua_remember"
                        value="forever"
                        <?php checked($args['value_remember'], true); ?>>
                    <span><?php echo esc_html($args['label_remember']); ?></span>
                </label>
            </div>
        <?php endif; ?>

        <!-- Submit Button -->
        <div class="attrua-form-row">
            <button type="submit"
                class="attrua-submit-button"
                data-loading-text="<?php esc_attr_e('Logging in...', 'attributes-user-access'); ?>">
                <?php echo esc_html($args['label_log_in']); ?>
            </button>
        </div>

        <?php if (!empty($redirect_to)): ?>
            <input type="hidden" name="redirect_to" value="<?php echo esc_url($redirect_to); ?>">
        <?php endif; ?>

        <!-- Additional Links -->
        <?php if (!empty($args['show_links'])): ?>
            <div class="attrua-form-links">
                <?php if (get_option('users_can_register')) : ?>
                    <?php
                    // Check if we have a custom registration page
                    $pages_options = get_option('attrua_pages_options', array());
                    $registration_page_id = $pages_options['register'] ?? null;
                    $register_url = $registration_page_id ? get_permalink($registration_page_id) : wp_registration_url();
                    ?>
                    <a href="<?php echo esc_url($register_url); ?>">
                        <?php esc_html_e('Register', 'attributes-user-access'); ?>
                    </a>
                    <span class="attrua-link-separator">|</span>
                <?php endif; ?>
                <?php
                // Check if we have a custom lost password page
                $lost_password_page_id = $pages_options['lost'] ?? null;
                $lostpassword_url = $lost_password_page_id ? get_permalink($lost_password_page_id) : wp_lostpassword_url();
                ?>
                <a href="<?php echo esc_url($lostpassword_url); ?>">
                    <?php esc_html_e('Lost password?', 'attributes-user-access'); ?>
                </a>
            </div>
        <?php endif; ?>

        <?php
        /**
         * Hook for adding custom fields to login form
         *
         */
        do_action('attrua_login_form_fields');
        ?>
    </form>

    <?php
    /**
     * Hook for adding content after login form
     *
     */
    do_action('attrua_after_login_form');
    ?>
</div>

<script>
    jQuery(document).ready(function($) {
        var registrationMethod = '<?php echo esc_js($registration_method); ?>';

        // Password toggle functionality
        $('.attrua-toggle-password').on('click', function(e) {
            e.preventDefault();

            const $field = $(this).closest('.attrua-password-field');
            const $input = $field.find('input');
            const $icon = $(this).find('.ti');

            // Toggle input type
            const isPassword = $input.attr('type') === 'password';
            $input.attr('type', isPassword ? 'text' : 'password');

            // Update icon
            $icon
                .removeClass(isPassword ? 'ti-eye' : 'ti-eye-off')
                .addClass(isPassword ? 'ti-eye-off' : 'ti-eye');
        });

        // Form validation
        $('.attrua-login-form').on('submit', function(e) {
            let isValid = true;
            const userLogin = $('#attrua_username').val().trim();
            const password = $('#attrua_password').val().trim();

            // Clear previous errors
            $('.attrua-field-error').text('').removeClass('error');

            // Validate username/email field
            if (!userLogin) {
                let errorMessage = '';
                switch (registrationMethod) {
                    case 'username':
                        errorMessage = '<?php esc_html_e('Please enter your username', 'attributes-user-access'); ?>';
                        break;
                    case 'email':
                        errorMessage = '<?php esc_html_e('Please enter your email address', 'attributes-user-access'); ?>';
                        break;
                    case 'both':
                    default:
                        errorMessage = '<?php esc_html_e('Please enter your username or email address', 'attributes-user-access'); ?>';
                        break;
                }
                $('#attrua_username').siblings('.attrua-field-error').text(errorMessage).addClass('error');
                isValid = false;
            } else {
                // Additional validation for email format when email-only is selected
                if (registrationMethod === 'email') {
                    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailRegex.test(userLogin)) {
                        $('#attrua_username').siblings('.attrua-field-error').text('<?php esc_html_e('Please enter a valid email address', 'attributes-user-access'); ?>').addClass('error');
                        isValid = false;
                    }
                }
            }

            // Validate password field
            if (!password) {
                $('#attrua_password').closest('.attrua-password-field').siblings('.attrua-field-error').text('<?php esc_html_e('Please enter your password', 'attributes-user-access'); ?>').addClass('error');
                isValid = false;
            }

            if (!isValid) {
                e.preventDefault();
                // Focus on first error field
                $('.attrua-field-error.error:first').prev('input').focus();
            }
        });

        // Clear error when user starts typing
        $('#attrua_username').on('input', function() {
            $(this).siblings('.attrua-field-error').text('').removeClass('error');

            // Real-time validation for email format (when email-only)
            if (registrationMethod === 'email') {
                const email = $(this).val().trim();
                if (email) {
                    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailRegex.test(email)) {
                        // Show subtle hint, not full error
                        $(this).addClass('invalid-format');
                    } else {
                        $(this).removeClass('invalid-format');
                    }
                } else {
                    $(this).removeClass('invalid-format');
                }
            }
        });

        $('#attrua_password').on('input', function() {
            $(this).closest('.attrua-password-field').siblings('.attrua-field-error').text('').removeClass('error');
        });
    });
</script>