<?php
namespace TotalTheme;

defined( 'ABSPATH' ) || exit;

/**
 * Error 404 Class.
 *
 * @package Total WordPress theme
 * @subpackage Framework
 * @version 5.4
 */
final class Error_404 {

	/**
	 * Class instance.
	 *
	 * @access private
	 * @var object Class object.
	 */
	private static $instance;

	/**
	 * Create or retrieve the instance of Custom_Actions.
	 */
	public static function instance() {
		if ( is_null( static::$instance ) ) {
			static::$instance = new self();
		}
		return static::$instance;
	}

	/**
	 * Constructor.
	 */
	public function __construct() {
		if ( ! get_theme_mod( 'custom_404_enable', true ) ) {
			return;
		}

		if ( wpex_is_request( 'admin' ) ) {
			self::admin_init();
		}

		if ( wpex_is_request( 'frontend' ) ) {
			self::init();
		}
	}

	/**
	 * Admin hooks.
	 */
	public static function admin_init() {
		add_action( 'admin_menu', __CLASS__ . '::add_submenu_page' );
		add_action( 'admin_init', __CLASS__ . '::register_page_options' );
	}

	/**
	 * Front-end hooks.
	 */
	public static function init() {

		// Redirect all pages home.
		if ( get_theme_mod( 'error_page_redirect', false ) ) {
			add_filter( 'template_redirect', __CLASS__ . '::redirect' );
		}

		// Display standard 404 page and register 404 page ID for custom page settings and content.
		elseif ( get_theme_mod( 'error_page_content_id' ) ) {
			add_filter( 'wpex_current_post_id', __CLASS__ . '::post_id' );
		}

	}

	/**
	 * Add sub menu page for the custom CSS input.
	 */
	public static function add_submenu_page() {
		add_submenu_page(
			WPEX_THEME_PANEL_SLUG,
			esc_html__( 'Custom 404', 'total' ),
			esc_html__( 'Custom 404', 'total' ),
			'edit_theme_options',
			WPEX_THEME_PANEL_SLUG . '-404',
			__CLASS__ . '::create_admin_page'
		);
	}

	/**
	 * Function that will register admin page options.
	 */
	public static function register_page_options() {

		// Register settings.
		register_setting(
			'wpex_error_page',
			'error_page',
			array(
				'sanitize_callback' => __CLASS__ . '::save_options',
				'default' => null,
			)
		);

		// Add main section to our options page.
		add_settings_section(
			'wpex_error_page_main',
			false,
			__CLASS__ . '::section_main_callback',
			'wpex-custom-error-page-admin'
		);

		// Redirect field.
		add_settings_field(
			'redirect',
			esc_html__( 'Redirect 404\'s', 'total' ),
			__CLASS__ . '::redirect_field_callback',
			'wpex-custom-error-page-admin',
			'wpex_error_page_main'
		);

		// Custom Page ID.
		add_settings_field(
			'error_page_id',
			esc_html__( 'Custom 404 Page', 'total' ),
			__CLASS__ . '::content_id_field_callback',
			'wpex-custom-error-page-admin',
			'wpex_error_page_main'
		);

		// Title field.
		add_settings_field(
			'error_page_title',
			esc_html__( '404 Page Title', 'total' ),
			__CLASS__ . '::title_field_callback',
			'wpex-custom-error-page-admin',
			'wpex_error_page_main'
		);

		// Content field.
		add_settings_field(
			'error_page_text',
			esc_html__( '404 Page Content', 'total' ),
			__CLASS__ . '::content_field_callback',
			'wpex-custom-error-page-admin',
			'wpex_error_page_main'
		);

	}

	/**
	 * Save options.
	 */
	public static function save_options( $options ) {

		// Set theme mods
		if ( isset( $options['redirect'] ) ) {
			set_theme_mod( 'error_page_redirect', 1 );
		} else {
			remove_theme_mod( 'error_page_redirect' );
		}

		if ( ! empty( $options['title'] ) ) {
			set_theme_mod( 'error_page_title', $options['title'] );
		} else {
			remove_theme_mod( 'error_page_title' );
		}

		if ( ! empty( $options['text'] ) ) {
			set_theme_mod( 'error_page_text', $options['text'] );
		} else {
			remove_theme_mod( 'error_page_text' );
		}

		if ( ! empty( $options['content_id'] ) ) {
			set_theme_mod( 'error_page_content_id', $options['content_id'] );
		} else {
			remove_theme_mod( 'error_page_content_id' );
		}

		// Don't actually save as an option since we are using mods.
		return;
	}

	/**
	 * Main Settings section callback.
	 */
	public static function section_main_callback( $options ) {
		// Leave blank
	}

	/**
	 * Fields callback functions.
	 */

	// Redirect field
	public static function redirect_field_callback() {
		$val = get_theme_mod( 'error_page_redirect' );
		echo '<input type="checkbox" name="error_page[redirect]" id="error-page-redirect" value="'. esc_attr( $val ) .'" '. checked( $val, true, false ) .'> ';
		echo '<span class="description">'. esc_html__( 'Automatically 301 redirect all 404 errors to your homepage.', 'total' ) .'</span>';
	}

	// Custom Error Page ID.
	public static function content_id_field_callback() {
		$page_id = get_theme_mod( 'error_page_content_id' );

		wp_dropdown_pages( array(
			'echo'             => true,
			'selected'         => $page_id,
			'name'             => 'error_page[content_id]',
			'id'               => 'error-page-content-id',
			'class'            => 'wpex-chosen',
			'show_option_none' => esc_html__( 'None', 'total' ),
		) ); ?>

		<br>

		<p class="description"><?php esc_html_e( 'Select a custom page to replace your default 404 page content.', 'total' ) ?></p>

		<?php if ( $page_id ) { ?>

			<br>

			<div id="wpex-footer-builder-edit-links">

				<a href="<?php echo admin_url( 'post.php?post='. $page_id .'&action=edit' ); ?>" class="button" target="_blank" rel="noopener noreferrer">
					<?php esc_html_e( 'Backend Edit', 'total' ); ?>
				</a>

				<?php if ( WPEX_VC_ACTIVE ) { ?>

					<a href="<?php echo admin_url( 'post.php?vc_action=vc_inline&post_id='. $page_id .'&post_type=page' ); ?>" class="button" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Frontend Edit', 'total' ); ?></a>

				<?php } ?>

				<a href="<?php echo esc_url( get_permalink( $page_id ) ); ?>" class="button" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Preview', 'total' ); ?></a>

			</div>

		<?php } ?>

	<?php }

	// Title field.
	public static function title_field_callback() { ?>
		<input type="text" name="error_page[title]" id="error-page-title" value="<?php echo get_theme_mod( 'error_page_title' ); ?>">
		<p class="description"><?php esc_html_e( 'Enter a custom title for your 404 page.', 'total' ) ?></p>
	<?php }

	// Content field.
	public static function content_field_callback() {
		wp_editor( get_theme_mod( 'error_page_text' ), 'error_page_text', array(
			'textarea_name' => 'error_page[text]'
		) );
	}

	/**
	 * Settings page output.
	 */
	public static function create_admin_page() {
		wp_enqueue_style( 'wpex-chosen' );
		wp_enqueue_script( 'wpex-chosen' );

		wp_enqueue_script(
			'wpex-custom-404',
			wpex_asset_url( 'js/dynamic/admin/wpex-custom-404.min.js' ),
			array( 'jquery' ),
			WPEX_THEME_VERSION
		);

		?>

		<div class="wrap">

			<h1><?php esc_html_e( 'Custom 404', 'total' ); ?></h1>

			<form method="post" action="options.php">
				<?php settings_fields( 'wpex_error_page' ); ?>
				<?php do_settings_sections( 'wpex-custom-error-page-admin' ); ?>
				<?php submit_button(); ?>
			</form>

		</div>
	<?php }

	/**
	 * Redirect all pages to the under cronstruction page if user is not logged in.
	 */
	public static function redirect() {
		if ( is_404() ) {
			wp_redirect( esc_url( home_url( '/' ) ), 301 );
			exit();
		}
	}

	/**
	 * Custom VC CSS for 404 custom page design.
	 */
	public static function post_id( $post_id ) {
		if ( is_404() ) {
			$error_page = self::get_template_id();
			if ( $error_page ) {
				$post_id = $error_page;
			}
		}
		return $post_id;
	}

	/**
	 * Returns inline CSS for the 404 page.
	 */
	public static function get_template_id() {
		return wpex_parse_obj_id( get_theme_mod( 'error_page_content_id' ), 'page' );
	}

	/**
	 * Returns inline CSS for the 404 page.
	 */
	protected static function get_template_css( $template_id ) {
		$css = '';
		$post_css = get_post_meta( $template_id, '_wpb_post_custom_css', true );
		$post_css = apply_filters( 'vc_post_custom_css', $post_css, $template_id );
		if ( $post_css ) {
			$css .= $post_css;
		}
		$shortcode_css = get_post_meta( $template_id, '_wpb_shortcodes_custom_css', true );
		$shortcode_css = apply_filters( 'vc_shortcodes_custom_css', $shortcode_css, $template_id );
		if ( $shortcode_css ) {
			$css .= $shortcode_css;
		}
		if ( $css ) {
			return '<style>' . wp_strip_all_tags( $css ) . '</style>';
		}
	}

	/**
	 * Returns custom 404 page content.
	 */
	public static function get_content() {
		$template_id = self::get_template_id();

		// Display template content.
		if ( $template_id && $current_id = wpex_get_current_post_id() ) {
			$post         = get_post( $current_id ); // get post
			$content      = wpex_parse_vc_content( $post->post_content ); // remove weird p tags and extra code
			$content      = wp_kses_post( $content ); // security
			$content      = do_shortcode( $content ); // parse shortcodes and echo
			$template_css = self::get_template_css( $current_id );
			if ( $template_css ) {
				$content = $template_css . $content;
			}
			return $content;
		}

		// Custom Text.
		$error_text = trim( wpex_get_translated_theme_mod( 'error_page_text' ) );

		if ( $error_text ) {
			return '<div class="custom-error404-content wpex-clr">' . wpex_the_content( $error_text, 'error404' ) .'</div>';
		}

		// Default.
		return '<div class="error404-content wpex-text-center wpex-py-30 wpex-clr"><h1 class="error404-content-heading wpex-m-0 wpex-mb-10 wpex-text-6xl">' . esc_html__( 'Sorry, this page could not be found.', 'total' ) . '</h1><div class="error404-content-text wpex-text-md wpex-last-mb-0">' . esc_html__( 'The page you are looking for doesn\'t exist, no longer exists or has been moved.', 'total' ) . '</div></div>';

	}

}