<?php

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

class AIEO_Server_Events {

	const PRUNE_HOOK     = 'aieo_server_events_log_prune';
	const SWEEP_HOOK     = 'aieo_server_events_sweep';
	const RETENTION_DAYS = 30;
	const SWEEP_DAYS     = 3;

	
	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		$dir = __DIR__ . '/';
		require_once $dir . 'sql/server-events-schema.php';
		require_once $dir . 'aieo-server-dispatch.php';
		require_once $dir . 'class-aieo-pii-hasher.php';
		require_once $dir . 'class-aieo-capi-sender.php';
		require_once $dir . 'class-aieo-ga4-sender.php';
		require_once $dir . 'class-aieo-pixel-display.php';
		require_once $dir . 'class-aieo-google-tag.php';
		require_once $dir . 'class-aieo-google-ads-ec-sender.php';
		require_once $dir . 'class-aieo-tiktok-events-sender.php';
		require_once $dir . 'class-aieo-tiktok-pixel-display.php';

		
		
		add_action( 'admin_init', array( $this, 'maybe_install' ) );

		
		
		
		add_action( self::PRUNE_HOOK, array( $this, 'prune_log' ) );
		if ( ! wp_next_scheduled( self::PRUNE_HOOK ) ) {
			wp_schedule_event( time() + DAY_IN_SECONDS, 'daily', self::PRUNE_HOOK );
		}

		
		
		
		
		add_action( self::SWEEP_HOOK, array( $this, 'sweep_missing_sends' ) );
		if ( ! wp_next_scheduled( self::SWEEP_HOOK ) ) {
			wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::SWEEP_HOOK );
		}

		
		
		
		
		
		
		add_action( 'plugins_loaded', array( $this, 'register' ), 20 );
	}

	
	public function register() {
		
		
		
		if ( ! defined( 'AIEO_RUNTIME_OWNS_AJAX' ) ) {
			AIEO_CAPI_Sender::instance()->register_hooks();
			AIEO_GA4_Sender::instance()->register_hooks();
			AIEO_TikTok_Events_Sender::instance()->register_hooks();
		}

		
		
		if ( ! defined( 'AIEO_RUNTIME_OWNS_PIXEL' ) ) {
			AIEO_Pixel_Display::instance()->register_display();
			AIEO_TikTok_Pixel_Display::instance()->register_display();
			
			
			AIEO_Google_Tag::instance()->register();
		}

		
		
		
		AIEO_Google_Ads_EC_Sender::instance()->register_hooks();
	}

	
	public function maybe_install() {
		global $wpdb;
		if ( ! function_exists( 'aieo_server_events_log_table' ) ) {
			return;
		}
		$t = aieo_server_events_log_table();
		if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) {
			aieo_server_events_log_create_table();
		}
	}

	
	public function prune_log() {
		global $wpdb;
		if ( ! function_exists( 'aieo_server_events_log_table' ) ) {
			return;
		}
		$t = aieo_server_events_log_table();
		if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) {
			return;
		}
		$cutoff = gmdate( 'Y-m-d H:i:s', time() - ( self::RETENTION_DAYS * DAY_IN_SECONDS ) );
		$wpdb->query( $wpdb->prepare( "DELETE FROM {$t} WHERE created_at < %s", $cutoff ) );
	}

	
	public function sweep_missing_sends() {
		if ( ! function_exists( 'wc_get_orders' ) ) {
			return;
		}
		$config = ( class_exists( 'AIEO_DMM_Conversions' ) && method_exists( 'AIEO_DMM_Conversions', 'get_config' ) )
			? AIEO_DMM_Conversions::get_config()
			: (array) get_option( 'aieo_dmm_conversions', array() );

		$fb_on = isset( $config['fb_mode'] ) && in_array( $config['fb_mode'], array( 'capi', 'both' ), true ) && class_exists( 'AIEO_CAPI_Sender' );
		$ga_on = isset( $config['ga_source'] ) && 'aieo' === $config['ga_source']
			&& isset( $config['ga_send_server'] ) && 'yes' === $config['ga_send_server'] && class_exists( 'AIEO_GA4_Sender' );
		
		
		
		$reconcile = class_exists( 'AIEO_Attribution' ) && method_exists( 'AIEO_Attribution', 'reconcile_session_from_order' );
		if ( ! $fb_on && ! $ga_on && ! $reconcile ) {
			return;
		}

		$orders = wc_get_orders( array(
			'limit'        => 200,
			'type'         => 'shop_order',
			'status'       => array( 'processing', 'completed' ),
			'date_created' => '>=' . ( time() - self::SWEEP_DAYS * DAY_IN_SECONDS ),
			'return'       => 'ids',
			'orderby'      => 'date',
			'order'        => 'DESC',
		) );
		foreach ( (array) $orders as $oid ) {
			$order = wc_get_order( $oid );
			if ( ! $order ) {
				continue;
			}
			
			$src = strtolower( (string) $order->get_meta( '_wc_order_attribution_utm_source' ) . '|' . (string) $order->get_meta( '_wc_order_attribution_utm_medium' ) );
			if ( preg_match( '/skroutz|shopflix|bestprice|marketplace/', $src ) ) {
				continue;
			}
			
			if ( $reconcile ) {
				AIEO_Attribution::reconcile_session_from_order( (int) $oid );
			}
			if ( $fb_on && ! $order->get_meta( AIEO_CAPI_Sender::SENT_META ) ) {
				AIEO_CAPI_Sender::instance()->maybe_send( (int) $oid );
			}
			if ( $ga_on && ! $order->get_meta( AIEO_GA4_Sender::SENT_META ) ) {
				AIEO_GA4_Sender::instance()->maybe_send( (int) $oid );
			}
		}
	}
}
