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

if ( ! class_exists( 'SftcyWordformPaymentSquare' ) ) {
	class SftcyWordformPaymentSquare {

		public static function get_settings() {
			$settings = SftcyWordformBase::wordform_settings_page_payment_config();

			return array(
				'enabled'        => isset( $settings['square_enabled'] ) ? sanitize_text_field( $settings['square_enabled'] ) : 'no',
				'mode'           => isset( $settings['square_mode'] ) ? sanitize_text_field( $settings['square_mode'] ) : 'sandbox',
				'application_id' => isset( $settings['square_application_id'] ) ? trim( sanitize_text_field( $settings['square_application_id'] ) ) : '',
				'access_token'   => isset( $settings['square_access_token'] ) ? trim( sanitize_text_field( $settings['square_access_token'] ) ) : '',
				'location_id'    => isset( $settings['square_location_id'] ) ? trim( sanitize_text_field( $settings['square_location_id'] ) ) : '',
				'currency'       => isset( $settings['payment_currency'] ) ? strtoupper( sanitize_text_field( $settings['payment_currency'] ) ) : 'USD',
			);
		}

		public static function get_sdk_url() {
			$settings = self::get_settings();
			return ( isset( $settings['mode'] ) && 'live' === $settings['mode'] ) ? 'https://web.squarecdn.com/v1/square.js' : 'https://sandbox.web.squarecdn.com/v1/square.js';
		}

		public static function get_api_base_url() {
			$settings = self::get_settings();
			return ( isset( $settings['mode'] ) && 'live' === $settings['mode'] ) ? 'https://connect.squareup.com' : 'https://connect.squareupsandbox.com';
		}

		public static function create_payment( $amount = 0, $currency = 'USD', $source_id = '', $verification_token = '', $form_id = '', $form_name = '', $buyer_email = '' ) {
			$settings = self::get_settings();

			if ( 'yes' !== $settings['enabled'] ) {
				return array(
					'status'  => 'fail',
					'reason'  => 'Square is disabled.',
					'comment' => __( 'Enable Square in Payment settings first.', 'wordform-pro' ),
				);
			}

			if ( empty( $settings['application_id'] ) || empty( $settings['access_token'] ) || empty( $settings['location_id'] ) ) {
				return array(
					'status'  => 'fail',
					'reason'  => 'Square credentials missing.',
					'comment' => __( 'Square Application ID, Access Token, or Location ID is missing.', 'wordform-pro' ),
				);
			}

			$amount    = max( 0, (float) $amount );
			$currency  = strtoupper( sanitize_text_field( $currency ) );
			$source_id = sanitize_text_field( $source_id );

			if ( $amount <= 0 ) {
				return array(
					'status'  => 'fail',
					'reason'  => 'Invalid Square amount.',
					'comment' => __( 'Payment amount must be greater than zero.', 'wordform-pro' ),
				);
			}

			if ( empty( $source_id ) ) {
				return array(
					'status'  => 'fail',
					'reason'  => 'Square source ID missing.',
					'comment' => __( 'Square payment token is missing.', 'wordform-pro' ),
				);
			}

			$body = array(
				'idempotency_key' => wp_generate_uuid4(),
				'source_id'       => $source_id,
				'location_id'     => $settings['location_id'],
				'autocomplete'    => true,
				'amount_money'    => array(
					'amount'   => (int) round( $amount * 100 ),
					'currency' => $currency,
				),
				'note'            => sprintf(
					/* translators: 1: form name, 2: form id */
					__( 'WordForm payment for %1$s (%2$s)', 'wordform-pro' ),
					sanitize_text_field( $form_name ),
					sanitize_text_field( $form_id )
				),
				'reference_id'    => sanitize_text_field( $form_id ),
			);

			if ( ! empty( $verification_token ) ) {
				$body['verification_token'] = sanitize_text_field( $verification_token );
			}

			if ( ! empty( $buyer_email ) && is_email( $buyer_email ) ) {
				$body['buyer_email_address'] = sanitize_email( $buyer_email );
			}

			$response = wp_remote_post(
				self::get_api_base_url() . '/v2/payments',
				array(
					'timeout' => 45,
					'headers' => array(
						'Square-Version' => '2025-10-16',
						'Authorization'  => 'Bearer ' . $settings['access_token'],
						'Content-Type'   => 'application/json',
					),
					'body'    => wp_json_encode( $body ),
				)
			);

			if ( is_wp_error( $response ) ) {
				return array(
					'status'  => 'fail',
					'reason'  => 'Square payment request failed.',
					'comment' => $response->get_error_message(),
				);
			}

			$response_code = (int) wp_remote_retrieve_response_code( $response );
			$decoded_body  = json_decode( wp_remote_retrieve_body( $response ), true );

			if ( $response_code < 200 || $response_code >= 300 || empty( $decoded_body['payment']['id'] ) ) {
				$error_message = __( 'Square payment could not be completed.', 'wordform-pro' );
				if ( ! empty( $decoded_body['errors'][0]['detail'] ) ) {
					$error_message = sanitize_text_field( $decoded_body['errors'][0]['detail'] );
				}
				if ( 401 === $response_code || ( ! empty( $decoded_body['errors'][0]['code'] ) && 'UNAUTHORIZED' === strtoupper( sanitize_text_field( $decoded_body['errors'][0]['code'] ) ) ) ) {
					$error_message = __( 'Square rejected the saved credentials. Check sandbox/live mode, Application ID, Access Token, and Location ID in Payment settings, then save and test again.', 'wordform' );
				}

				return array(
					'status'  => 'fail',
					'reason'  => 'Square payment creation failed.',
					'comment' => $error_message,
					'raw'     => $decoded_body,
				);
			}

			$payment     = $decoded_body['payment'];
			$card_details = isset( $payment['card_details']['card'] ) ? $payment['card_details']['card'] : array();

			return array(
				'status'      => 'success',
				'paymentId'   => isset( $payment['id'] ) ? sanitize_text_field( $payment['id'] ) : '',
				'paymentStatus' => isset( $payment['status'] ) ? sanitize_text_field( $payment['status'] ) : 'COMPLETED',
				'amount'      => isset( $payment['amount_money']['amount'] ) ? number_format( ((float) $payment['amount_money']['amount']) / 100, 2, '.', '' ) : number_format( $amount, 2, '.', '' ),
				'currency'    => isset( $payment['amount_money']['currency'] ) ? sanitize_text_field( $payment['amount_money']['currency'] ) : $currency,
				'sourceId'    => $source_id,
				'cardBrand'   => isset( $card_details['card_brand'] ) ? sanitize_text_field( $card_details['card_brand'] ) : '',
				'last4'       => isset( $card_details['last_4'] ) ? sanitize_text_field( $card_details['last_4'] ) : '',
				'receiptUrl'  => isset( $payment['receipt_url'] ) ? esc_url_raw( $payment['receipt_url'] ) : '',
				'raw'         => $decoded_body,
			);
		}
	}
}
