<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class DC_V2_Rewrite {

	public static function init() {
		add_action( 'init', array( __CLASS__, 'add_rules' ) );
		add_filter( 'query_vars', array( __CLASS__, 'query_vars' ) );
		add_action( 'template_redirect', array( __CLASS__, 'template_redirect' ) );
	}

	/**
	 * Optional demo-storefront extras (synced only to orderfromdm.rebornlabs.me/demo).
	 * Never present in the customer ZIP.
	 */
	private static function load_demo_chat_route() {
		static $loaded = null;
		if ( null !== $loaded ) {
			return $loaded;
		}
		$file = trailingslashit( DC_V2_PATH ) . 'demo-storefront/includes/class-demo-chat-route.php';
		if ( ! is_readable( $file ) ) {
			$loaded = false;
			return false;
		}
		require_once $file;
		$loaded = class_exists( 'DC_V2_Demo_Chat_Route', false );
		return $loaded;
	}

	public static function add_rules() {
		$demo = self::load_demo_chat_route();
		if ( $demo && DC_V2_Demo_Chat_Route::enabled() ) {
			DC_V2_Demo_Chat_Route::add_rewrite_rule();
		}
		add_rewrite_rule( '^c/([^/]+)/og\.png$', 'index.php?dc_v2_og_slug=$matches[1]', 'top' );
		add_rewrite_rule( '^c/([^/]+)/?$', 'index.php?dc_v2_slug=$matches[1]', 'top' );

		$stamp = ( $demo ? DC_V2_Demo_Chat_Route::rewrite_stamp() : 'v2-demo-storefront-absent' ) . '|og-v1';
		if ( get_option( 'dc_v2_rewrite_stamp' ) !== $stamp ) {
			update_option( 'dc_v2_rewrite_stamp', $stamp, false );
			flush_rewrite_rules( false );
		}
	}

	public static function query_vars( $vars ) {
		$vars[] = 'dc_v2_slug';
		$vars[] = 'dc_v2_og_slug';
		$vars[] = 'dc_v2_demo_chat';
		return $vars;
	}

	public static function template_redirect() {
		if ( class_exists( 'DC_V2_Og_Image', false ) ) {
			DC_V2_Og_Image::maybe_serve();
		}

		if ( self::load_demo_chat_route() && DC_V2_Demo_Chat_Route::maybe_render() ) {
			return;
		}

		$slug = get_query_var( 'dc_v2_slug' );
		if ( ! $slug ) {
			return;
		}
		$post = DC_V2_Document_CPT::find_by_slug( $slug );
		if ( ! $post ) {
			status_header( 404 );
			wp_die( 'Este pedido no existe.', 'No encontrado', array( 'response' => 404 ) );
		}
		$meta = DC_V2_Document_CPT::get_meta( $post->ID );
		if ( 'active' !== $meta['status'] && ! isset( $_GET['preview'] ) ) {
			status_header( 404 );
			wp_die( 'Este pedido no está disponible.', 'No disponible', array( 'response' => 404 ) );
		}
		if ( empty( $meta['lines'] ) ) {
			status_header( 404 );
			wp_die( 'Pedido sin productos.', 'No disponible', array( 'response' => 404 ) );
		}
		self::isolate_assets();
		self::suppress_seo_plugins();
		status_header( 200 );
		nocache_headers();
		global $wp_query;
		if ( $wp_query ) {
			$wp_query->is_404 = false;
		}
		include DC_V2_PATH . 'public-v2/views/chat.php';
		exit;
	}

	/**
	 * Keep Instagram / WhatsApp / iMessage previews on our OG tags, not the shop theme.
	 */
	public static function suppress_seo_plugins() {
		add_filter( 'wpseo_frontend_presenter_classes', '__return_empty_array' );
		add_filter( 'wpseo_opengraph_show_publish_date', '__return_false' );
		add_filter( 'wpseo_json_ld_output', '__return_false' );
		add_filter( 'rank_math/frontend/disable_adjacent_rel_links', '__return_true' );
		add_filter( 'rank_math/opengraph/facebook', '__return_false' );
		add_filter( 'rank_math/opengraph/twitter', '__return_false' );
		if ( defined( 'RANK_MATH_VERSION' ) ) {
			remove_all_actions( 'rank_math/head' );
		}
		add_filter( 'jetpack_enable_open_graph', '__return_false' );
	}

	public static function isolate_assets() {
		add_filter( 'show_admin_bar', '__return_false' );
		add_filter( 'body_class', array( __CLASS__, 'reset_body_class' ), 9999 );
		add_action( 'wp_enqueue_scripts', array( __CLASS__, 'dequeue_foreign_styles' ), 9999 );
		add_action( 'wp_print_styles', array( __CLASS__, 'dequeue_foreign_styles' ), 0 );
		add_filter( 'style_loader_tag', array( __CLASS__, 'filter_style_tag' ), 9999, 2 );
	}

	public static function filter_style_tag( $tag, $handle ) {
		return 'dc-v2-chat' === $handle ? $tag : '';
	}

	public static function reset_body_class( $classes ) {
		return array( 'dc-v2-body' );
	}

	public static function dequeue_foreign_styles() {
		$keep   = array( 'dc-v2-chat' );
		$styles = wp_styles();
		if ( ! $styles || empty( $styles->queue ) ) {
			return;
		}
		foreach ( (array) $styles->queue as $handle ) {
			if ( ! in_array( $handle, $keep, true ) ) {
				wp_dequeue_style( $handle );
			}
		}
	}
}
