<?php
namespace Elementor_Pay_Addons\Form\Actions;

use Elementor\Controls_Manager;
use Elementor_Pay_Addons\Shared\Controls;
use Elementor_Pay_Addons\Shared\Logger;
use Elementor_Pay_Addons\Shared\Utils;

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

Trait Stripe_Redirect_Action_Trait {

	public function register_settings_section_Core( $widget ) {
		$widget->start_controls_section(
			'section_stripe_checkout_redirect_setting',
			[
				'label' => __( 'Stripe Checkout Redirect<i class="epa-action-logo paicon-logo"></i>', 'pay-addons-for-elementor' ),
				'condition' => [
					'submit_actions' => $this->get_name(),
				],
			]
		);

		$widget->add_control(
			'stripe_checkout_redirect_warning_message',
			[
				'type' => Controls_Manager::RAW_HTML,
				'raw' => sprintf(
					__(
						'Submission will redirect to stripe hosting checkout page eventually.',
						'pay-addons-for-elementor'
					)
				),
				'content_classes' => 'elementor-panel-alert elementor-panel-alert-info',
			]
		);

		$checkout_setting_controls = Controls::get_session_checkout_setting_fields(self::$control_prefix);
		
		foreach($checkout_setting_controls as $control) {
			if($control[0] === self::$control_prefix . 'mode') continue;
			$widget->add_control($control[0], $control[1]);
		}
		$checkout_metadata_controls = Controls::get_session_checkout_metadata(self::$control_prefix);
		
		$widget->add_control($checkout_metadata_controls[0], $checkout_metadata_controls[1]);

		$widget->end_controls_section();

		$widget->start_controls_section(
			'section_stripe_checkout_redirect_fields',
			[
				'label' => __( 'Stripe Checkout Redirect Fields<i class="epa-action-logo paicon-logo"></i>', 'pay-addons-for-elementor' ),
				'condition' => [
					'submit_actions' => $this->get_name(),
				],
			]
		);

		$this->append_controls( Controls::general_controls( self::$control_prefix, true ), $widget );

		$widget->start_controls_tabs(
			self::$control_prefix . 'payment_type_tabs'
		);
		
		$widget->start_controls_tab(
			self::$control_prefix . 'onetime_tab',
			[
				'label' => esc_html__( 'One-Time', 'textdomain' ),
			]
		);

		$this->append_controls( Controls::onetime_controls( self::$control_prefix ), $widget );
		
		$widget->end_controls_tab();

		$widget->start_controls_tab(
			self::$control_prefix . 'sub_tab',
			[
				'label' => __( 'Subscription <i class="eicon-pro-icon"></i>', 'textdomain' ),
			]
		);

		$isPremium = epa_fs()->can_use_premium_code();
		if($isPremium) {
			$sub_controls = Controls::subscription_controls__premium_only( self::$control_prefix );
			$sub_controls = array_filter( $sub_controls, function($k) {
				return $k[0] !== self::$control_prefix . 'sub_iterations_field';
			});

			$this->append_controls( $sub_controls, $widget );
		} else {
			Controls::add_premium_warning_control($widget);	
		}
		
		$widget->end_controls_tab();
		
		$widget->end_controls_tabs();

		$widget->end_controls_section();
	}

	public function append_controls($fields_controls, $widget)
	{
		foreach ($fields_controls as $control) {
			$widget->add_control($control[0], $control[1]);
		}
	}

  protected function collect_form_field_settings($record, $fields_controls) {
    $settings = $record->get( 'form_settings' );

		$fields = [];

		foreach ($fields_controls as $control) {
			$key = $control[0];
			$setting = trim( $settings[ $key ] );
      if(str_contains($key, 'field')) {
        $setting = $record->replace_setting_shortcodes( $setting );
      }
			$fields[$key] = $setting;
		}

		$form_fields = $record->get_field(null);
		$form_fields_value = [];
		foreach($form_fields as $key => $value ) {
			$form_fields_value[$key] = $value['value'];	
		}

		return array_merge($settings, $fields, array(
			'form_data' => $form_fields_value
		));
  }

	protected function get_form_settings($record, $prefix)
	{
		$fields_controls = array_merge(
			Controls::general_controls($prefix),
			Controls::onetime_controls($prefix),
			Controls::general_controls_end($prefix)
		);
		if(epa_fs()->can_use_premium_code()) {
			$fields_controls = array_merge(
				$fields_controls,
				Controls::subscription_controls__premium_only($prefix)
			);
		}
		return $this->collect_form_field_settings($record, $fields_controls);
	}
	
	protected function is_subscription($form_settings, $prefix)
	{
		$payment_type = $form_settings[$prefix . 'payment_type'];
		if ($payment_type == 'flex') {
			$field_value = $form_settings[$prefix . 'payment_type_condition_field'];
			$operation = $form_settings[$prefix . 'payment_type_condition_operation'];
			$value = $form_settings[$prefix . 'payment_type_condition_value'];
			if (
				($operation == 'empty' && empty($field_value)) ||
				($operation == 'nonempty' && !empty($field_value)) ||
				($operation == 'equalto' && $field_value == $value) ||
				($operation == 'notequalto' && $field_value !== $value) ||
				($operation == 'checked' && filter_var($field_value, FILTER_VALIDATE_BOOLEAN)) ||
				($operation == 'notchecked' && !filter_var($field_value, FILTER_VALIDATE_BOOLEAN))
			) {
				$payment_type = 'subscription';
			}
		}
		return $payment_type === 'subscription';
	}

	protected function generate_line_items($form_settings, $is_subscription) {

		$line_item = [
			'quantity' => floatval($form_settings[$is_subscription ? self::$control_prefix . 'sub_quantity_field' : self::$control_prefix . 'onetime_quantity_field']),
		];

		// Add setup fee line item for subscription if enabled
		$line_items = [];
		if ($is_subscription && isset($form_settings[self::$control_prefix . 'sub_enable_setup_fee']) && $form_settings[self::$control_prefix . 'sub_enable_setup_fee'] === 'yes') {
			$setup_fee_amount = floatval($form_settings[self::$control_prefix . 'sub_setup_fee_amount_field']);
			$setup_fee_quantity = floatval($form_settings[self::$control_prefix . 'sub_setup_fee_quantity_field']);
			$setup_fee_name = $form_settings[self::$control_prefix . 'sub_setup_fee_product_name_field'];
			$setup_fee_desc = $form_settings[self::$control_prefix . 'sub_setup_fee_product_desc_field'];
			$setup_fee_currency = $form_settings[self::$control_prefix . 'sub_currency'];
			$setup_fee_item = [
				'price_data' => [
					'currency' => $setup_fee_currency,
					'unit_amount' => $setup_fee_amount * 100,
					'product_data' => [
						'name' => $setup_fee_name,
					],
				],
				'quantity' => $setup_fee_quantity,
			];
			if (!empty($setup_fee_desc)) {
				$setup_fee_item['price_data']['product_data']['description'] = $setup_fee_desc;
			}
			$line_items[] = $setup_fee_item;
		}

		if ($is_subscription && $form_settings[self::$control_prefix . 'sub_enable_pricing_plan'] == 'yes') {
			$price_id = $form_settings[self::$control_prefix . 'sub_price_id_field'];
			if (empty($price_id)) {
				$price_id = $form_settings[self::$control_prefix . 'sub_price_id'];
			}
			$line_item['price'] = $price_id;
		} else {
			$currency = strtolower($form_settings[$is_subscription ? self::$control_prefix . 'sub_currency' : self::$control_prefix . 'onetime_currency']);
			$unit_amount = floatval($form_settings[$is_subscription ? self::$control_prefix . 'sub_amount_field' : self::$control_prefix . 'onetime_amount_field']);
			$name = $form_settings[$is_subscription ? self::$control_prefix . 'sub_product_name_field' : self::$control_prefix . 'onetime_product_name_field'];
			$line_item['price_data'] = [
				'currency' => $currency,
				'unit_amount' => $unit_amount * 100,
				'product_data' => [
					'name' => $name,
				],
			];

			$desc =	$form_settings[$is_subscription ? self::$control_prefix . 'sub_product_desc_field' : self::$control_prefix . 'onetime_product_desc_field'];
			if (!empty($desc)) {
				$line_item['price_data']['product_data']['description'] = $desc;
			}

			if ($is_subscription) {
				$line_item['price_data']['recurring'] = [
					'interval' => strtolower($form_settings[self::$control_prefix . 'sub_interval_field']),
					'interval_count' => floatval($form_settings[self::$control_prefix . 'sub_interval_count_field']),
				];
			}

			if ($form_settings[self::$control_prefix . 'automatic_tax'] == 'yes') {
				$line_item['price_data']['tax_behavior'] = $form_settings[self::$control_prefix . 'tax_behavior'];
			}
		}

		// Add the main line item
		$line_items[] = $line_item;
		return $line_items;
	}

	protected function collect_session_checkout_args($record) {
		$form_settings = $this->get_form_settings($record, self::$control_prefix);

		$is_subscription = $this->is_subscription($form_settings, self::$control_prefix);

		$line_items = $this->generate_line_items($form_settings, $is_subscription);

		$success_url = get_permalink();
		$cancel_url = get_permalink();
		if(!empty($form_settings[self::$control_prefix . 'success_url'])) {
			$success_url = $form_settings[self::$control_prefix . 'success_url'];
		}
		if(!empty($form_settings[self::$control_prefix . 'cancel_url'])) {
			$cancel_url = $form_settings[self::$control_prefix . 'cancel_url'];
		}

		$checkout_session = [
			'payment_method_types' => $form_settings[self::$control_prefix . 'payment_method_types'],
			'line_items' => $line_items,
			'mode' => $is_subscription ? 'subscription' : 'payment',
			'success_url' => add_query_arg('session_id', '{CHECKOUT_SESSION_ID}', esc_url_raw($success_url)),
			'cancel_url' => esc_url_raw($cancel_url),
			'billing_address_collection' => $form_settings[self::$control_prefix . 'billing_address_collection'] == 'yes' ? 'required' : 'auto',
			'allow_promotion_codes' => $form_settings[self::$control_prefix . 'allow_promotion_codes'] == 'yes' ? true : false,
		];

		if ($form_settings[self::$control_prefix . 'automatic_tax'] == 'yes') {
			$checkout_session['automatic_tax'] = ['enabled' => true];
			$checkout_session['tax_id_collection'] = ['enabled' => true];
		}

		if(in_array('automatic', $checkout_session['payment_method_types'])) {
			unset($checkout_session['payment_method_types']);
		}

		if(!empty($form_settings[self::$control_prefix . 'email_field'])) {
			$checkout_session['customer_email'] = $form_settings[self::$control_prefix . 'email_field']; 
		}

		if($checkout_session['mode'] == 'payment' && !empty($form_settings[self::$control_prefix . 'submit_type'])) {
			$checkout_session['submit_type'] = $form_settings[self::$control_prefix . 'submit_type'];
		}

		if($form_settings[self::$control_prefix . 'phone_number_collection'] == 'yes') {
			$checkout_session['phone_number_collection'] = [ 'enabled' => true ];
		}

		if ($form_settings[self::$control_prefix . 'terms_of_service'] == 'yes') {
			$checkout_session['consent_collection'] = [
        'terms_of_service' => $form_settings[self::$control_prefix . 'terms_of_service'] == 'yes' ? 'required' :'none'
			];
		}

		if (!empty($form_settings[self::$control_prefix . 'shipping_address_collection'])) {
			$checkout_session['shipping_address_collection'] = [
				'allowed_countries' => $form_settings[self::$control_prefix . 'shipping_address_collection']
			];	
		}

		$checkout_session['payment_intent_data'] = [];
		$checkout_session['subscription_data'] = [];
		// Always inject the site domain so is_event_from_current_site() can filter
		// webhook events correctly when multiple sites share one Stripe account.
		$meta_obj = [
			'referer' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
		];
		$custom_metadata = [];
		if (!empty($form_settings[self::$control_prefix . 'metadata'])) {
			$meta_list = $form_settings[self::$control_prefix . 'metadata'];
			foreach($meta_list as $meta) {
				$key = $meta['metadata_key'];
  			if ($key !== '') {
	    			$custom_metadata[$key] = $meta['metadata_value'];
  			}
			}
		}
		$meta_obj = Utils::trim_metadata(
			array_merge(
				$meta_obj,
				$custom_metadata,
				$form_settings['form_data'] ?? []
			),
			49
		);
		if(!$is_subscription) {
			$checkout_session['payment_intent_data']['metadata'] = $meta_obj;
		}
		if($is_subscription) {
			$checkout_session['subscription_data']['metadata'] = $meta_obj;	
		}

		$name = $form_settings[$is_subscription ? self::$control_prefix . 'sub_product_name_field' : self::$control_prefix . 'onetime_product_name_field'];
		$desc =	$form_settings[$is_subscription ? self::$control_prefix . 'sub_product_desc_field' : self::$control_prefix . 'onetime_product_desc_field'];
		if($name) {
			$description = Utils::format_stripe_desc($name, $desc);
			if(!$is_subscription) {
				$checkout_session['payment_intent_data']['description'] = $description;
			}
			if($is_subscription) {
				$checkout_session['subscription_data']['description'] = $description;
			}
		}
		return $checkout_session;	
	}

	protected function insert_transaction($record, $session) {
		$meta = $record->get_form_meta( [ 'page_url', 'page_title', 'date', 'time', 'user_agent' ] );
		$args = [
			'customer_id' => $session['customer'] ?? '',
			'customer_name' => $session['customer_details']['name'] ?? '',
			'customer_email' => $session['customer_details']['email'] ?? ($session['customer_email'] ?? ''),
			'amount' => isset($session['amount_total']) ? ($session['amount_total']) : 0.00,
			'currency' => $session['currency'] ?? '',
			'recurring' => ($session['mode'] ?? '') === 'subscription' ? 1 : 0,
			'recurring_interval' => null,
			'recurring_count' => null,
			'payment_method' => $session['payment_method_types'][0] ?? '',
			'payment_status' => 'pending',
			'form_name' => $record->get_form_settings( 'form_name' ),
			'form_data' => $record->get_formatted_data(),
			'meta_data' => [
				'page_url' => $meta['page_url']['value'], 
				'page_title' => $meta['page_title']['value'], 
				'date' => $meta['date']['value'], 
				'time' => $meta['time']['value'], 
				'user_agent' => $meta['user_agent']['value'], 
			],
			'transaction_id' => $session['id'] ?? '',
			'source' => $session['payment_method_types'][0] ?? '',
		];

		$args = apply_filters( 'elementor_pay_addons/form/insert_transaction', $args );
		$txn_query = new \Elementor_Pay_Addons\Database\Transaction_Query();
		$txn_query->insert_transaction($session['id'], $args);
	}
}
