<?php
/**
 * WooCommerce Integration Class
 *
 * @package FunnelKit_Square
 */

namespace FKWCSQ\Includes\Integrations;

use FKWCSQ\Includes\Modules\Payment\Gateways\Card;
use FKWCSQ\Includes\Webhooks\Webhook_Handler;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

/**
 * FKWCSQ_WooCommerce Class
 */
class WooCommerce {

	/**
	 * Initialize the integration
	 */
	public static function init() {

		// Add Square as a payment gateway
		add_filter( 'woocommerce_payment_gateways', array( __CLASS__, 'add_payment_gateway' ) );

		add_action( 'woocommerce_order_item_add_action_buttons', array( __CLASS__, 'add_capture_button' ), 10, 1 );
		add_action( 'wp_ajax_fkwcsq_capture_payment', array( __CLASS__, 'ajax_capture_payment' ) );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'register_admin_scripts' ), 11 );
		if ( is_admin() ) {
			WC_Settings::init();
		}
		Webhook_Handler::init();
		self::upsell();
	}
	/**
	 * Register admin scripts
	 */
	public static function register_admin_scripts() {

		wp_add_inline_script(
			'wc-admin-meta-boxes',
			'jQuery(document).ready(function($) {
				$(".capture-square-payment").on("click", function(e) {
					e.preventDefault();
					var $button = $(this);

					if (!confirm("' . esc_js( __( 'Are you sure you want to capture this payment?', 'funnelkit-payment-gateway-square-for-woocommerce' ) ) . '")) {
						return;
					}

					$button.prop("disabled", true);

					$.ajax({
						url: ajaxurl,
						type: "POST",
						data: {
							action: "fkwcsq_capture_payment",
							order_id: $button.data("order"),
							nonce: $button.data("nonce")
						},
						success: function(response) {
							if (response.success) {
								window.location.reload();
							} else {
								alert(response.data.message);
								$button.prop("disabled", false);
							}
						}
					});
				});
			});'
		);
	}
	/**
	 * Check compatibility with required FunnelKit plugins.
	 *
	 * This function verifies that FunnelKit Pro is active before allowing
	 * the Square integration to function. It checks both regular and network-wide
	 * activated plugins in multisite installations.
	 *
	 * @return boolean True if dependencies are met, false otherwise.
	 * @since 1.0.0
	 */
	public static function wfocu_square_compatibility_dependency() {
		$active_plugins = (array) get_option( 'active_plugins', array() );
		if ( is_multisite() ) {
			$active_plugins = array_merge( $active_plugins, get_site_option( 'active_sitewide_plugins', array() ) );
		}

		if ( ! ( in_array( 'funnel-builder-pro/funnel-builder-pro.php', $active_plugins, true ) || array_key_exists( 'funnel-builder-pro/funnel-builder-pro.php', $active_plugins ) ) ) {
			return false;
		}

		return true;
	}
	/**
	 * Initialize Square upsell functionality.
	 *
	 * Sets up the Square payment gateway integration with FunnelKit upsells.
	 * Registers necessary hooks for payment processing and adds Square to supported
	 * gateways list. If dependencies are not met, displays an admin notice.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function upsell() {

		if ( self::wfocu_square_compatibility_dependency() ) {

			\FKWCSQ\Includes\Modules\Payment\Upsell\Card::get_instance();
			add_action( 'wc_ajax_wfocu_front_handle_fkwcsq_square_payments', '\FKWCSQ\Includes\Modules\Payment\Upsell\Card::process_client_payment' );

			add_filter( 'wfocu_subscriptions_get_supported_gateways', array( __CLASS__, 'wfocu_subscriptions_get_supported_gateways' ) );
			add_filter( 'wfocu_wc_get_supported_gateways', array( __CLASS__, 'wfocu_wc_get_supported_gateways' ) );

			return;
		}
	}
	/**
	 * Add Square gateway to supported subscription gateways.
	 *
	 * @since 1.0.0
	 * @param array $gateways Array of supported gateways.
	 * @return array Modified array of supported gateways.
	 */
	public static function wfocu_subscriptions_get_supported_gateways( $gateways ) {
		$gateways[] = 'fkwcsq_square';
		return $gateways;
	}
	/**
	 * Add Square gateway to supported WooCommerce gateways.
	 *
	 * @since 1.0.0
	 * @param array $gateways Array of supported gateways.
	 * @return array Modified array of supported gateways.
	 */
	public static function wfocu_wc_get_supported_gateways( $gateways ) {
		$gateways['fkwcsq_square'] = '\FKWCSQ\Includes\Modules\Payment\Upsell\Card';
		return $gateways;
	}

	/**
	 * Handle AJAX request to get saved payment token.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function ajax_get_saved_payment_token() {
		Card::get_instance()->ajax_get_saved_payment_token();
	}

	/**
	 * Add Square payment gateway
	 *
	 * @param array $gateways Available payment gateways
	 *
	 * @return array Modified payment gateways
	 */
	public static function add_payment_gateway( $gateways ) {
		$gateways[] = '\FKWCSQ\Includes\Modules\Payment\Gateways\Card';
		$gateways[] = '\FKWCSQ\Includes\Modules\Payment\Gateways\Google_Pay';
		$gateways[] = '\FKWCSQ\Includes\Modules\Payment\Gateways\Apple_Pay';
		$gateways[] = '\FKWCSQ\Includes\Modules\Payment\Gateways\Cash_App';
		$gateways[] = '\FKWCSQ\Includes\Modules\Payment\Gateways\ACH';
		$gateways[] = '\FKWCSQ\Includes\Modules\Payment\Gateways\Afterpay';
		$gateways[] = '\FKWCSQ\Includes\Modules\Payment\Gateways\Gift_Card';
		return $gateways;
	}

	/**
	 * Add capture button to order actions.
	 *
	 * @since 1.0.0
	 * @param \WC_Order $order WooCommerce order object.
	 * @return void
	 */
	public static function add_capture_button( $order ) {
		if ( $order->get_payment_method() !== 'fkwcsq_square' ) {
			return;
		}

		// Check if payment needs capture
		$payment_status = $order->get_meta( '_square_payment_status' );
		if ( $payment_status !== 'APPROVED' ) {
			return;
		}

		?>

		<button type="button"
				class="button capture-square-payment"
				data-order="<?php echo esc_attr( $order->get_id() ); ?>"
				data-nonce="<?php echo esc_attr( wp_create_nonce( 'fkwcsq_capture_payment' ) ); ?>">
			<?php esc_html_e( 'Capture Square Payment', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?>
		</button>

		<?php
	}

	/**
	 * Handle AJAX payment capture request.
	 *
	 * Validates the request, checks permissions, and processes
	 * the payment capture through the Square gateway.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function ajax_capture_payment() {
		check_ajax_referer( 'fkwcsq_capture_payment', 'nonce' );

		// Check user permissions
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission to perform this action.', 'funnelkit-payment-gateway-square-for-woocommerce' ) ) );
		}

		$order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;
		if ( ! $order_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid order.', 'funnelkit-payment-gateway-square-for-woocommerce' ) ) );
		}

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			wp_send_json_error( array( 'message' => __( 'Order not found.', 'funnelkit-payment-gateway-square-for-woocommerce' ) ) );
		}

		$gateway = new Card();
		$result  = $gateway->capture_payment( $order );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success();
	}
}

