<?php

namespace KaizenCoders\MagicLink;


class Shortcode {

    public function init() {
        // Primary tag (matches the namespaced underscore convention used elsewhere in the plugin).
        add_shortcode( 'magic_link_form', array( $this, 'magic_link_form_shortcode' ) );
        // Aliases for the names advertised in the readme and historically used in docs.
        add_shortcode( 'magic-link', array( $this, 'magic_link_form_shortcode' ) );
        add_shortcode( 'magic_link', array( $this, 'magic_link_form_shortcode' ) );

        add_action( 'wp_ajax_nopriv_request_magic_link', array( $this, 'handle_magic_link_request' ) );
        add_action( 'wp_ajax_request_magic_link', array( $this, 'handle_magic_link_request' ) );
    }

    public function magic_link_form_shortcode( $atts ) {
        $atts = shortcode_atts( array(
                'redirect'          => '',
                'show_registration' => 'true',
        ), $atts );

        if ( is_user_logged_in() ) {
            return '<p>' . __( 'You are already logged in.', 'magic-link' ) . '</p>';
        }

        ob_start();
        ?>
        <div class="magic-link-form-container">
            <form id="magic-link-form" class="magic-link-form">
                <div class="magic-link-field">
                    <label for="magic-link-email"><?php
                        _e( 'Email Address', 'magic-link' ); ?></label>
                    <input type="email" id="magic-link-email" name="email" required/>
                </div>

                <?php
                if ( $atts['show_registration'] === 'true' && get_option( 'magic_link_enable_registration' ) ): ?>
                    <div class="magic-link-field">
                        <label>
                            <input type="checkbox" id="magic-link-register" name="register" value="1"/>
                            <?php
                            _e( 'Create new account if email doesn\'t exist', 'magic-link' ); ?>
                        </label>
                    </div>
                <?php
                endif; ?>

                <input type="hidden" name="redirect_to" value="<?php
                echo esc_attr( $atts['redirect'] ); ?>"/>

                <div class="magic-link-field">
                    <button type="submit" class="magic-link-submit">
                        <?php
                        _e( 'Send Magic Link', 'magic-link' ); ?>
                    </button>
                </div>

                <div id="magic-link-message" class="magic-link-message"></div>
            </form>
        </div>

        <style>
            .magic-link-form-container {
                /*max-width: 400px;*/
                margin: 0 auto;
                padding: 20px;
                border: 1px solid #ddd;
                border-radius: 8px;
                background: #fff;
            }

            .magic-link-field {
                margin-bottom: 15px;
            }

            .magic-link-field label {
                display: block;
                margin-bottom: 5px;
                font-weight: bold;
            }

            .magic-link-field input[type="email"] {
                width: 100%;
                padding: 10px;
                border: 1px solid #ccc;
                border-radius: 4px;
                font-size: 16px;
            }

            .magic-link-submit {
                width: 100%;
                padding: 12px;
                background: #0073aa;
                color: white;
                border: none;
                border-radius: 4px;
                font-size: 16px;
                cursor: pointer;
            }

            .magic-link-submit:hover {
                background: #005a87;
            }

            .magic-link-submit:disabled {
                background: #ccc;
                cursor: not-allowed;
            }

            .magic-link-message {
                margin-top: 15px;
                padding: 10px;
                border-radius: 4px;
                display: none;
            }

            .magic-link-message.success {
                background: #d4edda;
                color: #155724;
                border: 1px solid #c3e6cb;
            }

            .magic-link-message.error {
                background: #f8d7da;
                color: #721c24;
                border: 1px solid #f5c6cb;
            }
        </style>

        <script>
			jQuery(document).ready(function ($) {
				$('#magic-link-form').on('submit', function (e) {
					e.preventDefault();

					var $form = $(this);
					var $button = $form.find('.magic-link-submit');
					var $message = $('#magic-link-message');

					$button.prop('disabled', true).text('<?php _e( 'Sending...', 'magic-link' ); ?>');
					$message.hide();

					$.ajax({
						url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
						type: 'POST',
						data: {
							action: 'request_magic_link',
							nonce: '<?php echo wp_create_nonce( 'magic_link_nonce' ); ?>',
							email: $('#magic-link-email').val(),
							register: $('#magic-link-register').is(':checked') ? 1 : 0,
							redirect_to: $('input[name="redirect_to"]').val()
						},
						success: function (response) {
							if (response.success) {
								$message.removeClass('error').addClass('success').text(response.data.message).show();
								$form[0].reset();
							} else {
								$message.removeClass('success').addClass('error').text(response.data.message).show();
							}
						},
						error: function () {
							$message.removeClass('success').addClass('error').text('<?php _e( 'Network error. Please try again.', 'magic-link' ); ?>').show();
						},
						complete: function () {
							$button.prop('disabled', false).text('<?php _e( 'Send Magic Link', 'magic-link' ); ?>');
						}
					});
				});
			});
        </script>
        <?php

        return ob_get_clean();
    }

    public function handle_magic_link_request() {
        // Verify nonce
        $nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
        if ( ! wp_verify_nonce( $nonce, 'magic_link_nonce' ) ) {
            wp_die( 'Security check failed' );
        }

        $email       = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
        $register    = isset( $_POST['register'] ) ? (bool) $_POST['register'] : false;
        $redirect_to = isset( $_POST['redirect_to'] ) ? esc_url_raw( wp_unslash( $_POST['redirect_to'] ) ) : '';

        if ( ! is_email( $email ) ) {
            wp_send_json_error( array( 'message' => __( 'Please enter a valid email address.', 'magic-link' ) ) );
        }

        if ( Cooldown::in_cooldown( $email ) ) {
            $wait = Cooldown::remaining( $email );
            wp_send_json_error( array(
                'message'            => sprintf(
                    /* translators: %d: seconds */
                    __( 'Please wait %d seconds before requesting another magic link.', 'magic-link' ),
                    $wait
                ),
                'cooldown_remaining' => $wait,
            ) );
        }

        $data = [
                'email'       => $email,
                'register'    => $register,
                'redirect_to' => $redirect_to,
        ];

        Cooldown::start( $email, apply_filters( 'kc_ml_resend_cooldown', Cooldown::DEFAULT_WINDOW ) );

        $result = Helper::generate_and_send_magic_link( $data );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
        } else {
            wp_send_json_success( array(
                    'message' => __( 'Magic link sent! Please check your email.', 'magic-link' ),
                    'data'    => []
            ) );
        }
    }

    private function generate_username_from_email( $email ) {
        $username = sanitize_user( substr( $email, 0, strpos( $email, '@' ) ) );

        // Ensure username is unique
        $counter           = 1;
        $original_username = $username;
        while ( username_exists( $username ) ) {
            $username = $original_username . $counter;
            $counter ++;
        }

        return $username;
    }

    private function generate_token() {
        if ( function_exists( 'random_bytes' ) ) {
            return bin2hex( random_bytes( 32 ) );
        }
        if ( function_exists( 'openssl_random_pseudo_bytes' ) ) {
            return bin2hex( openssl_random_pseudo_bytes( 32 ) );
        }
        $bytes = '';
        for ( $i = 0; $i < 32; $i++ ) {
            $bytes .= chr( mt_rand( 0, 255 ) );
        }
        return bin2hex( $bytes );
    }

    private function get_user_ip() {
        $ip_keys = array( 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'REMOTE_ADDR' );

        foreach ( $ip_keys as $key ) {
            if ( isset( $_SERVER[ $key ] ) && ! empty( $_SERVER[ $key ] ) ) {
                $ips = explode( ',', $_SERVER[ $key ] );

                return trim( $ips[0] );
            }
        }

        return isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
    }

}
