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

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

		/**
		 * Return Stripe configuration from Payment settings.
		 *
		 * @return array
		 */
		public static function get_settings() {
			$settings = SftcyWordformBase::wordform_settings_page_payment_config();

			return array(
				'enabled'         => isset( $settings['stripe_enabled'] ) ? sanitize_text_field( $settings['stripe_enabled'] ) : 'no',
				'mode'            => isset( $settings['stripe_mode'] ) ? sanitize_text_field( $settings['stripe_mode'] ) : 'test',
				'publishable_key' => isset( $settings['stripe_publishable_key'] ) ? trim( sanitize_text_field( $settings['stripe_publishable_key'] ) ) : '',
				'secret_key'      => isset( $settings['stripe_secret_key'] ) ? trim( sanitize_text_field( $settings['stripe_secret_key'] ) ) : '',
				'currency'        => isset( $settings['payment_currency'] ) ? strtoupper( sanitize_text_field( $settings['payment_currency'] ) ) : 'USD',
			);
		}

		/**
		 * Create a Stripe PaymentIntent using the official API endpoint.
		 *
		 * @param float  $amount        Total amount in major currency unit.
		 * @param string $currency      Currency code.
		 * @param string $form_id       WordForm ID.
		 * @param string $form_name     WordForm name.
		 * @param string $receipt_email Receipt email.
		 * @return array
		 */
		public static function create_payment_intent( $amount = 0, $currency = 'USD', $form_id = '', $form_name = '', $receipt_email = '' ) {
			$settings = self::get_settings();

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

			if ( empty( $settings['secret_key'] ) || empty( $settings['publishable_key'] ) ) {
				return array(
					'status'  => 'fail',
					'reason'  => 'Stripe API keys missing.',
					'comment' => __( 'Stripe publishable key or secret key is missing.', 'wordform-pro' ),
				);
			}

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

			$amount_in_smallest_unit = self::convert_to_smallest_currency_unit( $amount, $currency );
			$request_body            = array(
				'amount'                  => $amount_in_smallest_unit,
				'currency'                => $currency,
				'payment_method_types[0]' => 'card',
				'description'             => 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 )
				),
				'metadata[form_id]'       => sanitize_text_field( $form_id ),
				'metadata[form_name]'     => sanitize_text_field( $form_name ),
			);

			if ( ! empty( $receipt_email ) ) {
				$request_body['receipt_email'] = sanitize_email( $receipt_email );
			}

			$response = wp_remote_post(
				'https://api.stripe.com/v1/payment_intents',
				array(
					'timeout' => 45,
					'headers' => array(
						'Authorization' => 'Bearer ' . $settings['secret_key'],
						'Content-Type'  => 'application/x-www-form-urlencoded',
					),
					'body'    => $request_body,
				)
			);

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

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

			if ( $status_code < 200 || $status_code >= 300 || ! isset( $decoded_body['client_secret'] ) ) {
				$error_message = isset( $decoded_body['error']['message'] ) ? sanitize_text_field( $decoded_body['error']['message'] ) : __( 'Stripe payment intent could not be created.', 'wordform-pro' );

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

			return array(
				'status'            => 'success',
				'paymentIntentId'   => isset( $decoded_body['id'] ) ? sanitize_text_field( $decoded_body['id'] ) : '',
				'clientSecret'      => sanitize_text_field( $decoded_body['client_secret'] ),
				'publishableKey'    => $settings['publishable_key'],
				'currency'          => strtoupper( $currency ),
				'amount'            => number_format( $amount, 2, '.', '' ),
				'amountInSmallUnit' => $amount_in_smallest_unit,
				'mode'              => $settings['mode'],
			);
		}

		/**
		 * Convert amount to smallest currency unit.
		 *
		 * @param float  $amount
		 * @param string $currency
		 * @return int
		 */
		public static function convert_to_smallest_currency_unit( $amount = 0, $currency = 'usd' ) {
			$zero_decimal_currencies = array( 'bif', 'clp', 'djf', 'gnf', 'jpy', 'kmf', 'krw', 'mga', 'pyg', 'rwf', 'ugx', 'vnd', 'vuv', 'xaf', 'xof', 'xpf' );
			$currency                = strtolower( sanitize_text_field( $currency ) );

			if ( in_array( $currency, $zero_decimal_currencies, true ) ) {
				return (int) round( $amount );
			}

			return (int) round( $amount * 100 );
		}
	}
}
