<?php

namespace NF\WPBOUTIK;

class Logged_in_only {

	use Singleton;

	public function __construct() {
		add_action( 'template_redirect', array( __CLASS__, 'redirect_not_logged_users' ) );
		add_filter( 'wpboutik_login_redirect', array( __CLASS__, 'redirect_after_login' ) );
	}

	/**
	 * Redirect when the user is not logged
	 */
	public static function redirect_not_logged_users() {
		if ( in_array( 'wpboutik/wpboutik.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ), true ) ) {

			if ( is_user_logged_in() ) {
				return;
			}
			/**
			 * Filter arguments used to retrieve products from database
			 *
			 * @param bool $should_redirect Whether the not logged-in user should be redirect. Default: is_wpboutik() || is_page( wpboutik_get_page_id( 'cart' ) ) || is_page( wpboutik_get_page_id( 'checkout' ).
			 *
			 * @return bool New value
			 * @hook wpb_should_redirect_not_logged_in_user
			 */
			$should_redirect_not_logged_in_user = apply_filters( 'wpb_should_redirect_not_logged_in_user', is_wpboutik() || is_page( wpboutik_get_page_id( 'cart' ) ) || is_page( wpboutik_get_page_id( 'checkout' ) ) );

			if ( ! $should_redirect_not_logged_in_user ) {
				return;
			}

			$options = wpboutik_get_option('wpboutik_not_logged_redirect_pageid');

			$redirect_page = ( $options === false )
				? wpboutik_get_page_permalink( 'account' )
				: get_permalink( $options );
			/**
			 * Filter the redirect page URL
			 *
			 * @param string $redirect_page_url The page permalink URL.
			 *
			 * @return string New value.
			 * @hook wpb_redirect_page_url
			 */
			$redirect_page = apply_filters( 'wpb_redirect_page_url', $redirect_page );

			wp_safe_redirect( $redirect_page );
			exit;
		}
	}

		/**
		 * Redirect after login
		 *
		 * @param string $redirect_to Default WPBoutik redirect page.
		 */
	public static function redirect_after_login( $redirect_to ) {
			$options = wpboutik_get_option('wpboutik_redirect_afterlogin_pageid');

			if ( $options !== false ) {
				$redirect_to_option = get_permalink( $options );

				if ( $redirect_to_option ) {
					$redirect_to = $redirect_to_option;
				}
			}

			/**
			 * Filter the redirect after login page URL
			 *
			 * @param string $redirect_after_login_page_url The after login page permalink URL.
			 *
			 * @return string New value.
			 * @hook wpb_redirect_after_login_page_url
			 */
			$redirect_to = apply_filters( 'wpb_redirect_after_login_page_url', $redirect_to );

			return $redirect_to;
		}
}