<?php

/**
 * Plugin Name:  Codeandcore User Registration for CF7
 * Description: A plugin to handle user registration through Contact Form 7 submissions.
 * Version: 2.0.0
 * Author: Code and Core
 * Author URI: https://codeandcore.com/
 * Text Domain: codeandcore-user-registration-cf7
 * Requires at least: 5.0
 * Tested up to: 7.0
 * License: GPL2
 * Requires Plugins:  contact-form-7
 */

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

// Define Plugin Constants
define('CNC_CF7_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('CNC_CF7_PLUGIN_URL', plugin_dir_url(__FILE__));
define('CNC_CF7_VERSION', '2.0.0');

/* Hook into plugin activation to check if CF7 is active
 Hook into admin_init to check if CF7 is active */
add_action('admin_init', 'codeandcore_user_registration_cf7_register_plugin_deactivation');

// Function to check if CF7 is active and deactivate the plugin if it's not
function codeandcore_user_registration_cf7_register_plugin_deactivation()
{
    // Check if Contact Form 7 plugin is active
    if (! is_plugin_active('contact-form-7/wp-contact-form-7.php')) {
        // Deactivate your plugin if CF7 is not active
        deactivate_plugins(plugin_basename(__FILE__));
        // Display a notice in the admin dashboard
        add_action('admin_notices', 'codeandcore_user_registration_cf7_plugin_not_active_deactivation_notice');
    }
}


// Admin notice to inform the user that CF7 is not active
function codeandcore_user_registration_cf7_plugin_not_active_deactivation_notice()
{
    echo '<div class="error"><p><strong>Warning:</strong> This plugin requires Contact Form 7 to be active. It has been deactivated because CF7 is not active. Please install and activate Contact Form 7.</p></div>';
}

/**
 * Action: wp_enqueue_scripts
 *
 * - enqueue script in front side
 *
 */
function codeandcore_user_registration_cf7_wp_enqueue_scripts()
{
    // Define file paths
    $js_file  = 'js/codeandcore-user-registration-cf7.js';
    $css_file = 'css/all.css';

    // Define correct URLs
    $js_url  = plugin_dir_url(__FILE__) . $js_file;
    $css_url = plugin_dir_url(__FILE__) . $css_file;

    // Register JavaScript with defer attribute (WordPress 6.3+)
    wp_register_script(
        'cf7_user_registration',
        $js_url,
        array('jquery'),
        filemtime(plugin_dir_path(__FILE__) . $js_file),
        array('strategy' => 'defer') // Ensures it doesn't block rendering
    );

    // Enqueue the script
    wp_enqueue_script('cf7_user_registration');

    // Enqueue CSS (always loads in <head>)
    wp_enqueue_style(
        'cf7_user_registration_css',
        $css_url,
        array(),
        filemtime(plugin_dir_path(__FILE__) . $css_file)
    );

    // Localize script only if `cnc_cf7_selected_form` has a value
    $form_id = get_option('cnc_cf7_selected_form', '');
    if (!empty($form_id)) {
        wp_localize_script('cf7_user_registration', 'cf7forms_data', array(
            'reg_form_id' => $form_id,
            'ajax_url'    => admin_url('admin-ajax.php'),
            'nonce'       => wp_create_nonce('cf7_user_registration_nonce') // Adding nonce
        ));
    }
}
add_action('wp_enqueue_scripts', 'codeandcore_user_registration_cf7_wp_enqueue_scripts');


// Add custom CSS for the admin area
// Add custom CSS for the admin area
function codeandcore_user_registration_cf7_admin_enqueue_scripts()
{
    $css_file = plugin_dir_path(__FILE__) . 'css/admin-style.css';
    $js_file = plugin_dir_path(__FILE__) . 'js/cnc-admin-script.js';

    wp_enqueue_style(
        'cf7_user_registration_admin',
        plugin_dir_url(__FILE__) . 'css/admin-style.css',
        array(),
        file_exists($css_file) ? filemtime($css_file) : '1.0.0'
    );
    wp_enqueue_script(
        'admin-custom-js',
        plugin_dir_url(__FILE__) . 'js/cnc-admin-script.js',
        array('jquery'),
        file_exists($js_file) ? filemtime($js_file) : '1.0.0',
        true // Load script in footer
    );
}
add_action('admin_enqueue_scripts', 'codeandcore_user_registration_cf7_admin_enqueue_scripts');


/* Renders the content for the "User Role Tab" in the Contact Form 7 (CF7) settings. */
function codeandcore_user_registration_cf7_user_role_tab_content($post)
{
    $nonce = wp_create_nonce('cnc-admin-nonce');
    $selected_role         = get_post_meta($post->id(), 'cnc_cf7_user_role', true);
    $roles                 = wp_roles()->roles;
    $is_enabled            = get_post_meta($post->id(), 'cnc_cf7_enable_registration', true);
    $selected_success_url  = get_post_meta($post->id(), 'cnc_cf7_successurl_field', true); // Meta field for the selected success URL
    $disabled              = empty($is_enabled) ? 'disabled' : '';

    // Retrieve all CF7 forms
    $cf7_forms = get_posts(array(
        'post_type'   => 'wpcf7_contact_form',
        'numberposts' => -1,
    ));
?>
    <div class="cf7-user-role-tab">
        <!-- Add the checkbox to enable or disable the registration form -->
        <div class="cf7-row">
            <div class="cf7-heading"><?php echo esc_html_e('Enable Registration Form', 'codeandcore-user-registration-cf7'); ?></div>
            <div class="cf7-input">
                <label>
                    <input type="checkbox" id="cnc_cf7_enable_registration" name="cnc_cf7_enable_registration" value="1" <?php echo checked($is_enabled, '1', false); ?>>
                    <?php echo esc_html_e('Enable the registration form for this Contact Form 7 form.', 'codeandcore-user-registration-cf7'); ?>
                </label>
            </div>
        </div>
        <div class="cf7-row">
            <!-- User Role Field Selection -->
            <input type="hidden" name="admin_reg_nonce" value="<?php echo esc_attr($nonce); ?>">
            <div class="cf7-heading"><?php echo esc_html_e('Assign User Role', 'codeandcore-user-registration-cf7'); ?></div>
            <div class="cf7-input">
                <select name="cnc_cf7_user_role" id="cnc_cf7_user_role" <?php echo esc_attr($disabled); ?>>
                    <option value=""><?php echo esc_html_e('Select Role', 'codeandcore-user-registration-cf7'); ?></option>
                    <?php
                    foreach ($roles as $role_key => $role) {
                        echo '<option value="' . esc_attr($role_key) . '" ' . selected($selected_role, $role_key, false) . '>' . esc_html($role['name']) . '</option>';
                    }
                    ?>
                </select>
            </div>
        </div>


        <!--  Dropdown to select a CF7 form -->
        <div class="cf7-row">
            <div class="cf7-heading"><?php echo esc_html__('Select Contact Form 7 Form', 'codeandcore-user-registration-cf7'); ?></div>
            <div class="cf7-input">
            <select name="cnc_cf7_selected_form" id="cnc_cf7_selected_form" <?php echo esc_attr($disabled); ?>>
            <?php
                    // Verify nonce to prevent CSRF (Only if processing form data)
                    if (isset($_POST['admin_reg_nonce'])):
                        if(!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['admin_reg_nonce'])), 'cnc-admin-nonce')) {
                            wp_die(esc_html__('Security check failed.', 'codeandcore-user-registration-cf7'));
                        }
                    endif;

                    // Get the current form ID from the URL
                    $current_form_id = isset($_GET['post']) ? intval($_GET['post']) : 0;

                    if ($current_form_id) {
                        // Get the current form title
                        $current_form = get_post($current_form_id);
                        if ($current_form) {
                    ?>
                            <option value="<?php echo esc_attr($current_form_id); ?>" selected>
                                <?php echo esc_html($current_form->post_title); ?>
                            </option>
                        <?php
                        }
                    } else {
                        ?>
                        <option value=""><?php echo esc_html__('No form selected', 'codeandcore-user-registration-cf7'); ?></option>
                    <?php
                    }
                    ?>
                </select>
            </div>
        </div>
        <?php
        $pages = get_pages();
        // Add a dropdown for selecting the Success URL
        ?>
        <div class="cf7-row">
            <div class="cf7-heading"><?php echo esc_html_e('Select Success URL', 'codeandcore-user-registration-cf7'); ?></div>
            <div class="cf7-input">
                <select name="cnc_cf7_successurl_field" id="cnc_cf7_successurl_field" <?php echo esc_attr($disabled); ?>>
                    <option value=""><?php echo esc_html_e('Select Page', 'codeandcore-user-registration-cf7'); ?></option>
                    <?php
                    foreach ($pages as $page) {
                        echo '<option value="' . esc_url(get_permalink($page->ID)) . '" ' . selected($selected_success_url, get_permalink($page->ID), false) . '>' . esc_html($page->post_title) . '</option>';
                    }
                    ?>
                </select>
            </div>
        </div>
        <?php
        $checked_skip_email = get_post_meta($post->id(), 'cnc_cf7_skip_email', true) === 'on' ? 'checked' : '';
        ?>
        <div class="cf7-row">
            <div class="cf7-heading"><?php echo esc_html_e('Skip Contact Form 7 Email', 'codeandcore-user-registration-cf7'); ?></div>
            <div class="cf7-input">
                <fieldset>
                    <label>
                    <input type="checkbox" name="cnc_cf7_skip_email" value="on" <?php echo esc_attr($checked_skip_email); ?>>
                    <?php esc_html_e('Skip sending the email to the admin', 'codeandcore-user-registration-cf7'); ?>
                    </label>
                </fieldset>
            </div>
        </div>
        <?php 
            $user_approval_checked = get_post_meta($post->id(), 'cnc_cf7_user_approval', true) === 'on' ? 'checked' : ''; 
            ?>
            <div class="cf7-row">
                <div class="cf7-heading"><?php esc_html_e('Require User Approval Before Login', 'codeandcore-user-registration-cf7'); ?></div>
                <div class="cf7-input">
                    <fieldset>
                        <label>
                            <input type="checkbox" name="cnc_cf7_user_approval" value="on" <?php echo esc_attr($user_approval_checked); ?>>
                            <?php esc_html_e('Require approval before login', 'codeandcore-user-registration-cf7'); ?>
                        </label>
                    </fieldset>
                </div>
            </div>

            <?php if (get_post_meta($post->id(), 'cnc_cf7_user_approval', true) !== 'on') : ?>
                <?php
                $checked_login = get_post_meta($post->id(), 'cnc_cf7_auto_login', true) === 'on' ? 'checked' : '';
                ?>
                <div class="cf7-row">
                    <div class="cf7-heading"><?php esc_html_e('Enable Auto Login After User Registration', 'codeandcore-user-registration-cf7'); ?></div>
                    <div class="cf7-input">
                        <fieldset>
                            <label>
                                <input type="checkbox" name="cnc_cf7_auto_login" value="on" <?php echo esc_attr($checked_login); ?>>
                                <?php esc_html_e('Auto Login the Registered User', 'codeandcore-user-registration-cf7'); ?>
                            </label>
                        </fieldset>
                    </div>
                </div>
            <?php endif; ?>


        <?php
        $enable_password = get_post_meta($post->id(), 'cnc_cf7_enable_password_field', true);

        ?>
        <div class="cf7-row">
            <div class="cf7-heading"><?php echo esc_html_e('Enable Password Field', 'codeandcore-user-registration-cf7'); ?></div>
            <div class="cf7-input">
                <fieldset>
                    <label>
                    <input type="checkbox" name="cnc_cf7_enable_password_field" value="on" <?php checked($enable_password, 'on'); ?> >
                        <?php esc_html_e('Enable Password Field', 'codeandcore-user-registration-cf7'); ?>
                    </label>
                </fieldset>
            </div>
        </div>
        <div class="cf7-row">
            <div class="cf7-heading"><?php esc_html_e('Select Username Field', 'codeandcore-user-registration-cf7'); ?></div>
            <div class="cf7-input">
                <fieldset>
                    <label>
                        <select name="cnc_cf7_select_username_field" <?php echo empty($is_enabled) ? 'disabled' : ''; ?>>
                            <option value=""><?php esc_html_e('Select a field', 'codeandcore-user-registration-cf7'); ?></option>
                            <?php
                            // Get the current form ID from the URL
                            $form_id = isset($_GET['post']) ? intval($_GET['post']) : 0;

                            if ($form_id) {
                                // Retrieve the selected mapping field value
                                $selected_username_field = get_post_meta($form_id, 'cnc_cf7_select_username_field', true);

                                // Get the form content
                                $form_content = get_post_meta($form_id, '_form', true);

                                // Match all CF7 field names from this form
                                preg_match_all('/\[(?:text|email|tel|textarea|select|checkbox|radio|number|url|date|file|hidden|password)\*?\s+([^\]]+)\]/', $form_content, $matches);

                                if (!empty($matches[1])) {
                                    $unique_fields = array();

                                    foreach ($matches[1] as $field) {
                                        $field_name = explode(" ", trim($field))[0]; // Extract only the actual field name

                                        if (!in_array($field_name, $unique_fields)) {
                                            $unique_fields[] = $field_name;
                            ?>
                                            <option value="<?php echo esc_attr($field_name); ?>"
                                                <?php selected($selected_username_field, $field_name); ?>>
                                                <?php echo esc_html($field_name); ?>
                                            </option>
                            <?php
                                        }
                                    }
                                } else {
                                    echo '<option value="" disabled>' . esc_html__('No fields found in this form', 'codeandcore-user-registration-cf7') . '</option>';
                                }
                            } else {
                                echo '<option value="" disabled>' . esc_html__('Unable to determine form ID', 'codeandcore-user-registration-cf7') . '</option>';
                            }
                            ?>
                        </select>
                    </label>
                </fieldset>
            </div>
        </div>
        <div class="cf7-row">
            <div class="cf7-heading"><?php esc_html_e('Select Email Field', 'codeandcore-user-registration-cf7'); ?></div>
            <div class="cf7-input">
                <fieldset>
                    <label>
                    <select name="cnc_cf7_select_email_field" <?php echo empty($is_enabled) ? 'disabled' : ''; ?>>
                            <option value=""><?php esc_html_e('Select a field', 'codeandcore-user-registration-cf7'); ?></option>
                            <?php
                            // Get the current form ID from the URL
                            $form_id = isset($_GET['post']) ? intval($_GET['post']) : 0;

                            if ($form_id) {
                                // Retrieve the selected mapping field value
                                $cnc_cf7_select_email_field = get_post_meta($form_id, 'cnc_cf7_select_email_field', true);

                                // Get the form content
                                $form_content = get_post_meta($form_id, '_form', true);

                                // Match all CF7 field names from this form
                                preg_match_all('/\[(?:text|email|tel|textarea|select|checkbox|radio|number|url|date|file|hidden|password)\*?\s+([^\]]+)\]/', $form_content, $matches);

                                if (!empty($matches[1])) {
                                    $unique_fields = array();

                                    foreach ($matches[1] as $field) {
                                        $field_name = explode(" ", trim($field))[0]; // Extract only the actual field name

                                        if (!in_array($field_name, $unique_fields)) {
                                            $unique_fields[] = $field_name;
                            ?>
                                            <option value="<?php echo esc_attr($field_name); ?>"
                                                <?php selected($cnc_cf7_select_email_field, $field_name); ?>>
                                                <?php echo esc_html($field_name); ?>
                                            </option>
                            <?php
                                        }
                                    }
                                } else {
                                    echo '<option value="" disabled>' . esc_html__('No fields found in this form', 'codeandcore-user-registration-cf7') . '</option>';
                                }
                            } else {
                                echo '<option value="" disabled>' . esc_html__('Unable to determine form ID', 'codeandcore-user-registration-cf7') . '</option>';
                            }
                            ?>
                        </select>
                    </label>
                </fieldset>
            </div>
        </div>
        <div class="cf7-row">
            <div class="cf7-heading"><?php esc_html_e('Select Password Field', 'codeandcore-user-registration-cf7'); ?></div>
            <div class="cf7-input">
                <fieldset>
                    <label>
                    <select name="cnc_cf7_select_password_field" <?php echo empty($is_enabled) ? 'disabled' : ''; ?>>
                            <option value=""><?php esc_html_e('Select a field', 'codeandcore-user-registration-cf7'); ?></option>
                            <?php
                            // Get the current form ID from the URL
                            $form_id = isset($_GET['post']) ? intval($_GET['post']) : 0;

                            if ($form_id) {
                                // Retrieve the selected mapping field value
                                $cnc_cf7_select_password_field = get_post_meta($form_id, 'cnc_cf7_select_password_field', true);

                                // Get the form content
                                $form_content = get_post_meta($form_id, '_form', true);

                                // Match all CF7 field names from this form
                                preg_match_all('/\[(?:text|email|tel|textarea|select|checkbox|radio|number|url|date|file|hidden|password)\*?\s+([^\]]+)\]/', $form_content, $matches);

                                if (!empty($matches[1])) {
                                    $unique_fields = array();

                                    foreach ($matches[1] as $field) {
                                        $field_name = explode(" ", trim($field))[0]; // Extract only the actual field name

                                        if (!in_array($field_name, $unique_fields)) {
                                            $unique_fields[] = $field_name;
                            ?>
                                            <option value="<?php echo esc_attr($field_name); ?>"
                                                <?php selected($cnc_cf7_select_password_field, $field_name); ?>>
                                                <?php echo esc_html($field_name); ?>
                                            </option>
                            <?php
                                        }
                                    }
                                } else {
                                    echo '<option value="" disabled>' . esc_html__('No fields found in this form', 'codeandcore-user-registration-cf7') . '</option>';
                                }
                            } else {
                                echo '<option value="" disabled>' . esc_html__('Unable to determine form ID', 'codeandcore-user-registration-cf7') . '</option>';
                            }
                            ?>
                        </select>
                    </label>
                </fieldset>
            </div>
        </div>
        <div class="cf7-row">
            <div class="cf7-heading"><?php esc_html_e('Select Confirm Password Field', 'codeandcore-user-registration-cf7'); ?></div>
            <div class="cf7-input">
                <fieldset>
                    <label>
                          <select name="cnc_cf7_select_cpassword_field" <?php echo empty($is_enabled) ? 'disabled' : ''; ?>>
                            <option value=""><?php esc_html_e('Select a field', 'codeandcore-user-registration-cf7'); ?></option>
                            <?php
                            // Get the current form ID from the URL
                            $form_id = isset($_GET['post']) ? intval($_GET['post']) : 0;

                            if ($form_id) {
                                // Retrieve the selected mapping field value
                                $cnc_cf7_select_cpassword_field = get_post_meta($form_id, 'cnc_cf7_select_cpassword_field', true);

                                // Get the form content
                                $form_content = get_post_meta($form_id, '_form', true);

                                // Match all CF7 field names from this form
                                preg_match_all('/\[(?:text|email|tel|textarea|select|checkbox|radio|number|url|date|file|hidden|password)\*?\s+([^\]]+)\]/', $form_content, $matches);

                                if (!empty($matches[1])) {
                                    $unique_fields = array();

                                    foreach ($matches[1] as $field) {
                                        $field_name = explode(" ", trim($field))[0]; // Extract only the actual field name

                                        if (!in_array($field_name, $unique_fields)) {
                                            $unique_fields[] = $field_name;
                            ?>
                                            <option value="<?php echo esc_attr($field_name); ?>"
                                                <?php selected($cnc_cf7_select_cpassword_field, $field_name); ?>>
                                                <?php echo esc_html($field_name); ?>
                                            </option>
                            <?php
                                        }
                                    }
                                } else {
                                    echo '<option value="" disabled>' . esc_html__('No fields found in this form', 'codeandcore-user-registration-cf7') . '</option>';
                                }
                            } else {
                                echo '<option value="" disabled>' . esc_html__('Unable to determine form ID', 'codeandcore-user-registration-cf7') . '</option>';
                            }
                            ?>
                        </select>
                    </label>
                </fieldset>
            </div>
        </div>
    </div>
<?php
}

function codeandcore_user_registration_cf7_store_user_role_data($post_id)
{

    /* Prevent saving during autosave */
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    // Verify nonce to prevent CSRF
    if (!isset($_POST['admin_reg_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['admin_reg_nonce'])), 'cnc-admin-nonce')) {
        return;
    }

    // Check if the user has permission to edit
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    // Save selected user role
    if (isset($_POST['cnc_cf7_user_role'])) {
        update_post_meta($post_id, 'cnc_cf7_user_role', sanitize_text_field(wp_unslash($_POST['cnc_cf7_user_role'])));
    }

    // Save the enable registration setting
    if (!empty($_POST['cnc_cf7_enable_registration'])) {
        update_post_meta($post_id, 'cnc_cf7_enable_registration', '1');
    } else {
        delete_post_meta($post_id, 'cnc_cf7_enable_registration');
    }
    
    if (isset($_POST['cnc_cf7_enable_registration'])) {
        if (isset($_POST['cnc_cf7_selected_form'])) {
            $selected_form_id = intval($_POST['cnc_cf7_selected_form']);
            update_option('cnc_cf7_selected_form', $selected_form_id);
            update_post_meta($post_id, 'cnc_cf7_selected_form', sanitize_text_field(wp_unslash($_POST['cnc_cf7_selected_form'])));
        }
    } else {
        // Delete the form selection if registration is disabled
        delete_post_meta($post_id, 'cnc_cf7_selected_form');
        delete_option('cnc_cf7_selected_form');
    }


    if (isset($_POST['cf7_uname_field'])) {
        update_post_meta($post_id, 'cf7_uname_field', sanitize_text_field(wp_unslash($_POST['cf7_uname_field'])));
    } else {
        delete_post_meta($post_id, 'cf7_uname_field'); // Clean up if not selected
    }

    // Save the success URL
    if (isset($_POST['cnc_cf7_successurl_field'])) {
        update_post_meta($post_id, 'cnc_cf7_successurl_field', sanitize_text_field(wp_unslash($_POST['cnc_cf7_successurl_field'])));
    }

     // Save Auto Login
   // Save User Approval
   if (isset($_POST['cnc_cf7_user_approval'])) {
        update_post_meta($post_id, 'cnc_cf7_user_approval', 'on');
    } else {
        update_post_meta($post_id, 'cnc_cf7_user_approval','off');
    }

   // Handle Auto Login only if User Approval is off
    if (!isset($_POST['cnc_cf7_user_approval'])) { // Means approval is unchecked
        if (isset($_POST['cnc_cf7_auto_login'])) {
            update_post_meta($post_id, 'cnc_cf7_auto_login', 'on');
        } else {
            update_post_meta($post_id, 'cnc_cf7_auto_login', 'off');
        }
    } else {
        // If user approval is ON, disable auto login
        update_post_meta($post_id, 'cnc_cf7_auto_login', 'off');
    }

    if (isset($_POST['cnc_cf7_skip_email'])) {
        update_post_meta($post_id, 'cnc_cf7_skip_email', 'on');
    } else {
        delete_post_meta($post_id, 'cnc_cf7_skip_email');
    }
 
    // Save Enable Password Field setting
    if (!empty($_POST['cnc_cf7_enable_password_field'])) {
        update_post_meta($post_id, 'cnc_cf7_enable_password_field', 'on');
    } else {
        delete_post_meta($post_id, 'cnc_cf7_enable_password_field');
    }

    if (isset($_POST['cnc_cf7_select_username_field'])) {
        update_post_meta($post_id, 'cnc_cf7_select_username_field', sanitize_text_field(wp_unslash($_POST['cnc_cf7_select_username_field'])));
    }
    // Check if a field is selected
    if (isset($_POST['cnc_cf7_select_email_field'])) {
        $selected_field = sanitize_text_field(wp_unslash($_POST['cnc_cf7_select_email_field']));

        // Get CF7 form content
        $form_content = get_post_field('post_content', $post_id);

        // Check if the selected field is an email field
        if (!preg_match('/\[email[^\]]+\s' . preg_quote($selected_field, '/') . '\b/', $form_content)) {
            // Store error message in a transient
            set_transient('cnc_cf7_email_error', 'Please select a valid email field from the form. Only email fields are allowed.', 30);

            // Prevent saving
            return;
        }

        // Save the valid email field selection
        update_post_meta($post_id, 'cnc_cf7_select_email_field', $selected_field);
    }

    if (isset($_POST['cnc_cf7_select_password_field'])) {
        update_post_meta($post_id, 'cnc_cf7_select_password_field', sanitize_text_field(wp_unslash($_POST['cnc_cf7_select_password_field'])));
    }
    if (isset($_POST['cnc_cf7_select_cpassword_field'])) {
        update_post_meta($post_id, 'cnc_cf7_select_cpassword_field', sanitize_text_field(wp_unslash($_POST['cnc_cf7_select_cpassword_field'])));
    }
}
add_action('save_post', 'codeandcore_user_registration_cf7_store_user_role_data');


// Show error message inside the "User Role" tab
function codeandcore_user_registration_cf7_email_error_notice()
{
    if ($error = get_transient('cnc_cf7_email_error')) {
        echo '<div class="error"><p><strong>Error:</strong> ' . esc_html($error) . '</p></div>';
        delete_transient('cnc_cf7_email_error'); // Remove error after displaying it
    }
}
add_action('admin_notices', 'codeandcore_user_registration_cf7_email_error_notice');


/* Add nonce field to CF7 forms */
function codeandcore_user_registration_cf7_add_nonce_field($hidden_fields)
{
    $hidden_fields['cf7_user_reg_nonce'] = esc_attr(wp_create_nonce('cf7_user_reg_action'));
    return $hidden_fields;
}
add_filter('wpcf7_form_hidden_fields', 'codeandcore_user_registration_cf7_add_nonce_field');


// Retrieve the selected role during form processing
add_action('wpcf7_before_send_mail', 'codeandcore_user_registration_cf7_user_registration_handler', 10, 3);

// Register User Function
function codeandcore_user_registration_cf7_user_registration_handler($contact_form, &$abort, $object)
{
    $zurcf7_formid = (get_option('cnc_cf7_selected_form')) ? get_option('cnc_cf7_selected_form') : "";
    // Fetch form data
    $submission = WPCF7_Submission::get_instance();
    if (!$submission) return;

    $data = $submission->get_posted_data();
     // Check if cnc_cf7_enable_registration is set to 1
    // if (!isset($data['cnc_cf7_enable_registration']) || $data['cnc_cf7_enable_registration'] != 1) {
    //     return; // Exit early if registration is not enabled for this form
    // }
    if ($zurcf7_formid) {
        if (! isset($data['cf7_user_reg_nonce']) || ! wp_verify_nonce($data['cf7_user_reg_nonce'], 'cf7_user_reg_action')) {
            wp_die(esc_html('Security check failed. Please try again later.'));
        }
    }
    // Retrieve meta value for skipping email
    $skip_email = get_post_meta($contact_form->id(), 'cnc_cf7_skip_email', true);

    $enable_pass = get_post_meta($contact_form->id(), 'cnc_cf7_enable_password_field', true);

    if (!empty($zurcf7_formid)) {
        $cf7 = WPCF7_ContactForm::get_instance($zurcf7_formid);
        if (isset($cf7) && method_exists($cf7, 'collect_mail_tags')) {
            $tags = $cf7->collect_mail_tags();
        }
    }
    $form_id                    = $contact_form->id();
    $username_field_key         = get_post_meta($form_id, 'cnc_cf7_select_username_field', true);
    $user_email_tag             = get_post_meta($form_id, 'cnc_cf7_select_email_field', true);
    $password_field_tag         = get_post_meta($form_id, 'cnc_cf7_select_password_field', true);
    $confirm_password_field_tag = get_post_meta($form_id, 'cnc_cf7_select_cpassword_field', true);


    $user_login                 = sanitize_text_field($data[$username_field_key]);
    $user_email                 = sanitize_text_field($data[$user_email_tag]);
    $user_password              = sanitize_text_field($data[$password_field_tag]);
    $confirm_password           = sanitize_text_field($data[$confirm_password_field_tag]);
    $zurcf7_formid              = (get_option('cnc_cf7_selected_form')) ? get_option('cnc_cf7_selected_form') : "";

    //Registration form check
    if ($submission && ($zurcf7_formid == $form_id)) {
        $data = $submission->get_posted_data();
        $form_id = $contact_form->id();

        // Retrieve the selected form from the post meta
        $selected_form   = get_post_meta($contact_form->id(), 'cnc_cf7_selected_form', true);
        // Check if a registration form is selected
        if (empty($selected_form)) {
            $abort = true;
            $object->set_response('Registration form is not configured. Please contact the administrator.', 'codeandcore-user-registration-cf7');
            return;
        }


        if ($contact_form->id() != $selected_form) {
            $abort = true;
            $object->set_response('Please Select the Registration Form', 'codeandcore-user-registration-cf7');
            return;
        }


        // Basic email validation
        if (!is_email($user_email)) {
            $abort = true;
            $object->set_response('Please enter a valid email address.', 'codeandcore-user-registration-cf7');
            return;
        }

        // Check if email already exists
        if (email_exists($user_email)) {
            $abort = true;
            $object->set_response('This email address is already registered.', 'codeandcore-user-registration-cf7');
            return;
        }
        if ($enable_pass == 'on') {
            // Check if the user password is strong enough
            $password_check = codeandcore_user_registration_cf7_strong_password_check($user_password);
            if ($password_check !== true) {
                $abort = true;
                $object->set_response($password_check, 'codeandcore-user-registration-cf7');
                return;
            }
        }

        // Check if passwords match
        if ($user_password !== $confirm_password) {
            $abort = true;
            $object->set_response('Passwords do not match. Please try again.', 'codeandcore-user-registration-cf7');
            return;
        }
        $enable_registration = get_post_meta($contact_form->id(), 'cnc_cf7_enable_registration', true);

        // If the checkbox is not checked, abort the registration and show an error
        if (!$enable_registration) {
            $abort = true;
            $object->set_response('Please Enable the registration checkbox to proceed.', 'codeandcore-user-registration-cf7');
            return;
        }

        // Retrieve the selected role from the contact form meta
        $selected_role = get_post_meta($contact_form->id(), 'cnc_cf7_user_role', true);

        // Default to 'subscriber' if no role is selected
        if (empty($selected_role)) {
            $selected_role = 'subscriber';
        }

        // Create user
        $userdata = array(
            'user_login' => $user_login,
            'user_email' => $user_email,
            'user_pass'  => $user_password,
            'role'       => $selected_role,
        );

        // Insert user into the database
        $user_id = wp_insert_user($userdata);

        // Check for errors
        if (is_wp_error($user_id)) {
            $abort = true;
            $object->set_response($user_id->get_error_message(), 'codeandcore-user-registration-cf7');
            return;
        }


        // Retrieve the success URL from the meta
        $success_url = get_post_meta($contact_form->id(), 'cnc_cf7_successurl_field', true);

        // If a success URL is set, include it in the response
        if (!empty($success_url)) {
            add_filter('wpcf7_ajax_json_echo', function ($response) use ($success_url) {
                $response['success_url'] = $success_url;
                return $response;
            });
        }


        // Skip sending the email by setting $abort to true
        // Send registration email to user
        $user_info = get_userdata($user_id);
        $login_url = wp_login_url();


        $message = '<!DOCTYPE html>
                <html>
                <head>
                    <title>Welcome to Our Site</title>
                </head>
                <body>
                    <div class="container" style="width: 100%; max-width: 750px; margin: 50px auto 0; border: 1px solid gray; font-family: sans-serif;">
                        <h2 class="pass-title" style="background-color: #F4EFE6; color: #383838; padding: 40px 60px; margin: 0; font-size: 36px;">Welcome! Your account has been created successfully.</h2>
                        <div class="password-set" style="padding: 20px  20px; text-align: center;">
                            <p style="font-size: 18px; line-height: 28px;" class="main-p">Username: ' . esc_html($user_info->user_login) . '</p>
                            <p style="font-size: 18px; line-height: 28px;">Password: ' . esc_html($user_password) . '</p>
                            <a style="text-decoration: underline; font-weight: bold; color: #000;" class="btn" href="' . esc_url($login_url) . '">You can log in here</a>
                        </div>
                    </div>
                </body>
                </html>';

        // Email headers for sending HTML email
        $headers = array('Content-Type: text/html; charset=UTF-8');

        wp_mail($user_email, 'Welcome to Our Site!', $message, $headers);


        // Get the current user ID
        $post_id = $contact_form->id();  // Use the correct post ID context

        // Check if the user has the meta value "cnc_cf7_auto_login" set to "on"
        $auto_login = get_post_meta($post_id, 'cnc_cf7_auto_login', true);
        $success_url = get_post_meta($post_id, 'cnc_cf7_successurl_field', true);
        $cnc_cf7_user_approval = get_post_meta($post_id, 'cnc_cf7_user_approval', true);
        $cf7_successurl_field = get_post_meta($post_id, 'cnc_cf7_successurl_field', true);
        if ($auto_login === 'on' && $cnc_cf7_user_approval == 'off') { // done
            // If "on", "1", or true, log in the user automatically
            wp_set_auth_cookie($user_id);
            wp_set_current_user($user_id);
            add_filter('wpcf7_ajax_json_echo', function ($response, $result) use ($success_url) {
                $response['message'] = 'You are Registered Successfully!';
                $response['success_url'] = $success_url; // Redirect to admin dashboard
                return $response;
            }, 10, 2);
        } else if ($auto_login === 'off' && $cnc_cf7_user_approval == 'off') { //done
            add_filter('wpcf7_ajax_json_echo', function ($response, $result) use ($success_url) {
                $response['message'] = 'You are Registered Successfully!';
                $response['success_url'] = $success_url; // Redirect to admin dashboard
                return $response;
            }, 10, 2);
        } else if ($auto_login === 'off' && $cnc_cf7_user_approval == 'on') {

            add_filter('wpcf7_ajax_json_echo', function ($response, $result) use ($success_url) {
                $response['message'] = 'You are Registered Successfully. Your Account is Pending for Approval.';
                $response['success_url'] = $success_url; // Redirect to admin dashboard
                return $response;
            }, 10, 2);
        } else {
            add_filter('wpcf7_ajax_json_echo', function ($response, $result) {
                $response['message'] = 'You are Registered Successfully. Your Account is Pending for Approval.';
                return $response;
            }, 10, 2);
        }

        // Skip email silently if the meta value is "on"
        if ($skip_email === 'on') {
            $abort = true; // Abort only CF7 email sending
            add_filter('wpcf7_ajax_json_echo', function ($response) {
                // Prevent any "message aborted" text from being shown
                $response['mail_sent'] = true;
                $response['status'] = 'mail_sent'; // successful submission
                return $response;
            }, 10, 2);
        }
    }
}


function codeandcore_user_registration_cf7_validate_username_length($valid, $username)
{
    // Define the username length limit (e.g., between 5 and 20 characters)
    $min_length = 5;
    $max_length = 20;

    // Check the length of the username
    if (strlen($username) < $min_length || strlen($username) > $max_length) {
        return new WP_Error('username_length_error', sprintf(
            'Username must be between %d and %d characters long.',
            $min_length,
            $max_length
        ));
    }

    return $valid;
}
add_filter('validate_username', 'codeandcore_user_registration_cf7_validate_username_length', 10, 2);

function codeandcore_user_registration_cf7_strong_password_check($password)
{
    $min_length = 8; // Minimum password length

    // Check length first
    if (strlen($password) < $min_length) {
        return "Password must be at least $min_length characters long.";
    }

    // Check other conditions
    if (
        !preg_match("/[A-Z]/", $password) ||  // At least one uppercase letter
        !preg_match("/[a-z]/", $password) ||  // At least one lowercase letter
        !preg_match("/[0-9]/", $password) ||  // At least one number
        !preg_match("/[!,%,&,@,#,$,^,*,?,_,~]/", $password)
    ) {
        return "Password must include at least one uppercase letter, one lowercase letter, one number, and one special character.";
    }

    return true;
}




// Add a new tab in CF7 editor
add_filter('wpcf7_editor_panels', 'codeandcore_user_registration_cf7_add_user_role_tab');

function codeandcore_user_registration_cf7_add_user_role_tab($panels)
{
    $panels['user-role-panel'] = array(
        'title'    => __('Registration Settings', 'codeandcore-user-registration-cf7'),
        'callback' => 'codeandcore_user_registration_cf7_user_role_tab_content',
    );
    return $panels;
}

// Step 1: Add action to override CF7 thank-you message
add_filter('wpcf7_display_message', 'codeandcore_user_registration_cf7_thank_you_message', 10, 2);

function codeandcore_user_registration_cf7_thank_you_message($message, $status)
{
    // Prevent the default thank you message from showing
    if ($status === 'mail_sent') {
        return ''; // Empty message to avoid the default one
    }
    return $message;
}


// Save the checkbox value and update the field
add_action('wpcf7_save_contact_form', function ($contact_form) {
    // Verify nonce to prevent CSRF
    if (!isset($_POST['admin_reg_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['admin_reg_nonce'])), 'cnc-admin-nonce')) {
        return;
    }
    $post_id = $contact_form->id();
    $skip_email = isset($_POST['cnc_cf7_skip_email']) ? 'on' : 'off';
    update_post_meta($post_id, 'cnc_cf7_skip_email', $skip_email);
});

// Prevent email sending if the checkbox is checked
add_action('wpcf7_before_send_mail', function ($contact_form) {
    $submission = WPCF7_Submission::get_instance();
    if ($submission) {

        // Check if the form should skip email sending based on the form's metadata
        $post_id = $contact_form->id();
        $skip_email = get_post_meta($post_id, 'cnc_cf7_skip_email', true);

        if ($skip_email === 'on') {
            // Prevent email from being sent by clearing the recipient field
            $mail = $contact_form->prop('mail');
            $mail['recipient'] = ''; // Set recipient to empty string to stop sending
            $contact_form->set_properties(['mail' => $mail]);

            // Optionally, set a custom response message
            $submission->set_response(esc_html__('Email sending is disabled for this form.', 'codeandcore-user-registration-cf7'));
        }
    }
});



// Modify authentication to always approve admins and restrict unapproved users
add_filter('authenticate', function ($user, $username, $password) {
    if ($user instanceof WP_User) {
        // Always approved for admins
        if (user_can($user, 'administrator')) {
            update_user_meta($user->ID, '_user_approval_status', 'Approved');
            return $user;
        }

        // Get the user approval status
        $approval_status = get_user_meta($user->ID, '_user_approval_status', true);

        if ($approval_status !== 'Approved') {
            return new WP_Error('approval_required', __('Your account has not been approved yet. Please wait for admin approval.', 'codeandcore-user-registration-cf7'));
        }
    }

    return $user;
}, 30, 3);

// Add a new column for "Approval Status"
// Modify authentication to always approve admins and restrict unapproved users
add_filter('authenticate', function ($user, $username, $password) {
    if ($user instanceof WP_User) {
        // Always approved for admins
        if (user_can($user, 'administrator')) {
            update_user_meta($user->ID, '_user_approval_status', 'Approved');
            return $user;
        }

        // Check global approval setting
        $cnc_cf7_user_approval = get_option('cnc_cf7_user_approval', 'on');
        if ($cnc_cf7_user_approval === 'off') {
            update_user_meta($user->ID, '_user_approval_status', 'Approved');
            return $user;
        }

        // Get the user approval status
        $approval_status = get_user_meta($user->ID, '_user_approval_status', true);

        if ($approval_status !== 'Approved') {
            return new WP_Error('approval_required', __('Your account has not been approved yet. Please wait for admin approval.', 'codeandcore-user-registration-cf7'));
        }
    }

    return $user;
}, 30, 3);

// Add a new column for "Approval Status"
add_filter('manage_users_columns', function ($columns) {
    $columns['approval_status'] = __('Approval Status', 'codeandcore-user-registration-cf7');
    return $columns;
});

// Populate the "Approval Status" column with approve/reject buttons
add_filter('manage_users_custom_column', function ($value, $column_name, $user_id) {
    if ($column_name === 'approval_status') {
        if (user_can($user_id, 'administrator')) {
            return '<span style="color: green;">Approved</span>';
        }

        // Get the global approval setting
        $cnc_cf7_user_approval = get_option('cnc_cf7_user_approval', 'on');

        if ($cnc_cf7_user_approval === 'off') {
            update_user_meta($user_id, '_user_approval_status', 'Approved');
            return '<span style="color: green;">Approved</span>';
        }

        // Check individual user approval status
        $approval_status = get_user_meta($user_id, '_user_approval_status', true) ?: 'Pending';
        $status_color = ($approval_status === 'Approved') ? 'green' : (($approval_status === 'Rejected') ? 'red' : 'orange');
        $value = '<span style="color: ' . $status_color . ';">' . $approval_status . '</span><br>';

        // Generate approve/reject URLs
        $approve_url = esc_url(admin_url('users.php?action=approve_user&user_id=' . $user_id . '&cf7_user_reg_nonce=' . wp_create_nonce('approve_reject_user')));
        $reject_url = esc_url(admin_url('users.php?action=reject_user&user_id=' . $user_id . '&cf7_user_reg_nonce=' . wp_create_nonce('approve_reject_user')));

        // Conditionally show buttons based on current approval status
        if ($cnc_cf7_user_approval === 'on') {
            if ($approval_status === 'Pending') {
                $value .= '<a href="' . $approve_url . '" class="button btn-green">Approve</a> ';
                $value .= '<a href="' . $reject_url . '" class="button btn-danger button-secondary">Reject</a>';
            } elseif ($approval_status === 'Approved') {
                $value .= '<a href="' . $reject_url . '" class="button btn-danger button-secondary">Reject</a>';
            } elseif ($approval_status === 'Rejected') {
                $value .= '<a href="' . $approve_url . '" class="button btn-green">Approve</a>';
            }
        }
    }
    return $value;
}, 10, 3);


// Handle approve/reject user actions
add_action('admin_init', function () {
    if (isset($_GET['action'], $_GET['user_id'], $_GET['cf7_user_reg_nonce'])) {
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['cf7_user_reg_nonce'])), 'approve_reject_user')) {
            wp_die(esc_html__('Security check failed. Please try again.', 'codeandcore-user-registration-cf7'));
        }

        $action = sanitize_text_field(wp_unslash($_GET['action']));
        $user_id = intval($_GET['user_id']);

        if (!current_user_can('edit_users')) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'codeandcore-user-registration-cf7'));
        }

        if ($action === 'approve_user') {
            update_user_meta($user_id, '_user_approval_status', 'Approved');
        } elseif ($action === 'reject_user') {
            update_user_meta($user_id, '_user_approval_status', 'Rejected');
        }

        wp_safe_redirect(esc_url_raw(add_query_arg('user_approval_notice', $action, admin_url('users.php'))));
        exit;
    }
});

// Automatically set "Approved" for Administrators and when approval system is off
add_action('wp_insert_user', function ($user_id, $user) {
    $cnc_cf7_user_approval = get_option('cnc_cf7_user_approval', 'on');
    if (in_array('administrator', $user->roles) || $cnc_cf7_user_approval === 'off') {
        update_user_meta($user_id, '_user_approval_status', 'Approved');
    }
}, 10, 2);


/* FOR PASSWORD OPTION */
// Register the custom password form tag


function wpcf7_add_form_tag_k_password()
{
    $features = array('name-attr' => true);
    $features = apply_filters('codeandcore_user_registration_cf7_add_password_field_features', $features);
    wpcf7_add_form_tag(
        array('password', 'password*'),
        'wpcf7_k_password_form_tag_handler',
        $features
    );
}

function wpcf7_k_password_form_tag_handler($tag)
{
    if (empty($tag->name)) {
        return '';
    }


    $validation_error = wpcf7_get_validation_error($tag->name);

    $class = wpcf7_form_controls_class($tag->type, 'wpcf7-text');

    $class .= ' wpcf7-validates-as-password';

    if ($validation_error) {
        $class .= ' wpcf7-not-valid';
    }

    $atts = array();

    $atts['size'] = $tag->get_size_option('40');
    $atts['maxlength'] = $tag->get_maxlength_option();
    $atts['minlength'] = $tag->get_minlength_option();

    if (
        $atts['maxlength'] && $atts['minlength']
        && $atts['maxlength'] < $atts['minlength']
    ) {
        unset($atts['maxlength'], $atts['minlength']);
    }

    $atts['class'] = $tag->get_class_option($class);
    $atts['id'] = $tag->get_id_option();
    // $atts['tabindex'] = $tag->get_option( 'tabindex', 'signed_int', true );

    $atts['autocomplete'] = $tag->get_option(
        'autocomplete',
        '[-0-9a-zA-Z]+',
        true
    );

    $atts['password_strength'] = (int)$tag->get_option('password_strength', 'signed_int', true);
    $atts['password_check'] = $tag->get_option('password_check', '', true);
    $atts['specific_password_check'] = $tag->get_option('specific_password_check', '', true);
    $atts['hideIcon'] = $tag->has_option('hideIcon');

    $atts['Icon_position'] = $tag->get_option('Icon_position', '', true);
    $atts['Icon_float'] = $tag->get_option('Icon_float', '', true);
    $atts['Icon_top'] = $tag->get_option('Icon_top', '', true);
    $atts['Icon_margin'] = $tag->get_option('Icon_margin', '', true);
    $atts['Icon_marginleft'] = $tag->get_option('Icon_marginleft', '', true);

    if ($tag->has_option('Icon_position') && !empty($atts['Icon_position'])) {
        $style_attrib = 'position:' . $atts['Icon_position'] . '; ';
        if ($tag->has_option('Icon_float') && !empty($atts['Icon_float']))
            $style_attrib .= 'float:' . $atts['Icon_float'] . '; ';
        if ($tag->has_option('Icon_top') && !empty($atts['Icon_top']))
            $style_attrib .= 'top:' . $atts['Icon_top'] . '; ';
        if ($tag->has_option('Icon_margin') && !empty($atts['Icon_margin']))
            $style_attrib .= 'margin:' . $atts['Icon_margin'] . '; ';
        if ($tag->has_option('Icon_marginleft') && !empty($atts['Icon_marginleft']))
            $style_attrib .= 'margin-left:' . $atts['Icon_marginleft'] . '; ';
    } else {
        $style_attrib = 'position: relative; margin-left: -30px;';
    }

    if ($tag->is_required()) {
        $atts['aria-required'] = 'true';
    }

    if ($validation_error) {
        $atts['aria-invalid'] = 'true';
        $atts['aria-describedby'] = wpcf7_get_validation_error_reference(
            $tag->name
        );
    } else {
        $atts['aria-invalid'] = 'false';
    }

    $value = (string) reset($tag->values);

    // Support placeholder. Reference: modules/date.php in the contact form 7 plugin.
    if (
        $tag->has_option('placeholder')
        or $tag->has_option('watermark')
    ) {
        $atts['placeholder'] = $value;
        $value = '';
    }

    $value = $tag->get_default_option($value);

    $value = wpcf7_get_hangover($tag->name, $value);

    $atts['value'] = $value;

    if (wpcf7_support_html5()) {
        $atts['type'] = $tag->basetype;
    } else {
        $atts['type'] = 'password';
    }
    $atts['name'] = $tag->name;

    $atts = wpcf7_format_atts($atts);

    $tag_id = $tag->get_id_option();
    if (empty($tag_id)) $tag_id = $tag->name; // for the version 5.8 of Contact form 7: Contact form 7 ignores the id attribute if the same ID is already used for another element.

    if ($tag_id === $tag->name && !$tag->has_option('hideIcon')) {
        $html = sprintf(
            '<span class="wpcf7-form-control-wrap" data-name="%1$s"><input %2$s />%3$s<span style="' . $style_attrib . '"  id="buttonEye-' . $tag_id . '" class="fa fa-eye-slash" onclick="pushHideButton(\'' . $tag_id . '\')"></span></span>',
            sanitize_html_class($tag->name),
            $atts,
            $validation_error
        );
    } else {
        $html = sprintf(
            '<span class="wpcf7-form-control-wrap" data-name="%1$s"><input %2$s />%3$s</span>',
            sanitize_html_class($tag->name),
            $atts,
            $validation_error
        );
    }
    return $html;
}

function wpcf7_k_password_validation_filter($result, $tag)
{
    if (
        !isset($_POST['cf7_user_reg_nonce']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['cf7_user_reg_nonce'])), 'approve_reject_user')
    ) {
        $result->invalidate($tag, esc_html__('Security check failed. Please try again.', 'codeandcore-user-registration-cf7'));
        return $result; // Stop further processing if nonce fails
    }
    $name = $tag->name;

    $value = isset($_POST[$name])
        ? sanitize_text_field(wp_unslash($_POST[$name]))
        : '';
    $specific_password_check = $tag->get_option('specific_password_check', '', true);
    if (!empty($specific_password_check)) {
        $value_pass_array = explode("_", str_replace(" ", "", $specific_password_check));
        $flag = false;
        foreach ($value_pass_array as $each_value_pass) {
            if ($value === $each_value_pass) {
                $flag = true;
                break;
            }
        }
        if ($flag === false) {
            $result->invalidate($tag, __("Passwords do not match defined!", 'codeandcore-user-registration-cf7'));
        }
    }

    $password_check = $tag->get_option('password_check', '', true);

    if (!empty($password_check)) {
        $raw_input = isset($_POST[$password_check]) ? sanitize_text_field(wp_unslash($_POST[$password_check])) : '';
        $value_pass = sanitize_text_field(trim($raw_input)); // Then, sanitize input

        if ($value !== $value_pass) {
            $result->invalidate($tag, __("Passwords do not match!", 'codeandcore-user-registration-cf7'));
        }
    }



    $password_strength = (int)$tag->get_option('password_strength', 'signed_int', true);

    if ($password_strength < 0) {
        $password_strength = 0;
    }

    $pattern = preg_quote($tag->get_option('pattern'));

    if ($tag->is_required() and '' === $value) {
        $result->invalidate($tag, wpcf7_get_message('invalid_required'));
    } elseif ('' !== $value) {
        $maxlength = $tag->get_maxlength_option();
        $minlength = $tag->get_minlength_option();
        if ($maxlength and $minlength and $maxlength < $minlength) {
            $maxlength = $minlength = null;
        }
        $code_units = wpcf7_count_code_units($value);
        if (false !== $code_units) {
            if ($maxlength and $maxlength < $code_units) {
                $result->invalidate($tag, wpcf7_get_message('invalid_too_long'));
            } elseif ($minlength and $code_units < $minlength) {
                $result->invalidate($tag, wpcf7_get_message('invalid_too_short'));
            }
        }

        if ($password_strength > 0) {
            if ($password_strength === 1) {
                if (!preg_match("/^[0-9]+$/", $value)) {
                    $result->invalidate($tag, __("Please use the numbers only", 'codeandcore-user-registration-cf7'));
                }
            } elseif ($password_strength === 2) {
                if (!preg_match("/([0-9].*[a-z,A-Z])|([a-z,A-Z].*[0-9])/", $value)) {
                    $result->invalidate($tag, __("Please include one or more letters and numbers.", 'codeandcore-user-registration-cf7'));
                }
            } elseif ($password_strength === 3) {
                if (
                    !preg_match("/[0-9]/", $value) or
                    !preg_match("/([a-z].*[A-Z])|([A-Z].*[a-z])/", $value)
                ) {
                    $result->invalidate($tag, __("Please include one or more upper and lower case letters and numbers.", 'codeandcore-user-registration-cf7'));
                }
            } elseif ($password_strength === 4) {
                if (
                    !preg_match("/[0-9]/", $value) or
                    !preg_match("/([a-z].*[A-Z])|([A-Z].*[a-z])/", $value) or
                    !preg_match("/([!,%,&,@,#,$,^,*,?,_,~])/", $value)
                ) {
                    $result->invalidate($tag, __("Please include one or more upper and lower case letters, numbers, and marks.", 'codeandcore-user-registration-cf7'));
                }
            }
        }
    }

    return apply_filters('wpcf7_k_password_validation_filter', $result, $tag);
}

// Add Nonce Field in Admin UI
if (is_admin()) {
    add_action('wpcf7_admin_init', function () {
        $post_id = isset($_GET['post']) ? intval(wp_unslash($_GET['post'])) : 0;

        if ($post_id) {
            // Add a nonce field in the Contact Form 7 editor settings
            add_action('wpcf7_contact_form_editor', function () use ($post_id) {
                wp_nonce_field('cf7_user_reg_nonce_' . $post_id, 'cf7_user_reg_nonce_field');
            });

            // Verify nonce before processing data
            if (isset($_POST['cf7_user_reg_nonce_field'])) {
                $nonce = sanitize_text_field(wp_unslash($_POST['cf7_user_reg_nonce_field'])); // Unslash & sanitize

                if (empty($nonce) || !wp_verify_nonce($nonce, 'cf7_user_reg_nonce_' . $post_id)) {
                    wp_die(
                        esc_html__('Security check failed. Please reload the page and try again.', 'codeandcore-user-registration-cf7')
                    );
                }
            }

            // Retrieve the post meta value securely
            $password_enabled = get_post_meta($post_id, 'cnc_cf7_enable_password_field', true);

            if ($password_enabled === 'on') {
                add_action('wpcf7_admin_init', 'wpcf7_k_password_add_tag_generator', 55);
            }
        }
    }, 50);
}


function wpcf7_k_password_validation_on_init()
{
    // Only apply the logic when a form is submitted
    if (isset($_POST['_wpcf7'], $_POST['wpcf7_nonce'])) {
        // Verify nonce
        $nonce = sanitize_text_field(wp_unslash($_POST['wpcf7_nonce']));
        if (!wp_verify_nonce($nonce, 'wpcf7_form_submission')) {
            wp_die(esc_html__('Security check failed. Please try again.', 'codeandcore-user-registration-cf7'));
        }

        // Get the form ID safely
        $form_id = intval($_POST['_wpcf7']);

        // Retrieve the post meta for the specific form
        $enable_password_field = get_post_meta($form_id, 'cnc_cf7_enable_password_field', true);

        // Check if the password field should be enabled for this form
        if ('on' === $enable_password_field) {
            // Add the password validation filter for the form
            add_filter('wpcf7_validate_password', 'wpcf7_k_password_validation_filter', 10, 2);
            add_filter('wpcf7_validate_password*', 'wpcf7_k_password_validation_filter', 10, 2);
        }
    }
}
add_action('init', 'wpcf7_k_password_validation_on_init');

function wpcf7_k_password_add_tag_generator()
{
    $tag_generator = WPCF7_TagGenerator::get_instance();
    $tag_generator->add(
        'password',
        __('Password', 'codeandcore-user-registration-cf7'),
        'wpcf7_k_password_pane_confirm',
        array('nameless' => 1, 'version' => '2')
    );
}

function wpcf7_k_password_pane_confirm($contact_form, $options)
{
    $field_types = array(
        'password' => array(
            'display_name' => __('Password field', 'codeandcore-user-registration-cf7'),
            'heading' => __('Password field form-tag generator', 'codeandcore-user-registration-cf7'),
            'description' => __('Generate a form-tag for a password button.', 'codeandcore-user-registration-cf7'),
            'maybe_purpose' => 'author_name',
        )
    );

    $basetype = $options['id'];

    if (! in_array($basetype, array_keys($field_types))) {
        $basetype = 'password';
    }

    $tgg = new WPCF7_TagGeneratorGenerator($options['content']);
?>
    <header class="description-box">
        <h3><?php echo esc_html($field_types[$basetype]['heading']); ?></h3>

        <p><?php
            $description = wp_kses(
                $field_types[$basetype]['description'],
                array(
                    'a' => array('href' => array()), // Ensure proper attribute format
                    'strong' => array(),
                )
            );

            echo esc_html($description);
            ?></p>
    </header>


    <div class="control-box">
        <?php
        $tgg->print('field_type', array(
            'with_required' => true,
            'select_options' => array(
                $basetype => $field_types[$basetype]['display_name'],
            ),
        ));
        $tgg->print('field_name', array(
            'ask_if' => $field_types[$basetype]['maybe_purpose']
        ));
        ?>
        <fieldset>
            <legend id="<?php echo esc_attr($tgg->ref('name-option-legend')); ?>"><?php echo esc_html(__('Name', 'codeandcore-user-registration-cf7')); ?>
            </legend>
            <label><?php
                    echo sprintf(
                        '<input %s />',
                        esc_attr(wpcf7_format_atts(array(
                            'type' => 'text',
                            'aria-labelledby' => $tgg->ref('name-option-legend'),
                            'aria-describedby' => $tgg->ref('name-option-description'),
                            'data-tag-part' => 'option',
                            'data-tag-option' => 'name:',
                        )))
                    );
                    ?></label>
        </fieldset>
        <fieldset>
            <legend id="<?php echo esc_attr($tgg->ref('id-option-legend')); ?>"><?php echo esc_html(__('Id attribute', 'codeandcore-user-registration-cf7')); ?></legend>
            <label><?php
                    echo sprintf(
                        '<input %s />',
                        esc_attr(wpcf7_format_atts(array(
                            'type' => 'text',
                            'aria-labelledby' => $tgg->ref('id-option-legend'),
                            'aria-describedby' => $tgg->ref('id-option-description'),
                            'data-tag-part' => 'option',
                            'data-tag-option' => 'id:',
                        )))
                    );
                    ?></label>
        </fieldset>
        <?php

        $tgg->print('class_attr');

        $tgg->print('default_value', array(
            'with_placeholder' => true,
        ));
        ?>
    </div>

    <footer class="insert-box">
        <?php
        $tgg->print('insert_box_content');

        $tgg->print('mail_tag_tip');
        ?>
    </footer>

<?php
}
add_action('wpcf7_init', 'wpcf7_add_form_tag_k_password');
//Validate a password field (required or optional).


// save newly created cf7 field in the users meta
function codeandcore_user_registration_cf7_save_submission_meta($wpcf7)
{
    $submission = WPCF7_Submission::get_instance();

    if ($submission) {
        $form_data = $submission->get_posted_data();

        // Get current user ID
        $user_id = get_current_user_id();

        if (!$user_id) {
            return; // No logged-in user, exit
        }

        foreach ($form_data as $meta_key => $meta_value) {
            // Skip CF7 hidden fields (_wpcf7, _wpcf7_version, etc.)
            if (strpos($meta_key, '_wpcf7') === 0) {
                continue;
            }

            // Save each field dynamically as user meta
            update_user_meta($user_id, $meta_key, sanitize_text_field($meta_value));
        }
    }
}

add_action('wpcf7_mail_sent', 'codeandcore_user_registration_cf7_save_submission_meta');





// add_action('wp_footer', 'disable_password_field_if_off');
add_filter('wpcf7_contact_form_properties', function ($properties, $form) {
    // Get the current status of the password field from post meta
    $password_field_status = strtolower(get_post_meta($form->id(), 'cnc_cf7_enable_password_field', true));

    // If there is no form property, return it
    if (!isset($properties['form'])) {
        return $properties;
    }

    if ($password_field_status !== 'on') {
        // Remove Password Fields completely (including hidden password fields)
        $properties['form'] = preg_replace([ 
            '/<label[^>]*for="password"[^>]*>.*?<span[^>]*class="cf7-hide-password"[^>]*>.*?\[password\*? password[^\]]*\].*?<\/span>\s*<\/label>/is',
            '/<label[^>]*for="cpassword"[^>]*>.*?<span[^>]*class="cf7-hide-password"[^>]*>.*?\[password\*? cpassword[^\]]*\].*?<\/span>\s*<\/label>/is',
            '/\[password\*? password[^\]]*\]/is',
            '/\[password\*? cpassword[^\]]*\]/is',
            '/\[hidden password ""]\s*\[hidden cpassword ""]/is' // Remove hidden password fields
        ], '', $properties['form']);
    } elseif ($password_field_status === 'on' && !preg_match('/\[password\*\s+password/', $properties['form'])) {
        // Add Password Fields if the checkbox is checked
        $password_fields = '
        <label for="password"> Password
            <span class="cf7-hide-password">[password* password id:password placeholder "Password"]</span>
        </label>
        <label for="cpassword"> Confirm Password
            <span class="cf7-hide-password">[password* cpassword id:cpassword placeholder "Confirm Password"]</span>
        </label>';

        // Insert before the submit button wrapper
        $properties['form'] = preg_replace(
            '/(<div\s+class="submit-wrap[^"]*">)/is',
            $password_fields . "\n$1",
            $properties['form']
        );
    }

    // Explicitly update the post meta with the new form content
    update_post_meta($form->id(), '_form', $properties['form']);

    // Update post content in the posts table as well
    wp_update_post(array(
        'ID' => $form->id(),
        'post_content' => $properties['form'] // Update post content with the modified form
    ));

    return $properties;
}, 10, 2);

add_action('updated_post_meta', function ($meta_id, $post_id, $meta_key, $_meta_value) {
    if ($meta_key === 'cnc_cf7_enable_password_field') {
        $form = WPCF7_ContactForm::get_instance($post_id);

        if ($form) {
            // Reset the form's properties to reflect changes
            $form->reset_properties();
            
            // Manually update the _form meta with the new content
            update_post_meta($post_id, '_form', $form->prop('form'));

            // Update post content in the posts table
            wp_update_post(array(
                'ID' => $post_id,
                'post_content' => $form->prop('form') // Update post content with the new form
            ));
        }
    }
}, 10, 4);

/* ---------------------------------------------------------
   ADMIN & TRACKING INITIALIZATION
----------------------------------------------------------- */

/**
 * Include required files
 */
require_once CNC_CF7_PLUGIN_DIR . 'includes/class-cnc-cf7-tracking.php';
require_once CNC_CF7_PLUGIN_DIR . 'admin/class-cnc-cf7-admin.php';
require_once CNC_CF7_PLUGIN_DIR . 'admin/class-cnc-cf7-deactivation.php';

/**
 * Initialize classes
 */
CNC_CF7_Tracking::init();
CNC_CF7_Admin::init();
CNC_CF7_Deactivation::init();


