<?php
namespace TotalTheme;

defined( 'ABSPATH' ) || exit;

/**
 * Redirections Class.
 *
 * @package TotalTheme
 * @version 5.4
 */
final class Redirections {

	/**
	 * Potentially redirect the current page.
	 */
	public static function maybe_redirect() {
		if ( wpex_vc_is_inline() ) {
			return; // never redirect while editing a page
		}

		$redirect = self::get_redirect();

		if ( $redirect ) {
			if ( is_numeric( $redirect ) ) {
				$redirect = get_permalink( $redirect );
				if ( $redirect ) {
					self::safe_redirect( $redirect );
				}
			} else {
				self::redirect( $redirect );
			}
		}
	}

	/**
	 * Performs a standard redirection.
	 */
	protected static function redirect( $redirect = '' ) {
		wp_redirect( esc_url( $redirect ), self::get_status_code( $redirect ), 'Total WordPress Theme' );
		exit;
	}

	/**
	 * Performs a safe redirection.
	 */
	protected static function safe_redirect( $redirect = '' ) {
		wp_safe_redirect( esc_url( $redirect ), self::get_status_code( $redirect ), 'Total WordPress Theme' );
		exit;
	}

	/**
	 * Return status code for the redirection.
	 */
	protected static function get_status_code( $redirect = '' ) {

		/**
		 * Filters the status code used for theme redirections.
		 *
		 * @param int $status_code
		 * @param string $redirect_location
		 */
		$status_code = apply_filters( 'wpex_redirect_status_code', 301, $redirect );

		return $status_code;
	}

	/**
	 * Check if the current page has a redirection.
	 */
	protected static function get_redirect() {
		$redirect = '';

		if ( is_singular() ) {
			if ( 'link' === get_post_format() && ! apply_filters( 'wpex_redirect_link_format_posts', false ) ) {
				$redirect = '';
			} else {
				$redirect = wpex_get_custom_permalink();
			}
		} elseif ( is_tax() || is_category() || is_tag() ) {
			$redirect = get_term_meta( get_queried_object_id(), 'wpex_redirect', true );
		}

		return $redirect;
	}

}