<?php
/**
 * Abandoned Cart Triggers Trait.
 *
 * @package automation-web-platform
 */

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

/**
 * Trait WAWP_Abandoned_Cart_Triggers.
 */
trait WAWP_Abandoned_Cart_Triggers {

	/**
	 * Handle abandoned cart trigger.
	 *
	 * @param int    $cart_id Cart ID.
	 * @param string $type    Trigger type (abandoned_cart, potential_customer, or shopping).
	 */
	public function handle_abandoned_cart_trigger( $cart_id, $type ) {
		global $wpdb;
		$table = $wpdb->prefix . 'wawp_abandoned_carts';

		$results = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $cart_id ), 'wac_trigger_cart_' . $cart_id, 'wawp_ac', 60 );
		$cart    = ! empty( $results ) ? (object) $results[0] : null;

		if ( ! $cart || 'purchased' === $cart->status ) {
			return;
		}

		$contact_details = maybe_unserialize( $cart->contact_details );
		$phone           = $contact_details['billing_phone'] ?? null;
		$email           = $contact_details['billing_email'] ?? null;

		if ( ! $phone && ! $email ) {
			return;
		}

		$settings        = $this->get_settings();
		$matches         = $this->get_matching_rules( $settings, get_locale(), $type );
		$notif_settings  = WAWP()->get_wawp_setting( 'wawp_abandoned_cart_notifications_settings', array() );
		$coupon_settings = isset( $notif_settings['coupon_settings'] ) ? $notif_settings['coupon_settings'] : array();
		$coupon_code     = $cart->coupon_code ?? '';
		if ( ! empty( $coupon_settings['enable'] ) && empty( $coupon_code ) && class_exists( 'WAWP_Abandoned_Cart_Notifications' ) ) {
			$coupon_code = WAWP_Abandoned_Cart_Notifications::get_instance()->generate_coupon_code( $cart_id, $coupon_settings );
		}

		if ( empty( $matches ) ) {
			return;
		}

		$recipient = array(
			'phone'   => $phone,
			'email'   => $email,
			'user_id' => $cart->user_id,
		);

		$replacements = array(
			'{{first_name}}'                => $contact_details['billing_first_name'] ?? '',
			'{{last_name}}'                 => $contact_details['billing_last_name'] ?? '',
			'{{name}}'                      => trim( ( $contact_details['billing_first_name'] ?? '' ) . ' ' . ( $contact_details['billing_last_name'] ?? '' ) ) !== '' ? trim( ( $contact_details['billing_first_name'] ?? '' ) . ' ' . ( $contact_details['billing_last_name'] ?? '' ) ) : 'Valued Customer',
			'{{email}}'                     => $email ?? '',
			'{{phone_number}}'              => $phone ?? '',
			'{{billing_address_1}}'         => $contact_details['billing_address_1'] ?? '',
			'{{billing_city}}'              => $contact_details['billing_city'] ?? '',
			'{{billing_postcode}}'          => $contact_details['billing_postcode'] ?? '',
			'{{billing_country}}'           => $contact_details['billing_country'] ?? '',
			'{{cart_total}}'                => function_exists( 'wc_price' ) ? html_entity_decode( wp_strip_all_tags( wc_price( $cart->cart_total ) ), ENT_QUOTES, 'UTF-8' ) : $cart->cart_total,
			'{{coupon_code}}'               => $coupon_code,
			'{{product_in_cart_list}}'      => $this->get_cart_product_list( $cart, false ),
			'{{product_in_cart_list_html}}' => $this->get_cart_product_list( $cart, true ),
			'{{cart_recovery_url}}'         => add_query_arg(
				array(
					'wawp_restore_cart' => 1,
					'wac_id'            => $cart_id,
				),
				home_url( '/' )
			),
			'{{cart_id}}'                   => $cart_id,
			'{{site_title}}'                => get_bloginfo( 'name' ),
			'{{site_url}}'                  => home_url(),
		);

		foreach ( $matches as $rule ) {
			$this->schedule_or_send( $rule, $replacements, $recipient, 'Abandoned Cart Recovery', $cart_id, $type );
		}
	}

	/**
	 * Get product list for cart.
	 *
	 * @param object $cart   Cart object.
	 * @param bool   $is_html Whether to return HTML.
	 * @return string
	 */
	private function get_cart_product_list( $cart, $is_html = false ) {
		$cart_contents = maybe_unserialize( $cart->cart_contents );
		if ( ! is_array( $cart_contents ) ) {
			return '';
		}

		$list = $is_html ? '<ul>' : '';
		foreach ( $cart_contents as $item ) {
			$product = function_exists( 'wc_get_product' ) ? wc_get_product( $item['variation_id'] ? $item['variation_id'] : $item['product_id'] ) : null;
			if ( $product ) {
				$raw_price       = $product->get_price() * $item['quantity'];
				$formatted_price = function_exists( 'wc_price' ) ? wc_price( $raw_price ) : $raw_price;
				$plain_price     = html_entity_decode( wp_strip_all_tags( (string) $formatted_price ), ENT_QUOTES, 'UTF-8' );
				if ( $is_html ) {
					$list .= sprintf( '<li><a href="%s">%s</a> x %d - %s</li>', esc_url( $product->get_permalink() ), esc_html( $product->get_name() ), $item['quantity'], $formatted_price );
				} else {
					$list .= sprintf( "%s x %d - %s\n", $product->get_name(), $item['quantity'], $plain_price );
				}
			}
		}
		$list .= $is_html ? '</ul>' : '';

		return trim( $list );
	}
}
