<?php
/**
 * Authorize.net Gateway Capture Class
 *
 * Handles Capture payments through Authorize.net gateway for WooCommerce.
 *
 * @package    Authorize_Net_Payments_For_Woocommerce
 * @subpackage Authorize_Net_Payments_For_Woocommerce/admin
 * @since      1.0.0
 */

if (! defined('ABSPATH')) {
	exit;
}

use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;

require_once plugin_dir_path(__FILE__) . '../../trait-anet-order-meta.php';
/**
 * Anet_Credit_Card_Api class.
 *
 * Communicates with Authorize.net API.
 */
class Anet_Capture_Api
{
	use Anet_Order_Meta;
	/**
	 * Captures a previously authorized payment for a WooCommerce order.
	 *
	 * @param string $transactionid The transaction ID to capture.
	 * @param int    $order_id      The WooCommerce order ID.
	 *
	 * @return void Sends a JSON response with the capture result.
	 */
	public function capture_previously_authorized_amount($transactionid, $order_id)
	{
		try {
			$order = wc_get_order($order_id);
			if (! $order) {
				wp_send_json_error(array('error_msg' => 'Invalid Order ID.'));
				return;
			}
			if (! $transactionid) {
				wp_send_json_error(array('error_msg' => 'Transaction ID is required.'));
				exit;
			}
			$helper = new Anet_Api_Helper(ANET_PAYMENT_TYPE_CREDIT_CARD);
			$merchant_auth_request = $helper->merchant_authentication_request();
			$order_total = $order->get_total();
			// Now capture the previously authorized amount.
			$transaction_request_type = new AnetAPI\TransactionRequestType();
			$transaction_request_type->setTransactionType('priorAuthCaptureTransaction');
			$transaction_request_type->setAmount($order_total);
			$transaction_request_type->setRefTransId($transactionid);
			$transaction_request_type->setSolution($helper->get_solution_id());
			$request = new AnetAPI\CreateTransactionRequest();
			$request->setMerchantAuthentication($merchant_auth_request);
			$request->setTransactionRequest($transaction_request_type);
			if (isset($order_id)) {
				$request->setRefId($order_id);
			}
			$sanitized_request = Anet_Api_Helper::mask_sensitive_data($request); // Call the mask_sensitive_data function.
			Anet_Setting_Helper::log("\nRequest:\n" . $sanitized_request, ANET_PAYMENT_TYPE_CREDIT_CARD, 'debug');
			$controller = new AnetController\CreateTransactionController($request);
			$response = $controller->executeWithApiResponse($helper->controller_response());
			Anet_Setting_Helper::log("\nResponse:\n" . wp_json_encode($response->getTransactionResponse(), JSON_PRETTY_PRINT) . wp_json_encode($response, JSON_PRETTY_PRINT), ANET_PAYMENT_TYPE_CREDIT_CARD, 'debug');
			$result = [];
			if (null !== $response) {
				if (ANET_SANDBOX_STATUS_AUTHORIZED === $response->getMessages()->getResultCode()) {
					$transaction_response = $response->getTransactionResponse();
					if (null !== $transaction_response && null !== $transaction_response->getMessages()) {
						$result['status'] = 'success';
						$result['response_code'] = $transaction_response->getResponseCode();
						$result['trans_id'] = $transaction_response->getRefTransId();
						$result['capture_trans_id'] = $transaction_response->getTransId();
						$result['code'] = $transaction_response->getMessages()[0]->getCode();
						$result['description'] = $transaction_response->getMessages()[0]->getDescription();
						$result['amount'] = $order_total;
						$this->update_order_meta($order, '_anet_credit_card_capture_id', isset($result['capture_trans_id']) ? $result['capture_trans_id'] : '');
						if (ANET_WOOCOMMERCE_ORDER_STATUS_ON_HOLD === $order->get_status()) {
							$order->update_status(ANET_WOOCOMMERCE_ORDER_STATUS_PROCESSING, '');
							/* translators: Order notes for Capture Transaction ID*/
							$complete_message = sprintf(__("Capture Transaction ID: %s", 'authorize-net-payments-for-woocommerce'), $transactionid);
							$order->add_order_note($complete_message);
						}
						$order->save();
						$result['success'] = ANET_YES;
					} else {
						$result['status'] = ANET_WOOCOMMERCE_ORDER_STATUS_FAILED;
						$result['error'] = 'Transaction failed with no messages.';
					}
				} else {
					$result['status'] = ANET_WOOCOMMERCE_ORDER_STATUS_FAILED;
					$transaction_response = $response->getTransactionResponse();
					if (null !== $transaction_response && null !== $transaction_response->getErrors()) {
						$result['error_code'] = $transaction_response->getErrors()[0]->getErrorText();
					} else {
						$result['error_code'] = $response->getMessages()->getMessage()[0]->getCode();
						$result['error_message'] = $response->getMessages()->getMessage()[0]->getText();
					}
				}
			}
		} catch (Throwable $e) {
			$result['status'] = ANET_WOOCOMMERCE_ORDER_STATUS_FAILED;
			$result['error'] = 'Exception: ' . $e->getMessage();
		}
		wp_send_json($result);
	}
}
