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

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

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

/**
 * Class LoginFormBlockType
 *
 * Handle register, render block template
 */
class LoginFormBlockType extends AbstractBlockType {
	public $block_name = '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'       => false,
				'__experimentalFontWeight'      => true,
				'__experimentalLetterSpacing'   => false,
				'__experimentalTextTransform'   => true,
				'__experimentalDefaultControls' => array( 'fontSize' => true ),
			),
			'color'      => array(
				'background'                    => false,
				'text'                          => true,
				'link'                          => false,
				'gradients'                     => false,
				'__experimentalDefaultControls' => array(
					'text' => true,
				),
			),
			'spacing'    => array(
				'padding'                       => true,
				'margin'                        => true,
				'__experimentalDefaultControls' => array(
					'margin'  => false,
					'padding' => false,
				),
			),
		);
	}

	/**
	 * 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 = [
				'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 ];
			};

			$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' );

			$handle = 'thim-blocks-view-' . $this->block_name;
			wp_enqueue_script( $handle );

			ob_start();
			echo '<div ' . wp_kses_post( get_block_wrapper_attributes( array( 'class' => 'thim-blocks-login-form' ) ) ) . '>';

			if ( is_user_logged_in() ) {
				$current_user = wp_get_current_user();
				echo '<p>' . esc_html__( 'You are already logged in as ', 'thim-blocks' ) . esc_html( $current_user->display_name ) . '.</p>';
				echo '</div>';
				$html = ob_get_clean();
				return $html;
			}

			$action   = isset( $_GET['action'] ) ? sanitize_text_field( wp_unslash( $_GET['action'] ) ) : 'login';
			$errors   = array();
			$messages = array();

			if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset( $_POST['thim_blocks_login_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['thim_blocks_login_nonce'] ) ), 'thim_blocks_login_action' ) ) {
				$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 ) ) {
						$errors[] = __( 'Please fill in all fields.', 'thim-blocks' );
					} elseif ( $password !== $password_repeat ) {
						$errors[] = __( 'Passwords do not match.', 'thim-blocks' );
					} elseif ( username_exists( $username ) ) {
						$errors[] = __( 'Username already exists.', 'thim-blocks' );
					} elseif ( email_exists( $email ) ) {
						$errors[] = __( 'Email already in use.', 'thim-blocks' );
					} else {
						$user_id = wp_create_user( $username, $password, $email );

						if ( is_wp_error( $user_id ) ) {
							$errors[] = $user_id->get_error_message();
						} else {
							wp_set_current_user( $user_id );
							wp_set_auth_cookie( $user_id );
							wp_safe_redirect( home_url() );
							exit;
						}
					}
				} elseif ( $form_type === 'lostpassword' ) {
					$user_login = sanitize_text_field( wp_unslash( $_POST['user_login'] ?? '' ) );

					if ( empty( $user_login ) ) {
						$errors[] = __( 'Please enter your username or email address.', 'thim-blocks' );
					} else {
						// Let WordPress handle validation + sending reset email.
						$result = retrieve_password( $user_login );

						if ( is_wp_error( $result ) ) {
							$errors[] = $result->get_error_message();
						} else {
							$messages[] = __( 'Check your email for the confirmation link.', 'thim-blocks' );
							$action     = 'lostpassword';
						}
					}
				} else {
					$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 ) ) {
						$errors[] = $user->get_error_message();
					} else {
						wp_safe_redirect( home_url() );
						exit;
					}
				}
			}

			do_action( 'login_form' );
			?>
			
			<?php if ( ! empty( $messages ) ) : ?>
				<div class="login-messages">
					<?php foreach ( $messages as $message ) : ?>
						<p class="login-message"><?php echo wp_kses_post( $message ); ?></p>
					<?php endforeach; ?>
				</div>
			<?php endif; ?>

			<?php if ( ! empty( $errors ) ) : ?>
				<div class="login-errors">
					<?php foreach ( $errors as $error ) : ?>
						<p class="login-error"><?php echo wp_kses_post( $error ); ?></p>
					<?php endforeach; ?>
				</div>
			<?php endif; ?>

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

					<p class="password-field-wrapper">
						<?php if ( $show_labels ) : ?>
							<label style="display:block; margin-bottom:5px;"><?php echo esc_html( $lbl_repeat_password ); ?></label>
						<?php endif; ?>
						<input type="password" name="user_pass_repeat" id="user_pass_repeat" placeholder="<?php echo esc_attr( $lbl_repeat_password ); ?>" required>
						<button type="button" class="toggle-password" data-target="user_pass_repeat" aria-label="Toggle password visibility"><i class="tb-icon-eye"></i></button>
					</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="<?php echo esc_url( remove_query_arg( 'action', get_permalink() ) ); ?>">
							<?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_username_or_email ); ?></label>
						<?php endif; ?>
						<input type="text" name="user_login" placeholder="<?php echo esc_attr( $lbl_username_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="<?php echo esc_url( remove_query_arg( 'action', get_permalink() ) ); ?>">
							<?php esc_html_e( 'Back to login', 'thim-blocks' ); ?>
						</a>
						<span class="sep">|</span>
						<a href="<?php echo esc_url( add_query_arg( 'action', 'register', get_permalink() ) ); ?>">
							<?php esc_html_e( 'Create an account', 'thim-blocks' ); ?>
						</a>
					</p>
				</form>
			<?php else : ?>	
				<form name="loginform" id="loginform-custom" action="" method="post" novalidate>
					<p>
						<?php if ( $show_labels ) : ?>
							<label style="display:block; margin-bottom:5px;"><?php echo esc_html( $lbl_username_or_email ); ?></label>
						<?php endif; ?>
						<input type="text" name="log" id="user_login" class="input" value="" size="20"
							placeholder="<?php echo esc_attr( $lbl_username_or_email ); ?>" required>
					</p>
					<p class="password-field-wrapper">
						<?php if ( $show_labels ) : ?>
							<label style="display:block; margin-bottom:5px;"><?php echo esc_html( $lbl_password ); ?></label>
						<?php endif; ?>
						<input type="password" name="pwd" id="login_pass" class="input" value="" size="20"
							placeholder="<?php echo esc_attr( $lbl_password ); ?>" required>
						<button type="button" class="toggle-password" data-target="login_pass" aria-label="Toggle password visibility"><i class="lp-icon-eye"></i></button>
					</p>

					<?php
						// Call the core WordPress action hook 'login_form_middle'.
						// This hook exists in wp-login.php and is used by many plugins/themes
						// (e.g., captcha, two-factor authentication) to insert content into
						// the middle of the login form. We include it here to maintain compatibility.
						do_action( 'login_form_middle' );
					?>

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

					<?php
						// Call the core WordPress action hook 'login_form_bottom'.
						// This hook exists in wp-login.php and is used by many plugins/themes
						// to insert content at the bottom of the login form.
						// We include it here to maintain compatibility.
						do_action( 'login_form_bottom' );
					?>

					<p>
						<input type="submit" name="wp-submit" id="wp-submit" 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="<?php echo esc_url( add_query_arg( 'action', 'register', get_permalink() ) ); ?>">
							<?php esc_html_e( 'Register now', 'thim-blocks' ); ?>
						</a>
					</p>
				</form>
			<?php endif; ?>	
			<?php
			echo '</div>';
			$html = ob_get_clean();
		} catch ( Throwable $e ) {
			return $html;
		}

		return $html;
	}

}
