<?php
	require_once('vendor/autoload.php');

	add_action( 'wp_ajax_pafe_ajax_stripe_intents', 'pafe_ajax_stripe_intents' );
	add_action( 'wp_ajax_nopriv_pafe_ajax_stripe_intents', 'pafe_ajax_stripe_intents' );

	function find_element_recursive_stripe( $elements, $form_id ) {
		foreach ( $elements as $element ) {
			if ( $form_id === $element['id'] ) {
				return $element;
			}

			if ( ! empty( $element['elements'] ) ) {
				$element = find_element_recursive( $element['elements'], $form_id );

				if ( $element ) {
					return $element;
				}
			}
		}

		return false;
	}

	function generatePaymentResponse($intent) {
	    # Note that if your API version is before 2019-02-11, 'requires_action'
	    # appears as 'requires_source_action'.
	    if ($intent->status == 'requires_action' &&
	        $intent->next_action->type == 'use_stripe_sdk' || $intent->status == 'requires_source_action' &&
	        $intent->next_action->type == 'use_stripe_sdk') {
	      # Tell the client to handle the action
	      echo json_encode([
	        'requires_action' => true,
	        'payment_intent_client_secret' => $intent->client_secret
	      ]);
	    } else if ($intent->status == 'succeeded') {
	      # The payment didn’t need any additional actions and completed!
	      # Handle post-payment fulfillment
	      echo json_encode([
	        "success" => true
	      ]);
	    } else {
	      # Invalid status
	      http_response_code(500);
	      echo json_encode(['error' => 'Invalid PaymentIntent status']);
	    }
	}

	function pafe_ajax_stripe_intents() {
		global $wpdb;

		\Stripe\Stripe::setApiKey(get_option('piotnet-addons-for-elementor-pro-stripe-secret-key'));

		if ( !empty($_POST['post_id']) && !empty($_POST['form_id']) && !empty($_POST['fields']) && !empty($_POST['amount']) ) {
			$post_id = $_POST['post_id'];
			$form_id = $_POST['form_id'];
			$fields = stripslashes($_POST['fields']);
			$fields = json_decode($fields, true);
			$fields = array_unique($fields, SORT_REGULAR);

			$elementor = \Elementor\Plugin::$instance;

			if ( version_compare( ELEMENTOR_VERSION, '2.6.0', '>=' ) ) {
				$meta = $elementor->documents->get( $post_id )->get_elements_data();
			} else {
				$meta = $elementor->db->get_plain_editor( $post_id );
			}

			$form = find_element_recursive_stripe( $meta, $form_id );

			$widget = $elementor->elements_manager->create_element_instance( $form );
			$form['settings'] = $widget->get_active_settings();

			$amount = floatval($_POST['amount']) * 100;
			$currency = strtolower($form['settings']['pafe_stripe_currency']);

			$intent = \Stripe\PaymentIntent::create([
			    'amount' => $amount,
			    'currency' => $currency,
			]);

			echo $intent->client_secret;
		}
	}

?>