<?php
/**
 * Authorize.net Capture Class
 *
 * Adds and handles the capture functionality for authorized payments in WooCommerce admin.
 *
 * @package Authorize_Net_Payments_For_Woocommerce
 * @subpackage Authorize_Net_Payments_For_Woocommerce/includes
 */

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

use Automattic\WooCommerce\Caches\OrderCache;

require_once(dirname(__FILE__) . '/../../includes/api/payments/class-anet-capture-api.php');
require_once plugin_dir_path(__FILE__) . '../trait-anet-order-meta.php';

/**
 * Class Anet_Capture
 *
 * Handles the display and processing of the capture button for authorized transactions.
 */
class Anet_Capture
{
	use Anet_Order_Meta;
	/**
	 * Add Capture Button in Admin Page.
	 *
	 * @return void
	 */
	public function add_capture_button_to_admin_page()
	{
		add_action('woocommerce_order_item_add_action_buttons', array($this, 'add_capture_button'), ANET_ACTION_HOOK_DEFAULT_PRIORITY, ANET_VAL_ONE);
		add_action('wp_ajax_anet_capture_action', array($this, 'ajax_process_capture'));
	}
	/**
	 * Adds Capture Button in Admin Page.
	 *
	 * @param \WC_Order $order order details.
	 *
	 * @return void
	 */
	public function add_capture_button($order)
	{
		$classes    = array(
			'button',
			'partial-capture',
			'wc-anet-capture',
			'button-primary',
		);
		$tooltip    = '';
		$order_data = $order->get_data();
		$is_credit_card = ANET_CREDIT_CARD_GATEWAY_ID === $order_data['payment_method'];
		$is_shop_order = 'shop_order' === $order->get_type();
		if ($is_credit_card && $is_shop_order) {
			$this->load_capture_script($order);
			$blocked_statuses = array(
				ANET_WOOCOMMERCE_ORDER_STATUS_PROCESSING,
				ANET_WOOCOMMERCE_ORDER_STATUS_CANCELLED,
				ANET_WOOCOMMERCE_ORDER_STATUS_REFUNDED,
				ANET_WOOCOMMERCE_ORDER_STATUS_FAILED,
				ANET_WOOCOMMERCE_ORDER_STATUS_PENDING,
				ANET_WOOCOMMERCE_ORDER_STATUS_COMPLETED,
			);
			$is_blocked_status = in_array($order->get_status(), $blocked_statuses, true);
			if ($this->is_order_fully_captured($order) || $is_blocked_status) {
				$classes[] = 'tips disabled';
				if ($this->is_order_fully_captured($order)) {
					$tooltip = __('This charge has been fully captured.', 'authorize-net-payments-for-woocommerce');
				} else {
					$tooltip = __('This order cannot be captured.', 'authorize-net-payments-for-woocommerce');
				}
			}
			$class_string = implode(' ', $classes);
            $has_tooltip = !empty($tooltip);
?>
            <button type="button" id="capture-button" class="<?php echo esc_attr($class_string); ?>" <?php echo $has_tooltip ? 'data-tip="' . esc_attr($tooltip) . '"' : ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
                <?php esc_html_e('Capture Charge', 'authorize-net-payments-for-woocommerce'); ?>
            </button>
<?php
		}
	}
	/**
	 * Checks whether order is fully capture or not.
	 *
	 * @param object $order oder object.
	 *
	 * @return bool
	 */
	public function is_order_fully_captured($order)
	{
		$order_cache = wc_get_container()->get(OrderCache::class);
		$order_cache->remove($order->get_id());
		$captured = $this->get_order_meta($order, '_anet_credit_card_capture_id');
		$is_fully_captured = ANET_YES === $captured ? true : false;
		return $is_fully_captured;
	}
	/**
	 * Enqueues the assets for the Edit Order screen.
	 *
	 * @param \WC_Order $order order object.
	 */
	public function load_capture_script(\WC_Order $order)
	{
		$script_url = plugin_dir_url(__FILE__) . '../../assets/js/admin/anet-capture.js';
		wp_enqueue_script(
			'anet-capture-admin-order',
			$script_url,
			array('jquery'),
			ANET_PLUGIN_VERSION,
			true
		);
		wp_localize_script(
			'anet-capture-admin-order',
			'anet_capture_order',
			array(
				'ajax_url'            => admin_url('admin-ajax.php'),
				'gateway_id'          => $order->get_payment_method('edit'),
				'order_id'            => $order->get_id(),
				'capture_message'     => __(
					'Are you sure you wish to process this capture? The action cannot be reversed.',
					'authorize-net-payments-for-woocommerce'
				),
				'capture_action'      => 'anet_capture_action',
				'capture_nonce'       => wp_create_nonce('anet_capture_action'),
				'capture_error'       => __(
					'Something went wrong, and the capture could no be completed. Please try again.',
					'authorize-net-payments-for-woocommerce'
				),
				'total_amount'        => $order->get_total(),
				'order_status'        => $order->get_status(),
				'total_refund_amount' => $order->get_remaining_refund_amount(),
				'anet_yes'            => ANET_YES,
				'anet_val_one'        => ANET_SAVING_CARD_VAL_ONE,
			)
		);
	}
	/**
	 * Handles the AJAX request to process a previously authorized capture.
	 *
	 * @return void Sends a JSON response with success or error message.
	 */
	public function ajax_process_capture()
	{
		check_ajax_referer('anet_capture_action', 'nonce');
		$order_id = 0;
		if (isset($_POST['order_id'])) {
			$order_id = (int) $_POST['order_id'];
		}
		if (! current_user_can('edit_shop_orders')) { // phpcs:ignore WordPress.WP.Capabilities.Unknown
			wp_send_json_error(array('error_msg' => 'You do not have permission to capture payments.'));
			return;
		}
		$back_data = array(
			'error' => 0,
			'msg'   => '',
		);
		$order          = wc_get_order($order_id);
		$order_data     = $order->get_data();
		$transaction_id = $order_data['transaction_id'];
		$capture_api    = new Anet_Capture_Api();
		$response       = $capture_api->capture_previously_authorized_amount($transaction_id, $order_id);
		if (! $response['error'] && (ANET_YES === $response['success'])) {
			$back_data['success'] = 1;
			$back_data['msg']     = $response['alert_message'];
		} else {
			$back_data['success'] = 0;
			$back_data['msg']     = $response['error_msg'];
		}
		wp_send_json($back_data);
	}
}
