<?php
/**
 * Handle WC-Ajax request for creating a PeachPay transaction
 *
 * @package PeachPay
 */

defined( 'ABSPATH' ) || exit;

/**
 * Ajax hook function for creating a PeachPay transaction.
 */
function pp_wc_ajax_create_transaction() {
	$session_id = PeachPay_Payment::get_session();

	// PHPCS:disable WordPress.Security.NonceVerification.Missing
	$gateway_id        = isset( $_POST['gateway_id'] ) ? sanitize_text_field( wp_unslash( $_POST['gateway_id'] ) ) : null;
	$checkout_location = isset( $_POST['checkout_location'] ) ? sanitize_text_field( wp_unslash( $_POST['checkout_location'] ) ) : null;
	// PHPCS:enable

	if ( ! $gateway_id ) {
		peachpay_log( 'warning', 'PeachPay: Create transaction validation failed - gateway_id is required' );
		wp_send_json(
			array(
				'success' => false,
				'message' => '"gateway_id" is a required field.',
			)
		);

		return;
	}

	if ( ! $checkout_location ) {
		peachpay_log( 'warning', 'PeachPay: Create transaction validation failed - checkout_location is required' );
		wp_send_json(
			array(
				'success' => false,
				'message' => '"checkout_location" is a required field.',
			)
		);

		return;
	}

	peachpay_log( 'info', 'PeachPay: Create transaction started for gateway ' . $gateway_id . ' (session ' . substr( $session_id, 0, 8 ) . '...)' );
	$result = PeachPay_Payment::create_transaction( $session_id, $gateway_id, $checkout_location );
	if ( ! empty( $result['success'] ) ) {
		$transaction_id = $result['data']['transaction_id'] ?? '';
		if ( ! empty( $transaction_id ) ) {
			if ( session_status() === PHP_SESSION_ACTIVE ) {
				// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
				$_SESSION['peachpay_transaction_id'] = sanitize_text_field( $transaction_id );
			}
			if ( function_exists( 'WC' ) && WC()->session ) {
				WC()->session->set( 'peachpay_transaction_id', sanitize_text_field( $transaction_id ) );
			}
		}
		peachpay_log( 'info', 'PeachPay: Create transaction success - ' . ( $transaction_id ?: 'unknown' ) );
	} else {
		peachpay_log( 'error', 'PeachPay: Create transaction failed - ' . ( $result['message'] ?? 'Unknown error' ) );
	}
	wp_send_json( $result );
}
