<?php
/**
 * Trait for shared Abandoned Cart logic.
 *
 * @package automation-web-platform
 */

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

/**
 * Trait WAWP_Abandoned_Cart_Helper_Trait.
 */
trait WAWP_Abandoned_Cart_Helper_Trait {

	/**
	 * Get the current cart session ID from session or cookie.
	 *
	 * @return string|null
	 */
	protected function get_cart_session_id() {
		$session_id = null;

		// 1. Try PHP Session
		if ( ! empty( $_SESSION['wac_session'] ) ) {
			$session_id = sanitize_text_field( wp_unslash( $_SESSION['wac_session'] ) );
		}

		// 2. Try Cookie fallback
		if ( ! $session_id && ! empty( $_COOKIE['wac_session'] ) ) {
			$session_id = sanitize_text_field( wp_unslash( $_COOKIE['wac_session'] ) );
		}

		return $session_id;
	}

	/**
	 * Centralized logic to update cart status.
	 *
	 * @param string $session_id Session ID.
	 * @param string $status     Status string.
	 * @return bool
	 */
	protected function update_cart_status_logic( $session_id, $status ) {
		if ( ! $session_id || ! $status ) {
			return false;
		}

		if ( method_exists( $this, 'insert_or_update' ) ) {
			$this->insert_or_update( $session_id, get_current_user_id(), '', '', '', 0.0, $status );
			return true;
		}

		return false;
	}

	/**
	 * Centralized logic to capture billing fields.
	 *
	 * @param string $session_id Session ID.
	 * @param array  $data       Input data.
	 * @return array Sanitized billing data.
	 */
	public function capture_billing_logic( $session_id, $data ) {
		$billing_data = array();
		foreach ( $data as $key => $value ) {
			if ( 0 === strpos( $key, 'billing_' ) ) {
				$val = sanitize_text_field( trim( $value ) );
				if ( 'billing_phone' === $key && method_exists( $this, 'get_digits_only' ) ) {
					$val = $this->get_digits_only( $val );
				}
				$billing_data[ $key ] = $val;
			}
		}

		if ( ! empty( $billing_data['billing_phone'] ) ) {
			$carrier = null;
			if ( method_exists( $this, 'get_cart_session_id' ) ) {
				global $wpdb;
				$table   = $wpdb->prefix . 'wawp_abandoned_carts';
				$row     = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT contact_details FROM %i WHERE session_id = %s ORDER BY id DESC LIMIT 1', $table, $session_id ), 'wac_session_contact_' . md5( (string) $session_id ), 'wawp_abandoned_carts', 300 );
				$row_arr = ! empty( $row ) ? (array) $row[0] : null;
				if ( $row_arr ) {
					$existing_contact = maybe_unserialize( $row_arr['contact_details'] );
					if ( is_array( $existing_contact ) && ! empty( $existing_contact['billing_phone'] ) && $this->get_digits_only( $existing_contact['billing_phone'] ) === $billing_data['billing_phone'] && ! empty( $existing_contact['billing_carrier'] ) ) {
						$carrier = $existing_contact['billing_carrier'];
					}
				}
			}

			if ( ! $carrier && method_exists( $this, 'lookup_phone_carrier' ) ) {
				$carrier = $this->lookup_phone_carrier( $billing_data['billing_phone'] );
			}

			if ( $carrier ) {
				$billing_data['billing_carrier'] = $carrier;
			}
		}

		if ( ! empty( $billing_data ) && $session_id && method_exists( $this, 'insert_or_update' ) ) {
			$this->insert_or_update( $session_id, get_current_user_id(), maybe_serialize( $billing_data ), '', '', 0.0, '' );

			// Record history event for contact info submission.
			if ( method_exists( $this, 'add_history_event' ) ) {
				$this->add_history_event(
					'contact_info',
					array(
						'phone' => $billing_data['billing_phone'] ?? '',
						'email' => $billing_data['billing_email'] ?? '',
					)
				);
			}
		}

		return $billing_data;
	}
	/**
	 * Get a map of order IDs to their total amounts.
	 *
	 * @param array $order_ids List of order IDs.
	 * @return array Map of order ID => total amount.
	 */
	public function get_order_totals_map( $order_ids ) {
		if ( empty( $order_ids ) ) {
			return array();
		}

		$order_ids = array_unique( array_filter( array_map( 'intval', $order_ids ) ) );
		if ( empty( $order_ids ) ) {
			return array();
		}

		$totals_map = array();
		foreach ( $order_ids as $order_id ) {
			$order = function_exists( 'wc_get_order' ) ? wc_get_order( $order_id ) : null;
			if ( $order ) {
				$totals_map[ $order_id ] = (float) $order->get_total();
			}
		}

		return $totals_map;
	}
}
