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

if (!function_exists('doobert_create_new_token')) {

    function doobert_create_new_token($site_url)
    {
        $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);
            $request_args = array(
                'body' => array(
                    'website' => $site_url,
                ),
                'headers' => array(
                    'Authorization' => 'Bearer ' . $doobert_api_token_value,
                ),
            );
            $response = wp_remote_post('https://app.doobert.com/api/v1/plugin/get-access-token', $request_args);
            if (is_wp_error($response)) {
                return '';
            } else {
                $result_array = json_decode(wp_remote_retrieve_body($response), true);
                if (isset($result_array['status']) && $result_array['status'] == 1) {
                    $access_token_details = $result_array['access_token_details'];
                    $expires_in = $access_token_details['expires_in'];
                    $access_token = $access_token_details['access_token'];
                    $currentTimestamp = time();
                    $newTimestamp = $currentTimestamp + $expires_in;
                    update_option('_doobert_token_time_stamp', $newTimestamp);
                    update_option('_doobert_token_value', $access_token);
                    return $access_token;
                }
            }
        }
    }
}
add_action('wp_ajax_get_petcolove_adopt', 'get_petcolove_adopt');
add_action('wp_ajax_nopriv_get_petcolove_adopt', 'get_petcolove_adopt');

function get_petcolove_adopt()
{
    $settings = get_option('doobert-chatbot-petclove-settings');
    $adopts = get_option('doobert-chatbot-adopt-settings');

    $settings['adopt_pet']=$adopts['adopt_pet'];
    wp_send_json($settings);
}
add_action('wp_ajax_doobert_openai_request', 'doobert_openai_request');
add_action('wp_ajax_nopriv_doobert_openai_request', 'doobert_openai_request');
add_action('wp_ajax_doobert_petcolove', 'doobert_petcolove');
add_action('wp_ajax_nopriv_doobert_petcolove', 'doobert_petcolove');
add_action('wp_ajax_doobert_adoptpet', 'doobert_adoptpet');
add_action('wp_ajax_nopriv_doobert_adoptpet', 'doobert_adoptpet');
if (!function_exists('get_coordinates')) {
    function get_coordinates($address)
    {
        if (empty($address)) {
            return null;
        }
        $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);
            $body = ['address' => $address];
            $url = DOOBERT_API_BASE_URL . 'petcolove_location';
            $response = wp_remote_post($url, [
                'headers' => [
                    'Authorization' => 'Bearer ' . $doobert_api_token_value,
                    'Content-Type'  => 'application/x-www-form-urlencoded',
                ],
                'body' => $body,
                'timeout' => 10,
            ]);
            return wp_remote_retrieve_body($response);
        } else {
            return wp_json_encode([
                'status'  => 2,
                'message' => 'No token found.',
                'type'    => '',
                'flag'    => '',
                'data'    => '',
                'images' => '',
            ]);
        }
        return wp_json_encode([
            'status'  => 2,
            'message' => lost_pet_message('MESSAGE_4'),
            'type'    => '',
            'flag'    => '',
            'data'    => '',
            'images' => '',
        ]);
    }
}
if (!function_exists('upload_petcolove_images')) {
    function upload_petcolove_images()
    {
        if (empty($_FILES['images'])) {
            return ['error' => 'No files uploaded.'];
        }
        $uploadedImages = [];
        $upload_dir = plugin_dir_path(__FILE__) . 'assets/petcolove/';
        $upload_url = plugin_dir_url(__FILE__) . 'assets/petcolove/';
        if (!file_exists($upload_dir)) {
            wp_mkdir_p($upload_dir);
            chmod($upload_dir, 0777);
        }
        $upload_overrides = ['test_form' => false];
        foreach ($_FILES['images']['name'] as $key => $name) {
            $file_size = $_FILES['images']['size'][$key];
            if ($file_size > 4 * 1024 * 1024) {
                return ['error' => 'File size exceeds 4MB.'];
            }
            $allowed_types = ['image/jpeg', 'image/png', 'image/jpg'];
            $allowed_extensions = ['jpg', 'jpeg', 'png'];
            $file_type = $_FILES['images']['type'][$key];
            $file_name = $_FILES['images']['name'][$key];
            $file_ext  = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

            if (!in_array($file_type, $allowed_types) || !in_array($file_ext, $allowed_extensions)) {
                return ['error' => 'Only JPG, JPEG, and PNG files are allowed.'];
            }
            $file = [
                'name'     => sanitize_file_name($name),
                'type'     => $file_type,
                'tmp_name' => $_FILES['images']['tmp_name'][$key],
                'error'    => $_FILES['images']['error'][$key],
                'size'     => $file_size
            ];
            $upload = wp_handle_upload($file, $upload_overrides);
            if (!isset($upload['error'])) {
                $file_ext  = pathinfo($upload['file'], PATHINFO_EXTENSION);
                $file_name  = 'image_' . time() . '_' . $key . '.' . $file_ext;
                $new_path = $upload_dir . $file_name;
                $new_url = $upload_url . $file_name;
                if (rename($upload['file'], $new_path)) {
                    $uploadedImages[] = $new_url;
                }
            }
        }
        return $uploadedImages;
    }
}
function pm($message)
{
    echo "<pre>";
    print_r($message);
    wp_die();
}
// if (!function_exists('get_access_token')) {
//     function get_access_token() {
//         $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);
//             $url = DOOBERT_API_BASE_URL .'petcolove-access-token';
//             $response = wp_remote_get($url, [
//                 'headers' => [
//                     'Authorization' => 'Bearer ' . $doobert_api_token_value,
//                     'Content-Type'  => 'application/json',
//                 ],
//                 'timeout' => 10,
//             ]);
//             if ( is_wp_error( $response ) ) {
//                 return [ 'error' => $response->get_error_message() ];
//             }
//             return $body = wp_remote_retrieve_body($response);
//         } else {
//             return ['error' => 'No token found.'];
//         }
//     }
// }

if (!function_exists('doobert_adoptpet')) {
    function doobert_adoptpet()
    {
        check_ajax_referer('verify_doobert_token_nonce', 'security');
        $api_url = DOOBERT_API_BASE_URL . 'wp_adopt_pet';
        $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);
            parse_str($_POST['payload'], $filters);
            $prompt = $_POST['payload'];
            $species = $filters['specie_appdbrt'] ?? '';

            if (preg_match('/\b(cat|dog)\b/i', $prompt, $match)) {
                $species = ucfirst(strtolower($match[0]));
            }
            if (!empty($species) && !isset($filters['color_appdbrt'])) {
                $adopt_settings = get_option('doobert-chatbot-adopt-settings');
                $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']) : '';
                if ($shelter_zipcode == '' || $shelter_ids == '') {
                    $response_data = [
                        'status' => '4',
                        'data' => 'adopt_pet_response',
                        'message' => 'The Adopt a Pet configuration is missing. Please configure it and try again',
                        'last' => '',
                        'location' => '',
                        'type' => '',
                        'flag' => '',
                    ];
                    echo wp_json_encode($response_data);
                    wp_die();
                }
                $token = bin2hex(random_bytes(16));
                set_transient('token', $token, 3600);
                $request_args = array(
                    'body' => array(
                        'shelter_zipcode' => $shelter_zipcode,
                        'shelter_ids'     => $shelter_ids,
                        'adopt_image'     => $adopt_image,
                        'species'         => $species,
                        'token'           => $token, // pass token here instead
                    ),
                    'headers' => array(
                        'Authorization' => 'Bearer ' . $doobert_api_token_value,
                    ),
                    'timeout' => 10,
                );
                $response = wp_remote_post($api_url, $request_args);
                echo $response_body = wp_remote_retrieve_body($response);
                wp_die();
            } else if (isset($filters['color_appdbrt']) && $filters['color_appdbrt'] != '') {
                $request_args = array(
                    'body' => array(
                        'prompt' => $prompt,
                        'token'  => get_transient('token'),
                    ),
                    'headers' => array(
                        'Authorization' => 'Bearer ' . $doobert_api_token_value,
                    ),
                    'timeout' => 10,
                );
                $response = $response = wp_remote_post($api_url, $request_args);
                echo $response_body = wp_remote_retrieve_body($response);
                wp_die();
            } else {
                $response = wp_remote_post($api_url, [
                    'headers' => [
                        'Authorization' => 'Bearer ' . $doobert_api_token_value,
                        'Content-Type'  => 'application/json',
                    ],
                    'timeout' => 10,
                ]);
                echo $response_body = wp_remote_retrieve_body($response);
                wp_die();
            }
        } else {
            $response_data = [
                'status' => '1',
                'data' => 'adopt_pet_response',
                'message' => 'Unauthorized chatbot detected. Please register your chatbot from the WordPress dashboard.',
                'last' => '',
                'location' => '',
                'type' => '',
                'flag' => '',
            ];
            echo wp_json_encode($response_data);
            wp_die();
        }
    }
}
// if (!function_exists('report_pet_status')) {
//     function report_pet_status($api_data,$data)
//     {
//         $pet_colove_api_key= openssl_decrypt($api_data['pet_colove_api_key'], 'aes-256-cbc', 'doobert', 0, 16);
//         if (empty($api_data['pet_colove_base_url'])) {
//             return null;
//         }
//         $pet_colove_base_url = $api_data['pet_colove_base_url'];
//         $response = wp_remote_post($pet_colove_base_url, [
//             'headers' => [
//                 'x-api-key'    => $pet_colove_api_key,
//                 'Authorization' => 'Bearer ' . $api_data['access_token'],
//                 'Content-Type'  => 'application/json',
//             ],
//             'body'    => json_encode($data),
//             'timeout' => 10,
//         ]);
//         if (is_wp_error($response)) {
//             return ['error' => $response->get_error_message()];
//         }
//         //print_r($response);
//         return json_decode(wp_remote_retrieve_body($response), true);
//     }
// }
if (!function_exists('doobert_petcolove')) {
    function doobert_petcolove()
    {
        check_ajax_referer('verify_doobert_token_nonce', 'security');
        $has_no = isset($_POST['has_no']) ? sanitize_text_field($_POST['has_no']) : '';
        $flag = sanitize_text_field($_POST['flag']);
        $type = sanitize_text_field($_POST['type']);
        $payload = sanitize_text_field(trim($_POST['payload']));
        $response_input = sanitize_text_field($_POST['response_input']);
        $resultMessage = ($type == 'lost') ? 'lost_pet_message' : 'found_pet_message';
        $status = 1;
        $location = '';
        if ($flag == 'MESSAGE_1') {
            set_transient("{$type}{$response_input}MESSAGE_4",  null, 0);
        }
        if (preg_match('/\b(cat|dog)\b/i', $payload, $match) && preg_match('/\b(lost|lose|losing|found|find|missing)\b/i', $payload, $match2)) {
            $species = ucfirst(strtolower($match[0]));
            set_transient("{$type}{$response_input}MESSAGE_4", $species, 3600);
        }
        if (isset($_FILES['images'])) {
            global $wpdb;
            $uploadedImages = upload_petcolove_images();
            if (isset($uploadedImages['error'])) {
                $notfound_message = str_replace("zzzz", '<b>' . get_transient("{$type}{$response_input}MESSAGE_3") . '</b>', $resultMessage('MESSAGE_4'));
                echo wp_json_encode([
                    'status'  => 1,
                    'error'   => 2,
                    'type'    => $type,
                    'flag'    => 'MESSAGE_5',
                    'message' => $uploadedImages['error'] . '<br>' . $notfound_message
                ]);
                die();
            }
            if (!empty($uploadedImages)) {
                set_transient("{$type}{$response_input}images_path", $uploadedImages, 3600);
                $photos = $uploadedImages;
            }
        }
        $location = $_POST['petcolove_location'];
        if ($location != '' && $location != 'undefined') {

            if ($has_no == '') {
                $latitude = '';
                $longitude = '';
                $coordinates = json_decode(get_coordinates($payload));
                if (!empty($coordinates->location_detail)) {
                    $latitude = $coordinates->location_detail->latitude;
                    $longitude = $coordinates->location_detail->longitude;
                    set_transient("{$type}{$response_input}latitude", $coordinates->location_detail->latitude, 3600);
                    set_transient("{$type}{$response_input}longitude", $coordinates->location_detail->longitude, 3600);
                    set_transient("{$type}{$response_input}address", $payload, 3600);
                } else {
                    echo wp_json_encode([
                        'status'  => 1,
                        'message' => $resultMessage('MESSAGE_11'),
                        'type'    => $type,
                        'flag'    => 'MESSAGE_5',
                        'data'    => '',
                        'petcolove_location' => $location,
                    ]);
                    die();
                }
            } else {
                $latitude = get_transient("{$type}{$response_input}latitude");
                $longitude = get_transient("{$type}{$response_input}longitude");
            }
            $species_location = strtolower(get_transient("{$type}{$response_input}MESSAGE_4"));
            $save_address = strtolower(get_transient("{$type}{$response_input}address"));
            $location_url = ($type == 'lost') ? PETCOLOVE_LOCATION . "?latitude=$latitude&longitude=$longitude&searchType=found&searchRadius=50&address=" . urlencode($save_address) . "&start=" . date('m/d/Y') . "&view=map&showRecentOnly=false&species=$species_location" : PETCOLOVE_LOCATION . "?latitude=$latitude&longitude=$longitude&searchType=lost&searchRadius=50&address=" . urlencode($save_address) . "&view=map&showRecentOnly=false&species=$species_location";
            $message_string = ($type == 'lost') ? 'Pet Found Nearby' : 'Pet Lost Nearby';
            $response_data = [
                'error' => '0',
                'status' => '1',
                'petcolove_location' => '',
                'data' => '',
                'type' => '',
                'flag' => '',
                'message' =>  $resultMessage("MESSAGE_9") . '<br><a  href="' . $location_url . '" target="_blank" title="' . $message_string . '"><u ' . HYPER_LINK . '>' . $message_string . '</u></a>' . $resultMessage("MESSAGE_10")
            ];
            echo wp_json_encode($response_data);
            wp_die();
        }

        if ($flag == 'MESSAGE_5') {
            if (empty($_FILES['images']['name'][0])) {
                $coordinates = json_decode(get_coordinates($payload));
                if (!empty($coordinates->location_detail)) {
                    set_transient("{$type}{$response_input}latitude", $coordinates->location_detail->latitude, 3600);
                    set_transient("{$type}{$response_input}longitude", $coordinates->location_detail->longitude, 3600);
                    set_transient("{$type}{$response_input}address", $payload, 3600);
                } else {
                    echo wp_json_encode([
                        'status'  => 1,
                        'message' => $resultMessage('MESSAGE_11'),
                        'type'    => $type,
                        'flag'    => 'MESSAGE_5',
                        'data'    => '',
                        'petcolove_location' => '',
                    ]);
                    die();
                }
            }
            $species = strtolower(get_transient("{$type}{$response_input}MESSAGE_4"));
            $latitude = $coordinates->location_detail->latitude;
            $longitude = $coordinates->location_detail->longitude;
            $data = [
                "type" => $type,
                "species" => $species,
                "geopoint" => ["latitude" => $latitude, "longitude" => $longitude],
                "photos" => get_transient("{$type}{$response_input}images_path"),
                "specie_name" => get_transient("{$type}{$response_input}MESSAGE_3"),
            ];
            $petco_love_data = wp_report_pet_status($data);
            echo wp_json_encode($petco_love_data);
            die();
        }
        set_transient("{$type}{$response_input}$flag", $payload, 3600);
        $cached_message = get_transient("{$type}{$response_input}MESSAGE_3");
        $animal = get_transient("{$type}{$response_input}MESSAGE_4");
        if (($animal === 'Dog' || $animal === 'Cat') && (($flag === 'MESSAGE_3' && $type === 'lost') || ($flag === 'MESSAGE_2' && $type === 'found'))) {
            $flag = 'MESSAGE_4';
        }
        $nextCase = get_next_message_key($flag);
        $resultMessage = str_replace("zzzz",  '<b>' . $cached_message . '</b>', $resultMessage($flag));
        echo wp_json_encode([
            'status'  => $status,
            'message' => $resultMessage,
            'type'    => $type,
            'flag'    => $nextCase,
            'data'    => '',
            'images' => $uploadedImages
        ]);
        die();
    }
}
if (!function_exists('wp_report_pet_status')) {
    function wp_report_pet_status($data)
    {
        $api_url = DOOBERT_API_BASE_URL . 'wp_report_pet_status';
        $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);
            $request_args = array(
                'body'    => json_encode($data),
                'headers' => array(
                    'Authorization' => 'Bearer ' . $doobert_api_token_value,
                    'Content-Type'  => 'application/json',
                ),
                'timeout' => 10,
            );
            $response = wp_remote_post($api_url, $request_args);
            $response_petcolove = json_decode(wp_remote_retrieve_body($response), true);
            if (empty($response_petcolove)) {
                return $data = [
                    'status'  => 1,
                    'message' => lost_pet_message('MESSAGE_14'),
                    'type'    => '',
                    'flag'    => '',
                    'data'    => '',
                    'images' => '',
                ];
            }
            return $response_petcolove;
        } else {
            return wp_json_encode([
                'status'  => 1,
                'message' => 'No token found.',
                'type'    => '',
                'flag'    => '',
                'data'    => '',
                'images' => '',
            ]);
        }
        return wp_json_encode([
            'status'  => 1,
            'message' => lost_pet_message('MESSAGE_14'),
            'type'    => '',
            'flag'    => '',
            'data'    => '',
            'images' => '',
        ]);
    }
}
// if (!function_exists('get_config_data')) {
//     function get_config_data()
//     {
//         $api_url=DOOBERT_API_BASE_URL. 'get_config_data';
//         $response = wp_remote_post($api_url, [
//             'headers' => [                
//                 'Content-Type'  => 'application/json',
//             ],           
//             'timeout' => 10,
//         ]);
//         if (is_wp_error($response)) {
//             return ['error' => $response->get_error_message()];
//         }       
//         return json_decode(wp_remote_retrieve_body($response));
//     }
// }
if (!function_exists('get_next_message_key')) {
    function get_next_message_key($message)
    {
        return preg_replace_callback('/\d+$/', function ($matches) {
            return $matches[0] + 1; // Increment the number
        }, $message);
    }
}
if (!function_exists('lost_pet_message')) {
    function lost_pet_message($key)
    {
        $messages = [
            'MESSAGE_1' => "Sorry to hear that. Do you have a picture of your lost pet? <br><br> I can instantly search Petco Love Lost—a free tool that scans over 3,000 shelter databases, Nextdoor, Neighbors by Ring, and reports made directly by the community.",
            'MESSAGE_2' => "What is your pet's name?",
            'MESSAGE_3' => "Is zzzz a dog or a cat?",
            'MESSAGE_4' => "Can you tell me the location where zzzz was last seen? Please provide the complete address including city and state.",
            'MESSAGE_5' => "I've posted zzzz to the national Petco Love Lost database.",
            'MESSAGE_6' => "Here are the results of the photo-matching scanning for animals that might be a match:",
            'MESSAGE_7' => "and here are the results of nearby lost animals based on your address:",
            'MESSAGE_8' => "When you click these links they'll take you to Petco Love Lost and while you're there, be sure to complete your profile on Petco Love Lost so you can get notifications.",
            'MESSAGE_9' => "Here are the pets that have been found near your location:",
            'MESSAGE_10' => "<br>What else can I do to help you today? <br> Ask me anything!",
            'MESSAGE_11' => "Sorry, I couldn't find anything in the address you've entered. Can you provide the city and the state?",
            'MESSAGE_12' => "It looks like the photo you uploaded will not work for the photo matching search. Do you have a different photo you can upload?",
            'MESSAGE_13' => "Oops! The species you entered doesn't match any animal in our database.<br> Can you specify if it's a dog or a cat?",
            'MESSAGE_14' => "Hmm, something doesn’t look right. Please review your request or question and give it another go.",
            'MESSAGE_15' => "Looks like I'm having a server connection issue. Can you try again after a few seconds?"
        ];
        return $messages[$key] ?? '';
    }
}
if (!function_exists('found_pet_message')) {
    function found_pet_message($key)
    {
        $messages = [
            'MESSAGE_1' => "Awesome. Can you upload a picture so we can search Petco Love Lost for reported lost animals?",
            'MESSAGE_2' => "What is your pet's name?",
            'MESSAGE_3' => "Is the animal a dog or a cat?",
            'MESSAGE_4' => "Can you tell me the location where you found the pet? Please provide the complete address including city and state.",
            'MESSAGE_5' => "I've posted pet to the national Petco Love Lost database.",
            'MESSAGE_6' => "Here are the results of the photo-matching scanning for animals that might be a match:",
            'MESSAGE_7' => "and here are the results of nearby lost animals based on your address:",
            'MESSAGE_8' => "When you click these links they'll take you to Petco Love Lost and while you're there, be sure to complete your profile on Petco Love Lost so you can get notifications.",
            'MESSAGE_9' => "Here are the pets that have been reported lost near your location:",
            'MESSAGE_10' => "<br>What else can I do to help you today? <br> Ask me anything!",
            'MESSAGE_11' => "Sorry, I couldn't find anything in the address you've entered. Can you provide the city and the state?",
            'MESSAGE_12' => "It looks like the photo you uploaded will not work for the photo matching search. Do you have a different photo you can upload?",
            'MESSAGE_13' => "Oops! The species you entered doesn't match any animal in our database. Can you specify if it's a dog or a cat?",
            'MESSAGE_14' => "Hmm, something doesn’t look right. Please review your request or question and give it another go.",
            'MESSAGE_15' => "Looks like I'm having a server connection issue. Can you try again after a few seconds?"
        ];

        return $messages[$key] ?? '';
    }
}


if (!function_exists('doobert_openai_request')) {

    function doobert_openai_request()
    {
        check_ajax_referer('verify_doobert_token_nonce', 'security');
        $payload = sanitize_text_field($_POST['payload']);
        $language_selection = sanitize_text_field($_POST['language_selection']);
        $is_paid = sanitize_text_field($_POST['is_paid']);
        $plugin_version = sanitize_text_field($_POST['plugin_version']);
        $is_quick_response = sanitize_text_field($_POST['is_quick_response']);
        $site_url = site_url();
        $dbtr_time = get_option('_doobert_token_time_stamp');
        $token = get_option('_doobert_token_value');
        if (empty($token)) {
            $token = doobert_create_new_token($site_url);
        } else {
            if (time() >= $dbtr_time) {
                $token = doobert_create_new_token($site_url);
            }
        }
        $response = doobert_call_azure_chat_api($token, $payload, $site_url, $language_selection, $is_paid);

        $arrResult = json_decode($response, true);
        if (isset($arrResult['statusCode']) && $arrResult['statusCode'] == 401) {
            $token = doobert_create_new_token($site_url);
            $response = doobert_call_azure_chat_api($token, $payload, $site_url, $language_selection, $is_paid);
            $arrResult = json_decode($response, true);
        }

        $resultMessage = $arrResult["choices"][0]["message"]["content"];
        $is_last_is_question = 0;
        $status = 1;
        if (empty($resultMessage) || strpos($resultMessage, 'requested information is not') > 1) {
            $resultMessage = 'I’m sorry but I only have information from ' . get_bloginfo('name') . ' so I am unable to answer your question. Would you like me to get you to a human that can help?';
            $status = 2;
        } else {

            $pattern = "/\[doc(\d+)\]/";
            $resultMessage = preg_replace_callback($pattern, function ($matches) use (&$seen_docs) {
                $full_placeholder = $matches[0];
                $doc_id = $matches[1];
                if (isset($seen_docs[$doc_id])) {
                    return '';
                }
                $seen_docs[$doc_id] = true;
                return $full_placeholder;
            }, $resultMessage);
            $resultMessage = preg_replace('/:\s*-\s*|-/', '', $resultMessage);
            $resultMessage = preg_replace('/\s+([.,!?])/', '$1', $resultMessage);
            if (preg_match_all($pattern, $resultMessage, $matches)) {
                $result = array_combine($matches[0], $matches[1]);
                if (!empty($result)) {
                    $context = $arrResult["choices"][0]["message"]["context"]["messages"][0]["content"];
                    if (!empty($context)) {
                        $context = json_decode($context, true);
                        if (!empty($context) && isset($context['citations'])) {
                            $doc_array = $context['citations'];
                            $results_count = count($result);

                            $indexer = 0;
                            foreach ($result as $key => $id) {
                                $index = $id - 1;
                                $indexer = $indexer + 1;
                                $url = isset($doc_array[$index]['url']) ? $doc_array[$index]['url'] : '';
                                $title = isset($doc_array[$index]['title']) ? $doc_array[$index]['title'] : '';
                                if (!empty($url)) {
                                    //                                    $end_status = 1;
                                    if (substr($title, -1) === '?') {
                                        $is_last_is_question = 1;
                                    } else {
                                        $is_last_is_question = 0;
                                    }
                                    $is_dot = 0;
                                    if (strpos($resultMessage, $key . '.') > 0) {
                                        $is_dot = 1;
                                    }
                                    if ($indexer == $results_count || $is_dot == 1) {
                                        $link = '<a target="_blank" class="document_link" href="' . $url . '">' . $title . '</a>';
                                    } else {
                                        $link = '<a target="_blank" class="document_link" href="' . $url . '">' . $title . ', </a>';
                                    }
                                    $resultMessage = str_replace($key, $link, $resultMessage);
                                } else {
                                    $resultMessage = str_replace($key, '', $resultMessage);
                                }
                            }
                        }
                    }
                }
            }
        }

        if ($is_last_is_question == 1) {
            $resultMessage = substr($resultMessage, 0, -1);
        }
        global $wpdb;
        $table_name = $wpdb->prefix . 'doobert_chatbot_history';
        $datatime = gmdate('Y-m-d H:i:s');
        $meta_data = array(
            'version' => $plugin_version,
            'is_quick_response' => $is_quick_response
        );
        $meta_data_serialized = maybe_serialize($meta_data);
        $data = array(
            'question' => $payload,
            'answer' => $resultMessage,
            'datatime' => $datatime,
            'meta_data' => $meta_data_serialized
        );

        $format = array(
            '%s',
            '%s',
            '%s',
            '%s',
        );
        $wpdb->insert($table_name, $data, $format);

        echo wp_json_encode(array('status' => $status, 'message' => $resultMessage));
        die();
    }
}

if (!function_exists('doobert_call_azure_chat_api')) {

    function doobert_call_azure_chat_api($token, $payload, $site_url, $language_selection, $is_paid = 0)
    {

        $site_url = site_url();
        $site_url_http = str_replace("https://", "http://", $site_url);
        $site_url_https = str_replace("http://", "https://", $site_url);
        $payload = $payload;
        $indexer = '';
        $indexer = $language_selection . '-index';
        $language = $language_selection;
        if (empty($language_selection)) {
            $language = 'english';
            $indexer = $language . '-index';
        }
        $language_name = ucfirst($language);
        $title = 'title';
        $content = 'content';
        $filter = "website eq '$site_url_http' or website eq '$site_url_https' and (type eq 'post' or type eq 'page')";
        if ($is_paid == 1) {
            if ($language != 'english') {
                $title = 'title_' . $language;
                $content = 'content_' . $language;
            }
            $filter = "website eq '$site_url_http' or website eq '$site_url_https'";
        }
        $system_instructions = 'You are a customer service representative for ' . get_bloginfo('name') . '. Use ' . $language_name . ' language only. Use ' . $language_name . ' alphabet whenever possible. Your tone should be friendly and helpful. You should summarize as though you are speaking to a 12 year old person. You should always thank them for ' . get_bloginfo('name') . '. You should anticipate their next question and try and answer it at the same time. Your responses should be no more than 2 sentences in length. You should always ask them if you answered their question and if not, try again. Do not mention anywhere in your response about retrieved data or any documents, just say it is your knowledge. also please do not return words that are meaningless in term of reading. Do not mention your source document in response. Do not justify your answers. Do not give information not mentioned in the CONTEXT INFORMATION. if information not found in anywhere in CONTEXT INFORMATION reply message should include information not available.';

        $request_body = array(
            'dataSources' => array(
                array(
                    'type' => 'AzureCognitiveSearch',
                    'parameters' => array(
                        'endpoint' => 'https://chatbotsearch-service.search.windows.net',
                        'indexName' => $indexer,
                        'filter' => $filter,
                        'fieldsMapping' => array(
                            "titleField" => $title,
                            "urlField" => "url",
                            "filepathField" => "type",
                            "contentFields" => array(
                                $content
                            ),
                            "contentFieldsSeparator" => "\n"
                        )
                    ),
                ),
            ),
            'messages' => array(
                array('role' => 'system', 'content' => $system_instructions),
                array('role' => 'user', 'content' => $payload),
            ),
            'temperature' => 0,
            'top_p' => 1,
            'frequency_penalty' => 0,
            'presence_penalty' => 0,
            'max_tokens' => 0,
        );

        $request_args = array(
            'body' => wp_json_encode($request_body),
            'headers' => array(
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $token,
            ),
        );

        $response = wp_remote_post(
            'https://doobertchatinstance.openai.azure.com/openai/deployments/gpt-35-turbo/extensions/chat/completions?api-version=2023-08-01-preview',
            $request_args
        );
        $response_body = wp_remote_retrieve_body($response);
        return $response_body;
    }
}



add_action('wp_ajax_doobert_load_new_language_for_data', 'doobert_load_new_language_for_data');
add_action('wp_ajax_nopriv_doobert_load_new_language_for_data', 'doobert_load_new_language_for_data');

if (!function_exists('doobert_load_new_language_for_data')) {

    function doobert_load_new_language_for_data()
    {
        check_ajax_referer('verify_doobert_token_nonce', 'security');
        $langauge_selected = sanitize_text_field($_POST['langauge_selected']);
        if ($langauge_selected == 'english') {
            $settings_gen = get_option('doobert-chatbot-custom-settings');
            $title_translation = '';
            $placeholder_translation = '';
            $default_message_translation = '';
            $default_options_html = '';
            $title_translation = isset($settings_gen['header_title']) ? sanitize_text_field(stripslashes($settings_gen['header_title'])) : 'Hello!';
            $placeholder_translation = isset($settings_gen['send_message_placeholder']) ? sanitize_text_field(stripslashes($settings_gen['send_message_placeholder'])) : '';
            $default_message_translation = isset($settings_gen['def_msg_to_show']) ? sanitize_text_field(stripslashes($settings_gen['def_msg_to_show'])) : '';
            $default_options_translation = isset($settings_gen['def_options_to_show']) ? sanitize_text_field(stripslashes($settings_gen['def_options_to_show'])) : '';
            if (!empty($default_options_translation)) {
                $default_options_translation = explode(';', $default_options_translation);
                if (!empty($default_options_translation)) {
                    foreach ($default_options_translation as $data) {
                        $default_options_html .= '<div class="pre_button">' . $data . '</div>';
                    }
                }
            }
            echo wp_json_encode(array('status' => 1, 'title' => $title_translation, 'placeholder' => $placeholder_translation, 'default_msg' => $default_message_translation, 'default_options' => $default_options_html));
            die();
        } else {
            global $wpdb;
            $table_name = $wpdb->prefix . 'doobert_translations_data';

            $language_data = $wpdb->get_col(
                $wpdb->prepare(
                    "SELECT translations FROM {$wpdb->prefix}doobert_translations_data WHERE language = %s",
                    $language_selected
                )
            );

            $title_translation = '';
            $placeholder_translation = '';
            $default_message_translation = '';
            $default_options_html = '';
            if (!empty($language_data)) {
                $language_data = $language_data[0];
                $language_data = unserialize($language_data);
                $title_translation = isset($language_data['title_translation']) ? $language_data['title_translation'] : '';
                $placeholder_translation = isset($language_data['placeholder_translation']) ? $language_data['placeholder_translation'] : '';
                $default_message_translation = isset($language_data['default_message_translation']) ? $language_data['default_message_translation'] : '';
                $default_options_translation = isset($language_data['default_options_translation']) ? $language_data['default_options_translation'] : '';
                if (!empty($default_options_translation)) {
                    if ($langauge_selected == 'chinese') {
                        $default_options_translation = explode('；', $default_options_translation);
                    } else {
                        $default_options_translation = explode(';', $default_options_translation);
                    }

                    if (!empty($default_options_translation)) {
                        foreach ($default_options_translation as $data) {
                            $default_options_html .= '<div class="pre_button">' . $data . '</div>';
                        }
                    }
                }
            } else {
            }
            echo wp_json_encode(array('status' => 1, 'title' => $title_translation, 'placeholder' => $placeholder_translation, 'default_msg' => $default_message_translation, 'default_options' => $default_options_html));
            die();
        }
    }
}
