<?php
if (!defined('ABSPATH')) {
    exit;
}
// Hook to register the admin menu
add_action('admin_menu', 'brainx_crm_register_menu');

function brainx_crm_register_menu() {
    add_menu_page(
            __('brainX API', 'brainx-form-connector'), // Page title
            __('brainX API', 'brainx-form-connector'), // Menu title
            'manage_options', // Capability
            'brainx_crm_connector', // Menu slug
            'brainx_crm_ninja_forms_page_instructions', // Callback function
            plugin_dir_url(__FILE__) . '../assets/icon.png', // Pfad zum Icon
            70 // Position
    );

    add_submenu_page(
            'brainx_crm_connector',
            __('Ninja Forms', 'brainx-form-connector'),
            __('Ninja Forms', 'brainx-form-connector'),
            'manage_options',
            'brainx_crm_ninja_forms',
            'brainx_crm_ninja_forms_page'
    );

    add_submenu_page(
            'brainx_crm_connector',
            __('Formidable', 'brainx-form-connector'),
            __('Formidable', 'brainx-form-connector'),
            'manage_options',
            'brainx_crm_formidable',
            'brainx_crm_formidable_page'
    );

    add_submenu_page(
            'brainx_crm_connector',
            __('Einstellungen', 'brainx-form-connector'),
            __('Einstellungen', 'brainx-form-connector'),
            'manage_options',
            'brainx_crm_settings',
            'brainx_crm_settings_page'
    );

    add_submenu_page(
            'brainx_crm_connector',
            __('API Logs', 'brainx-form-connector'),
            __('API Logs', 'brainx-form-connector'),
            'manage_options',
            'brainxapi_logs',
            'brainx_api_logins_callback'
    );
}

function brainx_crm_ninja_forms_page_instructions() {
    include 'tabs/brainx-api-instructions.php';
}

if (!function_exists('brainx_api_logins_callback')) {

    function brainx_api_logins_callback() {
        // Initialize current and classes
        $current = 'ninja';
        $ninjaclass = 'mytabclass';
        $brainx_formidableclass = 'mytabclass';
        if (
                isset($_GET['brainx-form-nonceverification']) &&
                !wp_verify_nonce(
                        sanitize_text_field(wp_unslash($_GET['brainx-form-nonceverification'])),
                        'brainx-form-nonceverification-action'
                )
        ) {
            wp_die();
        }

        // Check if tab is set in query string
        if (isset($_GET['tab']) && sanitize_text_field(wp_unslash($_GET['tab'])) === 'formidable') {
            $current = 'formidable';
        }


        // Set current form type and class names based on selection
        if ($current === 'ninja') {
            $current = 'ninja_form';
            $ninjaclass = 'mytabclass active';
        } else {
            $current = 'formidable_form';
            $brainx_formidableclass = 'mytabclass active';
        }

        // Get the admin URL
        $brainx_admin_url = esc_url(admin_url());

        global $wpdb;
        $table_name = $wpdb->prefix . 'brainx_api_responses';
        if (preg_match('/^[a-zA-Z0-9_]+$/', $table_name)) {
            $brainx_results = $wpdb->get_results(
                    $wpdb->prepare(
                            "SELECT * FROM {$wpdb->prefix}brainx_api_responses WHERE form_type = %s ORDER BY id DESC",
                            $current
                    ),
                    ARRAY_A
            );
        }

        // Output HTML with proper escaping
        ?>

        <div class="brainx_logo">
            <div class="brainx_title">
                <img src="<?php echo esc_url(plugin_dir_url(dirname(__FILE__)) . 'admin/images/brain_X_logo_connector.svg'); ?>" alt="" />
            </div>
            <div class="brainx_version">
                <?php
                if (defined('BRAINX_API_CONNECTOR_VERSION')) {
                    $brainx_plugin_version = BRAINX_API_CONNECTOR_VERSION;
                    echo '<span>' . sprintf(
                            /* translators: %s: Plugin version number */
                            esc_html__('Version: %s', 'brainx-form-connector'),
                            esc_html($brainx_plugin_version)
                    ) . '</span>';
                } else {
                    echo '<span>' . esc_html__('Version konnte nicht geladen werden.', 'brainx-form-connector') . '</span>';
                }
                ?>
            </div>
        </div>



        <div class="wrap">
            <div class="form-table-head">

                <div><?php esc_html_e('API Logs', 'brainx-form-connector'); ?></div>
                <div>
                    <a class="<?php echo esc_attr($ninjaclass); ?>" style="margin-right:0" href="<?php echo esc_url($brainx_admin_url); ?>admin.php?page=brainxapi_logs"><?php esc_html_e('Ninja Form', 'brainx-form-connector'); ?></a><a class="<?php echo esc_attr($brainx_formidableclass); ?>" style="margin-right:0" href="<?php echo esc_url($brainx_admin_url); ?>admin.php?page=brainxapi_logs&tab=formidable"><?php esc_html_e('Formidable Form', 'brainx-form-connector'); ?></a>
                </div>
            </div>  

            <table class="form-table logs">
                <thead>
                    <tr>
                        <th style="width:10%"><?php esc_html_e('Formular-ID', 'brainx-form-connector'); ?></th>
                        <th style="width:10%"><?php esc_html_e('Beitrags-ID', 'brainx-form-connector'); ?></th>
                        <th style="width:20%"><?php esc_html_e('API Status', 'brainx-form-connector'); ?></th>
                        <th style="width:40%"><?php esc_html_e('Meldung', 'brainx-form-connector'); ?></th>
                        <th style="width:20%" ><?php esc_html_e('Datum/Uhrzeit', 'brainx-form-connector'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // Loop through results and display them
                    foreach ($brainx_results as $brainx_index => $brainx_res) {
                        // Generate unique textarea ID
                        $brainx_textarea_id = 'message_text_' . $brainx_index;
                        $brainx_text = $brainx_res['status'];
                        if ($brainx_text == 'error') {
                            $brainx_text = 'failed';
                        }
                        ?>
                        <tr class="<?php echo ($brainx_res['status'] == 'error') ? 'error_tr' : ''; ?>">
                            <td><?php echo esc_html($brainx_res['form_id']); ?></td>
                            <td><?php echo esc_html($brainx_res['entry_id']); ?></td>
                            <td class="statustext"><?php echo esc_html($brainx_text); ?></td>
                            <td>
                                <textarea id="<?php echo esc_attr($brainx_textarea_id); ?>" rows="3" cols="30"><?php echo esc_textarea($brainx_res['message']); ?></textarea>
                                <button type="button" onclick="kopiereText('<?php echo esc_js($brainx_textarea_id); ?>')"><?php esc_html_e('Copy to Clipboard', 'brainx-form-connector'); ?></button>
                            </td>
                            <td><?php echo esc_html($brainx_res['date']); ?></td>
                        </tr>    
                        <?php
                    }
                    ?>
                </tbody>
            </table>
        </div>
        <?php
    }

}

if (!function_exists('brainx_crm_custom_admin_styles')) {

    function brainx_crm_custom_admin_styles() {
        $pages = array('brainxapi_logs', 'brainx_crm_connector', 'brainx_crm_ninja_forms', 'brainx_crm_formidable', 'brainx_crm_settings');
        if (
                isset($_GET['brainx-form-nonceverification']) &&
                !wp_verify_nonce(
                        sanitize_text_field(wp_unslash($_GET['brainx-form-nonceverification'])),
                        'brainx-form-nonceverification-action'
                )
        ) {
            wp_die();
        }
        if (isset($_GET['page']) && in_array(wp_unslash($_GET['page']), $pages, true)) {
            wp_enqueue_style('select2_css', BRAINX_CRM_PLUGIN_URL . 'assets/sl_css.css');
            wp_enqueue_style('brainx-admin-styles', BRAINX_CRM_PLUGIN_URL . 'assets/admin.css', array(), '3.0.0', 'all');
            wp_enqueue_script('select2_js', BRAINX_CRM_PLUGIN_URL . 'assets/select2.min.js', array('jquery'), '1.0', true);
            wp_enqueue_script('brainx_admin_js', BRAINX_CRM_PLUGIN_URL . 'assets/brainx-admin.js', array('jquery'), '2.0.2', true);
            wp_localize_script('brainx_admin_js', 'brainxAdminData', array(
                'ajaxurl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('brainx-ninja-nonce')
            ));
        }
    }

}

add_action('admin_enqueue_scripts', 'brainx_crm_custom_admin_styles');

// Callback function for Ninja Forms page
if (!function_exists('brainx_crm_ninja_forms_page')) {

    function brainx_crm_ninja_forms_page() {
        $brainx_settings = get_option('_brainx_api_creds_settings');
        ?>

        <div class="brainx_logo">
            <div class="brainx_title">
                <img src="<?php echo esc_url(plugin_dir_url(dirname(__FILE__)) . 'admin/images/brain_X_logo_connector.svg'); ?>" alt="" />
            </div>
            <div class="brainx_version">
                <?php
                if (defined('BRAINX_API_CONNECTOR_VERSION')) {
                    $brainx_plugin_version = BRAINX_API_CONNECTOR_VERSION;
                    echo '<span>' . sprintf(
                            /* translators: %s: Plugin version number */
                            esc_html__('Version: %s', 'brainx-form-connector'),
                            esc_html($brainx_plugin_version)
                    ) . '</span>';
                } else {
                    echo '<span>' . esc_html__('Version konnte nicht geladen werden.', 'brainx-form-connector') . '</span>';
                }
                ?>
            </div>
        </div>

        <?php
        if (empty($brainx_settings)) {
            ?>
            <div class="wrap">
                <h3><?php esc_html_e('Bitte konfigurieren Sie die API-Einstellungen, um Felder zuzuordnen.', 'brainx-form-connector'); ?></h3>            </div>
            <?php
        } else {
            if (
                    isset($_GET['brainx-form-nonceverification']) &&
                    !wp_verify_nonce(
                            sanitize_text_field(wp_unslash($_GET['brainx-form-nonceverification'])),
                            'brainx-form-nonceverification-action'
                    )
            ) {
                wp_die();
            }
            echo '<div class="wrap">';
            $ninja_connect = isset($_GET['ninja_connect']) ? sanitize_text_field(wp_unslash($_GET['ninja_connect'])) : '';
            if (empty($ninja_connect)) {
                ?>
                <div class="wrap">
                    <div class="form-table-head no_flex">
                        <h1><?php esc_html_e('Ninja Forms', 'brainx-form-connector'); ?></h1>
                        <p><?php esc_html_e('Willkommen auf der Ninja Forms brainX Integrationsseite.', 'brainx-form-connector'); ?></p>
                    </div></div>
                <?php
            }
            include 'tabs/manage-ninja-form.php';
            ?>
            </div>
            <?php
        }
    }

}

// Callback function for Formidable page
if (!function_exists('brainx_crm_formidable_page')) {

    function brainx_crm_formidable_page() {
        $brainx_settings = get_option('_brainx_api_creds_settings');
        ?>

        <div class="brainx_logo">
            <div class="brainx_title">
                <img src="<?php echo esc_url(plugin_dir_url(dirname(__FILE__)) . 'admin/images/brain_X_logo_connector.svg'); ?>" alt="" />
            </div>
            <div class="brainx_version">
                <?php
                if (defined('BRAINX_API_CONNECTOR_VERSION')) {
                    $brainx_plugin_version = BRAINX_API_CONNECTOR_VERSION;
                    echo '<span>' . sprintf(
                            /* translators: %s: Plugin version number */
                            esc_html__('Version: %s', 'brainx-form-connector'),
                            esc_html($brainx_plugin_version)
                    ) . '</span>';
                } else {
                    echo '<span>' . esc_html__('Version konnte nicht geladen werden.', 'brainx-form-connector') . '</span>';
                }
                ?>
            </div>
        </div>

        <?php
        if (empty($brainx_settings)) {
            ?>

            <div class="wrap">
                <h3><?php esc_html_e('Bitte konfigurieren Sie die API-Einstellungen.', 'brainx-form-connector'); ?></h3>
            </div>
            <?php
        } else {
            if (
                    isset($_GET['brainx-form-nonceverification']) &&
                    !wp_verify_nonce(
                            sanitize_text_field(wp_unslash($_GET['brainx-form-nonceverification'])),
                            'brainx-form-nonceverification-action'
                    )
            ) {
                wp_die();
            }
            echo '<div class="wrap">';
            if (!isset($_GET['formidable_connect'])) {
                ?>
                <div class="wrap">
                    <div class="form-table-head no_flex">
                        <h1>Formidable</h1>
                        <p><?php esc_html_e('Willkommen auf der Formidable brainX Integrationsseite.', 'brainx-form-connector'); ?></p>
                    </div></div>
                <?php
            }
            include 'tabs/manage-brainx-formidable.php';
            ?>
            </div>
            <?php
        }
    }

}

// Callback function for Settings page

if (!function_exists('brainx_crm_settings_page')) {

    function brainx_crm_settings_page() {
        ?>

        <div class="brainx_logo">
            <div class="brainx_title"><img src="<?php echo esc_url(plugin_dir_url(dirname(__FILE__)) . '/admin/images/brain_X_logo_connector.svg'); ?>" alt=""/></div>
            <div class="brainx_version"><?php
                if (defined('BRAINX_API_CONNECTOR_VERSION')) {
                    $brainx_plugin_version = BRAINX_API_CONNECTOR_VERSION;
                    echo '<span>' . sprintf(
                            /* translators: %s: Plugin version number */
                            esc_html__('Version: %s', 'brainx-form-connector'), esc_html($brainx_plugin_version)
                    ) . '</span>';
                } else {
                    echo '<span>' . esc_html__('Version konnte nicht geladen werden.', 'brainx-form-connector') . '</span>';
                }
                ?></div>
        </div>

        <div class="card-wrapper">


            <div class="card-head">
                <h1><?php esc_html_e('Einstellungen', 'brainx-form-connector'); ?></h1>
                <p><?php esc_html_e('Konfigurieren Sie hier Ihre brainX API-Connector Einstellungen.', 'brainx-form-connector'); ?></p>
            </div>
            <div class="card-body">
                <?php
                include 'tabs/manage-brainx-api-settings.php';
                ?>

            </div></div>
        <?php
    }

}

add_action('wp_ajax_brainx_save_form_data_linking', 'brainx_save_form_data_linking');

if (!function_exists('brainx_save_form_data_linking')) {

    function brainx_save_form_data_linking() {
        // Check for nonce verification
        if (!isset($_POST['nonce']) || !check_ajax_referer('brainx-form-nonce', 'nonce', false)) {
            wp_send_json_error(array('message' => 'Nonce verification failed'), 400);
            return;
        }

        // Sanitize form_id (ensure it's an integer)
        if (isset($_POST['form_id'])) {
            $brainx_form_id = intval($_POST['form_id']);
        } else {
            wp_send_json_error(array('message' => 'Form ID is missing'), 400);
            return;
        }
        $checkfields = array();
        if (isset($_POST['checkfields'])) {
            $checkfields = array_map(
                    'sanitize_text_field',
                    (array) wp_unslash($_POST['checkfields'])  // Unsplash the input before sanitization
            );
        }

        // Sanitize mapping data (assuming it's an array or object)
        $brainx_mapping = array();
        $brainx_req = array();

        if (isset($_POST['mapping'])) {
            $brainx_mapping = array_map('sanitize_text_field', (array) wp_unslash($_POST['mapping']));
        }

        // Sanitize required field values (assuming it's an array of strings)
        if (isset($_POST['required_field_values'])) {
            $brainx_req = array_map('sanitize_text_field', (array) wp_unslash($_POST['required_field_values']));
        }

        // Build the key and array
        $brainx_key = 'brainx_crm_settings_for_form_' . $brainx_form_id;
        $brainx_key2 = 'brainx_crm_settings_ninja_checked_fields_' . $brainx_form_id;
        update_option($brainx_key2, $checkfields);
        $brainx_array = array(
            'mapping' => $brainx_mapping,
            'req' => $brainx_req
        );
        update_option($brainx_key, $brainx_array);
        brainx_update_logs_data_for_form($brainx_form_id, 'ninja', 'fields_saved');
        wp_send_json_success(array('message' => 'Data saved successfully.'));
        die();
    }

}

add_action('wp_ajax_brainx_save_form_data_linking_formidable', 'brainx_save_form_data_linking_formidable');
if (!function_exists('brainx_save_form_data_linking_formidable')) {

    function brainx_save_form_data_linking_formidable() {
        // Check for nonce verification
        if (!isset($_POST['nonce']) || !check_ajax_referer('brainx-form-nonce', 'nonce', false)) {
            wp_send_json_error(array('message' => 'Nonce verification failed'), 400);
            return;
        }
        $brainx_form_id = 0;
        // Sanitize form_id (ensure it's an integer)
        if (isset($_POST['form_id'])) {
            $brainx_form_id = intval($_POST['form_id']);
        } else {
            wp_send_json_error(array('message' => 'Form ID is missing'), 400);
            return;
        }
        $brainx_mapping = array();
        $checkfields = array();
        $brainx_req = array();
        // Sanitize mapping data (assuming it's an array or object)
        if (isset($_POST['mapping'])) {
            $brainx_mapping = array_map('sanitize_text_field', (array) wp_unslash($_POST['mapping']));
        }
        if (isset($_POST['checkfields'])) {
            $checkfields = array_map('sanitize_text_field', (array) wp_unslash($_POST['checkfields']));
        }

// Sanitize required field values (assuming it's an array of strings)
        if (isset($_POST['required_field_values'])) {
            $brainx_req = array_map('sanitize_text_field', (array) wp_unslash($_POST['required_field_values']));
        }


        // Build the key and array for saving
        $brainx_key = 'brainx_crm_settings_for_form_formidable_' . $brainx_form_id;
        $brainx_key2 = 'brainx_crm_settings_checked_fields_' . $brainx_form_id;
        update_option($brainx_key2, $checkfields);
        $brainx_array = array(
            'mapping' => $brainx_mapping,
            'req' => $brainx_req
        );
        update_option($brainx_key, $brainx_array);
        brainx_update_logs_data_for_form($brainx_form_id, 'formidable', 'fields_saved');
        wp_send_json_success(array('message' => 'Data saved successfully.'));
        die();
    }

}


add_action('wp_ajax_brainx_form_enable_disable', 'brainx_form_enable_disable');

if (!function_exists('brainx_update_logs_data_for_form')) {

    function brainx_update_logs_data_for_form($brainx_form_id, $brainx_form_type, $event) {

        if (isset($_POST['brainx_nonce'])) {
            $brainx_nonce = sanitize_text_field(wp_unslash($_POST['brainx_nonce']));
            if (!wp_verify_nonce($brainx_nonce, 'brainx_save_settings')) {
                wp_die(esc_html_e('Nonce verification failed', 'brainx-form-connector'));
            }
        }

        $brainx_key = 'brainx_formindable_form_last_updated_data_' . $brainx_form_id;
        if ($brainx_form_type == 'ninja') {
            $brainx_key = 'brainx_ninja_form_last_updated_data_' . $brainx_form_id;
        }
        $brainx_user_id = get_current_user_id();
        $brainx_date = gmdate('Y-m-d H:i:s');
        $brainx_dd = array(
            'user' => $brainx_user_id,
            'datetime' => $brainx_date,
            'event' => $event
        );
        update_option($brainx_key, $brainx_dd);
        global $wpdb;
        $table_name = $wpdb->prefix . 'brainx_api_form_updates_logs';
        $wpdb->insert(
                $table_name,
                array(
                    'user_id' => $brainx_user_id,
                    'form_id' => $brainx_form_id,
                    'form_type' => $brainx_form_type,
                    'event' => $event,
                    'datetime' => $brainx_date
                ),
                array(
                    '%d',
                    '%d',
                    '%s',
                    '%s',
                    '%s'
                )
        );
    }

}

if (!function_exists('brainx_form_enable_disable')) {

    function brainx_form_enable_disable() {
        if (!isset($_POST['nonce']) || !check_ajax_referer('brainx-ninja-nonce', 'nonce', false)) {
            wp_send_json_error(array('message' => 'Nonce verification failed'), 400);
            return;
        }

        $brainx_form_id = isset($_POST['form_id']) ? intval($_POST['form_id']) : 0;
        $brainx_checked_val = isset($_POST['checked_val']) ? sanitize_text_field(wp_unslash($_POST['checked_val'])) : 'Disable';
        $brainx_type_form = isset($_POST['type_form']) ? sanitize_text_field(wp_unslash($_POST['type_form'])) : 'ninja';

        if ($brainx_form_id <= 0) {
            wp_send_json_error(array('message' => 'Form ID is missing'), 400);
            return;
        }

        if ($brainx_checked_val !== 'Enable' && $brainx_checked_val !== 'Disable') {
            $brainx_checked_val = 'Disable';
        }

        if ($brainx_type_form === 'ninja') {
            $brainx_key = 'brainx_crm_ninja_form_status_' . $brainx_form_id;
        } else {
            $brainx_key = 'brainx_crm_formidable_form_status_' . $brainx_form_id;
        }

        update_option($brainx_key, $brainx_checked_val);
        brainx_update_logs_data_for_form($brainx_form_id, $brainx_type_form, 'status_changed');

        wp_send_json_success(array('message' => 'Status updated successfully.'));
    }

}
add_action('wp_ajax_brainx_load_field_mapping', 'brainx_load_field_mapping');
if (!function_exists('brainx_load_field_mapping')) {

    function brainx_load_field_mapping() {
        if (!isset($_POST['nonce']) || !check_ajax_referer('brainx-form-nonce', 'nonce', false)) {
            wp_send_json_error(array('message' => 'Nonce verification failed'), 400);
            return;
        }
        if (isset($_POST['form_id'])) {
            $brainx_form_id = intval($_POST['form_id']);
        }
        if (isset($_POST['type'])) {
            $brainx_type = sanitize_text_field(wp_unslash($_POST['type']));
        }

        if ($brainx_type == 'ninja') {
            include 'field_mapping/ninja-form-field-mapping.php';
        } else {
            include 'field_mapping/formidable-form-field-mapping.php';
        }
        die();
    }

}
if (!function_exists('brainx_get_ninja_form_fields')) {

    function brainx_get_ninja_form_fields($brainx_form_id) {
        global $wpdb;

        $brainx_results = $wpdb->get_results(
                $wpdb->prepare(
                        "SELECT * FROM {$wpdb->prefix}nf3_fields WHERE parent_id = %d ORDER BY `order` ASC",
                        $brainx_form_id
                )
        );

        return $brainx_results;
    }

}