<?php
/**
 * Login functionality
 *
 * @package Nisje
 */

declare( strict_types=1 );
namespace NisjeFrontend\Login;

use NisjeFrontend\ClientAssets;

if ( ! defined( 'ABSPATH' ) ) {
	die( 'Silence is golden.' );
}

/**
 * Send users to the frontpage after login
 */
add_filter( 'login_redirect', function( $url, $query, $user ) { // phpcs:ignore
	return home_url();
}, 10, 3 );

/**
 * Add login stylesheets
 */
function login_stylesheet() {
	$version = '1.0.0';

	wp_enqueue_style( 'nisje-wordpress', get_stylesheet_directory_uri() . '/build/wordpress/style.css', [], $version );
	wp_enqueue_style( 'nisje-login-font', ClientAssets\get_font_stylesheet(), [], '1.0.0' );
	wp_enqueue_style( 'nisje-settings', get_stylesheet_directory_uri() . '/build/settings/style.css', [], $version );
	wp_enqueue_style( 'nisje-login', get_stylesheet_directory_uri() . '/build/wordpress/login.css', [ 'nisje-settings', 'nisje-wordpress' ], $version );
}
add_action( 'login_enqueue_scripts', __NAMESPACE__ . '\\login_stylesheet' );

/**
 * Wrap login messages in a span
 *
 * @param string $message Message.
 * @return string
 */
function wrap_login_messages( $message ): string { // phpcs:ignore
	return '<span class="nisje-login-message">' . $message . '</span>';
}
add_filter( 'login_errors', __NAMESPACE__ . '\\wrap_login_messages' );
add_filter( 'login_messages', __NAMESPACE__ . '\\wrap_login_messages' );

/**
 * Add login description
 *
 * @param string $message Message.
 * @return string
 */
function login_message( $message ): string { // phpcs:ignore
	$nisje_message = '';
	if ( empty( $message ) && ! empty( get_bloginfo( 'description' ) ) ) {
		$nisje_message = get_bloginfo( 'description' );
	}

	return \NisjeFrontend\get( 'components', 'logo-banner', [ 'message' => $nisje_message ] ) . $message;
}
add_filter( 'login_message', __NAMESPACE__ . '\\login_message' );

/**
 * Login footer
 */
function footer() {
	$background_image = get_theme_mod( 'nisje_theme_images_login_background', false );

	if ( ! empty( $background_image ) ) {
		\NisjeFrontend\inc( 'components', 'background-image', [
			'url' => $background_image,
		] );
	}
}
add_action( 'login_footer', __NAMESPACE__ . '\\footer' );

/**
 * Wrap login page.
 */
function login_start() {
	echo '<div class="nisje-login-page">';
}
add_action( 'login_header', __NAMESPACE__ . '\\login_start', 0 );

/**
 * Wrap login page end.
 */
function login_end() {
	global $action;

	if ( function_exists( 'nisje_get_setting' ) ) {
		$message = nisje_get_setting( 'login_info_message', 'general' );

		if ( 'login' === $action && ! empty( $message ) ) {
			printf( '<p class="nisje-login-footer-message">%s</p>', esc_html( $message ) );
		}
	}

	echo '</div>';
}
add_action( 'login_footer', __NAMESPACE__ . '\\login_end', 9999 );
