<?php
/**
 * Ajax Handler for Razorpay Payment Verification.
 *
 * Handles payment verification requests with Razorpay through Ajax.
 * Manages the client-server communication and payment signature validation
 * to securely confirm the payment status.
 *
 * @since 2.7.1
 *
 * @package Masteriyo\Addons\Razorpay\AjaxHandlers
 */

namespace Masteriyo\Addons\Razorpay\AjaxHandlers;

defined( 'ABSPATH' ) || exit;


use Masteriyo\Abstracts\AjaxHandler;
use Masteriyo\Enums\OrderStatus;
use Masteriyo\Exceptions\RestException;
use Razorpay\Api\Api;
use Razorpay\Api\Errors\SignatureVerificationError;

/**
 * Class PaymentSignatureVerification
 *
 * Handles AJAX requests for payment signature verification with Razorpay.
 *
 * @package Masteriyo\Addons\Razorpay\AjaxHandlers
 *
 * @since 2.7.1
 */
class PaymentSignatureVerification extends AjaxHandler {

	/**
	 * The Ajax action for payment signature verification.
	 *
	 * @since 2.7.1
	 *
	 * @var string
	 */
	public $action = 'masteriyo_razorpay_payment_signature_verification';

	/**
	 * Register the AJAX handler for both authenticated and guest users.
	 *
	 * @since 2.7.1
	 */
	public function register() {
		add_action( "wp_ajax_nopriv_{$this->action}", array( $this, 'process' ) );
		add_action( "wp_ajax_{$this->action}", array( $this, 'process' ) );
	}

	/**
	 * Process the AJAX request, verify payment signature, and send JSON response.
	 *
	 * @since 2.7.1
	 *
	 * @throws RestException If request parameters are invalid.
	 *
	 * @return void Sends JSON response using wp_send_json_success() or wp_send_json_error().
	 */
	public function process() {
		masteriyo_get_logger()->info( 'Razorpay payment verification started.', array( 'source' => 'payment-razorpay' ) );

		if ( ! isset( $_POST['nonce'] ) ) {
			masteriyo_get_logger()->error( 'Nonce is required.', array( 'source' => 'payment-razorpay' ) );
			wp_send_json_error(
				array(
					'message' => __( 'Nonce is required.', 'learning-management-system' ),
				),
				400
			);
			return;
		}

		try {
			if ( ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'masteriyo-process-checkout-nonce' ) ) {
				masteriyo_get_logger()->error( 'Invalid nonce. Maybe you should reload the page.', array( 'source' => 'payment-razorpay' ) );
				throw new \Exception( __( 'Invalid nonce. Maybe you should reload the page.', 'learning-management-system' ) );
			}

			if ( ! isset( $_POST['payment_id'] ) && ! isset( $_POST['order_id'] ) && ! isset( $_POST['signature'] ) && ! isset( $_POST['masteriyo_order_id'] ) ) {
				masteriyo_get_logger()->error( 'Invalid request parameters!', array( 'source' => 'payment-razorpay' ) );
				throw new RestException( 'masteriyo_invalid_action', __( 'Invalid request parameters!', 'learning-management-system' ) );
			}

			$payment_id         = sanitize_text_field( $_POST['payment_id'] );
			$order_id           = sanitize_text_field( $_POST['order_id'] );
			$signature          = sanitize_text_field( $_POST['signature'] );
			$masteriyo_order_id = absint( $_POST['masteriyo_order_id'] );

			list($key, $secret) = masteriyo_razorpay_get_key_secret();

			try {
				$api = new Api( $key, $secret );

				$attributes = array(
					'razorpay_order_id'   => $order_id,
					'razorpay_payment_id' => $payment_id,
					'razorpay_signature'  => $signature,
				);

				$api->utility->verifyPaymentSignature( $attributes );

				$order = masteriyo_get_order( $masteriyo_order_id );

				if ( ! is_wp_error( $order ) && ! is_null( $order ) ) {
					$order->set_transaction_id( $payment_id );
					$order->set_status( OrderStatus::COMPLETED );
					$order->save();
				}
				masteriyo_get_logger()->info( 'Razorpay payment verification completed.', array( 'source' => 'payment-razorpay' ) );
				masteriyo_get_logger()->info( 'Razorpay payment ID : ' . $payment_id, array( 'source' => 'payment-razorpay' ) );
				wp_send_json_success();
			} catch ( SignatureVerificationError $e ) {
				masteriyo_get_logger()->error( $e->getMessage(), array( 'source' => 'payment-razorpay' ) );
				wp_send_json_error(
					array(
						'message' => $e->getMessage(),
					),
					400
				);
			}
		} catch ( \Exception $e ) {
			masteriyo_get_logger()->error( $e->getMessage(), array( 'source' => 'payment-razorpay' ) );
			wp_send_json_error(
				array(
					'message' => $e->getMessage(),
				),
				400
			);
		}
	}
}
