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

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

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

/**
 * Check if the current page is the privacy page
 *
 * @return boolean
 */
function is_privacy_page() : bool {
	$policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' );

	if ( ! empty( $policy_page_id ) && get_post_status( $policy_page_id ) === 'publish' && is_page( $policy_page_id ) ) {
		return true;
	}

	return false;
}

/**
 * Template
 *
 * @param null|string $template Template path.
 * @return null|string Template path
 */
function template( ?string $template ) : ?string {
	if ( bp_is_register_page() || bp_is_activation_page() ) {
		add_action( 'wp_enqueue_scripts', 'NisjeFrontend\ClientAssets\register_registration_scripts_and_styles' );
	} elseif ( is_privacy_page() ) {
		add_action( 'wp_enqueue_scripts', 'NisjeFrontend\ClientAssets\register_privacy_scripts_and_styles' );
		return locate_template( 'privacy.php' );
	} else {
		add_action( 'wp_enqueue_scripts', 'NisjeFrontend\ClientAssets\register_scripts_and_styles' );
	}

	return $template;
}
add_filter( 'template_include', __NAMESPACE__ . '\\template' );

/**
 * Redirect
 */
function redirect() {
	$is_registration_open = get_option( 'users_can_register' );
	$registration         = $is_registration_open && bp_is_register_page();

	if ( is_user_logged_in() ) {
		if ( $registration ) {
			wp_safe_redirect( home_url() );
			exit;
		}
	} elseif ( ! $registration && ! is_user_logged_in() && ! bp_is_activation_page() && ! is_privacy_page() ) {
		wp_safe_redirect( wp_login_url() );
		exit;
	}
}
add_action( 'template_redirect', __NAMESPACE__ . '\\redirect' );
