<?php
namespace Elementor_Pay_Addons\Form\Actions;

use Elementor_Pay_Addons\Form\API\Ajax_API_Form_Handler;
use Elementor_Pay_Addons\Shared\Logger;
use Elementor_Pay_Addons\Stripe\Stripe_Logger;
use Elementor_Pay_Addons\Stripe\Stripe_API;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

class Stripe_Checkout_Redirect_Action extends Action_Base {

	use Stripe_Redirect_Action_Trait;
	
	static $control_prefix = 'session-checkout-';

	public function get_name() {
		return 'epa-form-redirect-action';
	}

	public function get_label() {
		return esc_html__( 'Checkout Redirect (Pay-Addons)', 'pay-addons-for-elementor' );
	}

	public function register_settings_section( $widget ) {

		$this->register_settings_section_Core( $widget );

		$control_id = self::$control_prefix . 'onetime_amount_field';

		$controls = $widget->get_controls();
		if ( isset( $controls[ $control_id ] ) ) {
			$widget->update_control( $control_id, [
				'default' => '[field id="amount"]'
			] );
		}
	}

	public function on_export( $element ) {
		return $element;
	}

	public function run( $record, $ajax_handler ) {
		return;
	}

	public function run_core( $record, $ajax_handler ) {
		if ( \Elementor\Plugin::instance()->editor->is_edit_mode() ) {
			return false;
		}
		
		$settings = $record->get( 'form_settings' );
	
		$checkout_session = $this->collect_session_checkout_args($record);
		$checkout_session = apply_filters( 'elementor_pay_addons/form/create_checkout_session', $checkout_session );
		try {

			$session = Stripe_API::create_checkout_session($checkout_session);

			$this->insert_transaction($record, $session);

			$ajax_handler->add_response_data( 'checkout', 	[
				'redirect_url' => $session->url
			] );
		}
		catch (\Exception $ex) {
      Stripe_Logger::log('stripe_error ' . $ex->getMessage());

			$message = Ajax_API_Form_Handler::get_default_message( Ajax_API_Form_Handler::SERVER_ERROR, $settings );

			$ajax_handler->add_error_message( $ex->getMessage() );

			throw new \Exception( $message );
    }
	}
}
