<?php

namespace PWH_DCFH\App\Admin\Settings;

if (!defined('ABSPATH')) {
    exit;
}
if (!class_exists('PWH_DCFH_Epanel_Settings')) {
    class PWH_DCFH_Epanel_Settings
    {
        private $wp_mail_failed;

        /**
         * Initializer Of The Class
         * Add/Remove Necessary Actions/Filters
         */
        public function init()
        {
            add_action('admin_init', [$this, 'maybe_admin_hooks']);
            add_action('admin_menu', [$this, 'maybe_add_menu_links']);
            add_filter('et_epanel_tab_names', [$this, 'maybe_register_tab']);
            add_filter('et_epanel_layout_data', [$this, 'maybe_register_content']);
            // add_action('wp_ajax_process_ajax_requests', [$this, 'maybe_process_admin_ajax_requests']);
        }

        /**
         * Add Menu Links
         * @return void
         */
        public function maybe_add_menu_links()
        {
            global $submenu;
            if (current_user_can('manage_options')) {
                $menu_page = 'edit.php?post_type=pwh_dcfh';
                // phpcs:disable
                $submenu[$menu_page][] = [
                    __('SMTP Integration', 'pwh-dcfh'),
                    'edit_pages',
                    esc_url(admin_url('admin.php?page=et_divi_options#wrap-pwh-dcfh-epanel'))
                ];
                $submenu[$menu_page][] = [
                    __('Automations', 'pwh-dcfh'),
                    'edit_pages',
                    esc_url(admin_url('admin.php?page=et_divi_options#wrap-pwh-dcfh-epanel'))
                ];
            }

            // phpcs:enable
        }

        /**
         * Register Admin Hooks
         */
        public function maybe_admin_hooks()
        {
            add_action('wp_mail_failed', [$this, 'maybe_log_email_error']);
            add_action('wp_ajax_process_smtp_test', [$this, 'maybe_process_smtp_test']);
            add_action('wp_ajax_test_mail_delivery', [$this, 'maybe_proces_email_test']);
            $this->process_admin_actions();
        }

        /**
         * Add Custom Tab To Panel
         *
         * @param $tabs
         *
         * @return array
         */
        public function maybe_register_tab($tabs)
        {
            return array_merge($tabs, ['pwh-dcfh-epanel' => __('Divi Contact Form Helper', 'pwh-dcfh')]);
        }

        /**
         * Add Options To Custom Tab
         *
         * @param $options
         *
         * @return mixed
         */
        public function maybe_register_content($options)
        {

            $options[] = [
                'name' => 'wrap-pwh-dcfh-epanel',
                'type' => 'contenttab-wrapstart',
            ];
            $options[] = [
                'type' => 'subnavtab-start',
            ];
            $options[] = [
                'name' => 'pwh-dcfh-tab-miscellaneous',
                'type' => 'subnav-tab',
                'desc' => __('Miscellaneous', 'pwh-dcfh')
            ];
            $options[] = [
                'name' => 'pwh-dcfh-tab-smtp',
                'type' => 'subnav-tab',
                'desc' => __('SMTP Integration', 'pwh-dcfh')
            ];
            $options[] = [
                'name' => 'pwh-dcfh-tab-spam-protection',
                'type' => 'subnav-tab',
                'desc' => __('Spam Protection', 'pwh-dcfh')
            ];
            $options[] = [
                'name' => 'pwh-dcfh-tab-cron-jobs',
                'type' => 'subnav-tab',
                'desc' => __('Automations', 'pwh-dcfh')
            ];
            $options[] = [
                'name' => 'pwh-dcfh-tab-labels',
                'type' => 'subnav-tab',
                'desc' => __('Custom Text', 'pwh-dcfh')
            ];
            $options[] = [
                'name' => 'pwh-dcfh-tab-user-permissions',
                'type' => 'subnav-tab',
                'desc' => __('User Permissions', 'pwh-dcfh')
            ];
            $options[] = [
                'name' => 'pwh-dcfh-tab-logs',
                'type' => 'subnav-tab',
                'desc' => __('Logs', 'pwh-dcfh')
            ];
            $options[] = [
                'type' => 'subnavtab-end',
            ];
            $options = $this->misc_content($options);
            $options = $this->smtp_content($options);
            $options = $this->spam_protection_content($options);
            $options = $this->cronjobs_content($options);
            $options = $this->custom_text_content($options);
            $options = $this->permissions_content($options);
            $options = $this->logs_content($options);
            $options[] = [
                'name' => 'wrap-pwh-dcfh-epanel',
                'type' => 'contenttab-wrapend',
            ];

            return $options;
        }

        private function misc_content($options)
        {
            $options[] = [
                'name' => 'pwh-dcfh-tab-miscellaneous',
                'type' => 'subcontent-start',
            ];
            $options[] = [
                'name' => __('Enable Contact Forms Stats', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_stats_enabled',
                'type' => 'checkbox',
                'desc' => __('Choose to show contact form data stats widget on admin dashboard.', 'pwh-dcfh'),
                'std' => 'off',
            ];
            $options[] = [
                'name' => __('Enable Sent Email Logs', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_enable_sent_email_log',
                'type' => 'checkbox',
                'desc' => __('Choose to log email sent history to submitter from send email page.', 'pwh-dcfh'),
                'std' => 'off',
            ];
            $options[] = [
                'name' => __('Enable Clone Logs', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_enable_clone_log',
                'type' => 'checkbox',
                'desc' => __('Choose to log clone history of contact form data to other post types.', 'pwh-dcfh'),
                'std' => 'off',
            ];
            $options[] = [
                'name' => __('Remove Plugin Data When Uninstalled', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_delete_plugin_data',
                'type' => 'checkbox',
                'desc' => __('This setting will remove all plugin data and saved settings when you uninstall the plugin. Please use this setting carefully with the understanding that if you enable the setting you will lose all saved settings if you uninstall the plugin.', 'pwh-dcfh'),
                'std' => 'off',
            ];
            $options[] = [
                'name' => __('Allowed MIME Types', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_custom_mimes_types',
                'type' => 'textarea',
                'desc' => __('Enter any MIME types that you want to enabled on your WordPress site.', 'pwh-dcfh'),
                'std' => 'psd|image/vnd.adobe.photoshop,rar|application/x-rar',
                'validation_type' => 'nohtml'
            ];
            $options[] = [
                'name' => __('Optional Entry List Columns', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_entry_list_columns',
                'type' => 'text',
                'desc' => __('Enter any field ID from the contact form(s) which will be added as additional columns in the list of entries. You can add multiple IDs as needed separated by commas.', 'pwh-dcfh'),
                'std' => 'name',
                'validation_type' => 'nohtml'
            ];
            $options[] = [
                'name' => __('Entries Date Format', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_entries_date_format',
                'type' => 'text',
                'desc' => __('Enter a custom date format for the contact form entries using your preferred PHP parameters.', 'pwh-dcfh'),
                'std' => 'Y/m/d',
                'validation_type' => 'nohtml'
            ];
            $options[] = [
                'name' => __('Entries Time Format', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_entries_time_format',
                'type' => 'text',
                'desc' => __('Enter a custom time format for the contact form entries using your preferred PHP parameters.', 'pwh-dcfh'),
                'std' => 'h:i:sa',
                'validation_type' => 'nohtml'
            ];
            $options[] = [
                'name' => __('Merge Tag Date Format', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_mergetag_date_format',
                'type' => 'text',
                'desc' => __('Enter a custom date format for the contact form message merge tags using your preferred PHP parameters.', 'pwh-dcfh'),
                'std' => 'Y-m-d',
                'validation_type' => 'nohtml'
            ];
            $options[] = [
                'name' => __('Merge Tag Time Format', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_mergetag_time_format',
                'type' => 'text',
                'desc' => __('Enter a custom time format for the contact form message merge tags using your preferred PHP parameters.', 'pwh-dcfh'),
                'std' => 'h:i:sa',
                'validation_type' => 'nohtml'
            ];
            $options[] = [
                'name' => __('Clear ICS Cached Data', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_clear_ics_cache',
                'type' => 'callback_function',
                'function_name' => function () {
                    $cache_clear_url = add_query_arg([
                        'page' => 'et_divi_options',
                        'action' => 'clear_ics_cache',
                        '_wpnonce' => wp_create_nonce(__FILE__),
                    ], admin_url());
                    ?>
                    <a href="<?php echo esc_url($cache_clear_url); ?>" class="et-button">
                        <?php esc_html_e('Clear Cache', 'pwh-dcfh'); ?>
                    </a>
                    <?php
                },
                'desc' => '',
            ];
            $options[] = [
                'name' => 'pwh-dcfh-tab-miscellaneous',
                'type' => 'subcontent-end',
            ];

            return $options;
        }

        private function smtp_content($options)
        {
            $options[] = [
                'name' => 'pwh-dcfh-tab-smtp',
                'type' => 'subcontent-start',
            ];
            $options[] = [
                'name' => __('Enable SMTP Settings', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_smtp_enabled',
                'type' => 'checkbox2',
                'desc' => __('Choose to use SMTP configuration when sending emails WordPress must utilise a legitimate SMTP provider.', 'pwh-dcfh'),
                'std' => 'off',
            ];
            $options[] = [
                'name' => __('SMTP Host', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_smtp_host',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('This is the SMTP host address provided by your hosting company.', 'pwh-dcfh'),
                'std' => '',
            ];
            $options[] = [
                'name' => __('SMTP From Email', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_smtp_from_email',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('This is the email address which will be used to send all WordPress emails.', 'pwh-dcfh'),
                'std' => get_bloginfo('admin_email'),
            ];
            $options[] = [
                'name' => __('SMTP From Name', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_smtp_from_name',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('This name will be used to send emails. We recommend using your website’s title as from name.', 'pwh-dcfh'),
                'std' => get_bloginfo('name'),
            ];
            $options[] = [
                'name' => __('Encryption', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_smtp_encryption',
                'type' => 'select',
                'options' => [
                    'none' => __('None', 'pwh-dcfh'),
                    'ssl' => __('SSL', 'pwh-dcfh'),
                    'tls' => __('TLS', 'pwh-dcfh'),
                ],
                'et_save_values' => true,
                'desc' => __('The encryption method used by your mail server to send emails. Usually it is TLS.', 'pwh-dcfh'),
                'std' => 'none',
            ];
            $options[] = [
                'name' => __('SMTP Port', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_smtp_port',
                'type' => 'text',
                'validation_type' => 'number',
                'desc' => __('This is the port used by outgoing mail server.', 'pwh-dcfh'),
                'std' => '25',
            ];
            $options[] = [
                'name' => __('Auto TLS', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_smtp_autotls',
                'type' => 'checkbox2',
                'desc' => __('By default, TLS encryption is automatically used if the server supports it (recommended). In some cases, due to server misconfigurations, this can cause issues and may need to be disabled.',
                    'pwh-dcfh'),
                'std' => 'off',
            ];
            $options[] = [
                'name' => __('Authentication', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_smtp_authentication',
                'type' => 'checkbox2',
                'desc' => __('Email senders (clients) must have permission to use the email server in order to use SMTP authentication. Outgoing messages can only be sent by authorised users.', 'pwh-dcfh'),
                'std' => 'off',
            ];
            $options[] = [
                'name' => __('SMTP Username', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_smtp_username',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('This is usually the email address you are using to send emails.', 'pwh-dcfh'),
                'std' => '',
            ];
            $options[] = [
                'name' => __('SMTP Password', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_smtp_password',
                'type' => 'password',
                'validation_type' => 'nohtml',
                'desc' => __('This is the password for the email account you are using to send emails.', 'pwh-dcfh'),
                'std' => '',
            ];
            $options[] = [
                'name' => '',
                'id' => 'pwh_dcfh_smtp_test',
                'type' => 'callback_function',
                'function_name' => function () {
                    ?>
                    <button type="button" id="pwh-dcfh-smtp-button" class="et-button pwh-dcfh-smtp-button">
                        <?php esc_html_e('Check SMTP Integration Working', 'pwh-dcfh'); ?>
                    </button><p id="pwh-dcfh-smtp-response" class="pwh-dcfh-smtp-response"></p>
                    <?php

                },
                'desc' => '',
            ];
            $options[] = [
                'name' => __('Test Email Sending', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_test_mail_delivery',
                'type' => 'callback_function',
                'function_name' => function () {
                    ?>
                    <div id="pwh-dcfh-test-mail-container" class="pwh-dcfh-test-mail-container">
                        <hr>
                        <p><?php esc_html_e('If you\'re uncertain if your website is properly sending emails, you can verify it using our built-in email sending test tool. Simply enter your email address in the field below and click "Send Email." If the default email sending functionality of your site is working correctly, you will receive a test email in your inbox!', 'pwh-dcfh'); ?></p>
                        <p><?php esc_html_e('Please note that while this test verifies basic functionality, it\'s essential to configure SMTP settings to ensure consistent email delivery. Unlike the test email, which is sent via "wp_mail" and uses plan text and is not associated with SMTP, emails from contact forms usually contain more advanced input values, header information, or attachments. It\'s important to understand that mail servers enforce their own security protocols, making SMTP crucial for reliable email delivery and gaining approval from mail servers. Don\'t forget to set up SMTP for a dedicated server to guarantee optimal mail delivery."Send Email." If the default email sending functionality of your site is working correctly, you will receive a test email in your inbox!', 'pwh-dcfh'); ?></p>
                        <input title="<?php esc_html_e('Email Address', 'pwh-dcfh'); ?>" type="email" name="email_address" placeholder="<?php esc_attr_e('Email Address', 'pwh-dcfh'); ?>">
                        <button type="button" id="phw_dcfh_test_mail_btn" class="et-button">
                            <?php esc_html_e('Send Email', 'pwh-dcfh'); ?>
                        </button>
                        <p class="mail_delivery_log"></p>
                    </div>
                    <?php

                },
                'desc' => '',
            ];
            $options[] = [
                'name' => 'pwh-dcfh-tab-smtp',
                'type' => 'subcontent-end',
            ];

            return $options;
        }

        private function spam_protection_content($options)
        {
            $options[] = [
                'name' => 'pwh-dcfh-tab-spam-protection',
                'type' => 'subcontent-start',
            ];
            $options[] = [
                'name' => '',
                'id' => 'pwh_dcfh_divider_1',
                'type' => 'callback_function',
                'function_name' => function () {
                    echo sprintf('<h1>%s</h1>', __('Blacklist Settings', 'pwh-dcfh')); // phpcs:ignore
                },
                'desc' => '',
            ];
            $options[] = [
                'name' => __('Blacklisted Email Addresses', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_blacklisted_emails',
                'type' => 'textarea',
                'desc' => __('Enter specific email addresses to block form submissions containing these email addresses from being submitted. Separate each email address with a comma.', 'pwh-dcfh'),
                'std' => '',
                'validation_type' => 'nohtml'
            ];
            $options[] = [
                'name' => __('Blacklisted Email Address Domains', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_blacklisted_email_domains',
                'type' => 'textarea',
                'desc' => __('Enter specific domains (e.g., @domain.com) to block form submissions containing these domains from being submitted. Separate each domain with a comma.', 'pwh-dcfh'),
                'std' => '',
                'validation_type' => 'nohtml'
            ];
            $options[] = [
                'name' => __('Blacklisted Keywords', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_blacklisted_keywords',
                'type' => 'textarea',
                'desc' => __('Enter specific keywords to block form submissions containing these words in the email address, message subject, or message text from being submitted. Separate each keyword with a comma.', 'pwh-dcfh'),
                'std' => '',
                'validation_type' => 'nohtml'
            ];
            $options[] = [
                'name' => '',
                'id' => 'pwh_dcfh_divider_2',
                'type' => 'callback_function',
                'function_name' => function () {
                    echo sprintf('<h1>%s</h1>', __('Google reCAPTCHA V2 Settings', 'pwh-dcfh')); // phpcs:ignore
                },
                'desc' => '',
            ];
            $options[] = [
                'name' => __('Google reCAPTCHA V2 Site Key', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_googlerecaptcha_v2_sitekey',
                'type' => 'password',
                'desc' => __('Enter your Google reCAPTCHA V2 Site Key to integrate with this site. Remember to enable the setting in the Contact Form module to activate Google reCAPTCHA V2 as needed.', 'pwh-dcfh'),// TODO ADD IT
                'std' => '',
                'validation_type' => 'nohtml'
            ];
            $options[] = [
                'name' => __('Google reCAPTCHA V2 Secret Key', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_googlerecaptcha_v2_secretkey',
                'type' => 'password',
                'desc' => __('Enter your Google reCAPTCHA V2 Secret Key to integrate with this site. Remember to enable the setting in the Contact Form module to activate Google reCAPTCHA V2 as needed.', 'pwh-dcfh'),
                'std' => '',
                'validation_type' => 'nohtml'
            ];
            $options[] = [
                'name' => __('Completely Disable Google reCAPTCHA V3', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_disable_google_recaptcha',
                'type' => 'checkbox2',
                'desc' => __('Enable this setting to completely prevent Google reCAPTCHA from loading Google fonts on the site. This is necessary for GDPR compliance even if you have the invisible Google reCAPTCHA V3 option disabled in the Divi Contact Form module.', 'pwh-dcfh'),
                'std' => 'off',
            ];
            $options[] = [
                'name' => '',
                'id' => 'pwh_dcfh_divider_3',
                'type' => 'callback_function',
                'function_name' => function () {
                    echo sprintf('<h1>%s</h1>', __('Cloudflare Turnstile Settings', 'pwh-dcfh')); // phpcs:ignore
                },
                'desc' => '',
            ];
            $options[] = [
                'name' => __('Turnstile Site Key', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_turnstile_sitekey',
                'type' => 'password',
                'desc' => __('Enter your Cloudflare Turnstile Site Key to integrate with this site. Remember to enable the setting in the Contact Form module to activate Cloudflare Turnstile as needed.', 'pwh-dcfh'),
                'std' => '',
                'validation_type' => 'nohtml'
            ];
            $options[] = [
                'name' => __('Turnstile Secret Key', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_turnstile_secretkey',
                'type' => 'password',
                'desc' => __('Enter your Cloudflare Turnstile Secret Key to integrate with this site. Remember to enable the setting in the Contact Form module to activate Cloudflare Turnstile as needed.', 'pwh-dcfh'),
                'std' => '',
                'validation_type' => 'nohtml'
            ];
            $options[] = [
                'name' => 'pwh-dcfh-tab-spam-protection',
                'type' => 'subcontent-end',
            ];

            return $options;
        }

        private function cronjobs_content($options)
        {
            $messages = get_option('pwh_dcfh_entries_auto_backup_status');
            $options[] = [
                'name' => 'pwh-dcfh-tab-cron-jobs',
                'type' => 'subcontent-start',
            ];
            $options[] = [
                'name' => __('Auto Entries Backup', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_backup_enabled',
                'type' => 'checkbox2',
                'desc' => __('Choose to create an automatic backup of your contact form data.', 'pwh-dcfh'),
                'std' => 'off',
            ];
            $options[] = [
                'name' => __('Backup Email Address', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_backup_email',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter the email address where you want to receive the auto backup file. The default is the site administrator email address.', 'pwh-dcfh'),
                'std' => get_bloginfo('admin_email'),
            ];
            $options[] = [
                'name' => __('Backup Schedule', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_backup_schedule',
                'type' => 'select',
                'options' => [
                    'hourly' => __('Every Hour', 'pwh-dcfh'),
                    'twicedaily' => __('Every 12 Hours', 'pwh-dcfh'),
                    'daily' => __('Every Day', 'pwh-dcfh'),
                    'weekly' => __('Every Week', 'pwh-dcfh'),
                    'monthly' => __('Every Month', 'pwh-dcfh'),
                ],
                'et_save_values' => true,
                'desc' => __('Select the desired frequency schedule for the auto backup.', 'pwh-dcfh'),
                'std' => 'weekly',
            ];
            if (!empty($messages)) {
                $options[] = [
                    'name' => '',
                    'id' => 'pwh_dcfh_divider_1',
                    'type' => 'callback_function',
                    'function_name' => function () use ($messages) {
                        $status = $messages['sent'] ? __('Sent', 'pwh-dcfh') : __('Failed', 'pwh-dcfh');
                        $output = '<h1>'.__('Entries Backup Status', 'pwh-dcfh').'</h1>';
                        $output .= '<ul style="display: flex !important; flex-direction: column;">';
                        $output .= '<li><b>'.__('Status:', 'pwh-dcfh').'</b> '.$status.'</li>';
                        $output .= '<li><b>'.__('Date:', 'pwh-dcfh').'</b> '.date_i18n(get_option('date_format').' '.get_option('time_format'), $messages['datetime']).'</li>';
                        $output .= '<li><b>'.__('Details:', 'pwh-dcfh').'</b> '.esc_html($messages['message']).'</li>';
                        $output .= '</ul>';
                        echo wp_kses_post($output);
                    },
                    'desc' => '',
                ];
            }
            $options[] = [
                'name' => __('Auto Delete Entries', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_delete_entries_enabled',
                'type' => 'checkbox2',
                'desc' => __('Choose to automatically delete the contact form entries after a specific number of days.', 'pwh-dcfh'),
                'std' => 'off',
            ];
            $options[] = [
                'name' => __('Delete Entries Type', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_delete_entries_status',
                'type' => 'checkbox_list',
                'usefor' => 'custom',
                'index' => -1,
                'desc' => __('Choose which type of entries should be automatically deleted after the selected number of days.', 'pwh-dcfh'),
                'options' => [
                    'published' => __('Read', 'pwh-dcfh'),
                    'draft' => __('Unread', 'pwh-dcfh'),
                    'trash' => __('Trash', 'pwh-dcfh'),
                ],
                'default' => ['published' => 'on', 'trash' => 'on'],
                'validation_type' => 'on_off_array',
                'et_save_values' => true,
            ];
            $options[] = [
                'name' => __('Delete Entries After Number Of Days', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_delete_entries_schedule',
                'type' => 'text',
                'validation_type' => 'number',
                'desc' => __('Enter the number of days after the entries are received to when they should be automatically deleted.', 'pwh-dcfh'),
                'std' => '',
            ];
            $options[] = [
                'name' => 'pwh-dcfh-tab-cron-jobs',
                'type' => 'subcontent-end',
            ];

            return $options;
        }

        private function custom_text_content($options)
        {
            $options[] = [
                'name' => 'pwh-dcfh-tab-labels',
                'type' => 'subcontent-start',
            ];
            $options[] = [
                'name' => __('Enable Multilingual Languages', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_multilingual_enabled',
                'type' => 'checkbox2',
                'desc' => __('Enable this setting to hide the custom text fields and use the WordPress language files instead to translate any custom text added by our settings. ', 'pwh-dcfh'),
                'std' => 'off',
            ];
            $options[] = [
                'name' => '',
                'id' => 'pwh_dcfh_divider_1',
                'type' => 'callback_function',
                'function_name' => function () {
                    echo sprintf('<h1>%s</h1>', __('File Upload Custom Labels', 'pwh-dcfh')); // phpcs:ignore
                },
                'desc' => '',
            ];
            $options[] = [
                'name' => __('Upload File Button Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_file_upload_btn_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for upload file button.', 'pwh-dcfh'),
                'std' => 'Choose Files',
            ];
            $options[] = [
                'name' => __('Accepted File Types Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_accepted_file_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for accepted file types.', 'pwh-dcfh'),
                'std' => 'Accepted file types:',
            ];
            $options[] = [
                'name' => __('Max File Size Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_max_filesize_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for max file size.', 'pwh-dcfh'),
                'std' => 'Max. file size:',
            ];
            $options[] = [
                'name' => __('No Files Chosen Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_chosen_file_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for no file chosen.', 'pwh-dcfh'),
                'std' => 'No Files Chosen',
            ];
            $options[] = [
                'name' => __('Number Of Chosen Files Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_selected_files_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for selected files.', 'pwh-dcfh'),
                'std' => '{chosen_files_count} file{_s_} selected',
            ];
            $options[] = [
                'name' => __('Uploading Files Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_uploading_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text while uploading files.', 'pwh-dcfh'),
                'std' => '{percentage} uploaded your files, please wait for the system to continue.',
            ];
            $options[] = [
                'name' => __('File Already Attached Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_already_attached_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for files already attached.', 'pwh-dcfh'),
                'std' => 'File {filename} has already attached. Please choose another file.',
            ];
            $options[] = [
                'name' => __('File Size Warning Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_allow_filesize_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for maximum allow file size.', 'pwh-dcfh'),
                'std' => 'File {filename} not uploaded. Maximum file size {allowed_filesize}.',
            ];
            $options[] = [
                'name' => __('Number Of Allowed Files Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_x_files_allow_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for allow to upload only number of files.', 'pwh-dcfh'),
                'std' => 'Only {allowed_files} files are allowed to upload.',
            ];
            $options[] = [
                'name' => __('Remove File Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_remove_file_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for remove file.', 'pwh-dcfh'),
                'std' => 'Are you sure you want to remove {filename}?',
            ];
            $options[] = [
                'name' => __('Delete File Icon Hover Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_delete_file_icon_hover_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for delete file icon hover text.', 'pwh-dcfh'),
                'std' => 'Remove an attachment',
            ];
            $options[] = [
                'name' => __('Not Allowed To Upload', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_security_reason_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for file type not allowed to upload.', 'pwh-dcfh'),
                'std' => 'File {filename} has failed to upload. Sorry, this file type is not permitted for security reasons.',
            ];
            $options[] = [
                'name' => __('Filesize To Upload', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_allowedfilesize_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for max file size allowed to upload.', 'pwh-dcfh'),
                'std' => 'File {filename} not uploaded. Maximum file size {filesize}',
            ];
            $options[] = [
                'name' => '',
                'id' => 'pwh_dcfh_divider_2',
                'type' => 'callback_function',
                'function_name' => function () {
                    echo sprintf('<h1>%s</h1>', __('Signature Pad Custom Labels', 'pwh-dcfh')); // phpcs:ignore
                },
                'desc' => '',
            ];
            $options[] = [
                'name' => __('Empty Signature Pad Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_siganture_empty_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for empty signature pad alert message.', 'pwh-dcfh'),
                'std' => 'The signature pad is empty. Please sign it and then save.',
            ];
            $options[] = [
                'name' => __('Before Save Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_siganture_before_save_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for save alert message.', 'pwh-dcfh'),
                'std' => 'Are you sure you want to save the signature?',
            ];
            $options[] = [
                'name' => __('Save Message Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_siganture_save_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for save message.', 'pwh-dcfh'),
                'std' => 'The signature has been saved successfully!',
            ];
            $options[] = [
                'name' => __('Delete Message Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_siganture_delete_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for delete message.', 'pwh-dcfh'),
                'std' => 'The signature has been deleted successfully!',
            ];
            $options[] = [
                'name' => __('Save Button Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_siganture_save_btn_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for the save button.', 'pwh-dcfh'),
                'std' => 'Save',
            ];
            $options[] = [
                'name' => __('Clear Button Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_siganture_clear_btn_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for the clear button.', 'pwh-dcfh'),
                'std' => 'Clear',
            ];
            $options[] = [
                'name' => '',
                'id' => 'pwh_dcfh_divider_2',
                'type' => 'callback_function',
                'function_name' => function () {
                    echo sprintf('<h1>%s</h1>', __('Contact Form Module Custom Labels', 'pwh-dcfh')); // phpcs:ignore
                },
                'desc' => '',
            ];
            $options[] = [
                'name' => __('Required Fields Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_fill_message_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for required field message.', 'pwh-dcfh'),
                'std' => 'Please fill in the following fields:',
            ];
            $options[] = [
                'name' => __('Field Error Text', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_fix_message_text',
                'type' => 'text',
                'validation_type' => 'nohtml',
                'desc' => __('Enter custom text for the field error message.', 'pwh-dcfh'),
                'std' => 'Please fix the following errors:',
            ];
            $options[] = [
                'name' => 'pwh-dcfh-tab-labels',
                'type' => 'subcontent-end',
            ];

            return $options;
        }

        private function permissions_content($options)
        {
            $options[] = [
                'name' => 'pwh-dcfh-tab-user-permissions',
                'type' => 'subcontent-start',
            ];
            $roles = get_editable_roles();
            $excluded_roles = ['administrator', 'subscriber'];
            foreach ($roles as $key => $role) {
                // Skip excluded roles
                if (in_array($key, $excluded_roles, true)) {
                    continue;
                }
                $options[] = [
                    'type' => 'checkbox_list',
                    'id' => "pwh_dcfh_permission_$key",
                    'name' => sprintf('%s Permissions', $role['name']),
                    'desc' => __('Set specific permissions for each user role to manage access to contact form entries, take action on entries, and export entries to CSV.', 'pwh-dcfh'),
                    'index' => -1,
                    'options' => ['access_entries' => __('Access Entries', 'pwh-dcfh'), 'entry_actions' => __('Entry Actions', 'pwh-dcfh'), 'export_csv' => __('Export CSV', 'pwh-dcfh')],
                    'default' => ['post' => 'on'],
                    'validation_type' => 'on_off_array',
                    'et_save_values' => true,
                    'usefor' => 'custom',
                ];
            }
            $options[] = [
                'name' => '',
                'id' => 'pwh_dcfh_divider_1',
                'type' => 'callback_function',
                'function_name' => function () {
                    $sections = [
                        [
                            'title' => 'Access Entries Capabilities',
                            'items' => ['View Entries', 'Read Entry', 'View Form Details']
                        ],
                        [
                            'title' => 'Entry Actions Capabilities',
                            'items' => [
                                'Delete Entry Permanently', 'Move Entry To Trash', 'Mark Entry as Read', 'Mark Entry as Unread', 'Mark As Spam',
                                'Reply/Send Email Of Entry', 'Create Email Template', 'View Email Templates', 'Create Post From Entry'
                            ]
                        ],
                        [
                            'title' => 'Export CSV Capabilities',
                            'items' => ['Export Entries As CSV']
                        ]
                    ];
                    foreach ($sections as $section) {
                        printf('<b>%s</b>', esc_html($section['title']));
                        echo '<ul>';
                        foreach ($section['items'] as $item) {
                            printf('<li>%s</li>', esc_html($item));
                        }
                        echo '</ul>';
                    }
                },
                'desc' => '',
            ];
            $options[] = [
                'name' => 'pwh-dcfh-tab-user-permissions',
                'type' => 'subcontent-end',
            ];

            return $options;
        }

        private function logs_content($options)
        {
            $options[] = [
                'name' => 'pwh-dcfh-tab-logs',
                'type' => 'subcontent-start',
            ];
            $options[] = [
                'name' => __('Enable Contact Form Entry Logging', 'pwh-dcfh'),
                'id' => 'pwh_dcfh_logs_enabled',
                'type' => 'checkbox',
                'desc' => __('Enable this setting to start logging all entries submitted through Divi Contact Forms on your site. The logs will capture key form data, such as names, contact information, diagnosis details, and messages. Each log entry is timestamped and securely stored. These logs are useful for troubleshooting, reviewing submissions, monitoring form performance, and retrieving user data. Once logging is enabled, all form entries will be recorded and displayed. You can download all entries or copy the most recent log entries as needed.', 'pwh-dcfh'),
                'std' => 'off',
            ];
            $options[] = [
                'name' => '',
                'id' => 'pwh_dcfh_divider_1',
                'type' => 'callback_function',
                'function_name' => function () {
                    $et_ = et_();
                    $file_path = realpath(WP_CONTENT_DIR.'/divi_contact_form.log');
                    if ($et_->WPFS()->exists($file_path) && $et_->WPFS()->is_readable($file_path)) {
                        $file_content = $et_->WPFS()->get_contents($file_path);
                        $bytes = $et_->WPFS()->size($file_path);
                        $units = ['bytes', 'KB', 'MB', 'GB', 'TB'];
                        $power = $bytes > 0 ? floor(log($bytes, 1024)) : 0;
                        $file_size = round($bytes / (1024 ** $power), 2).' '.$units[$power];
                        $log_content = '';
                        $lines = explode("\n", $file_content);
                        $log_count = 1;
                        foreach ($lines as $line) {
                            if (preg_match('/^\[(.*?)]/', $line, $matches)) {
                                $timestamp = date_i18n('Y-m-d H:i:sa', strtotime($matches[1]));
                                $log_content .= "\n------ Entry#$log_count Timestamp: $timestamp ------\n";
                                $log_count++;
                            } elseif (trim($line) === '') {
                                continue;
                            } else {
                                $log_content .= "$line\n";
                            }
                        }
                        if (!empty($log_content)) {
                            printf('<textarea id="et_logs_display" class="et__logs_display">%s</textarea>', esc_html(trim($log_content)));
                            echo '<div class="et__logs_meta">';
                            printf(
                                '<a href="%s" download>%s</a>',
                                esc_url(content_url('divi_contact_form.log')),
                                sprintf(__('Download Full Log (%s)', 'pwh-dcfh'), esc_html($file_size))
                            );
                            printf(
                                '<a href="#" class="copy_debug_log">%s</a>',
                                esc_html__('Copy Recent Log Entries', 'pwh-dcfh')
                            );

                            printf(
                                '<a href="%s" onclick="return confirm(\'%s\');">%s</a>',
                                esc_url(add_query_arg([
                                    'page' => 'et_divi_options',
                                    'action' => 'delete_log_file',
                                    '_wpnonce' => wp_create_nonce(__FILE__),
                                ], admin_url())),
                                esc_js(__('Are you sure you want to delete the log file? This action cannot be undone.', 'pwh-dcfh')),
                                esc_html__('Delete Log File', 'pwh-dcfh')
                            );
                            echo '</div>';
                        }
                    } else {
                        printf(
                            '<p>%s</p>',
                            esc_html__('No contact form entry logs found.', 'pwh-dcfh')
                        );

                    }
                },
                'desc' => '',
            ];
            $options[] = [
                'name' => 'pwh-dcfh-tab-logs',
                'type' => 'subcontent-end',
            ];

            return $options;
        }

        /**
         * Get Wp Mail Errors
         *
         * @param $wp_error
         */
        public function maybe_log_email_error($wp_error)
        {
            if (isset($wp_error->errors['wp_mail_failed'])) {
                $args = $wp_error->get_error_data('wp_mail_failed');
                if (isset($args['subject'])) {
                    $subject = $args['subject'];
                    if (str_contains($subject, 'SMTP Integrated') || str_contains($subject, 'Email Sending Test By Divi Contact Form Helper')) {
                        $this->wp_mail_failed = $wp_error->get_error_message('wp_mail_failed');
                    }
                }
            }
        }

        /**
         * Process SMTP Intgeration Test
         */
        public function maybe_process_smtp_test()
        {
            if (!empty($_REQUEST['_wpnonce'])) {
                $_wpnonce = sanitize_text_field($_REQUEST['_wpnonce']);
                if (wp_verify_nonce($_wpnonce, 'admin-ajax-nonce')) {
                    $smtp_settings = get_option('et_divi');
                    if (isset($smtp_settings['pwh_dcfh_smtp_enabled'])) {
                        $errors = [];
                        if ('on' !== trim($smtp_settings['pwh_dcfh_smtp_enabled'])) {
                            $errors[] = __('Please save changes.', 'pwh-dcfh');
                        }
                        if ('' === trim($smtp_settings['pwh_dcfh_smtp_host'])) {
                            $errors[] = __('SMTP Host required.', 'pwh-dcfh');
                        }
                        if (('on' === trim($smtp_settings['pwh_dcfh_smtp_authentication'])) && '' === trim($smtp_settings['pwh_dcfh_smtp_username']) && '' === trim($smtp_settings['pwh_dcfh_smtp_password'])) {
                            $errors[] = __('SMTP Username & Password required.', 'pwh-dcfh');
                        }
                        if (!empty($errors)) {
                            $smtp_settings['pwh_dcfh_smtp_enabled'] = false;
                            update_option('et_divi', $smtp_settings);
                            wp_send_json_error(implode('<br>', $errors));
                        }
                        if (empty($errors)) {
                            $admin_email = get_bloginfo('admin_email');
                            $blog_name = get_bloginfo('name');
                            if (wp_mail($admin_email, __('SMTP Integrated', 'pwh-dcfh'), sprintf(__('Congrats, SMTP has been integrated on your site %s successfully!', 'pwh-dcfh'), $blog_name))) {
                                wp_send_json_success(sprintf(__('Test email is sent at %s successfully! Please check your inbox to make sure it was delivered.', 'pwh-dcfh'), $admin_email));
                            } else {
                                $failed_reason = $this->wp_mail_failed;
                                if (!empty($failed_reason)) {
                                    wp_send_json_error(make_clickable($failed_reason));
                                }
                            }
                        }
                    }
                }
            }
        }

        /**
         * Test Mail Delivery Action
         * @return void
         */
        public function maybe_proces_email_test()
        {
            // Check if nonce is set and verified
            if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field($_POST['nonce']), 'admin-ajax-nonce')) {
                wp_send_json_error([
                    'errorCode' => 'unknown',
                    'message' => __('Security check failed. Please refresh and try again.', 'pwh-dcfh'),
                ], 400);
            }
            // Get email address from POST data
            $to = isset($_POST['email_address']) ? sanitize_email($_POST['email_address']) : '';
            // Validate email address
            if (empty($to)) {
                wp_send_json_error(__('Email Address is required.', 'pwh-dcfh'));
            } elseif (!is_email($to)) {
                wp_send_json_error(__('A valid email address must be given.', 'pwh-dcfh'));
            }
            // Email subject
            $subject = esc_html('Email Sending Test By Divi Contact Form Helper');
            // Email content
            $message = "This is a test message sent by Divi Contact Form Helper to determine if email sending is configured properly on your WordPress website if you received this email in your inbox, congratulations, the mail sending function is working!";
            if (wp_mail($to, $subject, $message)) {
                wp_send_json_success(sprintf(__('Test email is sent at %s successfully! Please check your inbox to make sure it was delivered.', 'pwh-dcfh'), $to));
            } else {
                wp_send_json_error($this->wp_mail_failed);
            }
        }

        public function maybe_process_admin_ajax_requests()
        {
            if (isset($_POST['_wpnonce']) && wp_verify_nonce(sanitize_text_field($_POST['_wpnonce']), 'admin-ajax-nonce')) {
                pwh_dcfh_log($_POST);
            }
        }

        /**
         * ICS Actions
         * @return void
         */
        private function process_admin_actions()
        {
            if (isset($_GET['action'], $_GET['_wpnonce'])) {
                $action = sanitize_text_field($_GET['action']);
                $nonce = sanitize_text_field($_GET['_wpnonce']);
                if ($action === 'clear_ics_cache' && wp_verify_nonce($nonce, __FILE__)) {
                    $transients = [
                        'calendar.google.com',
                        'outlook.live.com',
                    ];
                    foreach ($transients as $transient) {
                        delete_transient(md5($transient));
                    }
                    wp_safe_redirect(remove_query_arg(['action', '_wpnonce']));
                    exit;
                }
                if ($action === 'delete_log_file' && wp_verify_nonce($nonce, __FILE__)) {
                    $et_ = et_();
                    $file_path = realpath(WP_CONTENT_DIR.'/divi_contact_form.log');
                    if ($et_->WPFS()->exists($file_path) && $et_->WPFS()->is_readable($file_path)) {
                        $et_->WPFS()->delete($file_path);
                    }
                    wp_safe_redirect(remove_query_arg(['action', '_wpnonce']));
                    exit;
                }
            }
        }
    }
}