<?php
/**
 * 247ChatMate — Founder QA product-state simulator
 *
 * Internal QA helper. Only an active Founder Beta entitlement can use it.
 * It never deletes or replaces the real licence/Founder entitlement.
 */

defined( 'ABSPATH' ) || exit;

if ( ! defined( 'MATEWA_FOUNDER_QA_MODE_OPTION' ) ) {
	define( 'MATEWA_FOUNDER_QA_MODE_OPTION', 'matewa_founder_qa_product_state' );
}

if ( ! function_exists( 'matewa_founder_qa_allowed_modes' ) ) {
	function matewa_founder_qa_allowed_modes() {
		return array(
			'normal'        => 'Normal (real entitlement)',
			'free'          => 'Free',
			'trial_active'  => 'Trial Active',
			'trial_expired' => 'Trial Expired',
			'pro'           => 'Pro',
		);
	}
}

if ( ! function_exists( 'matewa_founder_qa_is_available' ) ) {
	function matewa_founder_qa_is_available() {
		return function_exists( 'matewa_founder_beta_is_active' ) && matewa_founder_beta_is_active();
	}
}

if ( ! function_exists( 'matewa_founder_qa_get_mode' ) ) {
	function matewa_founder_qa_get_mode() {
		if ( ! matewa_founder_qa_is_available() ) {
			return 'normal';
		}

		$mode    = sanitize_key( (string) get_option( MATEWA_FOUNDER_QA_MODE_OPTION, 'normal' ) );
		$allowed = matewa_founder_qa_allowed_modes();

		return isset( $allowed[ $mode ] ) ? $mode : 'normal';
	}
}

if ( ! function_exists( 'matewa_founder_qa_forced_license_mode' ) ) {
	function matewa_founder_qa_forced_license_mode( $real_mode ) {
		$qa_mode = matewa_founder_qa_get_mode();

		if ( 'normal' === $qa_mode ) {
			return $real_mode;
		}

		$map = array(
			'free'          => defined( 'MATEWA_MODE_FREE' ) ? MATEWA_MODE_FREE : 'free',
			'trial_active'  => defined( 'MATEWA_MODE_TRIAL' ) ? MATEWA_MODE_TRIAL : 'trial_active',
			'trial_expired' => defined( 'MATEWA_MODE_TRIAL_EXPIRED' ) ? MATEWA_MODE_TRIAL_EXPIRED : 'trial_expired',
			'pro'           => defined( 'MATEWA_MODE_PRO' ) ? MATEWA_MODE_PRO : 'pro',
		);

		return isset( $map[ $qa_mode ] ) ? $map[ $qa_mode ] : $real_mode;
	}
}
add_filter( 'matewa_force_license_mode', 'matewa_founder_qa_forced_license_mode', 999 );

if ( ! function_exists( 'matewa_founder_qa_save_mode' ) ) {
	function matewa_founder_qa_save_mode() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) || ! matewa_founder_qa_is_available() ) {
			wp_die( esc_html__( 'You are not allowed to change the Founder QA state.', '247chatmate' ) );
		}

		check_admin_referer( 'matewa_founder_qa_save' );

		$requested = isset( $_POST['matewa_founder_qa_mode'] )
			? sanitize_key( wp_unslash( $_POST['matewa_founder_qa_mode'] ) )
			: 'normal';

		$allowed = matewa_founder_qa_allowed_modes();
		if ( ! isset( $allowed[ $requested ] ) ) {
			$requested = 'normal';
		}

		update_option( MATEWA_FOUNDER_QA_MODE_OPTION, $requested, false );

		/*
		 * Founder QA is frequently exercised on cached production/staging sites.
		 * When previewing Free, force the saved placement to the Free contract
		 * and clear page targeting so the widget is immediately sitewide.
		 */
		if ( in_array( $requested, array( 'free', 'trial_expired' ), true ) ) {
			$widget_settings = get_option( 'matewa_widget_settings', array() );
			$widget_settings = is_array( $widget_settings ) ? $widget_settings : array();

			$widget_settings['enabled']          = '1';
			$widget_settings['display_mode']     = 'all';
			$widget_settings['page_ids']         = array();
			$widget_settings['include_homepage'] = '0';

			update_option( 'matewa_widget_settings', $widget_settings, false );
		}

		// Clear WordPress/object caches plus common page-cache integrations.
		if ( function_exists( 'wp_cache_flush' ) ) {
			wp_cache_flush();
		}

		if ( function_exists( 'rocket_clean_domain' ) ) {
			rocket_clean_domain();
		}

		if ( function_exists( 'w3tc_flush_all' ) ) {
			w3tc_flush_all();
		}

		if ( has_action( 'litespeed_purge_all' ) ) {
			do_action( 'litespeed_purge_all' );
		}

		if ( function_exists( 'wpfc_clear_all_cache' ) ) {
			wpfc_clear_all_cache( true );
		}

		$url = add_query_arg(
			array(
				'page'             => '247chatmate-founder-qa',
				'matewa_qa_saved'  => '1',
			),
			admin_url( 'admin.php' )
		);
		wp_safe_redirect( $url );
		exit;
	}
}
add_action( 'admin_post_matewa_founder_qa_save', 'matewa_founder_qa_save_mode' );

if ( ! function_exists( 'matewa_render_founder_qa_page' ) ) {
	function matewa_render_founder_qa_page() {
		if ( ! current_user_can( 'manage_options' ) || ! matewa_founder_qa_is_available() ) {
			wp_die( esc_html__( 'Founder QA is only available on an active Founder Beta installation.', '247chatmate' ) );
		}

		$current = matewa_founder_qa_get_mode();
		$allowed = matewa_founder_qa_allowed_modes();
		?>
		<div class="wrap" style="max-width:900px;">
			<h1>247ChatMate Founder QA</h1>
			<?php if ( isset( $_GET['matewa_qa_saved'] ) ) : ?>
				<div class="notice notice-success is-dismissible"><p><strong>Test product state updated.</strong></p></div>
			<?php endif; ?>

			<div style="background:#fff;border:1px solid #dcdcde;border-radius:12px;padding:24px;margin-top:20px;">
				<h2 style="margin-top:0;">Test product state</h2>
				<p>
					Temporarily preview how this installation behaves in another product state.
					Your real Founder entitlement and licence data are left untouched.
				</p>

				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
					<input type="hidden" name="action" value="matewa_founder_qa_save">
					<?php wp_nonce_field( 'matewa_founder_qa_save' ); ?>

					<table class="form-table" role="presentation">
						<tr>
							<th scope="row"><label for="matewa_founder_qa_mode">Product state</label></th>
							<td>
								<select id="matewa_founder_qa_mode" name="matewa_founder_qa_mode">
									<?php foreach ( $allowed as $value => $label ) : ?>
										<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $current, $value ); ?>>
											<?php echo esc_html( $label ); ?>
										</option>
									<?php endforeach; ?>
								</select>
								<p class="description">
									Choose <strong>Free</strong> to test the fixed 2 × 2 Free visitor buttons.
									Choose <strong>Normal</strong> to return instantly to the real Founder state.
								</p>
							</td>
						</tr>
					</table>

					<?php submit_button( 'Apply test state' ); ?>
				</form>
			</div>

			<div style="background:#f0f6fc;border-left:4px solid #2271b1;padding:14px 18px;margin-top:18px;">
				<strong>QA only:</strong> this control does not remove the Founder key, change the registry record,
				or overwrite saved Pro/vertical settings.
			</div>
		</div>
		<?php
	}
}

if ( is_admin() ) {
	add_action(
		'admin_menu',
		function () {
			if ( matewa_founder_qa_is_available() ) {
				add_submenu_page(
					'247chatmate',
					'Founder QA',
					'Founder QA',
					'manage_options',
					'247chatmate-founder-qa',
					'matewa_render_founder_qa_page'
				);
			}
		},
		30
	);
}


/**
 * Founder-QA Free self-heal.
 * Keeps the test site on the same sitewide placement contract as a real Free install.
 */
add_action(
	'admin_init',
	function () {
		if ( ! matewa_founder_qa_is_available() ) {
			return;
		}

		$qa_mode = matewa_founder_qa_get_mode();
		if ( ! in_array( $qa_mode, array( 'free', 'trial_expired' ), true ) ) {
			return;
		}

		$settings = get_option( 'matewa_widget_settings', array() );
		$settings = is_array( $settings ) ? $settings : array();

		$needs_repair =
			'1' !== (string) ( $settings['enabled'] ?? '1' ) ||
			'all' !== (string) ( $settings['display_mode'] ?? 'all' ) ||
			! empty( $settings['page_ids'] ) ||
			'0' !== (string) ( $settings['include_homepage'] ?? '0' );

		if ( ! $needs_repair ) {
			return;
		}

		$settings['enabled']          = '1';
		$settings['display_mode']     = 'all';
		$settings['page_ids']         = array();
		$settings['include_homepage'] = '0';

		update_option( 'matewa_widget_settings', $settings, false );

		if ( function_exists( 'wp_cache_flush' ) ) {
			wp_cache_flush();
		}
	},
	20
);
