<?php
namespace ThimPress\ThimBlocks\Gutenberg\Blocks\LoginIcon;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

use ThimPress\ThimBlocks\Gutenberg\Blocks\AbstractBlockType;
use ThimPress\ThimBlocks\Helpers\SVGHelper;
use Throwable;

/**
 * Class LoginIconBlockType
 *
 * Handle register, render block template
 */
class LoginIconBlockType extends AbstractBlockType {
	public $block_name = 'login-icon';

	public function __construct() {
		parent::__construct();
		
		// Register AJAX handlers
		add_action( 'wp_ajax_thim_blocks_get_login_form', array( $this, 'ajax_get_login_form' ) );
		add_action( 'wp_ajax_nopriv_thim_blocks_get_login_form', array( $this, 'ajax_get_login_form' ) );
		add_action( 'wp_ajax_thim_blocks_submit_login_form', array( $this, 'ajax_submit_login_form' ) );
		add_action( 'wp_ajax_nopriv_thim_blocks_submit_login_form', array( $this, 'ajax_submit_login_form' ) );
	}

	public function get_supports(): array {
		return array(
			'align'      => array( 'wide', 'full', 'left', 'right', 'center' ),
			'typography' => array(
				'fontSize'                      => true,
				'lineHeight'                    => false,
				'fontWeight'                    => true,
				'__experimentalFontFamily'      => false,
				'__experimentalTextDecoration'  => false,
				'__experimentalFontStyle'       => true,
				'__experimentalFontWeight'      => true,
				'__experimentalLetterSpacing'   => false,
				'__experimentalTextTransform'   => true,
				'__experimentalDefaultControls' => array( 'fontSize' => true ),
			),
			'color'      => array(
				'background'                    => false,
				'text'                          => true,
				'link'                          => true,
				'gradients'                     => false,
				'__experimentalDefaultControls' => array(
					'text' => true,
					'link' => true,
				),
			),
			'spacing'    => array(
				'padding'                       => true,
				'margin'                        => true,
				'__experimentalDefaultControls' => array(
					'margin'  => false,
					'padding' => false,
				),
			),
		);
	}

	private function render_item( $type, $text, $url, $icon_class, $icon_svg, $icon_color = '', $icon_font_size = '', $show_avatar = false, $avatar_size = '' ): string {

		$icon_html = $style = $avatar_html = $text_html = '';

		if ( ! empty( $icon_color ) ) {
			$style .= 'color:' . esc_attr( $icon_color ) . ';';
		}

		if ( ! empty( $icon_font_size ) ) {
			$style .= 'font-size:' . intval( $icon_font_size ) . 'px;';
		}

		$style_attr = $style ? ' style="' . $style . '"' : '';

		if ( $type === 'profile' && $show_avatar && is_user_logged_in() ) {

			$current_user = wp_get_current_user();
			$avatar_size  = ! empty( $avatar_size ) ? intval( $avatar_size ) : 40;

			$avatar_html = get_avatar( $current_user->ID, $avatar_size );
		}

		if ( ! empty( $icon_svg ) ) {

			$svg_output = SVGHelper::render_svg( $icon_svg );

			if ( ! empty( $svg_output ) ) {

				$icon_html = '<span class="thim-login-icon">' . wp_kses( $svg_output, SVGHelper::allowed_tags() ) . '</span>';
			}
		} elseif ( ! empty( $icon_class ) ) {

			$icon_html = '<i class="thim-login-icon ' . esc_attr( $icon_class ) . '"' . $style_attr . '></i>';
		}

		if ( $text !== '' ) {
			$text_html = '<span class="thim-login-text">' . esc_html( $text ) . '</span>';
		}

		$content = $avatar_html . $icon_html . $text_html;

		if ( ! empty( $url ) ) {
			return '<a href="' . esc_url( $url ) . '" class="thim-login-item thim-login-' . esc_attr( $type ) . '">' . $content . '</a>';
		}

		return '<span class="thim-login-item thim-login-' . esc_attr( $type ) . '">' . $content . '</span>';
	}

	/**
	 * Render content of block tag
	 *
	 * @param array $attributes | Attributes of block tag.
	 *
	 * @return false|string
	 */
	public function render_content_block_template( array $attributes, $content, $block ): string {

		$html = '';

		try {

			$defaults = [
				'loginText'         => 'Login',
				'registerText'      => 'Register',
				'profileText'       => 'Profile',
				'logoutText'        => 'Logout',

				'loginIconClass'    => 'tb-icon-sign-in',
				'registerIconClass' => 'tb-icon-user',
				'profileIconClass'  => 'tb-icon-user',
				'logoutIconClass'   => 'tb-icon-sign-out',

				'loginIconSVG'      => '',
				'registerIconSVG'   => '',
				'profileIconSVG'    => '',
				'logoutIconSVG'     => '',

				'loginUrl'          => '',
				'registerUrl'       => '',
				'profileUrl'        => '',
				'iconColor'    		=> '',
				'iconFontSize' 		=> '',
				'showAvatar'        => false,
				'avatarSize'        => '',
				'enablePopup'       => false,
				'showLabels'        => false,
				'lblUsername'       => 'Username *',
				'lblEmail'          => 'Email *',
				'lblPassword'       => 'Password *',
				'lblRepeatPassword' => 'Repeat Password *',
				'lblUsernameOrEmail'=> 'Username or Email *',
			];

			$get_attr = function ( $key ) use ( $attributes, $defaults ) {
				return array_key_exists( $key, $attributes )
					? $attributes[ $key ]
					: $defaults[ $key ];
			};

			$login_text    = $get_attr( 'loginText' );
			$register_text = $get_attr( 'registerText' );
			$profile_text  = $get_attr( 'profileText' );
			$logout_text   = $get_attr( 'logoutText' );

			$login_url    = $get_attr( 'loginUrl' );
			$register_url = $get_attr( 'registerUrl' );
			$profile_url  = $get_attr( 'profileUrl' );

			$login_icon_class    = $get_attr( 'loginIconClass' );
			$register_icon_class = $get_attr( 'registerIconClass' );
			$profile_icon_class  = $get_attr( 'profileIconClass' );
			$logout_icon_class   = $get_attr( 'logoutIconClass' );

			$login_icon_svg    = $get_attr( 'loginIconSVG' );
			$register_icon_svg = $get_attr( 'registerIconSVG' );
			$profile_icon_svg  = $get_attr( 'profileIconSVG' );
			$logout_icon_svg   = $get_attr( 'logoutIconSVG' );
			$icon_color        = $get_attr( 'iconColor' );
			$icon_font_size    = $get_attr( 'iconFontSize' );
			$show_avatar       = $get_attr( 'showAvatar' );
			$avatarSize		   = $get_attr( 'avatarSize' );
			$enable_popup      = $get_attr( 'enablePopup' );

			$show_labels           = $get_attr( 'showLabels' );
			$lbl_username          = $get_attr( 'lblUsername' );
			$lbl_email             = $get_attr( 'lblEmail' );
			$lbl_password          = $get_attr( 'lblPassword' );
			$lbl_repeat_password   = $get_attr( 'lblRepeatPassword' );
			$lbl_username_or_email = $get_attr( 'lblUsernameOrEmail' );

			$is_logged_in = is_user_logged_in();

			// Enqueue view script if popup is enabled
			if ( $enable_popup && ! $is_logged_in ) {
				$handle = 'thim-blocks-view-' . $this->block_name;
				wp_enqueue_script( $handle );
				
				wp_localize_script( $handle, 'thimBlocksLoginPopup', array(
					'ajaxUrl' => admin_url( 'admin-ajax.php' ),
					'nonce'   => wp_create_nonce( 'thim_blocks_login_popup' ),
					'i18n'    => array(
						'loading'        => __( 'Loading...', 'thim-blocks' ),
						'failed_load'    => __( 'Failed to load form.', 'thim-blocks' ),
						'error_occurred' => __( 'An error occurred.', 'thim-blocks' ),
						'close'          => __( 'Close', 'thim-blocks' ),
					),
				) );

				// Enqueue login-form styles for popup
				wp_enqueue_style( 'thim-blocks-style-login-form' );
			}

			ob_start();

			echo '<div ' . wp_kses_post( get_block_wrapper_attributes( array(
				'class'                 => 'thim-blocks-login-icon',
				'data-enable-popup'     => esc_attr( $enable_popup ? 'true' : 'false' ),
				'data-show-labels'      => esc_attr( $show_labels ? 'true' : 'false' ),
				'data-lbl-username'     => esc_attr( $lbl_username ),
				'data-lbl-email'        => esc_attr( $lbl_email ),
				'data-lbl-password'     => esc_attr( $lbl_password ),
				'data-lbl-repeat'       => esc_attr( $lbl_repeat_password ),
				'data-lbl-user-or'      => esc_attr( $lbl_username_or_email ),
			) ) ) . '>';

			if ( ! $is_logged_in ) {

				if ( $login_text !== '' || ! empty( $login_icon_class ) || ! empty( $login_icon_svg ) ) {
					echo $this->render_item(
						'login',
						$login_text,
						$login_url,
						$login_icon_class,
						$login_icon_svg,
						$icon_color,
						$icon_font_size
					);
				}

				if ( $register_text !== '' || ! empty( $register_icon_class ) || ! empty( $register_icon_svg ) ) {
					echo $this->render_item(
						'register',
						$register_text,
						$register_url,
						$register_icon_class,
						$register_icon_svg,
						$icon_color,
						$icon_font_size
					);
				}
			}

			if ( $is_logged_in ) {

				if ( $profile_text !== '' || ! empty( $profile_icon_class ) || ! empty( $profile_icon_svg ) ||$show_avatar ) {

					echo $this->render_item(
						'profile',
						$profile_text,
						$profile_url,
						$profile_icon_class,
						$profile_icon_svg,
						$icon_color,
						$icon_font_size,
						$show_avatar,
						$avatarSize
					);
				}

				if ( $logout_text !== '' || ! empty( $logout_icon_class ) || ! empty( $logout_icon_svg )) {

					$logout_url = wp_logout_url( home_url() );

					echo $this->render_item(
						'logout',
						$logout_text,
						$logout_url,
						$logout_icon_class,
						$logout_icon_svg,
						$icon_color,
						$icon_font_size
					);
				}
			}

			// Render inner blocks content (popup content)
			if ( $enable_popup && ! empty( $content ) ) {
				echo '<div class="thim-login-popup-inner-content" style="display:none;">';
				echo $content;
				echo '</div>';
			}

			echo '</div>';

			$html = ob_get_clean();

		} catch ( Throwable $e ) {
			return $html;
		}

		return $html;
	}

	/**
	 * AJAX handler to get login form HTML
	 */
	public function ajax_get_login_form() {
		check_ajax_referer( 'thim_blocks_login_popup', 'nonce' );

		$form_action = isset( $_POST['form_action'] ) ? sanitize_text_field( wp_unslash( $_POST['form_action'] ) ) : 'login';
		
		$labels = array(
			'showLabels'         => isset( $_POST['showLabels'] ) && $_POST['showLabels'] === '1',
			'lblUsername'        => isset( $_POST['lblUsername'] ) ? sanitize_text_field( wp_unslash( $_POST['lblUsername'] ) ) : __( 'Username *', 'thim-blocks' ),
			'lblEmail'           => isset( $_POST['lblEmail'] ) ? sanitize_text_field( wp_unslash( $_POST['lblEmail'] ) ) : __( 'Email *', 'thim-blocks' ),
			'lblPassword'        => isset( $_POST['lblPassword'] ) ? sanitize_text_field( wp_unslash( $_POST['lblPassword'] ) ) : __( 'Password *', 'thim-blocks' ),
			'lblRepeatPassword'  => isset( $_POST['lblRepeatPassword'] ) ? sanitize_text_field( wp_unslash( $_POST['lblRepeatPassword'] ) ) : __( 'Repeat Password *', 'thim-blocks' ),
			'lblUsernameOrEmail' => isset( $_POST['lblUsernameOrEmail'] ) ? sanitize_text_field( wp_unslash( $_POST['lblUsernameOrEmail'] ) ) : __( 'Username or Email *', 'thim-blocks' ),
		);

		ob_start();
		$this->render_login_form_html( $form_action, $labels );
		$html = ob_get_clean();

		wp_send_json_success( array( 'html' => $html ) );
	}

	/**
	 * AJAX handler to submit login form
	 */
	public function ajax_submit_login_form() {
		if ( ! isset( $_POST['thim_blocks_login_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['thim_blocks_login_nonce'] ) ), 'thim_blocks_login_action' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'thim-blocks' ) ) );
		}

		$form_type = isset( $_POST['form_type'] ) ? sanitize_text_field( wp_unslash( $_POST['form_type'] ) ) : 'login';

		if ( $form_type === 'register' ) {
			$username = sanitize_user( wp_unslash( $_POST['user_login'] ?? '' ) );
			$email    = sanitize_email( wp_unslash( $_POST['user_email'] ?? '' ) );
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			$password = wp_unslash( $_POST['user_pass'] ?? '' );
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			$password_repeat = wp_unslash( $_POST['user_pass_repeat'] ?? '' );

			if ( empty( $username ) || empty( $email ) || empty( $password ) || empty( $password_repeat ) ) {
				wp_send_json_error( array( 'message' => __( 'Please fill in all fields.', 'thim-blocks' ) ) );
			}

			if ( $password !== $password_repeat ) {
				wp_send_json_error( array( 'message' => __( 'Passwords do not match.', 'thim-blocks' ) ) );
			}

			if ( username_exists( $username ) ) {
				wp_send_json_error( array( 'message' => __( 'Username already exists.', 'thim-blocks' ) ) );
			}

			if ( email_exists( $email ) ) {
				wp_send_json_error( array( 'message' => __( 'Email already in use.', 'thim-blocks' ) ) );
			}

			$user_id = wp_create_user( $username, $password, $email );

			if ( is_wp_error( $user_id ) ) {
				wp_send_json_error( array( 'message' => $user_id->get_error_message() ) );
			}

			wp_set_current_user( $user_id );
			wp_set_auth_cookie( $user_id );
			
			wp_send_json_success( array( 'redirect' => home_url() ) );

		} elseif ( $form_type === 'lostpassword' ) {
			$user_login = sanitize_text_field( wp_unslash( $_POST['user_login'] ?? '' ) );

			if ( empty( $user_login ) ) {
				wp_send_json_error( array( 'message' => __( 'Please enter your username or email address.', 'thim-blocks' ) ) );
			}

			$result = retrieve_password( $user_login );

			if ( is_wp_error( $result ) ) {
				wp_send_json_error( array( 'message' => $result->get_error_message() ) );
			}

			wp_send_json_success( array( 
				'message' => __( 'Check your email for the confirmation link.', 'thim-blocks' ),
				'show_message' => true
			) );

		} else {
			// Login
			$creds = array(
				'user_login'    => sanitize_user( wp_unslash( $_POST['log'] ?? '' ) ),
				// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
				'user_password' => wp_unslash( $_POST['pwd'] ?? '' ),
				'remember'      => ! empty( $_POST['rememberme'] ),
			);

			$user = wp_signon( $creds, is_ssl() );

			if ( is_wp_error( $user ) ) {
				wp_send_json_error( array( 'message' => $user->get_error_message() ) );
			}

			wp_send_json_success( array( 'redirect' => home_url() ) );
		}
	}

	/**
	 * Render login form HTML (reusable for both normal and AJAX)
	 */
	private function render_login_form_html( $action = 'login', $labels = array() ) {
		if ( empty( $labels ) ) {
			$labels = array(
				'showLabels'         => false,
				'lblUsername'        => __( 'Username *', 'thim-blocks' ),
				'lblEmail'           => __( 'Email *', 'thim-blocks' ),
				'lblPassword'        => __( 'Password *', 'thim-blocks' ),
				'lblRepeatPassword'  => __( 'Repeat Password *', 'thim-blocks' ),
				'lblUsernameOrEmail' => __( 'Username or Email *', 'thim-blocks' ),
			);
		}

		$show_labels       = $labels['showLabels'];
		$lbl_username      = $labels['lblUsername'];
		$lbl_email         = $labels['lblEmail'];
		$lbl_password      = $labels['lblPassword'];
		$lbl_repeat        = $labels['lblRepeatPassword'];
		$lbl_user_or_email = $labels['lblUsernameOrEmail'];

		if ( $action === 'register' ) {
			?>
			<form method="post" action="">
				<p>
					<?php if ( $show_labels ) : ?>
						<label style="display:block; margin-bottom:5px;"><?php echo esc_html( $lbl_username ); ?></label>
					<?php endif; ?>
					<input type="text" name="user_login" placeholder="<?php echo esc_attr( $lbl_username ); ?>" required>
				</p>
				<p>
					<?php if ( $show_labels ) : ?>
						<label style="display:block; margin-bottom:5px;"><?php echo esc_html( $lbl_email ); ?></label>
					<?php endif; ?>
					<input type="email" name="user_email" placeholder="<?php echo esc_attr( $lbl_email ); ?>" required>
				</p>
				<p>
					<?php if ( $show_labels ) : ?>
						<label style="display:block; margin-bottom:5px;"><?php echo esc_html( $lbl_password ); ?></label>
					<?php endif; ?>
					<span class="password-field-wrapper">
						<input type="password" name="user_pass" id="user_pass_popup" placeholder="<?php echo esc_attr( $lbl_password ); ?>" required>
						<button type="button" class="toggle-password" data-target="user_pass_popup" aria-label="Toggle password visibility"><i class="tb-icon-eye"></i></button>
					</span>
				</p>

				<p>
					<?php if ( $show_labels ) : ?>
						<label style="display:block; margin-bottom:5px;"><?php echo esc_html( $lbl_repeat ); ?></label>
					<?php endif; ?>
					<span class="password-field-wrapper">
						<input type="password" name="user_pass_repeat" id="user_pass_repeat_popup" placeholder="<?php echo esc_attr( $lbl_repeat ); ?>" required>
						<button type="button" class="toggle-password" data-target="user_pass_repeat_popup" aria-label="Toggle password visibility"><i class="tb-icon-eye"></i></button>
					</span>
				</p>

				<?php wp_nonce_field( 'thim_blocks_login_action', 'thim_blocks_login_nonce' ); ?>
				<input type="hidden" name="form_type" value="register">

				<p>
					<input type="submit" value="<?php esc_attr_e( 'Register', 'thim-blocks' ); ?>" />
				</p>

				<p class="register-login">
					<span>
						<?php esc_html_e( 'Already have an account? ', 'thim-blocks' ); ?>
					</span>
					<a href="#" data-action="login">
						<?php esc_html_e( 'Login Now', 'thim-blocks' ); ?>
					</a>
				</p>
			</form>
			<?php
		} elseif ( $action === 'lostpassword' ) {
			?>
			<form method="post" action="">
				<p>
					<?php if ( $show_labels ) : ?>
						<label style="display:block; margin-bottom:5px;"><?php echo esc_html( $lbl_user_or_email ); ?></label>
					<?php endif; ?>
					<input type="text" name="user_login" placeholder="<?php echo esc_attr( $lbl_user_or_email ); ?>" required>
				</p>

				<?php wp_nonce_field( 'thim_blocks_login_action', 'thim_blocks_login_nonce' ); ?>
				<input type="hidden" name="form_type" value="lostpassword">

				<p>
					<input type="submit" value="<?php esc_attr_e( 'Get New Password', 'thim-blocks' ); ?>" />
				</p>

				<p class="lostpassword-back">
					<a href="#" data-action="login">
						<?php esc_html_e( 'Back to login', 'thim-blocks' ); ?>
					</a>
						<span class="sep">|</span>
						<a href="#" data-action="register">
							<?php esc_html_e( 'Create an account', 'thim-blocks' ); ?>
						</a>
				</p>
			</form>
			<?php
		} else {
			?>
			<form name="loginform" id="loginform-popup" action="" method="post" novalidate>
				<p>
					<?php if ( $show_labels ) : ?>
						<label style="display:block; margin-bottom:5px;"><?php echo esc_html( $lbl_user_or_email ); ?></label>
					<?php endif; ?>
					<input type="text" name="log" id="user_login_popup" class="input" value="" size="20"
						placeholder="<?php echo esc_attr( $lbl_user_or_email ); ?>" required>
				</p>
				<p>
					<?php if ( $show_labels ) : ?>
						<label style="display:block; margin-bottom:5px;"><?php echo esc_html( $lbl_password ); ?></label>
					<?php endif; ?>
					<span class="password-field-wrapper">
						<input type="password" name="pwd" id="login_pass_popup" class="input" value="" size="20"
							placeholder="<?php echo esc_attr( $lbl_password ); ?>" required>
						<button type="button" class="toggle-password" data-target="login_pass_popup" aria-label="Toggle password visibility"><i class="tb-icon-eye"></i></button>
					</span>
				</p>

				<?php do_action( 'login_form_middle' ); ?>

				<p class="login-remember">
					<label>
						<input name="rememberme" type="checkbox" id="rememberme_popup" value="forever" />
						<?php esc_html_e( 'Remember Me', 'thim-blocks' ); ?>
					</label>
					<a class="login-lost-password-inline" href="#" data-action="lostpassword">
						<?php esc_html_e( 'Lost your password?', 'thim-blocks' ); ?>
					</a>
				</p>

				<?php do_action( 'login_form_bottom' ); ?>

				<p>
					<input type="submit" name="wp-submit" id="wp-submit-popup" class="button button-primary"
						value="<?php esc_attr_e( 'Log In', 'thim-blocks' ); ?>" />
					<input type="hidden" name="redirect_to" value="<?php echo esc_url( home_url() ); ?>" />
					<?php wp_nonce_field( 'thim_blocks_login_action', 'thim_blocks_login_nonce' ); ?>
				</p>

					<p class="login-register">
						<span>
							<?php esc_html_e( 'Not a member yet?', 'thim-blocks' ); ?>
						</span>
						<a href="#" data-action="register">
							<?php esc_html_e( 'Register now', 'thim-blocks' ); ?>
						</a>
					</p>
			</form>
			<?php
		}
	}

}
