<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class WOO_Klaviyo_TS4WC {

	/**
	 * Instance of this class.
	 *
	 * @var object Class Instance
	 */
	private static $instance;

	/**
	 * Initialize the main plugin function
	*/
	public function __construct() {
		$this->init();
	}
	
	/**
	 * Get the class instance
	 *
	 * @return WOO_Klaviyo_TS4WC
	*/
	public static function get_instance() {

		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/*
	* init from parent mail class
	*/
	public function init() {
		add_action( 'trackship_shipment_status_trigger', array( $this, 'ts_status_change_callback'), 10, 4 );
	}
	
	/**
	 * Schedule action callback for integrately_callback
	 */
	public function ts_status_change_callback( $order_id, $old_status, $new_status, $tracking_number ) {

		if ( !get_trackship_settings( 'klaviyo', '') ) {
			return;
		}

		$klaviyo_settings = get_option('klaviyo_settings');
		$api_key = isset($klaviyo_settings['klaviyo_public_api_key']) ? $klaviyo_settings['klaviyo_public_api_key'] : '';

		$logger = wc_get_logger();
		if ( !$api_key ) {
			$logger->warning( 'Klaviyo API key not found. Please configure it in Klaviyo settings.', array( 'source' => 'trackship-klaviyo-response' ) );
			return;
		}

		// API execution url
		$url = 'https://a.klaviyo.com/client/events/?company_id=' . $api_key;

		$row = trackship_for_woocommerce()->actions->get_shipment_row( $order_id , $tracking_number );

		$order = wc_get_order( $order_id );
		$phone = $order ? $order->get_billing_phone() : '';
		$items = $order ? $order->get_items() : [];

		$products = array();
		foreach ( $items as $item_id => $item ) {
			
			$variation_id = $item->get_variation_id();
			$product_id = $item->get_product_id();
			
			if ( 0 != $variation_id ) {
				$product_id = $variation_id;
			}
			
			$products[$item_id] = array(
				'item_id' => $item_id,
				'product_id' => $product_id,
				'product_name' => $item->get_name(),
				'product_qty' => $item->get_quantity(),
				'items_total_price' => $item->get_total(),
				'item_unit_price' => $item->get_subtotal() / $item->get_quantity(),
				'product_image' => get_the_post_thumbnail_url( $product_id, 'thumbnail' ),
			);
		}
		$products_array = trackship_for_woocommerce()->front->tracking_widget_product_array_callback ( $products, $order_id, [], '', $tracking_number );

		$body = array(
			'data' => array(
				'type' => 'event',
				'attributes' => array(
					'properties' => array(
						'order_id'						=> $order_id,
						'order_number'					=> $order ? $order->get_order_number() : $order_id,
						'tracking_number'				=> $tracking_number,
						'tracking_provider'				=> $row->shipping_provider,
						'tracking_event_status'			=> $row->shipment_status,
						'tracking_event_status_label'	=> apply_filters('trackship_status_filter', $row->shipment_status ),
						'tracking_est_delivery_date'	=> $row->est_delivery_date,
						'tracking_link'					=> trackship_for_woocommerce()->actions->get_tracking_page_link( $order_id, $tracking_number ),
						'latest_event' 					=> $row->last_event,
						'origin_country'				=> $row->origin_country,
						'destination_country'			=> $row->destination_country,
						'delivery_number'				=> $row->delivery_number,
						'delivery_provider'				=> $row->delivery_provider,
						'shipping_service'				=> $row->shipping_service,
						'last_event_time'				=> $row->last_event_time,
						'products'						=> array_values($products_array),
						'order_status'					=> $order->get_status(),
					),
					'metric' => array(
						'data' => array(
							'type' => 'metric',
							'attributes' => array(
								'name' => 'TrackShip Shipments events',
							)
						)
					),
					'profile' => array(
						'data' => array(
							'type' => 'profile',
							'attributes' => array(
								'email'			=> $order ? $order->get_billing_email() : '',
								'phone_number'	=> trackship_for_woocommerce()->actions->get_formated_number($phone, $order),
								'first_name'	=> $order ? $order->get_billing_first_name() : '',
								'last_name'		=> $order ? $order->get_billing_last_name() : '',
								'location'		=> array(
									'address1'		=> $order ? $order->get_billing_address_1() : '',
									'address2'		=> $order ? $order->get_billing_address_2() : '',
									'city'			=> $order ? $order->get_billing_city() : '',
									'country'		=> $order ? $order->get_billing_country() : '',
									'region'		=> $order ? $order->get_billing_state() : '',
									'zip'			=> $order ? $order->get_billing_postcode() : '',
								),
							)
						)
					),
				)
			)
		);

		if ( apply_filters( 'exclude_klaviyo_phone', false ) ) {
			unset( $body['data']['attributes']['profile']['data']['attributes']['phone_number'] );
		}

		// Add requirements header parameters in below array
		$args = array(
			'body'		=> wp_json_encode($body),
			'headers'	=> array(
				'accept'		=> 'application/json',
				'Content-Type'	=> 'application/json',
				'revision'		=> '2026-01-15',
			),
		);

		// Example API call on integrately
		$response = wp_remote_post( $url, $args );

		$content = print_r($response, true);
		$context = array( 'source' => 'trackship-klaviyo-response' );
		$logger->info( "Response \n" . $content . "\n", $context );

	}
}
