<?php

function formipay_field_type_collection() {
    $types = [ 
        'text' => __( 'Text', 'formipay' ), 
        'url' => __( 'URL', 'formipay' ), 
        'email' => __( 'Email', 'formipay' ), 
        'tel' => __( 'Telephone', 'formipay' ), 
        'number' => __( 'Number', 'formipay' ), 
        'date' => __( 'Date', 'formipay' ), 
        'datetime' => __( 'Date & Time', 'formipay' ), 
        'color' => __( 'Number', 'formipay' ),
        'select' => __( 'Select Dropdown', 'formipay' ), 
        'checkbox' => __( 'Checkbox', 'formipay' ), 
        'radio' => __( 'Radio', 'formipay' ),
        'hidden' => __( 'Hidden', 'formipay' ), 
        'textarea' => __( 'Textarea', 'formipay' ),
        'divider' => __( 'Divider', 'formipay' ), 
        'page_break' => __( 'Page Break', 'formipay' ), 
        'country_list' => __( 'Preset: Country List', 'formipay' )
    ];

    $types = apply_filters( 'formipay/form-config/field-type', $types);

    return $types;
}

function formipay_currency_array() {

    $json = file_get_contents(FORMIPAY_PATH . 'admin/assets/json/currencies.json');
    $array = json_decode($json, true);
    return $array;

}

function formipay_is_multi_currency_active() {

    $formipay_settings = get_option('formipay_settings');
    $is_active = $formipay_settings['enable_multicurrency'];

    return (bool) $is_active;

}

function formipay_default_currency($return='raw') {

    $formipay_settings = get_option('formipay_settings');
    $default_currency = $formipay_settings['default_currency'];

    switch ($return) {
        
        case 'symbol':
            $output = formipay_get_currency_data_by_value($default_currency, 'symbol');
            break;
        
        case 'title':
            $output = formipay_get_currency_data_by_value($default_currency, 'title');
            break;
        
        case 'decimal_digits':
            $output = $formipay_settings['default_currency_decimal_digits'];
            break;
        
        case 'decimal_symbol':
            $output = $formipay_settings['default_currency_decimal_symbol'];
            break;
        
        case 'thousand_separator':
            $output = $formipay_settings['default_currency_thousand_separator'];
            break;
        
        default:
            $output = $formipay_settings['default_currency'];
            break;
    }

    return $output;

}

function formipay_global_currency_options($output = 'options_array') {

    $formipay_settings = get_option('formipay_settings');
    // $currencies = (false !== boolval($formipay_settings['enable_multicurrency'])) ? formipay_default_currency() : [];
    $currencies = [];
    if(false !== boolval($formipay_settings['enable_multicurrency']) && !empty($formipay_settings['multicurrencies'])) {
        if($output === 'options_array'){
            foreach($formipay_settings['multicurrencies'] as $currency){
                $currency_value = $currency['currency'];
                $currency_label = formipay_get_currency_data_by_value($currency_value, 'title');
                $currencies[$currency_value] = $currency_label;
            }
        }elseif($output == 'raw'){
            $currencies = $formipay_settings['multicurrencies'];
        }
    }
    // if(empty($currencies)){
    //     $currencies[formipay_default_currency()] = formipay_default_currency('title');
    // }

    return $currencies;

}

function get_global_currency_array() {
    $multicurrency = formipay_is_multi_currency_active();
    $global_currencies = formipay_global_currency_options('raw');
    $default_currency = formipay_default_currency();

    $product_currency_group = [];

    $ifSingleCurrency = true;
    if(boolval($multicurrency)){
        $ifSingleCurrency = false;
        if(count($global_currencies) === 1){
            $ifSingleCurrency = true;
        }
    }

    if(false === $ifSingleCurrency){
        // $currency_sort = [];
        $default_sort_key = null;
        foreach($global_currencies as $key => $currency){
            $currency_value = $currency['currency'];
            if($currency_value === $default_currency){
                $default_sort_key = $key;
            }
        }
        $currency_sort = [$default_sort_key => $global_currencies[$default_sort_key]];
        unset($global_currencies[$default_sort_key]);
        $global_currencies = $currency_sort + $global_currencies;
    }else{
        if(false === boolval($multicurrency)){
            $global_currencies = [
                [
                    'currency' => formipay_default_currency(),
                    'decimal_digits' => formipay_default_currency('decimal_digits'),
                    'decimal_symbol' => formipay_default_currency('decimal_symbol'),
                    'thousand_separator' => formipay_default_currency('thousand_separator'),
                ]
            ];
        }
    }

    return $global_currencies;
}

function formipay_country_array() {

    $json = file_get_contents(FORMIPAY_PATH . 'admin/assets/json/country.json');
    $array = json_decode($json, true);
    return $array;

}

function formipay_get_flag_by_currency($currency) {

    if(strpos($currency, ':::')){
        $currency = explode(':::', $currency);
        $currency = $currency[0];
    }
    $json = file_get_contents(FORMIPAY_PATH . 'admin/assets/json/flags.json');
    $array = json_decode($json, true);
    foreach($array as $country){
        if($currency == $country['code']){
            return $country['flag'];
        }
    }
    return false;

}

function formipay_price_format($num = 0, $post_id = 0){

    $decimal_digits = 2;
    $decimal_symbol = '.';
    $thousand_separator_symbol = ',';

    if($post_id > 0 ){
        $currency_data = explode(':::', get_post_meta($post_id, 'product_currency', true));
        $decimal_digits = get_post_meta($post_id, 'product_currency_decimal_digits', true);
        $decimal_symbol = get_post_meta($post_id, 'product_currency_decimal_symbol', true);
        $thousand_separator_symbol = get_post_meta($post_id, 'product_currency_thousand_separator', true);
        if(isset($currency_data[2]) && !empty($currency_data[2])){
            $currency = $currency_data[2];
        }else{
            $currency = $currency_data[0];
        }
        return $currency .' '. number_format(floatval($num), intval($decimal_digits), $decimal_symbol, $thousand_separator_symbol);
    }

    return number_format(floatval($num), intval($decimal_digits), $decimal_symbol, $thousand_separator_symbol);

}

function formipay_currency_as_options($currency_code = '') {

    $currencies = formipay_currency_array();
    $result = [];
    foreach($currencies as $currency){
        $code = $currency['code'];
        $currency_id = implode(':::', $currency);
        if('' !== $currency_code && $code == $currency_code){
            $result = $currency_id;
            break;
        }
        $result[$currency_id] = ucwords($currency['name']);
    }

    return $result;

}

function formipay_post_currency($post_id){

    $currency = formipay_get_post_meta($post_id, 'product_currency');
    $currency = explode(':::', $currency);
    $currency_symbol = $currency[0];
    if(isset($currency[2]) && '' !== $currency[2]){
        $currency_symbol = $currency[2];
    }

    return $currency_symbol;

}

function formipay_get_currency_data_by_value($value, $data='') {

    $currency = explode(':::', $value);

    switch ($data) {
        case 'title':
            $output = $currency[1];
            break;
        
        case 'symbol':
            $output = $currency[0];
            // if(isset($currency[2]) && '' !== $currency[2] && false !== boolval($currency[2])){
            //     $output = $currency[2];
            // }
            break;
        
        default:
            $output = $value;
            break;
    }

    return $output;

}

function formipay_get_post_meta($post_id, $metakey) {

    $value = get_post_meta($post_id, $metakey, true);

    if(!empty($value) && false !== $value && '' !== $value){
        return $value;
    }

    return false;
    
}

function formipay_order_status_list() {

    $statuses = array(
        'on-hold'           => 'On Hold', 
        'payment-confirm'   => 'Payment Confirmed', 
        'in-progress'       => 'In Progress', 
        'shipping'          => 'Shipping', 
        'completed'         => 'Completed', 
        'failed'            => 'Failed',
        'refunded'          => 'Refunded', 
        'cancelled'         => 'Cancelled'
    );

    return $statuses;

}

function formipay_get_order($order_id) {

    $formipay_settings = get_option('formipay_settings');
    $order = apply_filters( 'formipay/order/get', false, $order_id );

    $order_data = [];

    if(false !== $order){
        foreach($order as $key => $data){
            $order_data[$key] = maybe_unserialize( $data );
            if($key == 'items'){
                foreach($order_data[$key] as $index => $item){
                    $order_data[$key][$index]['subtotal_formatted'] = formipay_price_format($item['subtotal'], $order_data['form_id']);
                }
            }
        }
        $order_data['total_formatted'] = formipay_price_format($order_data['total'], $order_data['form_id']);

        // Form Submission Data Process to Readable
        if(!empty($order_data['form_data'])){
            $field_types = formipay_field_type_collection();
            $form_field = get_post_meta($order_data['form_id'], 'formipay_settings', true);
            $form_field = $form_field['fields'];

            $all_fields = [];
            foreach($form_field as $key => $field){
                if(array_key_exists($field['field_type'], $field_types)){
                    $skip = false;
                    if(in_array($field['field_type'], ['divider', 'page_break'])){
                        $options = $field['field_options'];
                        if(!empty($options)){
                            foreach($options as $option){
                                if(!empty($option['amount'])){
                                    $skip = true;
                                }
                            }
                        }
                    }
                    if(false == $skip){
                        $all_fields[$key] = $field;
                    }
                }
            }

            $proceed_form_data = [];
            foreach($order_data['form_data'] as $name => $value){
                switch ($name) {
                    case 'qty':
                        $label = esc_html__( 'Quantity', 'formipay' );
                        break;

                    case 'payment':
                        $label = esc_html__( 'Payment', 'formipay' );
                        break;

                    case 'coupon_code':
                        $label = esc_html__( 'Coupon Code', 'formipay' );
                        break;

                    case 'payment_gateway':
                        $label = esc_html__( 'Payment Gateway', 'formipay' );
                        break;
                    
                    default:
                        if(!empty($all_fields[$name.'_config'])){
                            $label = $all_fields[$name.'_config']['label'];
                        }else{
                            $label = '';
                        }
                        break;

                }

                $data_value = $value;
                if(is_array($value)){
                    $data_value = $value['label'] !== 'undefined' ? $value['label'] : $value['value'];
                }
                if($name == 'payment'){
                    if(strpos($value, ':::') !== false){
                        $value = explode(':::', $value);
                        $data_value = isset($value[1]) ? $value[1] : $value[0];
                        // If this is bank_transfer
                        if(
                            $value[0] == 'bank_transfer' && 
                            isset($value[1]) && 
                            strpos($value[1], '-') !== false
                        ) {
                            $bank_account = explode('-', $value[1]);
                            $bank_account_index = intval($bank_account[1]) + 1;
                            // translators: %d is the bank account index number.
                            $bank_label = $bank_account[0] . ' (' . sprintf( __( 'Bank Accounts #%d', 'formipay' ), $bank_account_index) . ')';
                            $data_value = $bank_label;
                        }
                    }
                }
                
                $proceed_form_data[$name] = [
                    'name' => $name,
                    'value' => $data_value !== '' ? $data_value : '-',
                    'label' => $label
                ];
                
            }
            $order_data['form_data'] = $proceed_form_data;
        }

        $thankyou_link = site_url( $formipay_settings['thankyou_link'] . '/' . base64_encode( $order_data['form_id'] . ':::' . $order_id ) );

        $order_data['thankyou'] = [
            'link' => $thankyou_link,
            'pass_method' => !empty($order_data['meta_data']['access_method']) ? $order_data['meta_data']['access_method'] : 'magic_link',
            'pass_word' => (!empty($order_data['meta_data']['access_password']) && !empty($order_data['meta_data']['access_method'])) ? $order_data['meta_data']['access_password'] : formipay_generate_password(),
        ];

        if(!empty($order_data['meta_data'])){
            $proceed_meta_data = [];
            foreach($order_data['meta_data'] as $name => $value){
                $label = explode('_', $name);
                $__label = [];
                foreach($label as $_label){
                    if(strlen($_label) <= 3){
                        $__label[] = strtoupper($_label);
                    }else{
                        $__label[] = ucfirst($_label);
                    }
                }
                $proceed_meta_data[$name] = [
                    'label' => implode(' ', $__label),
                    'name' => $name,
                    'value' => $value !== '' ? $value : '-'
                ];
            }
            $order_data['meta_data'] = $proceed_meta_data;
        }

        // Payment Data Process to Readable
        if(!empty($order['payment_gateway'])){
            $trx_data = formipay_get_payment_data($order_id, $order['payment_gateway']);
            if(false !== $trx_data) {
                $order_data['transaction'] = $trx_data;
            }
            $timeline = [
                [
                    'time' => $order['created_date'],
                    // translators: %s is the payment gateway name.
                    'activity' => sprintf( __( 'Order created via %s', 'formipay'), ucwords(str_replace( '_', ' ', $order['payment_gateway'])) ),
                    'attachment' => 'none'
                ]
            ];
            if(!empty($trx_data)){
                foreach($trx_data as $trx){
                    if($order['payment_gateway'] == 'bank_transfer' && !empty($trx['meta_data']['transfer_receipt'])) {
                        $timeline[] = [
                            'time' => formipay_date($trx['meta_data']['transfer_receipt']['time']),
                            'activity' => __( 'Payment confirmation by uploading transfer receipt.', 'formipay' ),
                            'attachment' => !empty($trx['meta_data']['transfer_receipt']['attachment_url']) ? $trx['meta_data']['transfer_receipt']['attachment_url'] : 'none'
                        ];
                    }
                    if($order['payment_gateway'] == 'paypal' && !empty($trx['meta_data']) && $trx['meta_data']['status'] == 'COMPLETED') {
                        $timeline[] = [
                            'time' => formipay_date($trx['meta_data']['update_time']),
                            'activity' => __( 'Payment completed via Paypal.', 'formipay' ),
                            'attachment' => 'none'
                        ];
                    }
                }
            }
            $timeline = apply_filters( 'formipay/order/transaction/timeline', $timeline, $order_id );
            $order_data['transaction_timeline'] = $timeline;
        }
        $notif_data = formipay_get_notification_data($order_id);
        if(false !== $notif_data) {
            $order_data['notification'] = $notif_data;
        }

    }

    return $order_data;

}

function formipay_get_payment_data($order_id, $payment_gateway) {

    global $wpdb;

    if($payment_gateway !== 'cod'){
        $table_name = $wpdb->prefix . 'formipay_'.$payment_gateway.'_trx';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $get = $wpdb->get_results(
            $wpdb->prepare("SELECT * FROM %i WHERE `order_id` = %d", $table_name, $order_id), ARRAY_A
        );
    
        $trx_data = [];
        if(false !== $get){
            foreach($get as $index => $row){
                foreach($row as $key => $value){
                    $trx_data[$index][$key] = maybe_unserialize( $value );
                }
            }
        }
        return !empty($trx_data) ? $trx_data : $get;
    }

    return [];

}

function formipay_get_notification_data($order_id) {

    global $wpdb;

    $table_name = $wpdb->prefix . 'formipay_notification_log';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $get = $wpdb->get_results(
        $wpdb->prepare("SELECT * FROM %i WHERE `order_id` = %d", $table_name, $order_id), ARRAY_A
    );

    $notif_data = [];
    if(false !== $get){
        foreach($get as $row_key => $row){
            foreach($row as $key => $value){
                $notif_data[$row_key][$key] = maybe_unserialize( $value );
            }
            $notif_data[$row_key]['recipient'] = $notif_data[$row_key]['notification_data']['to'];
            $notif_data[$row_key]['title'] = $notif_data[$row_key]['notification_data']['subject'];
            
            switch ($notif_data[$row_key]['recipient_type']) {
                case 'email':
                    $icon = '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">
                                <g fill="#fff">
                                    <path d="M22 7.535V17a3 3 0 0 1-2.824 2.995L19 20H5a3 3 0 0 1-2.995-2.824L2 17V7.535l9.445 6.297l.116.066a1 1 0 0 0 .878 0l.116-.066z" />
                                    <path d="M19 4c1.08 0 2.027.57 2.555 1.427L12 11.797l-9.555-6.37a3 3 0 0 1 2.354-1.42L5 4z" />
                                </g>
                            </svg>';
                    break;
                case 'waba':
                case 'whatsapp':
                    $icon = '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">
                                <path fill="#fff" d="M18.497 4.409a10 10 0 0 1-10.36 16.828l-.223-.098l-4.759.849l-.11.011a1 1 0 0 1-.11 0l-.102-.013l-.108-.024l-.105-.037l-.099-.047l-.093-.058l-.014-.011l-.012-.007l-.086-.073l-.077-.08l-.067-.088l-.056-.094l-.034-.07l-.04-.108l-.028-.128l-.012-.102a1 1 0 0 1 0-.125l.012-.1l.024-.11l.045-.122l1.433-3.304l-.009-.014A10 10 0 0 1 5.056 4.83l.215-.203a10 10 0 0 1 13.226-.217M9.5 7.5A1.5 1.5 0 0 0 8 9v1a6 6 0 0 0 6 6h1a1.5 1.5 0 0 0 0-3h-1l-.144.007a1.5 1.5 0 0 0-1.128.697l-.042.074l-.022-.007a4.01 4.01 0 0 1-2.435-2.435l-.008-.023l.075-.041A1.5 1.5 0 0 0 11 10V9a1.5 1.5 0 0 0-1.5-1.5" />
                            </svg>';
                    break;
                
                default:
                    $icon = '';
                    break;

            }
        }
    }

    return !empty($notif_data) ? $notif_data : $get;

}

function formipay_update_order_status($args) {

    $data = wp_parse_args( $args, [
        'form_id' => 0,
        'order_id' => 0,
        'payment_gateway' => '',
        'status' => 'on-hold'
    ] );

    $order_id = intval($data['order_id']);
    $order = new Formipay_Order();
    // $get = $order->get($order_id);
    $update = $order->update($order_id, [
        'status' => $data['status']
    ]);

    if(is_wp_error( $update )){
        $response = [
            'valid' => false,
            'message' => str_replace( 
                [
                    '{{order_id}}', '{{system_error_message}}'
                ], 
                [
                    $order_id, $update->get_error_message()
                ],
                formipay_get_post_meta($data['form_id'], $data['payment_gateway'] . '_confirmation_message_error')
            )
        ];
    }else{
        $response = [
            'valid' => true,
            'message' => str_replace( 
                '{{order_id}}', 
                $order_id, 
                formipay_get_post_meta($data['form_id'], $data['payment_gateway'] . '_confirmation_message_success')
            )
        ];

    }

    return $response;

}

function formipay_date($format = '', $date = '') {
    if ($format == '') {
        $format = get_option('date_format') . ' ' . get_option('time_format');
    }
    $timezone = new DateTimeZone(wp_timezone_string());

    if (empty($date)) {
        $datetime = new DateTime('now', $timezone);
    } else {
        // Detect if $date is a timestamp (integer or numeric string)
        if (is_numeric($date) && (int)$date == $date) {
            // Create DateTime from timestamp
            $datetime = new DateTime('@' . $date); // UTC by default
            $datetime->setTimezone($timezone);
        } else {
            // Create DateTime from date string in UTC
            $datetime = new DateTime($date, new DateTimeZone('UTC'));
            $datetime->setTimezone($timezone);
        }
    }

    if ($format === 'timestamp') {
        return (int) $datetime->format('U');
    }

    return $datetime->format($format);
}


function formipay_editor_hints() {
    $hints = [
        'buyer_name'        => __( 'Buyer Name',            'formipay' ),
        'product_name'      => __( 'Product Name',          'formipay' ),
        'order_id'          => __( 'Order ID',              'formipay' ),
        'order_date'        => __( 'Order Date',            'formipay' ),
        'order_total'       => __( 'Order Total',           'formipay' ),
        'order_status'      => __( 'Order Status',          'formipay' ),
        'order_details'     => __( 'Order Details',         'formipay' ),
        'form_submission'   => __( 'All Field Submissions', 'formipay' ),
        'payment_details'   => __( 'Payment Details',       'formipay' )
    ];

    $hints = apply_filters( 'formipay/form-config/notification/hints', $hints );

    return $hints;
}

function formipay_is_HTML($string){
    return $string !== wp_strip_all_tags($string) ? true : false ;
}

function allow_style_attribute_for_all_tags($content) {

    // Get all standard HTML tags
    $allowed_tags = wp_kses_allowed_html('post');

    // Iterate over the allowed tags and add 'style' attribute to each
    foreach ($allowed_tags as $tag => $attributes) {
        $allowed_tags[$tag]['style'] = array(); // Allow 'style' attribute
    }

    // Sanitize the content with the updated allowed tags
    return wp_kses($content, $allowed_tags);
    
}

function formipay_isPopup($post_id) {
    if(formipay_get_post_meta($post_id, 'form_display_as') == 'popup'){
        return true;
    }

    return false;
}

function formipay_filesize($attachment_id) {

    $metadata = wp_get_attachment_metadata($attachment_id);
    $fileSize = $metadata['filesize'];
    $sizeLabels = ['B', 'KB', 'MB', 'GB'];
    $index = 0;
    while ($fileSize >= 1024 && $index < count($sizeLabels) - 1) {
        $fileSize /= 1024;
        $index++;
    }
    return number_format($fileSize, 2) . ' ' . $sizeLabels[$index];

}

function formipay_attachment_icon($attachment_id = 0){

    if($attachment_id > 0){
        $get_attach = get_post($attachment_id);
        $mime = $get_attach->post_mime_type;
        $mime = explode('/', $mime);
        $type = $mime[1];
    
        switch ($type) {
            case 'zip':
                $icon = '<i class="bi bi-file-earmark-zip formipay-download-icon"></i>';
                break;
    
            default:
                $icon = '<i class="bi bi-filetype-'.$type.' formipay-download-icon"></i>';
                break;
        }
    }else{
        $icon = '<i class="bi bi-link-45deg formipay-download-icon"></i>';
    }
    
    return $icon;

}

function order_meta_fields() {
    return array(
        'user_id', 'session_id', 'referrer', 'page_url', 'timestamp', 'utm_source', 'utm_medium', 'utm_campaign', 'ip_address', 'user_agent'
    );
}

function formipay_get_coupon_id_by_code($code, $form_id) {
    global $wpdb;
    
    // Validate input early
    if (empty($code) || empty($form_id)) {
        return false;
    }

    // Get coupon by code directly using title match
    $coupon_post = false;

    $query = new WP_Query([
        'post_type'      => 'formipay-coupon',
        'title'          => $code,
        'post_status'    => 'publish',
        'posts_per_page' => 1,
        'fields'         => 'all', // or 'ids' if you only need the ID
    ]);

    if (!empty($query->posts)) {
        $coupon_post = $query->posts[0]; // Returns the post object
    }
    
    if (!$coupon_post || $coupon_post->post_status !== 'publish') {
        return false;
    }

    $coupon_id = $coupon_post->ID;

    // Check active status first
    if (formipay_get_post_meta($coupon_id, 'active') !== 'on') {
        return false;
    }

    // Check form restrictions using meta query
    $allowed_forms = formipay_get_post_meta($coupon_id, 'forms');
    if (!empty($allowed_forms)) {
        $forms = array_map('intval', explode(',', $allowed_forms));
        if (!in_array((int)$form_id, $forms, true)) {
            return false;
        }
    }

    // Case sensitivity check
    if (formipay_get_post_meta($coupon_id, 'case_sensitive') === 'on') {
        $stored_code = get_the_title($coupon_id);
        if ($code !== $stored_code) {
            return false;
        }
    }

    // Check usage limits using meta counters
    $use_limit = (int)formipay_get_post_meta($coupon_id, 'use_limit');
    if ($use_limit > 0) {
        $usage_count = (int)formipay_get_post_meta($coupon_id, 'usage_count');
        if ($usage_count >= $use_limit) {
            return false;
        }
    }

    // Date validation with proper timezone handling
    $date_limit = formipay_get_post_meta($coupon_id, 'date_limit');
    if (!empty($date_limit) && is_numeric($date_limit)) {
        $current_time = current_time('timestamp', true);
        if ($current_time > (int)$date_limit) {
            return false;
        }
    }

    return $coupon_id;
}


// Function to check if a string contains HTML tags like <img>, <svg>, or <i>
function formipay_contains_html($string) {
    return preg_match('/<(img|svg|i)(\s|>)/i', $string);
}

function formipay_generate_password() {
    $characters       = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!!!';
    $charactersLength = strlen($characters);
    $password         = '';

    for ($i = 0; $i < 8; $i++) :
        $password .= $characters[wp_rand(0, $charactersLength - 1)];
    endfor;

    $set_password = $password;

    return $set_password;
}

function formipay_customer_mandatory_data() {

    $mandatory_data = ['name'];
    $formipay_settings = get_option( 'formipay_settings' );
    if(isset($formipay_settings['customer_mandatory_data'])) {
        foreach($formipay_settings['customer_mandatory_data'] as $category => $config){
            if($config['id'] == 'mandatory'){
                foreach($config['options'] as $data){
                    $mandatory_data[] = $data['id'];
                }
            }
        }
    }

    return $mandatory_data;
}

function formipay_phone_country_code_options() {
    $codes = formipay_country_array();
    $options = [];
    foreach($codes as $code){
        $country_code = $code['phone'];
        $options[$country_code] = '(' . $country_code . ') ' . $code['name'];
    }
    return $options;
}

function formipay_sanitize_array(array $input) {
    $sanitized = [];

    foreach ($input as $key => $value) {
        if (is_array($value)) {
            // Recursively sanitize nested arrays
            $sanitized[$key] = formipay_sanitize_array( $value);
        } else {
            // Sanitize scalar values (adjust sanitization as needed)
            $sanitized[$key] = sanitize_text_field( wp_unslash($value));
        }
    }

    return $sanitized;
}

function formipay_generate_privacy_policy() {
    // Check if page already exists
    $existing_page = get_page_by_path('privacy-policy', OBJECT, 'page');
    
    if (!$existing_page) {
        // Get site-specific information
        $site_name = esc_html(get_bloginfo('name'));
        $site_url = esc_url(home_url());
        $admin_email = sanitize_email(get_bloginfo('admin_email'));
        $current_year = formipay_date('Y');

        // Build policy content
        $content = file_get_contents(FORMIPAY_PATH . '/public/templates/privacy-policy.php');

        // Create privacy policy page
        $page_id = wp_insert_post([
            'post_title'    => __('Privacy Policy', 'formipay'),
            'post_name'     => 'privacy-policy',
            'post_content'  => $content,
            'post_status'   => 'draft', // Set to draft for admin review
            'post_type'     => 'page',
            'post_author'   => get_current_user_id(),
            'meta_input'    => [
                '_formipay_generated_policy' => true,
                '_formipay_policy_version'   => '1.0'
            ]
        ]);

        // Add admin notice
        if ($page_id && !is_wp_error($page_id)) {
            add_action('admin_notices', function() use ($page_id) {
                $edit_url = admin_url("post.php?post={$page_id}&action=edit");
                echo '<div class="notice notice-success">';
                echo '<p>' . sprintf(
                    // translators: %s is the drafted page URL.
                    esc_html__('Privacy Policy draft created. <a href="%s">Review and publish</a>', 'formipay'),
                    esc_url($edit_url)
                ) . '</p>';
                echo '</div>';
            });
        }
    }
}

function formipay_thankyoupage_allowed_html() {
    return [
        'div' => [
            'id' => true,
            'class' => true,
            'data-*' => true
        ],
        'h1' => [
            'id' => true,
            'class' => true,
            'style' => true
        ],
        'h2' => [
            'id' => true,
            'class' => true,
            'style' => true
        ],
        'h3' => [
            'id' => true,
            'class' => true,
            'style' => true
        ],
        'h4' => [
            'id' => true,
            'class' => true,
            'style' => true
        ],
        'h5' => [
            'id' => true,
            'class' => true,
            'style' => true
        ],
        'h6' => [
            'id' => true,
            'class' => true,
            'style' => true
        ],
        'form' => [
            'id' => true,
            'class' => true,
            'action' => true,
            'method' => true,
            'enctype' => true
        ],
        'input' => [
            'type' => true,
            'name' => true,
            'value' => true,
            'class' => true,
            'id' => true,
            'accept' => true,
            'style' => true,
            'data-*' => true
        ],
        'button' => [
            'id' => true,
            'class' => true,
            'type' => true,
            'data-*' => true
        ],
        'img' => [
            'src' => true,
            'alt' => true,
            'class' => true,
            'id' => true
        ],
        'p' => ['class' => true],
        'b' => [],
        'i' => ['class' => true],
        'table' => ['id' => true, 'class' => true],
        'tbody' => [],
        'tr' => [],
        'th' => [],
        'td' => [],
        'br' => []
    ];
}