<?php
/**
 * WooCommerce conversion bridge for traffic attribution.
 *
 * @package Niwa_AI
 */

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

class Niwa_AI_Traffic_Conversion_Tracker {

	const ORDER_SESSION_META = '_niwa_ai_traffic_session';
	const ORDER_ATTR_META    = '_niwa_ai_traffic_attribution';
	const ORDER_RECORDED     = '_niwa_ai_traffic_conversion_recorded';

	public function __construct(
		private readonly Niwa_AI_Traffic_Repository $repository
	) {}

	public function register_hooks(): void {
		add_action( 'woocommerce_checkout_create_order', array( $this, 'capture_order_attribution' ), 20, 2 );
		add_action( 'woocommerce_order_status_processing', array( $this, 'record_order_conversion' ), 20, 1 );
		add_action( 'woocommerce_order_status_completed', array( $this, 'record_order_conversion' ), 20, 1 );
		add_action( 'woocommerce_order_status_on-hold', array( $this, 'record_order_conversion' ), 20, 1 );
		add_action( 'woocommerce_order_status_refunded', array( $this, 'record_order_conversion' ), 20, 1 );
		add_action( 'woocommerce_order_status_cancelled', array( $this, 'record_order_conversion' ), 20, 1 );
		add_action( 'woocommerce_order_status_failed', array( $this, 'record_order_conversion' ), 20, 1 );
	}

	public function capture_order_attribution( $order, $data = array() ): void {
		unset( $data );
		if ( ! is_object( $order ) || ! method_exists( $order, 'update_meta_data' ) ) {
			return;
		}

		$public_session = isset( $_COOKIE[ Niwa_AI_Traffic_Attribution::SESSION_COOKIE ] )
			? sanitize_text_field( wp_unslash( $_COOKIE[ Niwa_AI_Traffic_Attribution::SESSION_COOKIE ] ) )
			: '';
		$verified_session = Niwa_AI_Session_Utils::resolve_verified_session( false );
		$session          = Niwa_AI_Session_Utils::bind_public_id( 'traffic', $public_session, $verified_session );
		if ( '' !== $session ) {
			$order->update_meta_data( self::ORDER_SESSION_META, substr( $session, 0, 96 ) );
		}

		$attr = Niwa_AI_Traffic_Attribution::attribution_from_cookie();
		if ( ! empty( $attr ) ) {
			$order->update_meta_data( self::ORDER_ATTR_META, wp_json_encode( $attr ) );
		}
	}

	public function record_order_conversion( $order_id ): void {
		$order = function_exists( 'wc_get_order' ) ? wc_get_order( $order_id ) : false;
		if ( ! $order || ! is_object( $order ) ) {
			return;
		}
		$status       = method_exists( $order, 'get_status' ) ? (string) $order->get_status() : '';
		$final_update = in_array( $status, array( 'cancelled', 'refunded', 'failed' ), true );
		if ( method_exists( $order, 'get_meta' ) && $order->get_meta( self::ORDER_RECORDED, true ) && ! $final_update ) {
			return;
		}

		if ( $this->repository->record_order_conversion( $order ) && method_exists( $order, 'update_meta_data' ) ) {
			$order->update_meta_data( self::ORDER_RECORDED, current_time( 'mysql' ) );
			if ( method_exists( $order, 'save' ) ) {
				$order->save();
			}
		}
	}
}
