<?php
/**
 * WeCodeArt Framework
 *
 * WARNING: This file is part of the core WeCodeArt Framework. DO NOT edit this file under any circumstances.
 * Please do all modifications in the form of a child theme.
 *
 * @package		WeCodeArt Framework
 * @subpackage  Gutenberg\Blocks
 * @copyright   Copyright (c) 2024, WeCodeArt Framework
 * @since		5.1.8
 * @version		6.7.4
 */

namespace WeCodeArt\Gutenberg\Blocks\Site;

defined( 'ABSPATH' ) || exit;

use WeCodeArt\Singleton;
use WeCodeArt\Gutenberg\Blocks\Dynamic;
use function WeCodeArt\Functions\{ get_prop, toJSON };

/**
 * Gutenberg Login block.
 */
class Login extends Dynamic {

	use Singleton;

	/**
	 * Block namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'core';

	/**
	 * Block name.
	 *
	 * @var string
	 */
	protected $block_name = 'loginout';

	/**
	 * Init.
	 */
	public function init() {
		\register_block_style( $this->get_block_type(), [
			'name'	=> 'modal',
            'label'	=> esc_html__( 'Modal', 'wecodeart' ),
		] );
	}

	/**
	 * Block args.
	 *
	 * @return 	array
	 */
	public function block_type_args(): array {
		return [
			'render_callback' => [ $this, 'render' ]
		];
	}

	/**
	 * Dynamically renders the `core/search` block.
	 *
	 * @param 	array 	$attributes	The attributes.
	 * @param 	string 	$content 	The block markup.
	 *
	 * @return 	string 	The block markup.
	 */
	public function render( array $attributes = [], string $content = '' ): string {
		// Build the redirect URL.
		$current_url 	= ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
		$contents 		= wp_loginout( get_prop( $attributes, [ 'redirectToCurrent' ] ) ? $current_url : '', false );
		$classnames 	= [];
		$classNames 	= explode( ' ', get_prop( $attributes, [ 'className' ], '' ) );
		
		// If logged-out and displayLoginAsForm is true, show the login form.
		if ( ! is_user_logged_in() && get_prop( $attributes, [ 'displayLoginAsForm' ] ) ) {
			// Add a class.
			$classnames[] 	= 'has-form';

			// Get the form.
			$form_html 		= self::render_form( [], false );
			
			// Is this a modal?
			if( in_array( 'is-style-modal', $classNames, true ) ) {
				$instance_id 	= wp_unique_id( 'wp-login-' );

				// Get the form.
				$contents		= wecodeart( 'dom' )::processor( $contents );

				if( $contents->next_tag( [ 'tag_name' => 'a' ] ) ) {
					$contents->remove_attribute( 'href' );
					$contents->set_attribute( 'role', 'button' );
					$contents->set_attribute( 'tabindex', '0' );
					$contents->set_attribute( 'class', 'nav-link' );
					$contents->set_attribute( 'aria-label', esc_attr__( 'Open login modal', 'wecodeart' ) );
					$contents->set_attribute( 'aria-controls', $instance_id . '-modal' );
					$contents->set_attribute( 'data-wp-interactive', 'wecodeart/modal' );
					$contents->set_attribute( 'data-wp-context', toJSON( [ 'backdrop' => 'static' ] ) );
					$contents->set_attribute( 'data-wp-init--validate', 'callbacks.validateConfig' );
					$contents->set_attribute( 'data-wp-init--setup', 'callbacks.onInit' );
					$contents->set_attribute( 'data-wp-on--click', 'actions.show' );
					$contents->set_attribute( 'data-wp-on-window--resize', 'callbacks.onResize' );
				}

				$contents = $contents->get_updated_html();
	
				// Modal
				self::get_modal( $form_html, $instance_id, $attributes );
			} else {
				$contents = $form_html;
			}
		} 
		
		$contents	= wecodeart( 'dom' )::processor( $contents );
		if( $contents->next_tag( [ 'tag_name' => 'a' ] ) ) {
			// Is this a button?
			$contents->add_class( in_array( 'wp-block-button', $classNames, true ) ? 'wp-element-button' : 'nav-link' );
			$contents->set_attribute( 'title', is_user_logged_in() ? esc_attr__( 'Logout', 'wecodeart' ) : esc_attr__( 'Login', 'wecodeart' ) );
		}
		$contents = $contents->get_updated_html();

		return wecodeart( 'dom' )::wrap( $this->get_asset_handle(), [
			[
				'tag' 	=> 'div',
				'attrs'	=> $this->get_block_wrapper_attributes( [
					'class' => join( ' ', array_filter( $classnames ) )
				] )
			]
		], $contents, [], false );
	}

	/**
	 * Render Modal
	 *
	 * @param 	string 	$content 		The block content.
	 * @param 	string 	$instance_id 	The block instance.
	 * @param 	array 	$attributes 	The block attributes.
	 */
	private static function get_modal( string $content, string $instance_id, array $attributes ): string {
		return wecodeart_template( 'general/modal', [
			'id'		=> $instance_id,
			'classes'	=> [ 'wp-modal--login', 'wp-modal--fullscreen:sm', 'fade' ],
			'title'		=> get_prop( $attributes, [ 'metadata', 'name' ] ) ?: esc_html__( 'Log In', 'wecodeart' ),
			'content' 	=> $content,
		], false );
	}

	/**
	 * Dynamically renders the `core/loginout` form.
	 *
	 * @param 	array 	$args	The form args.
	 * @param 	bool 	$echo	Echo or return the HTML.
	 *
	 * @return 	string 	The block markup.
	 */
	private static function render_form( $args = [], $echo = true ) {
		// Default args from wp_login_form();
		$defaults = [
			'redirect'       => ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],
			'label_username' => esc_html__( 'Username or Email Address', 'wecodeart' ),
			'label_password' => esc_html__( 'Password', 'wecodeart'  ),
			'label_remember' => esc_html__( 'Remember Me', 'wecodeart'  ),
			'label_log_in'   => esc_html__( 'Log In', 'wecodeart'  ),
			// 'id_username'    => 'user_login',
			// 'id_password'    => 'user_pass',
			// 'id_remember'    => 'rememberme',
			// 'id_submit'      => 'wp-submit',
			'remember'       => true,
			'value_username' => '',
			'value_remember' => false,
		];

		// We use same filters as WP - plugins will hook into those.
		return wecodeart_template( 'general/login', [
			'args' => wp_parse_args( $args, apply_filters( 'login_form_defaults', $defaults ) )
		], $echo );
	}

	/**
	 * Block styles
	 *
	 * @return 	string 	The block styles.
	 */
	public function styles() {
		return <<<CSS
			.wp-block-login {
				margin-bottom: 2rem;
			}
			.wp-block-loginout > :where(a) {
				text-decoration: none;
			}
		CSS;
	}
}
