<?php

namespace Cart\notify\WooCommerce;

defined( 'ABSPATH' ) || exit;

/**
 * WooCommerce runtime integration helper.
 */
class Integration {
	/**
	 * Cart event bridge helper.
	 *
	 * @var CartEvents
	 */
	private $cart_events;

	/**
	 * Initialize integration helpers.
	 *
	 * @param CartEvents|null $cart_events Cart event bridge.
	 */
	public function __construct( CartEvents $cart_events = null ) {
		$this->cart_events = $cart_events ? $cart_events : new CartEvents();
	}

	/**
	 * Check if WooCommerce runtime APIs are currently available.
	 *
	 * @return bool
	 */
	public function is_available() {
		return class_exists( 'WooCommerce' ) && function_exists( 'WC' );
	}

	/**
	 * Build WooCommerce script payload values.
	 *
	 * @return array
	 */
	public function get_script_data() {
		if ( ! $this->is_available() ) {
			return array();
		}

		$raw_ajax_url = '';
		$wc_ajax_url  = '';

		$wc_instance = WC();
		if ( $wc_instance && method_exists( $wc_instance, 'ajax_url' ) ) {
			$raw_ajax_url = $wc_instance->ajax_url();
		}

		if ( class_exists( '\WC_AJAX' ) ) {
			$wc_ajax_url = \WC_AJAX::get_endpoint( '%%endpoint%%' );
		}

		return array(
			'cns_raw_ajax_url' => $raw_ajax_url,
			'wc_ajax_url'      => $wc_ajax_url,
			'server_notice'    => $this->cart_events->consume_pending_notification(),
		);
	}
}
