<?php
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/EmptyPHP.php to edit this template
 */

function doobert_load_all_languages_for_user($doobert_api_token_value)
{

    $url = 'https://app.doobert.com/api/v1/plugin/check-subscription';
    $headers = array(
        'Authorization' => 'Bearer ' . $doobert_api_token_value . '',
    );

    $body = array(
        'website' => site_url(),
    );

    $args = array(
        'headers' => $headers,
        'body' => $body,
    );

    $response = wp_remote_post($url, $args);
    $output = array();
    if (is_wp_error($response)) {
        return $output;
    } else {
        $response = wp_remote_retrieve_body($response);
        return json_decode($response);
    }
}

add_action('wp_ajax_doobert_add_new_translation_data', 'doobert_add_new_translation_data');

if (!function_exists('doobert_add_new_translation_data')) {

    function doobert_add_new_translation_data()
    {

        check_ajax_referer('verify_doobert_translaton_nonce', 'security');
        $translation_code = isset($_POST['translation_code']) ? stripslashes(sanitize_text_field($_POST['translation_code'])) : '';
        if (!empty($translation_code)) {

            $site_url = site_url();
            $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 (!file_exists($csv_file_path)) {
                echo wp_json_encode(array('status' => '0', 'message' => 'Please Upload csv file to continue'));
                die();
            }



            $placeholder_translation = isset($_POST['placeholder_translation']) ? stripslashes(sanitize_text_field($_POST['placeholder_translation'])) : '';
            $default_message_translation = isset($_POST['default_message_translation']) ? stripslashes(sanitize_text_field($_POST['default_message_translation'])) : '';
            $title_translation = isset($_POST['title_translation']) ? stripslashes(sanitize_text_field($_POST['title_translation'])) : '';
            $default_options_translation = isset($_POST['default_options_translation']) ? stripslashes(sanitize_text_field($_POST['default_options_translation'])) : '';
            $translations = array(
                'title_translation' => $title_translation,
                'placeholder_translation' => $placeholder_translation,
                'default_message_translation' => $default_message_translation,
                'default_options_translation' => $default_options_translation,
            );
            $status = 'enable';
            $translations = serialize($translations);

            global $wpdb;
            $table_name = $wpdb->prefix . 'doobert_translations_data';

            $existing_language = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT language FROM {$wpdb->prefix}doobert_translations_data WHERE language = %s",
                    $translation_code
                )
            );

            if (!empty($existing_language)) {
                echo wp_json_encode(array('status' => '0', 'message' => 'Language already exits'));
                die();
            }

            $result = doobert_multi_language_upload_csv_file($csv_file_path, $site_url, $file_name, $translation_code);
            if (!$result->status) {
                $msg = $result->error;
                if (isset($result->message) && !empty($result->message)) {
                    $msg = $result->message;
                }
                echo wp_json_encode(array('status' => '0', 'message' => $msg));
                die();
            }

            $data = array(
                'language' => $translation_code,
                'translations' => $translations,
                'status' => $status,
                'code' => $translation_code
            );
            $data_format = array('%s', '%s', '%s', '%s');
            $wpdb->insert($table_name, $data, $data_format);
            echo wp_json_encode(array('status' => '1', 'message' => 'Langauge saved successfully.'));
            die();
        } else {
            echo wp_json_encode(array('status' => '0', 'message' => 'Please select language'));
        }
        die();
    }
}
if (!function_exists('doobert_multi_language_upload_csv_file')) {

    function doobert_multi_language_upload_csv_file($csv_file_path, $site_url, $file_name, $translation_code)
    {
        $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);
            if (!function_exists('WP_Filesystem')) {
                include_once ABSPATH . 'wp-admin/includes/file.php';
            }
            if (WP_Filesystem()) {
                global $wp_filesystem;
            }
            $local_file = $csv_file_path;
            $file_contents = $wp_filesystem->get_contents($local_file);
            $post_fields = array(
                'filename' => $file_name,
                'website' => $site_url,
                'language' => $translation_code
            );
            $boundary = wp_generate_password(24);
            $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/upload-language-csv';
            $headers = array(
                'content-type' => 'multipart/form-data; boundary=' . $boundary,
                'Authorization' => 'Bearer ' . $doobert_api_token_value . ''
            );
            $response = wp_remote_post(
                $endpoint_url,
                array(
                    'headers' => $headers,
                    'body' => $payload,
                )
            );
            $response_body = wp_remote_retrieve_body($response);
            $response_body = json_decode($response_body);

            return $response_body;
        } else {
            $response = array(
                'status' => false,
                'error' => 'Some error occured while uploading file'
            );
            $obj = wp_json_encode(wp_json_encode($response));
            return $obj;
        }
    }
}


add_action('wp_ajax_doobert_update_translation_data', 'doobert_update_translation_data');

if (!function_exists('doobert_update_translation_data')) {

    function doobert_update_translation_data()
    {
        check_ajax_referer('verify_doobert_translaton_nonce', 'security');
        $id_to_update = isset($_POST['id_to_update']) ? sanitize_text_field($_POST['id_to_update']) : '';
        $status = isset($_POST['status']) ? sanitize_text_field($_POST['status']) : 'enable';
        $title_translation = isset($_POST['title_translation']) ? stripslashes(sanitize_text_field($_POST['title_translation'])) : '';
        $placeholder_translation = isset($_POST['placeholder_translation']) ? stripslashes(sanitize_text_field($_POST['placeholder_translation'])) : '';
        $default_message_translation = isset($_POST['default_message_translation']) ? stripslashes(sanitize_text_field($_POST['default_message_translation'])) : '';
        $default_options_translation = isset($_POST['default_options_translation']) ? stripslashes(sanitize_text_field($_POST['default_options_translation'])) : '';
        if ($id_to_update > 0) {
            global $wpdb;
            $table_name = $wpdb->prefix . 'doobert_translations_data';

            $translations = array(
                'title_translation' => $title_translation,
                'placeholder_translation' => $placeholder_translation,
                'default_message_translation' => $default_message_translation,
                'default_options_translation' => $default_options_translation,
            );
            $translations = serialize($translations);
            $data = array(
                'translations' => $translations,
                'status' => $status
            );
            $where = array('id' => $id_to_update);
            $data_format = array('%s', '%s');
            $where_format = array('%d');
            $wpdb->update($table_name, $data, $where, $data_format, $where_format);
            echo wp_json_encode(array('status' => '1', 'message' => 'Data Updated'));
        } else {
            echo wp_json_encode(array('status' => '0', 'message' => 'Some error occure'));
        }
        die();
    }
}

add_action('wp_ajax_doobert_load_all_languages_flages', 'doobert_load_all_languages_flages');
add_action('wp_ajax_nopriv_doobert_load_all_languages_flages', 'doobert_load_all_languages_flages');
if (!function_exists('doobert_load_all_languages_flages')) {

    function doobert_load_all_languages_flages()
    {
        check_ajax_referer('verify_doobert_token_nonce', 'security');
        $doobert_api_token_value = get_option('doobert_api_token_value');
        $html = '';
        $default = '';
        ob_start();
?>
        <div class="chat_flage_to_show">
            <img class="language_flage" src="<?php echo esc_attr(DOOBERT_CHAPI_URL) . 'assets/flags/usa.png'; ?>" />
            <span class="langauge_dropdown"><img class="chat_flage_to_show_arrow" src="<?php echo esc_attr(DOOBERT_CHAPI_URL) . 'assets/arrow_down.png'; ?>" /></span>
        </div>
        <?php
        $default = ob_get_clean();
        $inside = 0;
        $flages_html = '';
        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);
            $is_true = 0;
            if (!empty($languages_array) && isset($languages_array->status)) {
                $is_true = (int) $languages_array->status;
            }
            if ($is_true == 1) {
                global $wpdb;
                $table_name = $wpdb->prefix . 'doobert_translations_data';
                $total_allowed_languages = isset($languages_array->allowed_languages) ? $languages_array->allowed_languages : 1;
                $uploaded_languages = isset($languages_array->uploaded_languages) ? $languages_array->uploaded_languages : '';
                $allowed_languages = (array) $languages_array->available_languages;
                $languages_array = array();
                $languages_array = $uploaded_languages;
                ob_start();
                if (!empty($languages_array)) {
                    foreach ($languages_array as $language) {

                        $existing_language = $wpdb->get_var(
                            $wpdb->prepare(
                                "SELECT status FROM {$wpdb->prefix}doobert_translations_data WHERE language = %s",
                                $language
                            )
                        );

                        if ($existing_language == 'enable') {
                            $inside = 1;
                            $name_of_lng = $allowed_languages[$language]->name;
                            $icon = $allowed_languages[$language]->icon;
        ?>
                            <div class="single_language <?php echo esc_attr($language); ?>" data-language="<?php echo esc_attr($language); ?>">
                                <div class="single_langauge_one">
                                    <img class="language_flage language_flage_dropdown" src="<?php echo esc_attr($icon); ?>" />
                                    <span><?php echo esc_attr($name_of_lng); ?></span>
                                </div>
                                <div class="single_langauge_two"> <span class="langauge_checked">&#10003;</span></div>
                            </div>
<?php
                        }
                    }
                }
                $flages_html .= ob_get_clean();
                if ($inside == 1) {
                    $default .= '<div class="langauge_dropdown_selection hide_it">
                                        <div class="single_language english_usa choosen_langauge" data-language="english">
                                            <div class="single_langauge_one"> 
                                                <img class="language_flage language_flage_dropdown" src="' . esc_attr(DOOBERT_CHAPI_URL) . 'assets/flags/usa.png' . '" />
                                                <span>English</span>
                                            </div>
                                            <div class="single_langauge_two"> 
                                                <span class="langauge_checked">&#10003;</span>
                                            </div>
                                        </div>';
                    $default .= $flages_html;
                    $default .= '</div>';
                    $html = $default;
                }
            }
        }
        echo wp_json_encode(array('html' => $html, 'status' => $is_true));
        die();
    }
}

add_action('wp_ajax_doobert_delete_pdf_file', 'doobert_delete_pdf_file');
if (!function_exists('doobert_delete_pdf_file')) {

    function doobert_delete_pdf_file()
    {
        // Security check
        check_ajax_referer('verify_doobert_translaton_nonce', 'security');
        if (empty($_POST['pdf_id'])) {
            wp_send_json_error('Invalid PDF ID.');
        }
        $pdf_id = intval($_POST['pdf_id']);
        $deleted = wp_delete_attachment($pdf_id, true); // true = force delete
        if ($deleted) {
            wp_send_json_success();
        } else {
            wp_send_json_error('Could not delete PDF.');
        }
    }
}
add_action('wp_ajax_doobert_upload_pdf_file', 'doobert_upload_pdf_file');
if (!function_exists('doobert_upload_pdf_file')) {

    function doobert_upload_pdf_file()
    {
        // Verify nonce for security
        check_ajax_referer('verify_doobert_translaton_nonce', 'security');
        // Sanitize inputs
        $languages_string = !empty($_POST['languages']) ? sanitize_text_field($_POST['languages']) : '';
        $filename = sanitize_text_field($_POST['filename']);
        $website = site_url();
        $file_data = $_FILES['file'];
        // Handle file upload
        $uploaded_file = wp_handle_upload($file_data, array('test_form' => false));
        if (isset($uploaded_file['error'])) {
            echo 0;
            exit;
        }
        $file_type = wp_check_filetype(basename($uploaded_file['file']), null);
        $attachment = array(
            'guid'           => $uploaded_file['url'],
            'post_mime_type' => $file_type['type'],
            'post_title'     => $filename ? $filename : preg_replace('/\.[^.]+$/', '', basename($uploaded_file['file'])),
            'post_content'   => '',
            'post_status'    => 'inherit'
        );
        // Insert into DB
        $attach_id = wp_insert_attachment($attachment, $uploaded_file['file']);

        // Save unique column (custom meta field)
        update_post_meta($attach_id, '_doobert_filename_pdf', $filename);


        // Prepare languages array
        $languages = !empty($languages_string) ? array_map('trim', explode(',', $languages_string)) : array();
        // API details
        $request_url = 'https://app.doobert.com/api/v1/plugin/upload-pdf';
        $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);
        }
        // Prepare cURL request
        $ch = curl_init();
        $postfields = array(
            'filename' => $filename,
            'website'  => $website,
            'pdf'      => new CURLFile($uploaded_file['file'], 'application/pdf', basename($uploaded_file['file']))
        );
        // Add languages
        foreach ($languages as $language) {
            $postfields['language[]'] = $language;
        }
        curl_setopt_array($ch, array(
            CURLOPT_URL => $request_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => array(
                'Authorization: Bearer ' . $doobert_api_token_value
            ),
            CURLOPT_POSTFIELDS => $postfields
        ));
        // Execute cURL
        $response = curl_exec($ch);
        curl_close($ch);
        // Decode JSON response
        $response = json_decode($response, true);
        // echo '<pre>';
        // print_r($response);
        // exit;
        // Return status
        if ($response['status']) {
            echo 1;
        } else {
            echo 0;
        }
        exit;
    }
}
