<?php
/**
 * File Path: includes/class-mbs-buy-link-router.php
 *
 * Buy-Link Click Router -- INSIGHTS-1
 *
 * Registers the /?mbs_click={link_id} 302 redirect endpoint.
 * - Redirect fires on ALL tiers (broken links must never result from FREE license).
 * - Click recording in mbs_buy_link_clicks is PRO-gated.
 * - Affiliate rewriter skips URLs containing mbs_click= (guard in that class).
 *
 * Registration:
 *   new MBS_Buy_Link_Router() in MBS_Plugin::load_admin_services().
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class MBS_Buy_Link_Router
 *
 * Handles /?mbs_click={id} redirect requests.
 *
 * @since 1.0.0
 */
class MBS_Buy_Link_Router {

	/**
	 * Constructor -- wire query_vars and template_redirect hooks.
	 */
	public function __construct() {
		add_filter( 'query_vars',        array( $this, 'add_query_var' ) );
		add_action( 'template_redirect', array( $this, 'handle' ) );
	}

	/**
	 * Register the mbs_click query variable.
	 *
	 * @param array $vars Existing query vars.
	 * @return array
	 */
	public function add_query_var( array $vars ): array {
		$vars[] = 'mbs_click';
		return $vars;
	}

	/**
	 * Handle the /?mbs_click={link_id} request.
	 *
	 * Fetches the link record, optionally records the click (PRO only),
	 * then issues a 302 redirect to the destination URL.
	 *
	 * @return void
	 */
	public function handle(): void {
		$raw = get_query_var( 'mbs_click', '' );
		if ( '' === (string) $raw ) {
			return;
		}

		$link_id = absint( $raw );
		if ( ! $link_id ) {
			wp_die( esc_html__( 'Invalid link.', 'my-book-showroom' ), '', array( 'response' => 404 ) );
		}

		$link = MBS_Buy_Link_DAO::get_active_by_id( $link_id );

		if ( ! $link || empty( $link->url ) ) {
			wp_die( esc_html__( 'Link not found.', 'my-book-showroom' ), '', array( 'response' => 404 ) );
		}

		// Record click (PRO-gated).
		if ( mbs_is_pro() ) {
			$referer_raw  = wp_get_referer();
			$referer_host = $referer_raw ? (string) wp_parse_url( $referer_raw, PHP_URL_HOST ) : '';

			MBS_Buy_Link_Clicks_DAO::log_click(
				(int) $link->id,
				(int) $link->post_id,
				sanitize_key( (string) ( $link->retailer_key ?? '' ) ),
				sanitize_text_field( $referer_host )
			);
		}

		// PLG-007: Apply affiliate rewriter (PRO) so click-tracked links also carry the tag.
		// The rewriter's own guard (strpos $url 'mbs_click=') does not fire here because
		// we are rewriting the raw stored URL, not the click-tracker URL itself.
		$raw_url = $link->url;
		if ( mbs_is_pro() ) {
			$raw_url = MBS_Affiliate_Rewriter::rewrite(
				$raw_url,
				sanitize_key( (string) ( $link->retailer_key ?? '' ) )
			);
		}
		$destination = esc_url_raw( $raw_url );
		wp_safe_redirect( $destination, 302 );
		exit;
	}
}
