<?php
namespace Formipay;
use Formipay\Traits\SingletonTrait;

if ( ! defined( 'ABSPATH' ) ) exit;

class Form {

    use SingletonTrait;

	/**
	 * Initializes the plugin by setting filters and administration functions.
	 */
    
    protected function __construct() {

        add_action( 'init',                                 [$this, 'cpt'] );
        add_action( 'admin_menu',                           [$this, 'menu'] );
    
        add_action( 'add_meta_boxes_formipay-form',         [$this, 'metaboxes'] );
        add_action( 'save_post_formipay-form',              [$this, 'save_formipay_metabox'] );
        add_action( 'admin_enqueue_scripts',                [$this, 'enqueue_admin'] );

        add_filter( 'formipay/admin-editor/field-form',     [$this, 'form_builder_canvas'] );

        add_filter( 'stm_wpcfto_boxes',                     [$this, 'cpt_post_fields_box'] );
        add_filter( 'stm_wpcfto_fields',                    [$this, 'cpt_post_fields_content'] );
        add_filter( 'formipay/form-config',                 [$this, 'settings_config'], 20 );
        add_filter( 'formipay/form-config',                 [$this, 'appearance_config'], 40 );
        add_filter( 'formipay/form-config',                 [$this, 'cart_config'], 80 );
        add_filter( 'formipay/form-config',                 [$this, 'donation_config'], 90 );
        add_filter( 'formipay/form-config',                 [$this, 'submission_config'], 100 );

        add_action( 'wp_ajax_fetch_formipay_settings',      [$this, 'fetch_formipay_settings'] );
        add_action( 'wp_ajax_fetch_formipay_fields',        [$this, 'fetch_formipay_fields'] );

        add_action( 'wp_ajax_formipay-tabledata-forms',     [$this, 'formipay_tabledata_forms'] );
        add_action( 'wp_ajax_formipay-create-form-post',    [$this, 'formipay_create_form_post'] );
        add_action( 'wp_ajax_formipay-delete-form',         [$this, 'formipay_delete_form'] );
        add_action( 'wp_ajax_formipay-bulk-delete-form',    [$this, 'formipay_bulk_delete_form'] );
        add_action( 'wp_ajax_formipay-duplicate-form',      [$this, 'formipay_duplicate_form'] );

    }

    public function cpt() {
        
        $labels = array(
            'name'                  => __('Form', 'formipay'),
            'singular_name'         => __('Form', 'formipay'),
            'menu_name'             => 'Formipay',
            'add_new'               => __('Add New', 'formipay'),
            'add_new_item'          => __('Add New Form', 'formipay'),
            'edit'                  => __('Edit', 'formipay'),
            'edit_item'             => __('Edit Form', 'formipay'),
            'new_item'              => __('New Form', 'formipay'),
            'view'                  => __('View', 'formipay'),
            'view_item'             => __('View Form', 'formipay'),
            'search_items'          => __('Search Form', 'formipay'),
            'not_found'             => __('No forms found', 'formipay'),
            'not_found_in_trash'    => __('No forms found in trash', 'formipay'),
            'parent'                => __('Form Parent', 'formipay')
        );
    
        $args = array(
            'label'                 => 'Formipay',
            'description'           => __('Form builder to initiate any payment purpose', 'formipay'),
            'labels'                => $labels,
            'public'                => false,
            'supports'              => array( 'title', ),
            'hierarchical'          => true,
            // 'taxonomies'            => array( 'formipay-form-category' ),
            'has_archive'           => true,
            'rewrite'               => array( 'slug' => 'form' ),
            'show_ui'               => true,
            'show_in_menu'          => false,
            'show_in_rest'          => false,
            'query_var'             => false,
        );
    
        register_post_type( 'formipay-form', $args );
    }

    public function menu() {
        add_submenu_page( 
            'formipay', 
            __( 'Forms', 'formipay' ), 
            __( 'Forms', 'formipay' ), 
            'manage_options', 
            'formipay',
            [$this, 'formipay_form'] ,
            5
        );
    }

    public function formipay_form() {
        include_once FORMIPAY_PATH . 'admin/page-forms.php';
    }

    public function metaboxes($post) {

        global $current_screen;

        add_meta_box(
            'formipay_canvas',
            'Formipay',
            [$this, 'render_formipay_metabox'],
            'formipay-form',
            'advanced',
            'high'
        );

        if($current_screen->post_type == 'formipay-form' && $current_screen->base == 'post'){
            add_meta_box(
                'form_shortcode',
                'Shortcode',
                [$this, 'render_shortcode_metabox'],
                'formipay-form',
                'side',
                'high'
            );
        }

    }

    public function cpt_post_fields_box($boxes) {
        $boxes['formipay_form_settings'] = array(
            'post_type' => array('formipay-form'),
            'label' => __('Config', 'formipay'),
        );
    
        return $boxes;
    }

    public function cpt_post_fields_content($fields) {

        $fields['formipay_form_settings'] = array();

        $fields = apply_filters( 'formipay/form-config', $fields );
    
        return $fields;

    }

    public function settings_config($fields) {

        // Group : Fields
        $field_group = array(
            'setting_field_group' => array(
                'type'  => 'group_title',
                'label' => __( 'Field', 'formipay' ),
                'group' => 'started'
            ),
            'label_visibility' => array(
                'type' => 'select',
                'label' => __('Label Visibility', 'formipay'),
                'options' => array(
                    'show' => 'Show',
                    'hide' => 'Hide',
                ),
                'value' => 'show'
            ),
            'field_placeholder' => array(
                'type' => 'select',
                'label' => __( 'Placeholder', 'formipay' ),
                'options' => array(
                    'placeholder' => __( 'Placeholder', 'formipay' ),
                    'label' => __( 'Label', 'formipay' )
                ),
                'value' => 'label'
            ),
            'required_field_sign' => array(
                'type' => 'select',
                'label' => __( 'Required Field Sign', 'formipay' ),
                'options' => array(
                    'asterisk' => __('Asterisk', 'formipay'),
                    'text' => __( 'Text', 'formipay' )
                ),
                'value' => 'asterisk'
            ),
            'required_field_text' => array(
                'type' => 'text',
                'label' => __( 'Required Field Text', 'formipay' ),
                'value' => __('(required)', 'formipay'),
                'dependency' => array(
                    'key' => 'required_field_sign',
                    'value' => 'text'
                )
            ),
            'required_field_color' => array(
                'type' => 'color',
                'label' => __( 'Required Field Sign/Text Color', 'formipay' ),
                'value' => 'rgba(255, 0, 0, 1)',
                'required' => true
            ),
            'empty_required_text_field' => array(
                'type' => 'hint_textarea',
                'label' => __( 'Empty Required Text Field', 'formipay' ),
                'value' => __( 'Ups! {{field}} is required.', 'formipay' ),
                'hints' => array(
                    'field' => __( 'Current Field', 'formipay' )
                ),
                'description' => __('Type {{field}} to get the label of the field', 'formipay'),
                'required' => true
            ),
            'empty_required_select_field' => array(
                'type' => 'hint_textarea',
                'label' => __( 'Empty Required Select Field', 'formipay' ),
                'value' => __( 'Select an option of {{field}} is required.', 'formipay' ),
                'hints' => array(
                    'field' => __( 'Current Field', 'formipay' )
                ),
                'description' => __('Type {{field}} to get the label of the field', 'formipay'),
                'required' => true
                // 'group' => 'ended'
            )
        );

        $field_group = apply_filters( 'formipay/form-settings/tab:settings/group:fields', $field_group );

        $last_field_group = array_key_last($field_group);
        $field_group[$last_field_group]['group'] = 'ended';

        // Group Summary
        $summary_group = array(
            'setting_field' => array(
                'type'  => 'group_title',
                'label' => __( 'Summary', 'formipay' ),
                'group' => 'started'
            ),
            'order_review_title' => array(
                'type' => 'text',
                'label' => __( 'Order Review Title', 'formipay' ),
                'value' => 'Order Review',
                // 'group' => 'ended'
            ),
        );

        $summary_group = apply_filters( 'formipay/form-settings/tab:settings/group:summary', $summary_group );

        $last_summary_group = array_key_last($summary_group);
        $summary_group[$last_summary_group]['group'] = 'ended';

        $settings_all_fields = array_merge($field_group, $summary_group);

        $settings_all_fields = apply_filters( 'formipay/form-settings/tab:settings', $settings_all_fields );

        $fields['formipay_form_settings']['settings'] = array(
            'name' => __('Settings', 'formipay'),
            'fields' => $settings_all_fields
        );

        return $fields;

    }

    public function appearance_config($fields) {

        // Schedule Group
        $schedule_group = array(
            'conditional_schedule_group' => array(
                'type'  => 'group_title',
                'label' => __( 'Schedule', 'formipay' ),
                'description' => __( 'You can control start to end date for showing this form.', 'formipay' ),
                'submenu' => __( 'Display Logic', 'formipay' ),
                'group' => 'started'
            ),
            'schedule_toggle' => array(
                'type' => 'checkbox',
                'label' => __( 'Activate Schedule', 'formipay' ),
                'submenu' => __( 'Display Logic', 'formipay' ),
            ),
            'daterange' => array(
                'type' => 'dates',
                'label' => __( 'Date Range', 'formipay' ),
                'dependency' => array(
                    'key' => 'schedule_toggle',
                    'value' => 'not_empty'
                ),
                'submenu' => __( 'Display Logic', 'formipay' ),
                'required' => true
            ),
            'waiting_message' => array(
                'type' => 'editor',
                'label' => __( 'Waiting Message', 'formipay' ),
                'value' => 'This form will be available on .....',
                'dependency' => array(
                    'key' => 'schedule_toggle',
                    'value' => 'not_empty'
                ),
                'submenu' => __( 'Display Logic', 'formipay' ),
                'required' => true
            ),
            'expired_message' => array(
                'type' => 'editor',
                'label' => __( 'Expired Message', 'formipay' ),
                'value' => 'This form is no longer available.',
                'dependency' => array(
                    'key' => 'schedule_toggle',
                    'value' => 'not_empty'
                ),
                'submenu' => __( 'Display Logic', 'formipay' ),
                'required' => true
            )
        );

        $schedule_group = apply_filters( 'formipay/form-settings/tab:appearance/group:schedule', $schedule_group );

        $last_schedule_group = array_key_last($schedule_group);
        $schedule_group[$last_schedule_group]['group'] = 'ended';

        // Layout Group
        $layout_group = array(
            'form_layout_columns' => array(
                'type' => 'image_select',
                'label' => __( 'Layout Column', 'formipay' ),
                'width' => 100,
                'height' => 100,
                'value' => 1,
                'options' => array(
                    1 => array(
                        'alt'   => '1 Column',
                        'img'   => FORMIPAY_URL . 'admin/assets/img/formipay_layout_1.png'
                    ),
                    2 => array(
                        'alt'   => '2 Columns',
                        'img'   => FORMIPAY_URL . 'admin/assets/img/formipay_layout_2.png'
                    ),
                ),
                'submenu' => __('Layout', 'formipay'),
                'description' => __( 'Choose your preferred layout. 2 columns layout will separates the order review box and submit button to the right side but will not applied when you have page break inner the form. ', 'formipay' ),
            ),
            'form_static_elements_sort' => array(
                'type' => 'sorter',
                'label' => __( 'Static Elements Sort', 'formipay' ),
                'options' => array(
                    array(
                        'id' => 'inactive',
                        'name' => __( 'Inactive', 'formipay' ),
                        'options' => apply_filters('formipay/admin-editor/layout/static-elements-sort',  [
                            [
                                'id' => 'submit_response_notice',
                                'label' => __( 'Submit Response Notice', 'formipay' ),
                            ]    
                        ]),
                    ),
                    array(
                        'id' => 'active',
                        'name' => __( 'Active', 'formipay' ),
                        'options' => array(
                            array(
                                'id' => 'payment_methods',
                                'label' => __( 'Payment Methods', 'formipay' ),
                            ),
                            array(
                                'id' => 'order_review',
                                'label' => __( 'Order Review', 'formipay' )
                            ),
                            array(
                                'id' => 'submit_button',
                                'label' => __( 'Submit Button', 'formipay' ),
                                'icon' => 'fa fa-exclamation',
                                'class' => 'disable'
                            )
                        )
                    )
                ),
                'submenu' => __('Layout', 'formipay'),
                'required' => true
            ),
            'form_display_as' => array(
                'type' => 'image_select',
                'label' => __( 'Display as', 'formipay' ),
                'width' => 100,
                'height' => 100,
                'value' => 'div',
                'options' => array(
                    'div' => array(
                        'alt'   => 'On Page',
                        'img'   => FORMIPAY_URL . 'admin/assets/img/formipay_layout_2.png'
                    ),
                    'popup' => array(
                        'alt'   => 'Popup',
                        'img'   => FORMIPAY_URL . 'admin/assets/img/formipay_display_popup.png'
                    )
                ),
                'submenu' => __('Layout', 'formipay'),
                'description' => __( 'Choose your preferred layout. Display as popup will show the button only on the page, and the form will be shown after button click.', 'formipay' ),
            )
        );

        // Popup Group
        $popup_group = array(
            'popup_button_group' => array(
                'type'          => 'group_title',
                'label'         => __( 'Popup Button', 'formipay' ),
                'submenu'       => __( 'Layout', 'formipay' ),
                'description'   => __( 'Popup button is the only element that will be shown until it clicked and pop a modal, not the button inner the form.', 'formipay' ),
                'dependency' => array(
                    'key' => 'form_display_as',
                    'value' => 'popup'
                ),
                'group'         => 'started'
            ),
            'popup_click_selector' => array(
                'type' => 'checkbox',
                'label' => __( 'Define selector instead build a button', 'formipay' ),
                'description' => __( 'If active, you only need to input a class or ID of the target element. So on click the element will trigger open the popup.', 'formipay' ),
                'dependency' => array(
                    'key' => 'form_display_as',
                    'value' => 'popup'
                ),
                'submenu' => __( 'Layout', 'formipay' ),
            ),
            'popup_trigger_selector' => array(
                'type' => 'text',
                'label' => __( 'Selector', 'formipay' ),
                'description' => __( 'Example: <code>#buy</code> for element ID or <code>.paynow</code> for element class', 'formipay' ),
                'dependency' => array(
                    array(
                        'key' => 'form_display_as',
                        'value' => 'popup'
                    ),
                    array(
                        'key' => 'popup_click_selector',
                        'value' => 'not_empty'
                    )
                ),
                'dependencies' => '&&',
                'submenu' => __( 'Layout', 'formipay' ),
            ),
            'popup_button_text' => array(
                'type' => 'text', 
                'label' => __('Trigger Button Text', 'formipay'),
                'value' => __( 'Order Now', 'formipay' ),
                'dependency' => array(
                    array(
                        'key' => 'form_display_as',
                        'value' => 'popup'
                    ),
                    array(
                        'key' => 'popup_click_selector',
                        'value' => 'empty'
                    )
                ),
                'dependencies' => '&&',
                'submenu' => __( 'Layout', 'formipay' ),
                'required' => true
            ),
            'popup_button_bg_color' => array(
                'type' => 'link_color', 
                'label' => __('Background Color', 'formipay'),
                'dependency' => array(
                    array(
                        'key' => 'form_display_as',
                        'value' => 'popup'
                    ),
                    array(
                        'key' => 'popup_click_selector',
                        'value' => 'empty'
                    )
                ),
                'dependencies' => '&&',
                'submenu' => __( 'Layout', 'formipay' ),
                'required' => true
            ),
            'popup_button_text_color' => array(
                'type' => 'link_color', 
                'label' => __('Text Color', 'formipay'),
                'dependency' => array(
                    array(
                        'key' => 'form_display_as',
                        'value' => 'popup'
                    ),
                    array(
                        'key' => 'popup_click_selector',
                        'value' => 'empty'
                    )
                ),
                'dependencies' => '&&',
                'submenu' => __( 'Layout', 'formipay' ),
                'required' => true
            ),
            'popup_button_border_color' => array(
                'type' => 'link_color', 
                'label' => __('Border Color', 'formipay'),
                'dependency' => array(
                    array(
                        'key' => 'form_display_as',
                        'value' => 'popup'
                    ),
                    array(
                        'key' => 'popup_click_selector',
                        'value' => 'empty'
                    )
                ),
                'dependencies' => '&&',
                'submenu' => __( 'Layout', 'formipay' ),
                'required' => true
            ),
            'popup_button_width' => array(
                'type' => 'select',
                'label' => __('Button Width', 'formipay'),
                'options' => array(
                    'fullwidth' => __( 'Fullwidth', 'formipay' ),
                    'fit-content' => __( 'Fit Content', 'formipay' )
                ),
                'value' => 'fullwidth',
                'submenu' => __( 'Layout', 'formipay' ),
                'dependency' => array(
                    array(
                        'key' => 'form_display_as',
                        'value' => 'popup'
                    ),
                    array(
                        'key' => 'popup_click_selector',
                        'value' => 'empty'
                    )
                ),
                'dependencies' => '&&',
                'required' => true
            ),
            'popup_button_alignment' => array(
                'type' => 'radio',
                'label' => __('Button Alignment', 'formipay'),
                'options'   => array(
                    'left'      => '<i class="bi bi-text-left"></i> Left',
                    'center'    => '<i class="bi bi-text-center"></i> Center',
                    'right'     => '<i class="bi bi-text-right"></i> Right',
                ),
                'value' => 'center',
                'submenu' => __( 'Layout', 'formipay' ),
                'dependency' => array(
                    array(
                        'key' => 'form_display_as',
                        'value' => 'popup'
                    ),
                    array(
                        'key' => 'popup_button_width',
                        'value' => 'fit-content'
                    ),
                    array(
                        'key' => 'popup_click_selector',
                        'value' => 'empty'
                    )
                ),
                'dependencies' => '&&',
                'group' => 'ended',
                'required' => true
            ),
            'popup_wrapper_group' => array(
                'type'          => 'group_title',
                'label'         => __( 'Popup Wrapper', 'formipay' ),
                'submenu'       => __( 'Layout', 'formipay' ),
                'description'   => __( 'Your form will be included in this wrapper.', 'formipay' ),
                'dependency' => array(
                    'key' => 'form_display_as',
                    'value' => 'popup'
                ),
                'group'         => 'started'
            ),
            'popup_content_wrapper_width' => array(
                'type' => 'text',
                'label' => __('Width', 'formipay'),
                'value' => '600',
                'submenu' => __( 'Layout', 'formipay' ),
                'dependency' => array(
                    'key' => 'form_display_as',
                    'value' => 'popup'
                ),
                'required' => true,
                'description' => __( 'Set the width in pixel (px)', 'formipay' )
            ),
            'popup_content_wrapper_title' => array(
                'type' => 'text',
                'label' => __('Title', 'formipay'),
                'value' => 'Checkout',
                'submenu' => __( 'Layout', 'formipay' ),
                'dependency' => array(
                    'key' => 'form_display_as',
                    'value' => 'popup'
                ),
                'required' => true
            ),
            'popup_content_wrapper_backdrop_color' => array(
                'type' => 'color',
                'label' => __('Backdrop Color', 'formipay'),
                'value' => 'rgba(0, 0, 0, .75)',
                'submenu' => __( 'Layout', 'formipay' ),
                'dependency' => array(
                    'key' => 'form_display_as',
                    'value' => 'popup'
                ),
                'required' => true
            )
        );
        
        $popup_group = apply_filters( 'formipay/form-settings/tab:appearance/group:popup', $popup_group );

        $last_popup_group = array_key_last($popup_group);
        $popup_group[$last_popup_group]['group'] = 'ended';

        // Multistep Group
        $multistep_group = array(
            'setting_multistep_point_group' => array(
                'type'  => 'group_title',
                'label' => __( 'Multistep Point', 'formipay' ),
                'description' => __( 'Multistep points are located on the top of the form. This setting only applied if you have page breaks in the form.', 'formipay' ),
                'submenu' => __( 'Multistep', 'formipay' ),
                'group' => 'started'
            ),
            'multistep_point_shape' => array(
                'type' => 'image_select',
                'label' => __( 'Point Shape', 'formipay' ),
                'options' => array(
                    'rectangle' => array(
                        'alt' => __( 'Rectangle', 'formipay' ),
                        'img' => FORMIPAY_URL . 'admin/assets/img/multistep_point_shape_rectangle.png'
                    ),
                    'rounded' => array(
                        'alt' => __( 'Rounded', 'formipay' ),
                        'img' => FORMIPAY_URL . 'admin/assets/img/multistep_point_shape_rounded.png'
                    ),
                    'circle' => array(
                        'alt' => __( 'Circle', 'formipay' ),
                        'img' => FORMIPAY_URL . 'admin/assets/img/multistep_point_shape_circle.png'
                    ),
                ),
                'value' => 'circle',
                'submenu' => __( 'Multistep', 'formipay' ),
            ),
            'multistep_point_symbol' => array(
                'type' => 'image_select',
                'label' => __( 'Point Symbol', 'formipay' ),
                'options' => array(
                    'index' => array(
                        'alt' => __( 'Incremental', 'formipay' ),
                        'img' => FORMIPAY_URL . 'admin/assets/img/multistep_sort.png'
                    ),
                    'icon' => array(
                        'alt' => __( 'Icon', 'formipay' ),
                        'img' => FORMIPAY_URL . 'admin/assets/img/multistep_icon.png'
                    )
                ),
                'value' => 'index',
                'submenu' => __( 'Multistep', 'formipay' )
            ),
            'multistep_point_icons' => array(
                'type' => 'repeater',
                'label' => __( 'Point Icon', 'formipay' ),
                'fields' => array(
                    'field_id' => array(
                        'type' => 'text',
                        'label' => __( 'Field ID', 'formipay' ),
                        'description' => __( 'Copy one of your page break field ID to match the icon', 'formipay' ),
                        'is_group_title' => true,
                        'required' => true
                    ),
                    'script' => array(
                        'type' => 'textarea',
                        'label' => __( 'Icon Script', 'formipay' ),
                        'description' => sprintf( 'Choose your preferred icon from <a href="https://icon-sets.iconify.design/" target="_blank">Icon Sets</a> and copy its SVG code', 'formipay' ),
                        'required' => true
                    )
                ),
                'dependency' => array(
                    'key' => 'multistep_point_symbol',
                    'value' => 'icon'
                ),
                'submenu' => __( 'Multistep', 'formipay' )
            )
        );
        
        $multistep_group = apply_filters( 'formipay/form-settings/tab:appearance/group:multistep', $multistep_group );

        $last_multistep_group = array_key_last($multistep_group);
        $multistep_group[$last_multistep_group]['group'] = 'ended';

        // Multistep Button Group
        $multistep_button_group = array(
            'setting_multistep_button_group' => array(
                'type'  => 'group_title',
                'label' => __( 'Multistep Button', 'formipay' ),
                'description' => __( 'Multistep buttons are located on the top of the form. This setting only applied if you have page breaks in the form.', 'formipay' ),
                'submenu' => __( 'Multistep', 'formipay' ),
                'group' => 'started'
            ),
            'multistep_btn_next_text' => array(
                'type' => 'text',
                'label' => __( 'Next Button Text', 'formipay' ),
                'value' => __( 'Next', 'formipay' ),
                'submenu' => __( 'Multistep', 'formipay' ),
                'required' => true
            ),
            'multistep_btn_prev_text' => array(
                'type' => 'text',
                'label' => __( 'Prev Button Text', 'formipay' ),
                'value' => __( 'Prev', 'formipay' ),
                'submenu' => __( 'Multistep', 'formipay' ),
                'required' => true
            ),
            'multistep_btn_size' => array(
                'type' => 'select',
                'label' => __( 'Size', 'formipay' ),
                'options' => array(
                    'smaller_than_submit' => __( 'Smaller than submit button', 'formipay' ),
                    'same_as_submit' => __( 'Same as submit button', 'formipay' ),
                    'larger_than_submit' => __( 'Larger than submit button', 'formipay' )
                ),
                'value' => 'same_as_submit',
                'submenu' => __( 'Multistep', 'formipay' )
            )
        );
        
        $multistep_button_group = apply_filters( 'formipay/form-settings/tab:appearance/group:multistep-button', $multistep_button_group );

        $last_multistep_button_group = array_key_last($multistep_button_group);
        $multistep_button_group[$last_multistep_button_group]['group'] = 'ended';

        // Submit Button Group 
        $submit_button_group = array(
            'setting_submit_button' => array(
                'type'  => 'group_title',
                'label' => __( 'Submit Button', 'formipay' ),
                'description' => __( 'All settings are only affect to form submit button, unless background and text color.', 'formipay' ),
                'submenu' => __( 'Submit Button', 'formipay' ),
                'group' => 'started'
            ),
            'button_text' => array(
                'type' => 'text', 
                'label' => __('Text', 'formipay'),
                'placeholder' => 'Submit',
                'value' => 'Submit',
                'submenu' => __( 'Submit Button', 'formipay' ),
                'required' => true
            ),
            'button_processing_text' => array(
                'type' => 'text', 
                'label' => __('Processing Text', 'formipay'),
                'placeholder' => 'Processing',
                'value' => 'Processing...',
                'submenu' => __( 'Submit Button', 'formipay' ),
                'required' => true
            ),
            'button_bg_color' => array(
                'type' => 'link_color', 
                'label' => __('Background Color', 'formipay'),
                'submenu' => __( 'Submit Button', 'formipay' ),
                'value' => [
                    'regular'  => '#587FE4',
                    'hover'    => '#2357df',
                    'active'   => '#2357df',
                ],
                'required' => true
            ),
            'button_text_color' => array(
                'type' => 'link_color', 
                'label' => __('Text Color', 'formipay'),
                'submenu' => __( 'Submit Button', 'formipay' ),
                'value' => [
                    'regular'  => '#ffffff',
                    'hover'    => '#ffffff',
                    'active'   => '#ffffff',
                ],
                'required' => true
            ),
            'button_border_color' => array(
                'type' => 'link_color', 
                'label' => __('Border Color', 'formipay'),
                'submenu' => __( 'Submit Button', 'formipay' ),
                'value' => [
                    'regular'  => '#587FE4',
                    'hover'    => '#2357df',
                    'active'   => '#2357df',
                ],
                'required' => true
            ),
            'button_width' => array(
                'type' => 'select', 
                'label' => __('Width', 'formipay'),
                'options' => array(
                    'fullwidth' => 'Fullwidth',
                    'fit-content' => 'Fit Content'
                ),
                'value' => 'fullwidth',
                'submenu' => __( 'Submit Button', 'formipay' ),
            ),
            'button_position' => array(
                'type' => 'radio', 
                'label' => __('Alignment', 'formipay'),
                'options'   => array(
                    'left'      => '<i class="bi bi-text-left"></i> Left',
                    'center'    => '<i class="bi bi-text-center"></i> Center',
                    'right'     => '<i class="bi bi-text-right"></i> Right',
                ),
                'value' => 'right',
                'dependency' => array(
                    'key' => 'button_width',
                    'value' => 'fit-content'
                ),
                'required' => true,
                'submenu' => __( 'Submit Button', 'formipay' )
            )
        );
        
        $submit_button_group = apply_filters( 'formipay/form-settings/tab:appearance/group:submit-button', $submit_button_group );

        $last_submit_button_group = array_key_last($submit_button_group);
        $submit_button_group[$last_submit_button_group]['group'] = 'ended';

        $appearance_all_fields = array_merge($schedule_group, $layout_group, $popup_group, $multistep_group, $multistep_button_group, $submit_button_group);

        $appearance_all_fields = apply_filters( 'formipay/form-settings/tab:appearance', $appearance_all_fields );

        $fields['formipay_form_settings']['appearance'] = array(
            'name' => __('Appearance', 'formipay'),
            'fields' => $appearance_all_fields
        );

        return $fields;

    }

    public function cart_config($fields) {

        $cart_behavior = [
            'cart_behavior_group' => [
                'type'          => 'group_title',
                'label'         => __( 'Cart Behavior', 'formipay' ),
                'group'         => 'started',
                'description'   => __( 'This will affect to the cart items that calculated in the form.', 'formipay' )
            ],
            'added_to_cart_items' => [
                'type'          => 'checkbox',
                'label'         => __( 'Add cart items to order items.', 'formipay' ),
                'description'   => __( 'Form will check if cart has items and add them to the order items.', 'formipay' ),
            ]
        ];

        $cart_behavior = apply_filters( 'formipay/form-settings/tab:cart/group:behavior', $cart_behavior );

        $last_cart_behavior = array_key_last($cart_behavior);
        $cart_behavior[$last_cart_behavior]['group'] = 'ended';

        $global_currencies = get_global_currency_array();
        $default_currency = formipay_default_currency();

        $cart_items = [
            'cart_items_group' => [
                'type'          => 'group_title',
                'label'         => __( 'Additional Order Items', 'formipay' ),
                'group'         => 'started',
                'description'   => __( 'Add static product or custom item to form as default and non-editable item in order items.', 'formipay' )
            ],
            // 'static_products' => [
            //     'type'          => 'autocomplete',
            //     'post_type'     => ['formipay-product'],
            //     'label'         => __( 'Assign Product', 'formipay' ),
            //     'description'   => __( 'Selected products will be added to the order items automatically, even if it is not added to cart.', 'formipay' )
            // ],
            'static_product' => [
                'type'          => 'repeater',
                'label'         => __( 'Static Product', 'formipay' ),
                'description'   => __( 'Selected products will be added to the order items automatically, even if it is not added to cart.', 'formipay' ),
                'fields' => [
                    'default_qty' => [
                        'type' => 'number',
                        'label' => __( 'Default Qty', 'formipay' ),
                        'description' => __( 'Set default quantity', 'formipay' )
                    ],
                    'editable_qty' => [
                        'type' => 'checkbox',
                        'label' => __( 'Editable Qty', 'formipay' ),
                        'description' => __( 'User can set quantity as they want', 'formipay' )
                    ],
                    'minimum_qty' => [
                        'type' => 'number',
                        'label' => __( 'Minimum Qty', 'formipay' ),
                        'description' => __( 'Restrict buyer to set below this number', 'formipay' ),
                        'dependency' => [
                            'key' => 'editable_qty',
                            'value' => 'not_empty'
                        ]
                    ],
                    'maximum_qty' => [
                        'type' => 'number',
                        'label' => __( 'Minimum Qty', 'formipay' ),
                        'description' => __( 'Restrict buyer to set below this number', 'formipay' ),
                        'dependency' => [
                            'key' => 'editable_qty',
                            'value' => 'not_empty'
                        ]
                    ],
                ]
            ],
            'static_items'    => [
                'type'          => 'repeater',
                'label'         => __( 'Static Items', 'formipay' ),
                'description'   => __( 'Static items will behave like fee that will affect to order calculation but nothing will be delivered.', 'formipay' ),
                'fields'        => [
                    'label'     => [
                        'type'  => 'text',
                        'label' => __( 'Item Label', 'formipay' ),
                        'required'  => true,
                        'is_group_title' => true
                    ],
                    'quantity'  => [
                        'type'  => 'number',
                        'label' => __( 'Item Quantity', 'formipay' ),
                        'value' => 1,
                        'required'  => true
                    ],
                ]
            ]
        ];

        foreach($global_currencies as $currency){
            $default_currency_symbol = formipay_get_currency_data_by_value($default_currency, 'symbol');
            $currency_symbol = formipay_get_currency_data_by_value($currency['currency'], 'symbol');
            $currency_title = ucwords(formipay_get_currency_data_by_value($currency['currency'], 'title'));
            $decimal_digits = intval($currency['decimal_digits']);
            $step = $decimal_digits * 10;
            $step = $step > 0 ? 1 / $step : 1;
            $cart_items['static_items']['fields']['amount_'.$currency_symbol] = [
                'type'          => 'number',
                'step'          => $step,
                'min'           => 0,
                'label'         => __( 'Item Price in '.$currency_symbol, 'formipay' ),
                'description'   => __( 'Will be calculated to item quantity', 'formipay' ),
                'placeholder'   => __( 'Auto', 'formipay' )
            ];

            if(count($global_currencies) > 1){
                if($default_currency_symbol === $currency_symbol){
                    $cart_items['static_items']['fields']['amount_'.$currency_symbol]['description'] = sprintf(
                        __( 'This is your default currency. <a href="%s" target="_blank">Change in Settings</a>', 'formipay' ),
                        admin_url('/admin.php?page=formipay-settings')
                    );
                    $cart_items['static_items']['fields']['amount_'.$currency_symbol]['required'] = true;
                    $cart_items['static_items']['fields']['amount_'.$currency_symbol]['placeholder'] = __( 'Enter Price...', 'formipay' );
                }else{
                    $cart_items['static_items']['fields']['amount_'.$currency_symbol]['description'] = sprintf(
                        __( 'System will calculate the price in %s based on exchange rate against %s when you leave these empty.', 'formipay' ),
                        $currency_symbol, $default_currency_symbol
                    );
                }
            }else{
                $cart_items['static_items']['fields']['amount_'.$currency_symbol]['label'] = __( 'Item Price', 'formipay' );
                $cart_items['static_items']['fields']['amount_'.$currency_symbol]['placeholder'] = __( 'Enter Price...', 'formipay' );
            }
        }

        $cart_items = apply_filters( 'formipay/form-settings/tab:cart/group:items', $cart_items );

        $last_cart_items = array_key_last($cart_items);
        $cart_items[$last_cart_items]['group'] = 'ended';

        $cart_fields = array_merge($cart_behavior, $cart_items);

        $fields['formipay_form_settings']['cart_items'] = array(
            'name' => __('Cart Items', 'formipay'),
            'fields' => $cart_fields
        );

        return $fields;

    }

    public function donation_config($fields) {
        $donation_set = [
            'donation_group' => [
                'type'          => 'group_title',
                'label'         => __( 'Donation', 'formipay' ),
                'group'         => 'started',
                'description'   => sprintf(__( '⚠️ <b>When enabled, the donation amount will override the total price at checkout.</b>
                                    All products or order items attached to this form will be charged according to the donation amount specified here, regardless of their individual prices.
                                    This allows donors to contribute a custom or preset donation amount instead of paying the sum of product prices.', 'formipay' ))
            ],
            'donation_active' => [
                'type'          => 'checkbox',
                'label'         => __( 'Activate', 'formipay' ),
            ],
            'donation_amount_preset' => [
                'type'          => 'repeater',
                'label'         => __( 'Amount Presets', 'formipay' ),
                'description'   => __( 'This will be sorted as clickable button to set the donation amount on checkout.', 'formipay' ),
                'fields'        => [
                    'preset_amount' => [
                        'type' => 'number',
                        'label' => __( 'Value', 'Formipay' ),
                        'step' => 0.01,
                        'required' => true
                    ],
                    'preset_label' => [
                        'type' => 'text',
                        'label' => __( 'Label', 'formipay' ),
                        'is_group_title' => true,
                        'required' => true
                    ]
                ],
                'dependency' => [
                    'key' => 'donation_active',
                    'value' => 'not_empty'
                ]
            ],
            'donation_custom_amount_label' => [
                'type'  => 'text',
                'label' => __( 'Custom Amount Label', 'formipay' ),
                'value' => __( 'Other Amount', 'formipay' ),
                'description' => __( 'Leave this empty to disable other amount button.', 'formipay' ),
                'dependency' => [
                    'key' => 'donation_active',
                    'value' => 'not_empty'
                ]
            ]    
        ];

        $donation_set = apply_filters( 'formipay/form-settings/tab:cart/group:donation', $donation_set );

        $last_donation_set = array_key_last($donation_set);
        $donation_set[$last_donation_set]['group'] = 'ended';

        $fields['formipay_form_settings']['donation'] = array(
            'name' => __('Donation', 'formipay'),
            'fields' => $donation_set
        );

        return $fields;

    }

    public function submission_config($fields) {

        $hints = formipay_editor_hints();

        $success_response_hints = apply_filters( 'formipay/admin-editor/config/success-response-hints', [
            'order_id' => __( 'Order ID', 'formipay' ),
            'order_status' => __( 'Order Status', 'formipay' )
        ] );

        // Submit Response Group
        $submit_response_group = array(
            'submit_response_group' => array(
                'type'  => 'group_title',
                'label' => __( 'Submit Response', 'formipay' ),
                'description' => __( 'After clicking the submit button, visitor will get notice message that tells the submission is success or failed, before the action triggered.', 'formipay' ),
                'group' => 'started'
            ),
            'response_type' => array(
                'type' => 'select',
                'label' => __( 'Response Type', 'formipay' ),
                'options' => array(
                    'notice' => __( 'Notice', 'formipay' ),
                    'popup' => __( 'Popup', 'formipay' )
                ),
                'value' => 'notice',
                'required' => true
            ),
            'success_response_content' => array(
                'type' => 'hint_textarea',
                'label' => __( 'Success Response Content', 'formipay' ),
                'value' => 'Order #{{order_id}} has been created.',
                'hints' => $success_response_hints
            ),
            'failed_response_content' => array(
                'type' => 'hint_textarea',
                'label' => __( 'Failed Response Content', 'formipay' ),
                'value' => 'Failed on submiting data. Please try again.',
                'hints' => [
                    'error_message' => __( 'System Error Message', 'formipay' )
                ],
            )
        );

        $submit_response_group = apply_filters( 'formipay/form-settings/tab:submission/group:submit-response', $submit_response_group );

        $last_submit_response_group = array_key_last($submit_response_group);
        $submit_response_group[$last_submit_response_group]['group'] = 'ended';

        // Submit Action Group
        $submit_action_group = array(
            'submit_confirmation_group' => array(
                'type'  => 'group_title',
                'label' => __( 'Submit Action', 'formipay' ),
                'description' => __( 'Action will triggered to process the submitted data further.', 'formipay' ),
                'group' => 'started'
            ),
            'submit_action_type' => array(
                'type' => 'select',
                'label' => __('Action Type', 'formipay'),
                'options' => array(
                    'thankyou' => __( 'Thank-you Screen', 'formipay'),
                    'redirect' => __( 'Redirect to custom URL', 'formipay' ),
                    'whatsapp' => __( 'Redirect to WhatsApp', 'formipay' )
                ),
                'value' => 'thankyou',
            ),
            'redirect_url' => array(
                'type' => 'text',
                'label' => __( 'Redirect URL', 'formipay' ),
                'dependency' => array(
                    'key' => 'submit_action_type',
                    'value' => 'redirect'
                )
            ),
            'whatsapp_message' => array(
                'type' => 'hint_textarea',
                'label' => __( 'Content', 'formipay' ),
                'hints' => $hints,
                'dependency' => array(
                    'key' => 'submit_action_type',
                    'value' => 'whatsapp'
                ),
            ),
            'whatsapp_admin' => array(
                'type' => 'text',
                'label' => __( 'Send to WhatsApp Number', 'formipay' ),
                'dependency' => array(
                    'key' => 'submit_action_type',
                    'value' => 'whatsapp'
                ),
                'description' => sprintf( 'Use country code without + sign.<br><b>True: 62812xx</b><br>False: +62812xx', 'formipay' )
            ),
            'thankyou_screen_width' => array(
                'type' => 'number',
                'label' => __( 'Screen Width', 'formipay' ),
                'value' => '600',
                'dependency' => array(
                    'key' => 'submit_action_type',
                    'value' => 'thankyou'
                ),
            ),
            'thankyou_screen_content' => array(
                'type' => 'tinymce',
                'label' => __( 'Content', 'formipay' ),
                'value' => '<h2 style="text-align: center">Thankyou for purchasing:<strong>{{product_name}}</strong><br></h2><p style="text-align: center">Here is your order details:</p><p style="text-align: center"><span style="color: var(--bs-body-color);text-align: var(--bs-body-text-align)">{{form_submission}}</span></p><p style="text-align: center"><span style="color: var(--bs-body-color);text-align: var(--bs-body-text-align)">Your order status is&nbsp;&nbsp;</span><u>{{order_status}}</u></p><p style="text-align: center"><span style="color: var(--bs-body-color);text-align: var(--bs-body-text-align)">{{payment_details}}<br></span></p>',
                'hints' => $hints,
                'dependency' => array(
                    'key' => 'submit_action_type',
                    'value' => 'thankyou'
                ),
                'description' => __( '{{payment_details}} only rendered when the order status is not completed yet.', 'formipay' )
            ),
            'thankyou_screen_table_alignment' => array(
                'type'      => 'radio',
                'label'     => __('Table Content Alignment', 'formipay'),
                'value' => 'center',
                'options'   => array(
                    'left'      => '<i class="bi bi-text-left"></i> Left',
                    'center'    => '<i class="bi bi-text-center"></i> Center',
                    'right'     => '<i class="bi bi-text-right"></i> Right',
                ),
                'dependency' => array(
                    'key' => 'submit_action_type',
                    'value' => 'thankyou'
                ),
                'required' => true
            )
        );

        $submit_action_group = apply_filters( 'formipay/form-settings/tab:submission/group:submit-action', $submit_action_group );

        $last_submit_action_group = array_key_last($submit_action_group);
        $submit_action_group[$last_submit_action_group]['group'] = 'ended';

        $submission_all_fields = array_merge($submit_response_group, $submit_action_group);

        $submission_all_fields = apply_filters( 'formipay/form-settings/tab:submission', $submission_all_fields );

        $fields['formipay_form_settings']['submission'] = array(
            'name' => __('Submission', 'formipay'),
            'fields' => $submission_all_fields
        );

        return $fields;
    }

    public function save_formipay_metabox($post_id) {

        if (!isset($_POST['formipay_builder_canvas']) || 
            !wp_verify_nonce( sanitize_text_field(wp_unslash($_POST['formipay_builder_canvas'])), 'formipay-form-builder-canvas')) {
            return;
        }
    
        if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {
            return;
        }
    
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        $thePost = $_POST;
    
        $update_fields = [];
        $search_value = 'config';
        
        if (!empty($thePost) && is_array($thePost)) {
            foreach (array_keys($thePost) as $key) {
                if (preg_match("/{$search_value}/i", $key) && isset($thePost[$key])) {
                    $raw_data = wp_unslash($thePost[$key]);
                    
                    $config_data = json_decode($raw_data, true);
                    
                    if (json_last_error() === JSON_ERROR_NONE) {
                        $sanitized_config = [];
                        foreach ($config_data as $field => $value) {
                            $sanitized_config[sanitize_text_field($field)] = $this->sanitize_config_field($value);
                        }
                        
                        if (isset($sanitized_config['field_id'])) {
                            $sanitized_config['field_id'] = sanitize_title(
                                str_replace(' ', '_', $sanitized_config['field_id'])
                            );
                        }
                        
                        $update_fields[sanitize_key($key)] = $sanitized_config;
                    }
                }
            }
        }
    
        if (!empty($update_fields)) {
            update_post_meta(
                $post_id,
                'formipay_settings',
                ['fields' => $update_fields]
            );
        }
    }

    public function render_formipay_metabox() {
        ?>
        <div class="formipay-editor-tab-content nav-content-section bg-light py-0" id="canvas">
            <?php 
            include_once FORMIPAY_PATH . 'admin/templates/editor-canvas.php';
            ?>
        </div>
        <?php
    }

    public function render_shortcode_metabox() {
        global $post;
        ?>
        <div class="formipay_post_shortcode">
            <input class="form-control" value="[formipay form=<?php echo esc_attr($post->ID) ?>]" disabled>
        </div>
        <?php
    }

    public function enqueue_admin() {
        global $current_screen, $post;
        
        // Check that we are on the 'Checker' post editor screen
        if ( $current_screen->post_type === 'formipay-form' && $current_screen->base === 'post' ) {
            
            wp_enqueue_style( 'bootstrap', FORMIPAY_URL . 'vendor/Bootstrap/bootstrap.min.css', [], '5.3.2' );
            wp_enqueue_style( 'jquery-ui', FORMIPAY_URL . 'vendor/jQuery-UI/jquery-ui.min.css', [], '1.13.2' );
            wp_enqueue_style( 'formipay-admin-editor', FORMIPAY_URL . 'admin/assets/css/admin-editor.css', [], FORMIPAY_VERSION );
            wp_enqueue_style( 'formipay-form-field', FORMIPAY_URL . 'admin/assets/css/form-field.css', [], FORMIPAY_VERSION );
            wp_enqueue_style( 'daterangepicker', FORMIPAY_URL . 'vendor/DateRangePicker/daterangepicker.min.css', [], '5.3.2' );
    
            wp_enqueue_script( 'handlebars', FORMIPAY_URL . 'vendor/HandleBars/handlebars.min.js', [], '4.7.7', true);
            wp_enqueue_script( 'bootstrap', FORMIPAY_URL . 'vendor/Bootstrap/bootstrap.bundle.min.js', ['jquery'], '5.3.2', true );
            wp_enqueue_script( 'jquery-ui', FORMIPAY_URL . 'vendor/jQuery-UI/jquery-ui.min.js', ['jquery'], '1.13.2', true );
            wp_enqueue_script( 'moment', FORMIPAY_URL . 'vendor/MomentJS/moment.min.js', ['jquery'], '2.18.1', true );
            wp_enqueue_script( 'daterangepicker', FORMIPAY_URL . 'vendor/DateRangePicker/daterangepicker.min.js', ['jquery', 'bootstrap', 'moment'], '5.19.2', true );
            wp_enqueue_script( 'formipay-admin-editor', FORMIPAY_URL . 'admin/assets/js/admin-editor.js', ['jquery'], FORMIPAY_VERSION, true );
            wp_enqueue_script( 'formipay-wpmedia-modal', FORMIPAY_URL . 'admin/assets/js/formipay-wpmedia-modal.js', ['jquery'], FORMIPAY_VERSION, true );
            wp_enqueue_script( 'formipay-admin-handlebars', FORMIPAY_URL . 'admin/assets/js/admin-handlebars.js', array('jquery', 'handlebars'), FORMIPAY_VERSION, true);
            wp_enqueue_script( 'sweetalert2', FORMIPAY_URL . 'vendor/SweetAlert2/sweetalert2.min.js', ['jquery'], '11.14.5', true);

            wp_localize_script( 'formipay-admin-editor', 'formipay_admin', [
                'ajax_url' => admin_url('admin-ajax.php'),
                'site_url' => site_url(),
                'page_title' => esc_html__( 'Edit Form', 'formipay' ),
                'form_id' => $post->ID,
                'preset' => [
                    'country_list' => json_encode(formipay_country_array())
                ],
                'config' => [
                    'autocomplete' => [
                        'placeholder' => esc_html__( 'Type to search {field_label}', 'formipay' )
                    ],
                    'datamapping' => [
                        'placeholder' => esc_html__( '-- Choose related field', 'formipay' )
                    ]
                ],
                'nonce' => wp_create_nonce('formipay-form-editor'),
                'multicurrency' => formipay_is_multi_currency_active(),
                'all_currencies' => formipay_currency_as_options(),
                'global_selected_currencies' => formipay_global_currency_options(),
                'default_currency' => formipay_default_currency()
            ] );

            wp_enqueue_media();
        }

        if($current_screen->base == 'toplevel_page_formipay') {

            wp_enqueue_style( 'page-forms', FORMIPAY_URL . 'admin/assets/css/page-forms.css', [], FORMIPAY_VERSION, 'all' );
            wp_enqueue_script( 'page-forms', FORMIPAY_URL . 'admin/assets/js/page-forms.js', ['jquery', 'gridjs'], FORMIPAY_VERSION, true );

            wp_localize_script( 'page-forms', 'formipay_forms_page', [
                'ajax_url' => admin_url('admin-ajax.php'),
                'site_url' => site_url(),
                'columns' => [
                    'id' => esc_html__( 'ID', 'formipay' ),
                    'title' => esc_html__( 'Title', 'formipay' ),
                    'categories' => esc_html__( 'Categories', 'formipay' ),
                    'date' => esc_html__( 'Date', 'formipay' ),
                    'price' => esc_html__( 'Price', 'formipay' ),
                    'status' => esc_html__( 'Status', 'formipay' ),
                    'shortcode' => esc_html__( 'Shortcode', 'formipay' )
                ],
                'filter_form' => [
                    'categories' => [
                        'placeholder' => esc_html__( 'Filter by Category', 'formipay' ),
                        'noresult_text' => esc_html__( 'No results found', 'formipay' )
                    ],
                    'currencies' => [
                        'placeholder' => esc_html__( 'Filter by Currency', 'formipay' ),
                        'noresult_text' => esc_html__( 'No results found', 'formipay' )
                    ]
                ],
                'modal' => [
                    'add' => [
                        'title' => esc_html__( 'Your New Form', 'formipay' ),
                        'validation' => esc_html__( 'Form\'s title is still empty. Please input the title before continue', 'formipay' ),
                        'cancelButton' => esc_html__( 'Cancel', 'formipay' ),
                        'confirmButton' => esc_html__( 'Create New Form', 'formipay' )
                    ],
                    'delete' => [
                        'question' => esc_html__( 'Do you want to delete the form?', 'formipay' ),
                        'cancelButton' => esc_html__( 'Cancel', 'formipay' ),
                        'confirmButton' => esc_html__( 'Delete Permanently', 'formipay' )
                    ],
                    'bulk_delete' => [
                        'question' => esc_html__( 'Do you want to delete the selected the form(s)?', 'formipay' ),
                        'cancelButton' => esc_html__( 'Cancel', 'formipay' ),
                        'confirmButton' => esc_html__( 'Confirm', 'formipay' )
                    ],
                    'duplicate' => [
                        'question' => esc_html__( 'Do you want to duplicate the form?', 'formipay' ),
                        'cancelButton' => esc_html__( 'Cancel', 'formipay' ),
                        'confirmButton' => esc_html__( 'Confirm', 'formipay' )
                    ]
                ],
                'toast' => [
                    'copy_button' => [
                        'copy' => esc_html__( 'Copy', 'formipay' ),
                        'copied' => esc_html__( 'Copied', 'formipay' ),
                        'title' => esc_html__( 'Shortcode copied!', 'formipay' ),
                    ]
                ],
                'nonce' => wp_create_nonce('formipay-admin-post')
            ] );
        }

    }

    public function form_builder_canvas($fields){
        
        $field_types = formipay_field_type_collection();

        $register_new_fields = [
            [
                'type' => 'select',
                'id' => 'field_type',
                'label' => __( 'Field Type', 'formipay'),
                'options' => $field_types,
                'custom_class' => ['main-field']
            ],
            [
                'type' => 'text',
                'id' => 'label',
                'label' => __( 'Label', 'formipay'),
                'custom_class' => ['main-field']
            ],
            [
                'type' => 'text',
                'id' => 'field_id',
                'label' => __( 'Field ID', 'formipay'),
                'custom_class' => ['main-field']
            ],
            [
                'type' => 'repeater',
                'id' => 'field_options',
                'label' => __( 'Field Options', 'formipay' ),
                'fields' => [
                    [
                        'type' => 'image',
                        'id' => 'thumbnail',
                        'label' => __( 'Thumbnail', 'formipay' ),
                        'toggle' => 'yes',
                        'display' => 'none'
                    ],
                    [
                        'type' => 'text',
                        'id'    => 'label',
                        'label' => __( 'Label', 'formipay' ),
                        'toggle' => 'no'
                    ],
                    [
                        'type' => 'text',
                        'id'    => 'value',
                        'label' => __( 'Custom Value', 'formipay' ),
                        'toggle' => 'yes',
                        'display' => 'none'
                    ],
                    [
                        'type' => 'number',
                        'id'    => 'amount',
                        'label' => __( 'Additional Price', 'formipay' ),
                        'toggle' => 'yes',
                        'display' => 'none'
                    ],
                    [
                        'type' => 'number',
                        'id'    => 'weight',
                        'label' => __( 'Additional Weight', 'formipay' ),
                        'toggle' => 'yes',
                        'display' => 'none'
                    ],
                    [
                        'type'  => 'toggle',
                        'id'    => 'quantity',
                        'label' => __( 'Influenced by Quantity', 'formipay' ),
                        'display' => 'none'
                    ]
                ],
                'conditional' => [
                    [
                        'key' => 'field_type',
                        'value' => ['select', 'radio', 'checkbox']
                    ]
                ]
            ],
            [
                'type' => 'number',
                'id' => 'option_grid_columns',
                'label' => __( 'Option Grid Columns', 'formipay' ),
                'conditional' => [
                    [
                        'key' => 'field_type',
                        'value' => ['radio', 'checkbox']
                    ]
                ]
            ],
            [
                'type' => 'text',
                'id' => 'placeholder',
                'label' => __( 'Placeholder', 'formipay' ),
                'conditional' => [
                    [
                        'key' => 'field_type',
                        'value' => [ 
                            'country_list',
                            'text', 'url', 'email', 'tel', 'number', 'date', 'datetime', 'color',
                            'select', 'checkbox', 'radio',
                            'hidden', 'textarea'
                        ] 
                    ]
                ]
            ],
            [
                'type' => 'text',
                'id' => 'default_value',
                'label' => __( 'Default Value', 'formipay' ),
                'conditional' => [
                    [
                        'key' => 'field_type',
                        'value' => [ 
                            'text', 'url', 'email', 'tel', 'number', 'date', 'datetime', 'color',
                            'select', 'checkbox', 'radio',
                            'hidden', 'textarea'
                        ] 
                    ]
                ]
            ],
            [
                'type' => 'text',
                'id' => 'description',
                'label' => __( 'Description', 'formipay' ),
                'conditional' => [
                    [
                        'key' => 'field_type',
                        'value' => [ 
                            'divider', 'page_break', 
                            'text', 'url', 'email', 'tel', 'number', 'date', 'datetime', 'color',
                            'select', 'checkbox', 'radio',
                            'hidden', 'textarea'
                        ] 
                    ]
                ],
                'custom_class' => ['main-field']
            ],
            [
                'type' => 'checkbox',
                'id' => 'is_required',
                'label' => __( 'Required', 'formipay' ),
                'conditional' => [
                    [
                        'key' => 'field_type',
                        'value' => [ 
                            'text', 'url', 'email', 'tel', 'number', 'date', 'datetime', 'color',
                            'select', 'checkbox', 'radio',
                            'hidden', 'textarea'
                        ] 
                    ]
                ]
            ],
        ];

        foreach($register_new_fields as $field){
            $fields[] = $field;
        }

        $fields = apply_filters( 'formipay/canvas/builder', $fields );

        return $fields;
        
    }

    public function fetch_formipay_settings() {

        check_ajax_referer( 'formipay-form-editor', '_wpnonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => 'Unauthorized' ] );
        }

        if(isset($_GET['post_id'])){
            $post_id = intval($_GET['post_id']);
            $formipay_post_meta = get_post_meta($post_id, 'formipay_settings', true);
            $saved_config = $formipay_post_meta['fields'];
        
            wp_send_json_success( array('fields' => $saved_config) );
        }
        
    }

    public function fetch_formipay_fields() {
        wp_send_json_success( array(
            'fields' => apply_filters( 'formipay/admin-editor/field-form', [] ) 
        ) );
    }

    public function formipay_tabledata_forms() {

        check_ajax_referer( 'formipay-admin-post', '_wpnonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => 'Unauthorized' ] );
        }

        global $wpdb;
        
        // Initialize default args
        $base_args = [
            'post_type' => 'formipay-form',
            'post_status' => ['publish', 'draft', 'pending'],
            'fields' => 'ids' // Optimize initial query
        ];
    
        // Handle status filtering
        if (isset($_REQUEST['post_status']) && 'all' !== $_REQUEST['post_status']) {
            $base_args['post_status'] = [sanitize_key($_REQUEST['post_status'])];
        }
    
        // Search functionality
        if (!empty($_REQUEST['search'])) {
            $base_args['s'] = isset($_REQUEST['search']) ? sanitize_text_field(wp_unslash($_REQUEST['search'])) : '';
        }
    
        // Sorting
        if (!empty($_REQUEST['orderby'])) {
            $orderby = sanitize_key($_REQUEST['orderby']);
            $order = isset($_REQUEST['sort']) ? sanitize_key($_REQUEST['sort']) : 'ASC';
            
            if ('price' === $orderby) {
                // phpcs:ignore	WordPress.DB.SlowDBQuery.slow_db_query_meta_key
                $base_args['meta_key'] = 'product_price';
                $base_args['orderby'] = 'meta_value_num';
            } else {
                $base_args['orderby'] = $orderby;
            }
            $base_args['order'] = $order;
        }
    
        // Pagination
        if (isset($_REQUEST['limit'])) {
            $base_args['posts_per_page'] = absint($_REQUEST['limit']);
        }
        if (isset($_REQUEST['offset'])) {
            $base_args['offset'] = intval($_REQUEST['offset']);
        }
    
        // Main query
        $query = new \WP_Query($base_args);
        $form_ids = $query->posts;
        $total_forms = $query->found_posts;
    
        // Process results
        $forms = [];
        foreach ($form_ids as $form_id) {
            $form = get_post($form_id);
            $forms[] = [
                'ID' => $form_id,
                'title' => $form->post_title,
                'date' => $form->post_date,
                'status' => $form->post_status,
            ];
        }
    
        // Get status counts using WordPress API
        $counts = wp_count_posts('formipay-form');
        $status_counts = [];
        foreach ($counts as $status => $count) {
            $status_counts[$status] = $count;
        }
        $status_counts['all'] = array_sum($status_counts);
    
        wp_send_json([
            'results' => $forms,
            'total' => $total_forms,
            'posts_report' => array_map('intval', (array)$status_counts)
        ]);
    }

    public function formipay_create_form_post() {

        check_ajax_referer( 'formipay-admin-post', '_wpnonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => 'Unauthorized' ] );
        }

        $title = isset($_REQUEST['title']) ? sanitize_text_field( wp_unslash($_REQUEST['title']) ) : '';

        if( !empty($title) && '' !== $title ){
            $post_id = wp_insert_post( [
                'post_title' => $title,
                'post_type' => 'formipay-form',
            ], true );

            if(is_wp_error($post_id)){
                wp_send_json_error( [
                    'message' => $post_id->get_error_message()
                ] );
            }

            $setup = [
                'fields' => [
                    'name_config' => [
                        'label' => esc_html__( 'Fullname', 'formipay' ),
                        'field_id' => 'name',
                        'field_type' => 'text',
                        'placeholder' => esc_html__( 'Your Fullname', 'formipay' ),
                        'default_value' => '',
                        'description' => esc_html__( 'Fill with your fullname', 'formipay' ),
                        'is_required' => 'yes',
                        'show_toggle' => [
                            'image' => 'no',
                            'value' => 'no',
                            'amount' => 'no'
                        ],
                        'layout' => '',
                        'field_options' => []
                    ],
                    'email_config' => [
                        'label' => esc_html__( 'Email', 'formipay' ),
                        'field_id' => 'email',
                        'field_type' => 'email',
                        'placeholder' => esc_html__( 'Your Email', 'formipay' ),
                        'default_value' => '',
                        'description' => esc_html__( 'Fill with your valid email', 'formipay' ),
                        'is_required' => 'yes',
                        'show_toggle' => [
                            'image' => 'no',
                            'value' => 'no',
                            'amount' => 'no'
                        ],
                        'layout' => '',
                        'field_options' => []
                    ]
                ]
            ];
            
            update_post_meta($post_id, 'formipay_settings', $setup);
            // update_post_meta($post_id, 'product_currency', 'USD:::United States dollar:::$');

            wp_send_json_success( [
                'edit_post_url' => admin_url('post.php?post='.$post_id.'&action=edit')
            ] );
        }

        wp_send_json_error( [
            'message' => esc_html__( 'Item\'s title is empty.', 'formipay' )
        ] );
        
    }

    public function formipay_delete_form() {

        check_ajax_referer( 'formipay-admin-post', '_wpnonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => 'Unauthorized' ] );
        }

        $form_id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : '';

        $delete = wp_delete_post($form_id, true);

        if(is_wp_error( $delete )){
            wp_send_json_error( [
                'title' => esc_html__( 'Failed', 'formipay' ),
                'message' => esc_html__( 'Failed to delete form. Please try again.', 'formipay' ),
                'icon' => 'error'
            ] );
        }

        wp_send_json_success( [
            'title' => esc_html__( 'Deleted', 'formipay' ),
            'message' => esc_html__( 'Form is deleted permanently.', 'formipay' ),
            'icon' => 'success'
        ] );

    }

    public function formipay_bulk_delete_form() {

        check_ajax_referer( 'formipay-admin-post', '_wpnonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => 'Unauthorized' ] );
        }

        if( empty($_REQUEST['ids']) ){
            wp_send_json_error( [
                'title' => esc_html__( 'Failed', 'formipay' ),
                'message' => esc_html__( 'There is no form selected. Please try again.', 'formipay' ),
                'icon' => 'error'
            ] );
        }

        $ids = isset($_REQUEST['ids']) ? $_REQUEST['ids'] : [];

        $success = 0;
        $failed = 0;
        $report = __( 'Done.', 'formipay' );
        if(!empty($ids)){
            foreach($ids as $id){
                $delete = wp_delete_post($id, true);
                if(is_wp_error( $delete )){
                    $failed++;
                }else{
                    $success++;
                }
            }
        }

        if($success > 0){
            $report .= sprintf( __( ' Deleted %d form(s).', 'formipay' ), $success);
        }
        if($failed > 0){
            $report .= sprintf( __( ' Failed %d form(s).', 'formipay' ), $failed);
        }

        wp_send_json_success( [
            'title' => esc_html__( 'Done!', 'formipay' ),
            'message' => $report,
            'icon' => 'info'
        ] );

    }

    public function formipay_duplicate_form() {

        check_ajax_referer( 'formipay-admin-post', '_wpnonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => 'Unauthorized' ] );
        }

        $post_id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : '';
        $post = get_post($post_id);
        if (!$post) {
            wp_send_json_error( [
                'title' => esc_html__('Failed', 'formipay'),
                'message' => esc_html__( 'Form is not defined.', 'formipay' ),
                'icon' => 'error'
            ] );
        }
    
        if (!in_array($post->post_type, ['formipay-form'])) {
            wp_send_json_error( [
                'title' => esc_html__('Failed', 'formipay'),
                'message' => esc_html__( 'Wrong Post Type.', 'formipay' ),
                'icon' => 'error'
            ] );
        }
    
        $duplicate_post = [
            'post_title'   => $post->post_title . ' (Copy)',
            'post_content' => $post->post_content,
            'post_status'  => 'draft', // Set sebagai draft
            'post_type'    => $post->post_type,
            'post_author'  => $post->post_author,
        ];
    
        $new_post_id = wp_insert_post($duplicate_post);
    
        if (is_wp_error($new_post_id)) {
            wp_send_json_error( [
                'title' => esc_html__('Failed', 'formipay'),
                'message' => esc_html__( 'Something happened. Please try again.', 'formipay' ),
                'icon' => 'error'
            ] );
        }
    
        $meta_data = get_post_meta($post_id);
        foreach ($meta_data as $key => $values) {
            foreach ($values as $value) {
                update_post_meta($new_post_id, $key, maybe_unserialize($value));
            }
        }
    
        $taxonomies = get_object_taxonomies($post->post_type);
        foreach ($taxonomies as $taxonomy) {
            $terms = wp_get_object_terms($post_id, $taxonomy, ['fields' => 'slugs']);
            wp_set_object_terms($new_post_id, $terms, $taxonomy);
        }
    
        wp_send_json_success( [
            'title' => esc_html__('Duplicated!', 'formipay'),
            'message' => esc_html__( 'Form is successfully duplicated.', 'formipay' ),
            'icon' => 'success'
        ] );
    }

    private function sanitize_config_field($value) {
        if (is_array($value)) {
            return array_map([$this, 'sanitize_config_field'], $value);
        }
        
        // Add custom sanitization rules based on your field types
        if (is_numeric($value)) {
            return floatval($value);
        }
        if (filter_var($value, FILTER_VALIDATE_URL)) {
            return esc_url_raw($value);
        }
        
        return wp_kses_post($value);
    }

}