<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
add_action('admin_menu', 'doobert_chatbot_settings_menu');

if (!function_exists('doobert_chatbot_settings_menu')) {

    function doobert_chatbot_settings_menu()
    {
        add_menu_page(
            __('Doobert Chatbot Settings', 'doobert-chatbot'),
            __('Doobert Chatbot', 'doobert-chatbot'),
            'manage_options',
            'doobert-chatbot-settings',
            'doobert_chatbot_settings_page',
            DOOBERT_CHAPI_URL . 'assets/iconpaw.png',
            30
        );

        add_submenu_page(
            'doobert-chatbot-settings',
            __('Upgrade to Premium', 'doobert-chatbot'),
            __('Upgrade to Premium', 'doobert-chatbot'),
            'manage_options',
            'doobert-upgrade-premium-features',
            'doobert_upgrade_to_premium_page'
        );

        add_submenu_page(
            'doobert-chatbot-settings',
            __('Premium Features', 'doobert-chatbot'),
            __('Premium Features', 'doobert-chatbot'),
            'manage_options',
            'doobert-premium-features',
            'doobert_premium_features_page'
        );
    }
}
if (!function_exists('doobert_upgrade_to_premium_page')) {

    function doobert_upgrade_to_premium_page() {}
}
if (!function_exists('doobert_premium_features_page')) {

    function doobert_premium_features_page() {}
}
if (!function_exists('doobert_admin_enqueue_admin_styles')) {

    function doobert_admin_enqueue_admin_styles()
    {
        $current_screen = get_current_screen();
        if ($current_screen && $current_screen->id === 'toplevel_page_doobert-chatbot-settings') {
            wp_enqueue_media();
            wp_enqueue_style('admin_sl_css', DOOBERT_CHAPI_URL . 'assets/admin/admin_sl_css.min.css', array(), '1.0', 'all');
            wp_enqueue_style('admin_doobert_css', DOOBERT_CHAPI_URL . 'assets/admin/doobert-admin.css', array(), '2.0.0', 'all');
            wp_enqueue_script('admin_sl_js', DOOBERT_CHAPI_URL . 'assets/admin/admin_sl_js.min.js', array('jquery'), '1.0', true);
            wp_enqueue_script('admin_doobert_js', DOOBERT_CHAPI_URL . 'assets/admin/doobert-admin.js', array('jquery', 'admin_sl_js'), '3.6.5', true);
            wp_localize_script('admin_doobert_js', 'obj', array(
                'ajaxurl' => admin_url('admin-ajax.php'),
                'admin_url' => admin_url(),
                'security' => wp_create_nonce("verify_doobert_token_nonce"),
                'nonce' => wp_create_nonce('doobert-chatbot-settings'),
                'email_nonce' => wp_create_nonce('doobert-audit-nonce'),
            ));
        }
        wp_enqueue_script('admin_doobert_all_js', DOOBERT_CHAPI_URL . 'assets/admin/doobert-admin-all.js', array('jquery'), '3.0.0', true);
        $is_true = 0;
        $doobert_api_token_value = get_option('doobert_api_token_value');
        if (!empty($doobert_api_token_value)) {
            $doobert_api_token_value = openssl_decrypt($doobert_api_token_value, 'aes-256-cbc', 'doobert', 0, 16);
            $languages_array = doobert_load_all_languages_for_user($doobert_api_token_value);
            if (!empty($languages_array) && isset($languages_array->status)) {
                $is_true = (int) $languages_array->status;
            }
        }
        wp_localize_script('admin_doobert_all_js', 'obj2', array(
            'status' => $is_true
        ));
    }
}

add_action('admin_enqueue_scripts', 'doobert_admin_enqueue_admin_styles');
if (!function_exists('doobert_chatbot_settings_page')) {

    function doobert_chatbot_settings_page()
    {

        //    $options_array = array('doobert-chatbot-custom-settings', 'doobert_api_token_value', 'doobert_is_training_data_loaded', '_doobert_token_time_stamp', '_doobert_token_value', 'doobert_validation_data');
        //    foreach ($options_array as $op) {
        //        delete_option($op);
        //    }
        $is_valid_user = get_option('doobert_validation_data');
        $doobert_token_value = get_option('_doobert_token_value');
?>
        <div class="wrap_doobert">
            <div class="doobert_intro">
                <img src="<?php echo esc_attr(DOOBERT_CHAPI_URL) . 'assets/doober_icon.png'; ?>">
                <h3><?php echo esc_html__('Doobert ChatBot', 'doobert-chatbot'); ?></h3>
            </div>
            <?php
            $pageurl = admin_url('admin.php') . '?page=doobert-chatbot-settings';
            $pageurl = 'https://app.doobert.com/external-call?redirect_url=' . esc_url($pageurl) . '&dbrt_url=https://app.doobert.com/chatbot-premium-plans';
            if (!empty($is_valid_user) && !empty($doobert_token_value)) {
            ?>
                <div class="buy_pro_link">
                    <div class="button button-primary"><a style="color:white;" target="_blank" href="<?php echo esc_url($pageurl); ?>"><?php echo esc_html__('Upgrade to Premium', 'doobert-chatbot'); ?></a></div>
                </div>
            <?php } ?>
            <div class="notice notice-information is-dismissible">
                <p><b>
                        <?php echo esc_html__('We will update the information that the chatbot reads on your website every two weeks, from the day you installed the plugin', 'doobert-chatbot'); ?>
                    </b></p>
            </div>
        </div>
        <?php
        if (isset($_POST['save_settings']) && isset($_POST['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'doobert-chatbot-settings')) {

            $def_msg_to_show = isset($_POST['def_msg_to_show']) ? stripslashes(sanitize_text_field($_POST['def_msg_to_show'])) : '';
            //            $def_options_to_show = isset($_POST['def_options_to_show']) ? stripslashes(sanitize_text_field($_POST['def_options_to_show'])) : '';
            $news_letter_email = !empty($_POST['news_letter_email']) ? sanitize_email($_POST['news_letter_email']) : '';
            $contact_us_page = !empty($_POST['contact_us_page']) ? sanitize_text_field($_POST['contact_us_page']) : '';
            $header_title = !empty($_POST['header_title']) ? stripslashes(sanitize_text_field($_POST['header_title'])) : '';
            $send_message_placeholder = !empty($_POST['send_message_placeholder']) ? stripslashes(sanitize_text_field($_POST['send_message_placeholder'])) : '';
            $adopt_image = !empty($_POST['adopt_image']) ? stripslashes(sanitize_text_field($_POST['adopt_image'])) : '';
            doobert_upload_default_image_wp($adopt_image);
            $shelter_zipcode = !empty($_POST['shelter_zipcode']) ? stripslashes(sanitize_text_field($_POST['shelter_zipcode'])) : '';
            $display_pages = isset($_POST['display_pages']) ? array_map('intval', $_POST['display_pages']) : array();
            $default_options_tag = isset($_POST['default_options_tag']) ? array_map('sanitize_text_field', $_POST['default_options_tag']) : array();
            if (!empty($default_options_tag)) {
                $default_options_tag = implode(';', $default_options_tag);
            } else {
                $default_options_tag = '';
            }
            $shelter_ids = isset($_POST['shelter_ids']) ? array_map('sanitize_text_field', $_POST['shelter_ids']) : array();
            if (!empty($shelter_ids)) {
                $shelter_ids = implode(',', $shelter_ids);
            } else {
                $shelter_ids = '';
            }

            $array = array(
                'enable_doobert' => sanitize_text_field($_POST['enable_doobert']),
                'display_pages' => $display_pages,
                'def_msg_to_show' => $def_msg_to_show,
                'def_options_to_show' => $default_options_tag,
                'contact_us_page' => $contact_us_page,
                'news_letter_email' => $news_letter_email,
                'header_title' => $header_title,
                'send_message_placeholder' => $send_message_placeholder,
            );
            update_option('doobert-chatbot-custom-settings', $array);

            // $encrypted_api_key = wp_encrypt($_POST['doobert_api_key']);

            $key = 'doobert';
            $iv = openssl_random_pseudo_bytes(16);
            $original_string = sanitize_text_field($_POST['doobert_api_key']);
            $encrypted_value = openssl_encrypt($original_string, 'aes-256-cbc', 'doobert', 0, 16);
            update_option('doobert_api_token_value', $encrypted_value);

            if (!empty($news_letter_email) && !empty($original_string)) {
                $data = array('website' => site_url(), 'email' => $news_letter_email);
                $request_args = array(
                    'body' => $data,
                    'headers' => array(
                        'Authorization' => 'Bearer ' . $original_string,
                    ),
                    'timeout' => 60,
                    'redirection' => 5,
                    'sslverify' => false,
                );
                $response = wp_remote_post('https://app.doobert.com/api/v1/plugin/update-email', $request_args);
            }
        }
        $settings = get_option('doobert-chatbot-custom-settings');
        $petclove_settings = get_option('doobert-chatbot-petclove-settings');
        $adopt_settings = get_option('doobert-chatbot-adopt-settings');
        $enable_doobert = isset($settings['enable_doobert']) ? $settings['enable_doobert'] : '';
        $display_pages = isset($settings['display_pages']) ? $settings['display_pages'] : '';
        $def_msg_to_show = isset($settings['def_msg_to_show']) ? stripslashes($settings['def_msg_to_show']) : '';
        $news_letter_email = isset($settings['news_letter_email']) ? $settings['news_letter_email'] : '';
        $petco_love = isset($petclove_settings['petco_love']) ? $petclove_settings['petco_love'] : '';
        $adopt_pet = isset($adopt_settings['adopt_pet']) ? $adopt_settings['adopt_pet'] : '';
        $def_options_to_show = isset($settings['def_options_to_show']) ? stripslashes($settings['def_options_to_show']) : '';
        $contact_us_page = isset($settings['contact_us_page']) ? $settings['contact_us_page'] : '';
        $header_title = isset($settings['header_title']) ? $settings['header_title'] : 'Hello!';
        $adopt_image = isset($adopt_settings['adopt_image']) ? $adopt_settings['adopt_image'] : '';
        $shelter_zipcode = isset($adopt_settings['shelter_zipcode']) ? $adopt_settings['shelter_zipcode'] : '';
        $shelter_ids = isset($adopt_settings['shelter_ids']) ? stripslashes($adopt_settings['shelter_ids']) : '';
        $send_message_placeholder = isset($settings['send_message_placeholder']) ? $settings['send_message_placeholder'] : '';
        $doobert_api_token_value = get_option('doobert_api_token_value');
        if (!empty($doobert_api_token_value)) {
            $doobert_api_token_value = openssl_decrypt($doobert_api_token_value, 'aes-256-cbc', 'doobert', 0, 16);
        }

        $pages = get_pages(array(
            'post_type' => 'page',
        ));

        $is_valid_user = get_option('doobert_validation_data');
        $doobert_token_value = get_option('_doobert_token_value');
        if (!empty($is_valid_user) && !empty($doobert_token_value)) {

            $active_gen = 'nav-tab-active';
            $active_des = '';
            if (isset($_GET['tab']) && $_GET['tab'] == 'design') {
                $active_gen = '';
                $active_des = 'nav-tab-active';
            }

            $languages_array = doobert_load_all_languages_for_user($doobert_api_token_value);
        ?>

            <div class="wrap_doobert">
                <h3><?php echo esc_html__('Doobert Settings', 'doobert-chatbot'); ?></h3>
                <div class="doobert_tab nav-tab-wrapper">
                    <a class="nav-tab <?php echo !isset($_GET['tab']) ? 'nav-tab-active' : ''; ?>" href="admin.php?page=doobert-chatbot-settings"><?php echo esc_html__('General Settings', 'doobert-chatbot'); ?></a>
                    <a class="nav-tab <?php
                                        if (isset($_GET['tab']) && $_GET['tab'] == 'design') {
                                            echo 'nav-tab-active';
                                        }
                                        ?>" href="admin.php?page=doobert-chatbot-settings&tab=design"><?php echo esc_html__('Design Settings', 'doobert-chatbot'); ?></a>
                    <?php
                    $is_true = 0;
                    if (!empty($languages_array) && isset($languages_array->status)) {
                        $is_true = (int) $languages_array->status;
                    }
                    if ($is_true == 1) {
                    ?>
                        <input type="hidden" id="is_already_paid_version" value="1" />
                        <a class="nav-tab <?php
                                            if (isset($_GET['tab']) && $_GET['tab'] == 'premium-settings') {
                                                echo 'nav-tab-active';
                                            }
                                            ?>" href="admin.php?page=doobert-chatbot-settings&tab=premium-settings"><?php echo esc_html__('Premium Settings', 'doobert-chatbot'); ?></a>

                    <?php } ?>

                    <a class="nav-tab <?php
                                        if (isset($_GET['tab']) && $_GET['tab'] == 'resource-library') {
                                            echo 'nav-tab-active';
                                        }
                                        ?>" href="admin.php?page=doobert-chatbot-settings&tab=resource-library"><?php echo esc_html__('Resource Library', 'doobert-chatbot'); ?></a>

                </div>
                <?php
                if (isset($_GET['tab']) && $_GET['tab'] == 'design') {
                    include 'tabs/doober-chatbot-design-settings.php';
                } else if (isset($_GET['tab']) && $_GET['tab'] == 'premium-settings') {
                    include 'tabs/doober-chatbot-languages-settings.php';
                } else if (isset($_GET['tab']) && $_GET['tab'] == 'resource-library') {
                    include 'tabs/doobert-chatbot-resource-library.php';
                } else {
                    $training_loaded = get_option('doobert_is_training_data_loaded');
                    if ($training_loaded != 1) {
                ?>
                        <div class="message notice">
                            <p><?php echo esc_html__('Please Load train data to enable chatbot', 'doobert-chatbot'); ?></p>
                        </div>
                    <?php
                    }
                    if (isset($_GET['loaded'])) {
                    ?>
                        <div class="notice notice-success is-dismissible">
                            <p><?php echo esc_html__('Data updated successfully.', 'doobert-chatbot'); ?></p>
                        </div>
                    <?php
                    }
                    $nonce = wp_create_nonce('doobert-chatbot-settings');
                    ?>
                    <form method="post" action="">
                        <table class="form-table">
                            <tr>
                                <td><a href="?load_csv=1&_wpnonce=<?php echo esc_attr($nonce); ?>" class="button button-primary"><?php echo esc_html__('Update Data', 'doobert-chatbot'); ?></a></td>
                                <td><?php echo esc_html__('If you have added more pages/posts to your website, please click the “Update Data” to the left. This will do a quick scan of your website to find any new content you’ve added so the Chatbot can respond accurately.', 'doobert-chatbot'); ?></td>
                            </tr>
                        </table>
                    </form>

                    <form method="post" action="">
                        <table class="form-table">
                            <tr>
                                <th><?php echo esc_html__('Enable/Disable', 'doobert-chatbot'); ?></th>
                                <td>
                                    <select name="enable_doobert">
                                        <option <?php selected($enable_doobert, 'enable'); ?> value="enable"><?php echo esc_html__('Enable', 'doobert-chatbot'); ?></option>
                                        <option <?php selected($enable_doobert, 'disable'); ?> value="disable"><?php echo esc_html__('Disable', 'doobert-chatbot'); ?></option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th><?php echo esc_html__('Doobert API Key', 'doobert-chatbot'); ?></th>
                                <td>
                                    <input type="password" id="doobert_api_key" name="doobert_api_key" value="<?php echo esc_attr($doobert_api_token_value); ?>" required>
                                    <span class="show_hide_icon"><span class="show"><?php echo esc_html__('Show', 'doobert-chatbot'); ?></span><span class="hide"><?php echo esc_html__('Hide', 'doobert-chatbot'); ?></span></span>
                                </td>
                            </tr>
                            <tr>
                                <th><?php echo esc_html__('Display chatbot ONLY on a specific page(s)', 'doobert-chatbot'); ?></th>
                                <td>
                                    <select class="full_select" name="display_pages[]" multiple>
                                        <?php
                                        foreach ($pages as $page) {
                                            $selected = '';
                                            if (!empty($display_pages) && is_array($display_pages) && in_array($page->ID, $display_pages)) {
                                                $selected = 'selected=""';
                                            }
                                            echo '<option value="' . esc_attr($page->ID) . '" ' . esc_attr($selected) . '>' . esc_attr($page->post_title) . '</option>';
                                        }
                                        ?>
                                    </select>

                                    <br>
                                    <small><?php echo esc_html__('Keep empty if you want to show on all pages', 'doobert-chatbot'); ?></small>
                                </td>
                            </tr>

                            <tr>
                                <th><?php echo esc_html__('Choose Contact Us Page', 'doobert-chatbot'); ?></th>
                                <td>
                                    <select class="full_select" name="contact_us_page">
                                        <option value="">Select</option>
                                        <?php
                                        foreach ($pages as $page) {
                                            $selected = '';
                                            if (!empty($contact_us_page) && $contact_us_page == $page->ID) {
                                                $selected = 'selected=""';
                                            }
                                            echo '<option value="' . esc_attr($page->ID) . '" ' . esc_attr($selected) . '>' . esc_attr($page->post_title) . '</option>';
                                        }
                                        ?>
                                    </select>
                                </td>
                            </tr>

                            <tr>
                                <th><?php echo esc_html__('Header Title', 'doobert-chatbot'); ?></th>
                                <td><input type="text" name="header_title" value="<?php echo esc_attr($header_title); ?>"></td>
                            </tr>

                            <tr>
                                <th><?php echo esc_html__('Send Message input Placeholder', 'doobert-chatbot'); ?></th>
                                <td><input type="text" name="send_message_placeholder" value="<?php echo esc_attr($send_message_placeholder); ?>"></td>
                            </tr>

                            <tr>
                                <th><?php echo esc_html__('Default quick question prompts', 'doobert-chatbot'); ?></th>
                                <td><textarea name="def_msg_to_show" cols="35" rows="5"><?php echo esc_attr($def_msg_to_show); ?></textarea></td>
                            </tr>


                            <tr>
                                <th><?php echo esc_html__('Default Options to show', 'doobert-chatbot'); ?></th>
                                <td>
                                    <select id="default_options_tag" name="default_options_tag[]" multiple="multiple" style="width: 100%">
                                        <?php
                                        if (!empty($def_options_to_show)) {
                                            $def_options_to_show = explode(';', $def_options_to_show);
                                            foreach ($def_options_to_show as $val) {
                                        ?>
                                                <option value="<?php echo esc_attr($val); ?>" selected=""><?php echo esc_attr($val); ?></option>
                                        <?php
                                            }
                                        }
                                        ?>
                                    </select>
                                    <br><small><?php echo esc_html__('Please avoid one word options as this does not provide the best responses', 'doobert-chatbot'); ?></small>
                                </td>
                            </tr>




                            <tr>
                                <th><?php echo esc_html__('Newsletter Email', 'doobert-chatbot'); ?> <br><?php echo esc_html__('(Add your email and be notified of updates)', 'doobert-chatbot'); ?></th>
                                <td>
                                    <input style="margin-bottom: 30px;" type="email" name="news_letter_email" value="<?php echo esc_attr(sanitize_email($news_letter_email)); ?>">
                                </td>
                            </tr>

                        </table>
                        <h3><?php echo esc_html__('Monthly Audit Log', 'doobert-chatbot'); ?></h3>
                        <p><?php echo esc_html__('The account owner will receive a monthly email report containing an audit log of the questions asked and', 'doobert-chatbot'); ?><br>
                            <?php echo esc_html__('responses provided by our chatbot. This report will help you keep track of interactions,', 'doobert-chatbot'); ?><br>
                            <?php echo esc_html__('ensuring transparency, and improving overall service quality.', 'doobert-chatbot'); ?><br>
                        </p>
                        <?php wp_nonce_field('doobert-chatbot-settings'); ?>
                        <input type="submit" name="save_settings" class="button button-primary" value="<?php echo esc_html__('Save Settings', 'doobert-chatbot'); ?>">
                    </form>
                <?php } ?>
            </div>
        <?php



        } else {
        ?>
            <div class="wrap_doobert">
                <h3><?php echo esc_html__('Verify your identity to continue with Doobert Chatbot', 'doobert-chatbot'); ?></h3>
                <table>
                    <tr>

                        <th><?php echo esc_html__('Enter your API Key', 'doobert-chatbot'); ?></th>
                        <td>
                            <input type="text" id="doobert_authorization_token">
                        </td>

                    </tr>
                    <tr>
                        <td></td>
                        <td><em>
                                <?php echo esc_html__('You can get your API key by logging in to your Doobert organization account and copying it from the “Chatbot Plugin” section.', 'doobert-chatbot'); ?>
                            </em></td>
                    </tr>
                    <tr>
                        <td>
                            <div class="button button-primary verify_token"><?php echo esc_html__('Verify', 'doobert-chatbot'); ?></div>
                        </td>
                    </tr>
                </table>
                <p style="color:red" class="doobert_error"></p>
                <p style="color:green;" class="token_correct"></p>
            </div>
<?php
        }
    }
}
add_action('init', 'doobert_scrape_doober_init');

if (!function_exists('doobert_scrape_doober_init')) {

    function doobert_scrape_doober_init()
    {
        if (is_admin() && isset($_GET['load_csv']) && isset($_GET['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'doobert-chatbot-settings')) {

            if (!wp_next_scheduled('custom_scrape_doobert_data')) {
                $is_sch = wp_schedule_single_event(time() + 60, 'custom_scrape_doobert_data');
                if (!$is_sch) {
                    doobert_scrape_doober_data_to_server(3);
                }
            }
            doobert_scrape_doober_data_to_server(1);
        }
    }
}

add_action('custom_scrape_doobert_data', 'doobert_scrape_doober_callback');

if (!function_exists('doobert_scrape_doober_callback')) {

    function doobert_scrape_doober_callback()
    {
        wp_clear_scheduled_hook('custom_scrape_doobert_data');
        doobert_scrape_doober_data_to_server(2);
    }
}

if (!function_exists('doobert_scrape_doober_data_to_server')) {

    function doobert_scrape_doober_data_to_server($type)
    {
        update_option('doobert_is_training_data_loaded', 1);
        $site_url = site_url();
        $url2 = $site_url . '/wp-admin/admin.php?page=doobert-chatbot-settings&loaded=1';
        if ($type == 1) {
            wp_redirect($url2);
            exit;
        }

        $doobert_api_token_value = get_option('doobert_api_token_value');
        if (!empty($doobert_api_token_value)) {
            $doobert_api_token_value = openssl_decrypt($doobert_api_token_value, 'aes-256-cbc', 'doobert', 0, 16);

            $posts = get_posts(array(
                'post_type' => array('post', 'page'),
                'post_status' => 'publish',
                'posts_per_page' => -1,
                'orderby' => 'date',
                'order' => 'DESC',
            ));
            $exlude_posts = get_option('_doobert_excluded_posts_from_api');
            $posts_data = array();
            foreach ($posts as $post) {
                if (!empty($exlude_posts) && is_array($exlude_posts) && in_array($post->ID, $exlude_posts)) {
                    continue;
                }
                $post_title = sanitize_text_field($post->post_title);
                $post_content = sanitize_text_field(wp_strip_all_tags(strip_shortcodes(doobert_remove_builders($post->post_content))));
                $post_type = $post->post_type;
                $post_url = rtrim(get_permalink($post->ID), '/');
                $site_url = site_url();
                $content_length = strlen($post_content);

                if ($content_length > 30000) {
                    $chunks = str_split($post_content, 30000);

                    foreach ($chunks as $index => $chunk) {
                        $posts_data[] = array(
                            'website' => $site_url,
                            'title' => $post_title,
                            'type' => $post_type,
                            'content' => $chunk,
                            'url' => $post_url,
                        );
                    }
                } else {
                    $posts_data[] = array(
                        'website' => $site_url,
                        'title' => $post_title,
                        'type' => $post_type,
                        'content' => $post_content,
                        'url' => $post_url,
                    );
                }
            }

            $csv_content = "\xEF\xBB\xBF"; // UTF-8 BOM for proper encoding
            $csv_content .= "website,title,type,content,url\n";
            foreach ($posts_data as $data) {
                $csv_content .= '"' . implode('","', array_map('doobert_esc_csv', $data)) . "\"\n";
            }

            $host = wp_parse_url($site_url, PHP_URL_HOST);
            $file_name = preg_replace('/[^a-zA-Z0-9]/', '', $host);
            $csv_file_path = DOOBERT_CHAPI_PLUGIN_DIR . $file_name . '.csv';

            if (!function_exists('WP_Filesystem')) {
                include_once ABSPATH . 'wp-admin/includes/file.php';
            }

            if (WP_Filesystem()) {

                global $wp_filesystem;

                if (!$wp_filesystem->exists($csv_file_path)) {
                    if (!$wp_filesystem->put_contents($csv_file_path, '')) {
                    }
                }

                if (!$wp_filesystem->put_contents($csv_file_path, $csv_content, FS_CHMOD_FILE)) {
                }
            }

            $local_file = $csv_file_path;
            $file_contents = $wp_filesystem->get_contents($local_file);
            $post_fields = array(
                'filename' => $file_name,
                'website' => $site_url
            );
            $boundary = wp_generate_password(24);
            $headers = array(
                'content-type' => 'multipart/form-data; boundary=' . $boundary,
                'Authorization' => 'Bearer ' . $doobert_api_token_value . ''
            );

            $payload = '';
            foreach ($post_fields as $name => $value) {
                $payload .= '--' . $boundary . "\r\n";
                $payload .= 'Content-Disposition: form-data; name="' . $name . '"' . "\r\n\r\n";
                $payload .= $value . "\r\n";
            }

            if ($local_file && file_exists($local_file)) {
                $payload .= '--' . $boundary . "\r\n";
                $payload .= 'Content-Disposition: form-data; name="csv_file"; filename="' . basename($local_file) . '"' . "\r\n";
                $payload .= 'Content-Type: ' . mime_content_type($local_file) . "\r\n\r\n";
                $payload .= $file_contents . "\r\n";
            }

            $payload .= '--' . $boundary . '--';

            $endpoint_url = 'https://app.doobert.com/api/v1/plugin/add-action';

            $response = wp_remote_post(
                $endpoint_url,
                array(
                    'headers' => $headers,
                    'body' => $payload,
                )
            );

            $response_body = wp_remote_retrieve_body($response);

            if ($type == 3) {
                wp_redirect($url2);
                exit;
            }
        }
    }
}

if (!function_exists('doobert_remove_builders')) {

    function doobert_remove_builders($content)
    {
        $builder_patterns = array(
            '/\[vc_[^\]]*\]/i',
            '/\[et_pb_[^\]]*\]/i',
            '/\[elementor[^\]]*\]/i',
            '/\[wp_[^\]]*\]/i',
            '/\[themify_[^\]]*\]/i',
            '/\[av_[^\]]*\]/i',
        );

        return preg_replace($builder_patterns, '', $content);
    }
}

if (!function_exists('doobert_esc_csv')) {

    function doobert_esc_csv($value)
    {
        return str_replace('"', '""', $value);
    }
}

add_action('wp_ajax_doobert_save_excluded_posts', 'doobert_save_excluded_posts');

if (!function_exists('doobert_save_excluded_posts')) {

    function doobert_save_excluded_posts()
    {
        check_ajax_referer('doobert-audit-nonce', 'email_nonce');
        $selectedValues = isset($_POST['selectedValues']) ? $_POST['selectedValues'] : array();
        $selectedValues = array_map('trim', $selectedValues);
        update_option('_doobert_excluded_posts_from_api', $selectedValues);
        die();
    }
}
add_action('wp_ajax_doobert_petcolove_setting_save', 'doobert_petcolove_setting_save');
if (!function_exists('doobert_petcolove_setting_save')) {

    function doobert_petcolove_setting_save()
    {
        check_ajax_referer('doobert-audit-nonce', 'email_nonce');
        $site_url = site_url();
        $petco_love = isset($_POST['petco_love']) ? $_POST['petco_love'] : 0;
        $array = array(
            'petco_love' => $petco_love
        );
        update_option('doobert-chatbot-petclove-settings', $array);
        echo '1';
        wp_die();
    }
}
add_action('wp_ajax_doobert_adopt_setting_save', 'doobert_adopt_setting_save');
if (!function_exists('doobert_adopt_setting_save')) {

    function doobert_adopt_setting_save()
    {
        check_ajax_referer('doobert-audit-nonce', 'email_nonce');
        $site_url = site_url();
        $shelter_zipcode = isset($_POST['shelter_zipcode']) ? sanitize_text_field($_POST['shelter_zipcode']) : '';
        $shelter_ids = isset($_POST['shelter_ids']) ? array_map('sanitize_text_field', $_POST['shelter_ids']) : array();
        if (!empty($shelter_ids)) {
            $shelter_ids = implode(',', $shelter_ids);
        } else {
            $shelter_ids = '';
        }
        $adopt_pet = isset($_POST['adopt_pet']) ? $_POST['adopt_pet'] : 0;
        $adopt_image = isset($_POST['adopt_image']) ? stripslashes(sanitize_text_field($_POST['adopt_image'])) : '';
        if (!empty($adopt_image))
            doobert_upload_default_image_wp($adopt_image);

        $array = array(
            'shelter_zipcode' => $shelter_zipcode,
            'shelter_ids' => $shelter_ids,
            'adopt_pet' => $adopt_pet,
            'adopt_image' => $adopt_image,
        );
        update_option('doobert-chatbot-adopt-settings', $array);
        echo '1';
        wp_die();
    }
}
add_action('wp_ajax_doobert_verify_token', 'doobert_verify_token');

add_action('wp_ajax_doobert_monthly_audit_email_save', 'doobert_monthly_audit_email_save');
if (!function_exists('doobert_monthly_audit_email_save')) {

    function doobert_monthly_audit_email_save()
    {
        check_ajax_referer('doobert-audit-nonce', 'email_nonce');
        $site_url = site_url();
        $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
        $doobert_api_token_value = get_option('doobert_api_token_value');
        if ($email && !empty($doobert_api_token_value)) {
            $doobert_api_token_value = openssl_decrypt($doobert_api_token_value, 'aes-256-cbc', 'doobert', 0, 16);
            $host = wp_parse_url($site_url, PHP_URL_HOST);
            $request_args = array(
                'method' => 'POST',
                'body' => array(
                    'website' => $site_url,
                    'email' => $email,
                ),
                'headers' => array(
                    'Authorization' => 'Bearer ' . $doobert_api_token_value,
                ),
            );
            update_option('doobert_audit_email', $email);
            $response = wp_remote_post('https://app.doobert.com/api/v1/plugin/update-email', $request_args);
            if (is_wp_error($response)) {
                $error_message = $response->get_error_message();
                echo 0;
            } else {
                echo 1;
            }
        }
        wp_die();
    }
}
add_action('wp_ajax_doobert_verify_token', 'doobert_verify_token');

if (!function_exists('doobert_verify_token')) {

    function doobert_verify_token()
    {
        check_ajax_referer('verify_doobert_token_nonce', 'security');

        $token = isset($_POST['token']) ? sanitize_text_field($_POST['token']) : '';
        $plugin_version = doobert_get_plugin_version();
        $site_url = site_url();
        $request_args = array(
            'body' => array(
                'website' => $site_url,
                //                'chatbot_version' => $plugin_version
            ),
            'headers' => array(
                'Authorization' => 'Bearer ' . $token,
            ),
        );

        $response = wp_remote_post('https://app.doobert.com/api/v1/plugin/verify-token', $request_args);

        if (is_wp_error($response)) {
            echo 0;
        } else {
            $http_code = wp_remote_retrieve_response_code($response);
            if ($http_code === 200) {
                $result_array = json_decode(wp_remote_retrieve_body($response), true);
                if (isset($result_array['status']) && $result_array['status'] == 1) {
                    $expires_in = $result_array['organization_details']['expires_in'];
                    $access_token = $result_array['organization_details']['access_token'];
                    $currentTimestamp = time();
                    $newTimestamp = $currentTimestamp + $expires_in;
                    update_option('_doobert_token_time_stamp', $newTimestamp);
                    update_option('_doobert_token_value', $access_token);
                    update_option('doobert_validation_data', $response);
                    $encrypted_value = openssl_encrypt($token, 'aes-256-cbc', 'doobert', 0, 16);
                    update_option('doobert_api_token_value', $encrypted_value);
                    echo 1;
                }
            } else {
                echo 0;
            }
        }
        die();
    }
}



if (!function_exists('doobert_get_plugin_version')) {

    function doobert_get_plugin_version()
    {
        $plugin_slug = 'doobert-chatbot';
        $plugin_file = WP_PLUGIN_DIR . '/' . $plugin_slug . '/' . $plugin_slug . '.php';

        if (!file_exists($plugin_file)) {
            return '0.0';
        }
        if (!function_exists('get_plugin_data')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
            $plugin_data = get_plugin_data($plugin_file);
        }
        return isset($plugin_data['Version']) ? $plugin_data['Version'] : '0.0';
    }
}

if (!function_exists('doobert_upload_default_image_wp')) {
    function doobert_upload_default_image_wp($image_url, $save_file_name = null)
    {
        // Load WP Filesystem API
        if (! function_exists('wp_handle_sideload')) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }
        if (! function_exists('wp_get_image_editor')) {
            require_once ABSPATH . 'wp-admin/includes/image.php';
        }

        $upload_dir = wp_upload_dir();
        $upload_path = trailingslashit($upload_dir['basedir']) . 'chatbot_files/';

        // Create directory if it doesn't exist
        if (! file_exists($upload_path)) {
            wp_mkdir_p($upload_path);
        }

        // Get image extension and filename
        $path_parts = pathinfo($image_url);
        $extension = strtolower($path_parts['extension'] ?? 'jpg');
        $file_name = $save_file_name ?: $path_parts['basename'];
        $destination = $upload_path . $file_name;

        // Fetch the image from URL
        $image_data = wp_remote_get($image_url);
        if (is_wp_error($image_data) || wp_remote_retrieve_response_code($image_data) !== 200) {
            return false;
        }

        $body = wp_remote_retrieve_body($image_data);
        if (empty($body)) {
            return false;
        }

        // Save the image temporarily
        file_put_contents($destination, $body);

        // Resize image to 150x150
        $editor = wp_get_image_editor($destination);
        if (is_wp_error($editor)) {
            return false;
        }

        $editor->resize(150, 150, true); // Crop to exact size
        $saved = $editor->save($destination);

        return is_wp_error($saved) ? false : $destination;
    }
}
