<?php
namespace Elementor_Pay_Addons\Form\Actions;

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

use \Elementor_Pay_Addons\Shared\Controls;

abstract class Action_Base {

	abstract public function get_name();

	abstract public function get_label();

	/**
	 * Get the action ID.
	 *
	 * TODO: Make it an abstract function that will replace `get_name()`.
	 *
	 * @since 3.5.0
	 *
	 * @return string
	 */
	public function get_id() {
		return $this->get_name();
	}

	/**
	 * @param Form_Record  $record
	 * @param Ajax_Handler $ajax_handler
	 */
	abstract public function run( $record, $ajax_handler );

	/**
	 * @param Form $form
	 */
	abstract public function register_settings_section( $form );

	/**
	 * @param array $element
	 */
	abstract public function on_export( $element );

	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::subscription_controls__premium_only($prefix),
			Controls::general_controls_end($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';
	}
}
