<?php
/**
 * Ajax handler for removing applied coupon.
 *
 * @since 2.5.12
 */

namespace Masteriyo\Addons\Coupons;

defined( 'ABSPATH' ) || exit;


use Masteriyo\Abstracts\AjaxHandler;
use Masteriyo\Notice;

class RemoveAppliedCouponAjaxHandler extends AjaxHandler {

	/**
	 * Checkout ajax action.
	 *
	 * @since 2.5.12
	 *
	 * @var string
	 */
	public $action = 'masteriyo_remove_applied_coupon';

	/**
	 * Process checkout ajax request.
	 *
	 * @since 2.5.12
	 */
	public function register() {
		add_action( "wp_ajax_{$this->action}", array( $this, 'remove_applied_coupon' ) );
		add_action( "wp_ajax_nopriv_{$this->action}", array( $this, 'remove_applied_coupon' ) );
	}

	/**
	 * Apply coupon.
	 *
	 * @since 2.5.12
	 */
	public function remove_applied_coupon() {
		try {
			// Bail early if there no nonce.
			if ( ! isset( $_POST['_wpnonce'] ) ) {
				throw new \Exception( __( 'Nonce is required.', 'learning-management-system' ) );
			}

			if ( ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['_wpnonce'] ) ), 'masteriyo_remove_applied_coupon' ) ) {
				throw new \Exception( __( 'Invalid nonce. Maybe you should reload the page.', 'learning-management-system' ) );
			}

			$coupon_code = sanitize_text_field( trim( $_POST['coupon'] ) );
			$coupon_code = masteriyo_format_coupon_code( $coupon_code );
			$coupon      = masteriyo_get_coupon_by_code( $coupon_code );
			$coupons     = masteriyo_coupons();

			if ( ! is_object( $coupon ) ) {
				throw new \Exception( __( 'Invalid coupon.', 'learning-management-system' ) );
			}

			if ( ! $coupons->remove_coupon( $coupon->get_code() ) ) {
				throw new \Exception( __( 'Applied coupon could not be removed!', 'learning-management-system' ) );
			}

			$this->send_success_response();
		} catch ( \Exception $e ) {
			masteriyo_add_notice( $e->getMessage(), Notice::ERROR );
			$this->send_failure_response();
		}
	}

	/**
	 * If the AJAX operation failed, send failure response.
	 *
	 * @since 2.5.12
	 */
	protected function send_success_response() {
		// Bail early if not ajax.
		if ( ! masteriyo_is_ajax() ) {
			return;
		}

		// Only print notices if not reloading the checkout, otherwise they're lost in the page reload.
		$messages = masteriyo_display_all_notices( true );

		$response = array(
			'messages'  => isset( $messages ) ? $messages : '',
			'fragments' => masteriyo_get_checkout_fragments(),
		);

		wp_send_json_success( $response );
	}

	/**
	 * If the AJAX operation failed, send failure response.
	 *
	 * @since 2.5.12
	 */
	protected function send_failure_response() {
		// Bail early if not ajax.
		if ( ! masteriyo_is_ajax() ) {
			return;
		}

		// Only print notices if not reloading the checkout, otherwise they're lost in the page reload.
		$messages = masteriyo_display_all_notices( true );

		$response = array(
			'messages' => isset( $messages ) ? $messages : '',
		);

		wp_send_json_error( $response, 400 );
	}
}
