<?php
defined( 'ABSPATH' ) || exit;

/* ================================================================
   247ChatMate — Opt-In Sync Engine (Production Hardened)
   - Daily WP-Cron sync
   - Sends email, domain, locale, site hash, opt-ins, UA, version
   - Non-blocking, GDPR-safe, silent on error
================================================================ */

define( 'MATEWA_OPTIN_ENDPOINT', 'https://247trademate.pro/matewa/optin.php' );

/* ------------------------------------------------------
   REGISTER DAILY CRON (safe)
------------------------------------------------------ */
add_action(
	'init',
	function () {
		// Never schedule cron inside cron or AJAX.
		if ( wp_doing_ajax() || wp_doing_cron() ) {
			return;
		}

		if ( ! wp_next_scheduled( 'matewa_optin_daily_sync' ) ) {
			wp_schedule_event( time() + 300, 'daily', 'matewa_optin_daily_sync' );
		}
	}
);

add_action( 'matewa_optin_daily_sync', 'matewa_send_optin_payload' );

/* ------------------------------------------------------
   SEND PAYLOAD
------------------------------------------------------ */
function matewa_send_optin_payload() {

	// Prevent more than 1 sync per 24 hours.
	$matewa_last = intval( get_option( 'matewa_optin_last_sent' ) );
	if ( $matewa_last && ( time() - $matewa_last ) < 86400 ) {
		return;
	}

	// Load user email from widget settings.
	$matewa_settings = get_option( 'matewa_widget_settings', array() );
	$matewa_email    = sanitize_email( $matewa_settings['email'] ?? '' );

	if ( ! $matewa_email ) {
		return;
	}

	// Sanitised opt-ins.
	$matewa_updates = get_option( 'matewa_optin_updates', 'no' ) === 'yes' ? 'yes' : 'no';
	$matewa_skool   = get_option( 'matewa_optin_skool', 'no' ) === 'yes' ? 'yes' : 'no';

	// Unique fingerprint.
	$matewa_site_hash = hash( 'sha256', site_url() );

	// User agent (cleaned).
	$matewa_ua = isset( $_SERVER['HTTP_USER_AGENT'] )
		? substr( sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ), 0, 240 )
		: 'unknown';

	// Payload.
	$matewa_body = array(
		'email'     => $matewa_email,
		'updates'   => $matewa_updates,
		'skool'     => $matewa_skool,
		'domain'    => site_url(),
		'locale'    => get_locale(),
		'version'   => MATEWA_VERSION,
		'site_hash' => $matewa_site_hash,
		'ua'        => $matewa_ua,
		'timestamp' => time(),
	);

	// Fire-and-forget request.
	wp_remote_post(
		MATEWA_OPTIN_ENDPOINT,
		array(
			'timeout'  => 1,
			'blocking' => false,
			'body'     => $matewa_body,
		)
	);

	// Mark as synced.
	update_option( 'matewa_optin_last_sent', time() );

	// Log if debug enabled.
	if ( function_exists( 'matewa_debug_log' ) ) {
		matewa_debug_log( "Opt-in sync sent for: $matewa_email" );
	}
}