<?php

namespace StoreEngine\Addons\Razorpay;

use StoreEngine\Classes\AbstractAjaxHandler;
use StoreEngine\Utils\Helper;

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

class Ajax extends AbstractAjaxHandler {

	public static function init() {
		$self = new self();
		$self->dispatch_actions();
	}

	public function __construct() {
		$this->actions = [
			'payment_method/razorpay/save_payment_id' => [
				'callback'             => [ $this, 'save_payment_id' ],
				'allow_visitor_action' => true,
				'fields'               => [
					'razorpay_payment_id' => 'string',
					'order_id'            => 'integer',
				],
			],
		];
	}

	public function save_payment_id( array $payload ) {
		if ( empty( $payload['razorpay_payment_id'] ) ) {
			wp_send_json_error( __( 'Payment Id is required.', 'storeengine' ) );
		}

		if ( empty( $payload['order_id'] ) ) {
			$order = Helper::get_recent_draft_order();
		} else {
			$order = Helper::get_order( $payload['order_id'] );
		}

		if ( is_wp_error( $order ) ) {
			wp_send_json_error( __( 'Order not found!', 'storeengine' ) );
		}

		// verify payments.
		$razorpay_payment = RazorpayService::init()->get_payment( $payload['razorpay_payment_id'] );
		if ( is_wp_error( $razorpay_payment ) ) {
			wp_send_json_error( $razorpay_payment );
		}

		$order->set_transaction_id( $razorpay_payment['id'] );
		$order->update_meta_data( '_razorpay_payment_id', $razorpay_payment['id'] );
		$order->update_meta_data( '_razorpay_payment_method', $razorpay_payment['method'] );
		$order->save();

		wp_send_json_success( [
			'success' => true,
		] );
	}
}
