<?php
/**
 * Base Tracking
 *
 * @link       https://personalizewp.com/
 * @since      3.2.0 Merged into PWP
 * @since      1.0.0
 *
 * @package    PersonalizeWP
 * @subpackage PersonalizeWP/Tracking
 */

namespace PersonalizeWP\Tracking;

use PersonalizeWP\Pro\Pro;

defined( 'ABSPATH' ) || exit; // Exit if accessed directly.

/**
 * Tracking Base
 *
 * What all other Tracking classes extend
 */
abstract class Base {

	/**
	 * Should tracking store personal information.
	 *
	 * @var bool
	 */
	protected $anonymise_profiles = false;

	/**
	 * Should anonymouse profiles be tracked.
	 *
	 * @since 3.2.0
	 *
	 * @var bool
	 */
	protected $track_anonymous = false;

	/**
	 * Class constructor
	 */
	public function __construct() {
		// Ensure all tracking has this available.
		$this->anonymise_profiles = personalizewp()->should_anonymise_profiles();
		$this->track_anonymous    = personalizewp()->should_track_anonymous_users();
	}

	/**
	 * Outputs a hidden input to be populated with JS
	 *
	 * @since 2.2.0
	 *
	 * @return void
	 */
	public function add_hidden_input_field() {

		echo '<input type="hidden" name="_pwp_id" value="pwp_hidden_value">';

		static $script_added = false;

		if ( $script_added ) {
			return;
		}
		$script_added = true;

		add_action( 'wp_footer', array( $this, 'add_input_field_js' ) );
	}

	/**
	 * Returns the known UID that was POST submitted. Checks and ignores default value.
	 *
	 * @since 2.2.0
	 *
	 * @return string
	 */
	protected function get_uid() {

		if ( empty( $_POST['_pwp_id'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
			return '';
		}

		$uid = sanitize_text_field( wp_unslash( $_POST['_pwp_id'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
		// Ensure not default
		if ( 'pwp_hidden_value' === $uid ) {
			return '';
		}

		return $uid;
	}

	/**
	 * Outputs JS to populate any known hidden inputs to be populated with JS, as well as triggering the next tracking activity submission.
	 *
	 * Populate inputs with UID and flags user as maybe known for tracking.
	 * Hooks into DOMContentLoaded fired by browser and when blocks are inserted
	 * as well as custom event in case the PWP user data hasn't been created at the
	 * point this JS initially runs (such as if this is the first page loaded).
	 *
	 * @since 2.2.0
	 *
	 * @return void
	 */
	public function add_input_field_js() {
		?>
<script>
(function(){
const trackPWPUser=()=>{
	let pUsr=localStorage.getItem('pwp_tracked_user')||'';
	if(!pUsr){return;}
	pUsr=JSON.parse(pUsr);
	const qi=document.querySelectorAll('input[name="_pwp_id"][value="pwp_hidden_value"]');
	if(qi && 0<qi.length){ qi.forEach(function(i){i.value=pUsr.id}); }
	const maybeKnown = window?.PersonalizeWP?.tracking?.maybeUserKnown || null;
	if(typeof maybeKnown === "function"){maybeKnown();}
}
document.addEventListener('DOMContentLoaded',trackPWPUser);
document.addEventListener('PWP:userCreation',trackPWPUser);
})();
</script>
		<?php
	}
}
