<?php
namespace Cool_FormKit_Pro\Widgets\HelloPlusAddons;

use HelloPlus\Modules\Forms\Fields\Field_Base;
use HelloPlus\Includes\Utils;

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


if(!class_exists('HelloPlus_Currency_Field')) {	
class HelloPlus_Currency_Field extends Field_Base {

	public $depended_scripts = array(
		'helloplus-currency-field-script'
	);

    /**
     * Get field type.
     *
     * Retrieve currency field unique ID.
     *
     * @since 1.0.0
     * @return string
     */
	public function get_type() {
		return 'currency';
	}

    /**
     * Get field name.
     *
     * Retrieve currency field label.
     *
     * @since 1.0.0
     * @return string
     */
	public function get_name() {
		return __( 'Currency', 'cool-formkit' );
	}

	/**
	 * @param      $item
	 * @param      $item_index
	 * @param Form       $form
	 */

	public function render( $item, $item_index, $form ) {
        $form_settings = $form->get_settings_for_display();
        $field_name = $form->get_attribute_name($item, $item_index);
    
        // Add attributes directly to the input field
        $form->add_render_attribute(
            $field_name,
            [
                'id' => 'form-field-' . esc_attr($item["custom_id"]),
                'class' => 'elementor-field-textual elementor-field elementor-currency elementor-currency-result  elementor-repeater-item-'.$item['_id'],
                'data-currency-selected' => esc_attr($item['cfkef-select-currency']),
                'data-deci-upto' => esc_attr($item['cfkef-decimal-upto']),
                'name' => esc_attr($field_name)
            ]
        );
    
        // Render the input field with the attributes
		echo '<input type="text" ' . $form->get_render_attribute_string($field_name) . '>';
    }
    
    /**
     * Field constructor.
     *
     * @since 1.0.0
     */
	public function __construct() {
		parent::__construct();
		add_action( 'wp_enqueue_scripts', array( $this, 'add_assets_files' ) );
		add_action( 'elementor/preview/init', array( $this, 'editor_preview_footer' ) );

        add_action( 'elementor/element/ehp-form/section_form_fields/before_section_end', [ $this, 'update_controls' ] );

	}

	/**
	 * Register common assets for the plugin.
	 */
	public function add_assets_files() {
		$js_common_dep = array( 'jquery', 'elementor-frontend' );
        if ( ! \Elementor\Plugin::$instance->preview->is_preview_mode() && is_user_logged_in() ) {
            $js_common_dep = array_merge(array( 'elementor-common' ), $js_common_dep);
        }

		wp_register_script( 'helloplus-currency-field-script', CFKEF_PLUGIN_URL . 'assets/helloplus-addons/js/helloplus-currency-field.js', $js_common_dep, CFKEF_PLUGIN_VERSION, true );
	}

    /**
     * Get script dependencies for this field.
     *
     * @return array
     */
    public function get_script_depends() : array {
        return $this->depended_scripts;
    }

    /**
     * Elementor editor preview.
     *
     * @since 1.0.0
     * @return void
     */
	public function editor_preview_footer() {
			add_action( 'wp_footer', array( $this, 'content_template_script' ) );
	}

    /**
     * Content template script.
     *
     * @since 1.0.0
     * @return void
     */
    public function content_template_script() {
        ?>
        <script>
        jQuery( document ).ready( () => {

            elementor.hooks.addFilter(
                'elementor_pro/forms/content_template/field/<?php echo esc_attr( $this->get_type() ); ?>',
                function ( inputField, item, i ) {
                    <?php if ( 'currency' === esc_attr( $this->get_type() ) ) { ?>
                    const currencySelected  = '' !== item['cfkef-select-currency'] && undefined !== item['cfkef-select-currency'] ? item['cfkef-select-currency'] : '';
                    const decimalUpto  = '' !== item['cfkef-decimal-upto'] && undefined !== item['cfkef-decimal-upto'] ? item['cfkef-decimal-upto'] : '';
                    <?php } ?> 

                    const fieldType  = 'currency';  
                    const fieldId    = `form_field_${i}`;
                    const fieldClass = `elementor-field-textual elementor-field elementor-currency elementor-repeater-item-'.${item['_id']} ${item.css_classes}`;
                    const title      = "<?php echo esc_html__( 'currency name', 'cool-formkit' ); ?>";

                    return `<input type="${fieldType}" id="${fieldId}" class="${fieldClass}" title="${title}" data-currency-selected="${currencySelected}" data-deci-upto="${decimalUpto}">`;					
                }, 10, 3  
            );

        });
        </script>
        <?php
	}

	/**
	 * Update form widget controls to include the currency field control.
	 *
	 * Adds currency field control to allow users to customize the currency field.
	 *
	 * @since 1.0.0
	 * @access public
	 * @param \Elementor\Widget_Base $widget The form widget instance.
	 * @return void
	 */
	public function update_controls( $widget ) {
		$elementor    = Utils::elementor();
		$control_data = $elementor->controls_manager->get_control_from_stack( $widget->get_unique_name(), 'form_fields' );
		if ( is_wp_error( $control_data ) ) {
				return;
		}

		$field_controls = array(
			'cfkef-select-currency'             => array(
				'name'         => 'cfkef-select-currency',
				'label'        => esc_html__( 'Select Currency', 'cool-formkit' ),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => array(
			        '؋' => __('Afghanistan Afghani (؋)', 'cool-formkit'),
					'Lek' => __('Albania Lek (Lek)', 'cool-formkit'),
					'$' => __('Argentine Peso ($)', 'cool-formkit'),
					'ƒ' => __('Aruba Guilder (ƒ)', 'cool-formkit'),
					'$2' => __('Australia Dollar ($)', 'cool-formkit'),
                    '₼' => __('Azerbaijan Manat (₼)', 'cool-formkit'), //comma (,) as the decimal separator and a space as the thousand separator.	
					'$3' => __('Bahamas Dollar ($)', 'cool-formkit'),                   
                    '$4' => __('Barbados Dollar ($)', 'cool-formkit'),			
                    'Br' => __('Belarus Ruble (Br)', 'cool-formkit'), //comma (,) as the decimal separator and a space as the thousand separator.			
                    'BZ$' => __('Belize Dollar (BZ$)', 'cool-formkit'),			
                    '$5' => __('Bermuda Dollar ($)', 'cool-formkit'),			
                    '$b' => __('Bolivia Bolíviano ($b)', 'cool-formkit'),			
                    'KM' => __('Bosnia and Herzegovina Convertible Mark (KM)', 'cool-formkit'),			
                    'P' => __('Botswana Pula (P)', 'cool-formkit'),			
                    'лв6' => __('Bulgaria Lev (лв)', 'cool-formkit'), //comma (,) as the decimal separator and a space as the thousand separator.	
                    'R$' => __('Brazil Real (R$)', 'cool-formkit'),			
                    '$6' => __('Brunei Darussalam Dollar ($)', 'cool-formkit'),			
                    '៛' => __('Cambodia Riel (៛)', 'cool-formkit'),			
                    '$7' => __('Canada Dollar ($)', 'cool-formkit'),			
                    '$8' => __('Cayman Islands Dollar ($)', 'cool-formkit'),			
                    '$9' => __('Chile Peso ($)', 'cool-formkit'),			
                    '¥' => __('China Yuan Renminbi (¥)', 'cool-formkit'),			
                    '$10' => __('Colombia Peso ($)', 'cool-formkit'),			
                    '₡' => __('Costa Rica Colon (₡)', 'cool-formkit'),			
                    'kn' => __('Croatia Kuna (kn)', 'cool-formkit'),			
                    '₱ 1' => __('Cuba Peso (₱)', 'cool-formkit'),			
                    'Kč' => __('Czech Republic Koruna (Kč)', 'cool-formkit'),
                    'kr' => __('Denmark Krone (kr)', 'cool-formkit'),			
                    'RD$' => __('Dominican Republic Peso (RD$)', 'cool-formkit'),			
                    '$11' => __('East Caribbean Dollar ($)', 'cool-formkit'),			
                    '£' => __('Egypt Pound (£)', 'cool-formkit'),			
                    '$12' => __('El Salvador Colon ($)', 'cool-formkit'),			
                    '€' => __('Euro Member Countries (€)', 'cool-formkit'),			
                    '£2' => __('Falkland Islands (Malvinas) Pound (£)', 'cool-formkit'),			
                    '$13' => __('Fiji Dollar ($)', 'cool-formkit'),			
                    '¢' => __('Ghana Cedi (¢)', 'cool-formkit'),			
                    '£3' => __('Gibraltar Pound (£)', 'cool-formkit'),			
                    'Q' => __('Guatemala Quetzal (Q)', 'cool-formkit'),			
                    '£4' => __('Guernsey Pound (£)', 'cool-formkit'),
                    '$14' => __('Guyana Dollar ($)', 'cool-formkit'),
                    'L' => __('Honduras Lempira (L)', 'cool-formkit'),			
                    '$15' => __('Hong Kong Dollar ($)', 'cool-formkit'),			
                    'Ft' => __('Hungary Forint (Ft)', 'cool-formkit'),			
                    'kr1' => __('Iceland Krona (kr)', 'cool-formkit'),			
                    '₨' => __('India Rupee (₨)', 'cool-formkit'),			
                    'Rp' => __('Indonesia Rupiah (Rp)', 'cool-formkit'),			
                    '﷼' => __('Iran Rial (﷼)', 'cool-formkit'),			
                    '£5' => __('Isle of Man Pound (£)', 'cool-formkit'),			
                    '₪' => __('Israel Shekel (₪)', 'cool-formkit'),			
                    'J$' => __('Jamaica Dollar (J$)', 'cool-formkit'),			
                    '¥1' => __('Japan Yen (¥)', 'cool-formkit'),			
                    '£6' => __('Jersey Pound (£)', 'cool-formkit'),
                    'лв1' => __('Kazakhstan Tenge (лв)', 'cool-formkit'), //Thousand separator: Space ( ) Decimal separator: Period (.)			
                    '₩' => __('Korea (North) Won (₩)', 'cool-formkit'),	//Thousand separator: Space ( ) Decimal separator: Period (.)		
                    '₩' => __('Korea (South) Won (₩)', 'cool-formkit'),			
                    'лв2' => __('Kyrgyzstan Som (лв)', 'cool-formkit'),	 //Thousand separator: Space ( ) Decimal separator: Period (.)		
                    '₭' => __('Laos Kip (₭)', 'cool-formkit'),	
                    '£7' => __('Lebanon Pound (£)', 'cool-formkit'),			
                    '$16' => __('Liberia Dollar ($)', 'cool-formkit'),			
                    'ден' => __('Macedonia Denar (ден)', 'cool-formkit'),			
                    'RM' => __('Malaysia Ringgit (RM)', 'cool-formkit'),			
                    '₨2' => __('Mauritius Rupee (₨)', 'cool-formkit'),			
                    '$17' => __('Mexico Peso ($)', 'cool-formkit'),			
                    '₮' => __('Mongolia Tughrik (₮)', 'cool-formkit'),			
                    'MT' => __('Mozambique Metical (MT)', 'cool-formkit'),			
                    '$18' => __('Namibia Dollar ($)', 'cool-formkit'),			
                    '₨3' => __('Nepal Rupee (₨)', 'cool-formkit'),		  	
                    'ƒ1' => __('Netherlands Antilles Guilder (ƒ)', 'cool-formkit'),			
                    '$19' => __('New Zealand Dollar ($)', 'cool-formkit'),			
                    'C$' => __('Nicaragua Cordoba (C$)', 'cool-formkit'),			
                    '₦' => __('Nigeria Naira (₦)', 'cool-formkit'),			
                    'kr2' => __('Norway Krone (kr)', 'cool-formkit'),			
                    '﷼5'=> __('Oman Rial (﷼)', 'cool-formkit'),			
                    '₨4' => __('Pakistan Rupee (₨)', 'cool-formkit'),			
                    'B/.' => __('Panama Balboa (B/.)', 'cool-formkit'),			
                    'Gs' => __('Paraguay Guarani (Gs)', 'cool-formkit'),	
                    'S/.' => __('Peru Sol (S/.)', 'cool-formkit'),		
                    '₱' => __('Philippines Peso (₱)', 'cool-formkit'),		
                    'zł' => __('Poland Zloty (zł)', 'cool-formkit'),		
                    '﷼0' => __('Qatar Riyal (﷼)', 'cool-formkit'),		
                    'lei' => __('Romania Leu (lei)', 'cool-formkit'),		
                    '₽' => __('Russia Ruble (₽)', 'cool-formkit'),	 // space as the thousand separator and a comma (,) as the decimal separator.		
                    '£8' => __('Saint Helena Pound (£)', 'cool-formkit'),		
                    '﷼1' => __('Saudi Arabia Riyal (﷼)', 'cool-formkit'),		
                    'Дин.' => __('Serbia Dinar (Дин.)', 'cool-formkit'),		
                    '₨5' => __('Seychelles Rupee (₨)', 'cool-formkit'),		
                    '$20' => __('Singapore Dollar ($)', 'cool-formkit'),		
                    '$21' => __('Solomon Islands Dollar ($)', 'cool-formkit'),		
                    'S' => __('Somalia Shilling (S)', 'cool-formkit'),		
                    'R' => __('South Africa Rand (R)', 'cool-formkit'),		
                    '₨6' => __('Sri Lanka Rupee (₨)', 'cool-formkit'),		
                    'kr3' => __('Sweden Krona (kr)', 'cool-formkit'), // space as the thousand separator and a comma (,) as the decimal separator.		
                    'CHF' => __('Switzerland Franc (CHF)', 'cool-formkit'),		
                    '$22' => __('Suriname Dollar ($)', 'cool-formkit'),		
                    '£9' => __('Syria Pound (£)', 'cool-formkit'),		
                    'NT$' => __('Taiwan New Dollar (NT$)', 'cool-formkit'),
                    '฿' => __('Thailand Baht (฿)', 'cool-formkit'),		    	
                    'TT$' => __('Trinidad and Tobago Dollar (TT$)', 'cool-formkit'),		    	
                    '₺' => __('Turkey Lira (₺)', 'cool-formkit'),		    	
                    '$23' => __('Tuvalu Dollar ($)', 'cool-formkit'),		    	
                    '₴' => __('Ukraine Hryvnia (₴)', 'cool-formkit'),// space as the thousand separator and a comma (,) as the decimal separator.			    	
                    '£10' => __('United Kingdom Pound (£)', 'cool-formkit'),		    	
                    '$24'=> __('United States Dollar ($)', 'cool-formkit'),		    	
                    '$U' => __('Uruguay Peso ($U)', 'cool-formkit'),		    	
                    'лв3' => __('Uzbekistan Som (лв)', 'cool-formkit'),// space as the thousand separator and a comma (,) as the decimal separator.			    			    	
                    'Bs' => __('Venezuela Bolívar (Bs)', 'cool-formkit'),		    	
                    '₫' => __('VietNam Dong (₫)', 'cool-formkit'),		    	
                    '3﷼' => __('Yemen Rial (﷼)', 'cool-formkit'),		    	
                    '$25' => __('Zimbabwe Dollar ($)', 'cool-formkit'),		    		    	
				),
                'default'      => '$24', 
				'condition'    => array(
					'field_type' => 'currency',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),

            'cfkef-decimal-upto'  => array(
				'name'         => 'cfkef-decimal-upto',
				'label'        => esc_html__( 'Decimal upto', 'cool-formkit' ),
                'type' => \Elementor\Controls_Manager::NUMBER,
                'step' => 1,
                'default' => 2,
                'condition' => array(
                    'field_type' => 'currency',
                    ),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
		);
        

		$control_data['fields'] = \array_merge( $control_data['fields'], $field_controls );
		$widget->update_control( 'form_fields', $control_data );
	}

    public function validation( $field, $record, $ajax_handler ) {
        $value = $field['value'];
        $is_required = ! empty( $field['required'] );

        if ( ! $is_required ) {
            return;
        }

        $cleaned = preg_replace( '/[^0-9]/', '', $value );

        if ( empty( $cleaned ) ) {
            $ajax_handler->add_error( $field['id'], __( 'This field is required.', 'cool-formkit' ) );
        }
    }
    
}
}
?>
