<?php
defined('ABSPATH') or die("You can't access this file directly.");

class Qcld_voice_audio_sttforms{

    public function __construct(){

        add_shortcode( 'qcld_stt_form', [ $this, 'qc_voice_stt_audio_shortcode' ] );

        add_shortcode( 'qcld_mp3_transcribe_form', [ $this, 'qc_voice_stt_audio_fiile_input_shortcode' ] );

    }

    public function qc_voice_stt_audio_shortcode( $atts = [] ) {

        $atts = shortcode_atts( [
            'id'    => '',
            'title' => '',
            'name'  => ''
        ], $atts );

        global $post;

        wp_enqueue_style( 'qc_audio_font_awesomess', QC_VOICEWIDGET_ASSETS_URL . 'css/font-awesome.min.css', false );
        wp_enqueue_style( 'qc-stt-frontend-css',  QC_VOICEWIDGET_ASSETS_URL . 'css/stt_frontend.css', false );

        wp_enqueue_script( 'qc-voice-widgets-recorders-js', QC_VOICEWIDGET_ASSETS_URL .  'audio/WebAudioRecorder.min.js', ['jquery'], QC_VOICEWIDGET_VERSION, true );
        wp_enqueue_style( 'dashicons' );

        $speech_stt_type  = get_option('qc_voice_to_speech_stt_type');
        if(isset($speech_stt_type) && $speech_stt_type == 'google' ){

            wp_enqueue_script( 'qc-voice-stt-frontend-js', QC_VOICEWIDGET_ASSETS_URL .  'js/stt_frontend.js', ['jquery', 'qc-voice-widgets-recorders-js'], QC_VOICEWIDGET_VERSION, true );

        }else{

           // wp_enqueue_script( 'qc-voice-stt-transcribe-js', 'https://cdn.jsdelivr.net/npm/@transcribe/shout@1.0.7/index.min.js', ['jquery', 'qc-voice-widgets-recorders-js'], QC_VOICEWIDGET_VERSION, true );
            wp_enqueue_script( 'qc-voice-stt-frontend-js', QC_VOICEWIDGET_ASSETS_URL .  'js/stt_web_frontend.js', ['jquery', 'qc-voice-widgets-recorders-js'], QC_VOICEWIDGET_VERSION, true );
        }

        $qc_voice_stt_audio_lan_speak_now              =  get_option('qc_voice_stt_audio_lan_speak_now') ? get_option('qc_voice_stt_audio_lan_speak_now'): 'Speak now';
        $qc_voice_stt_audio_lan_stop_save              =  get_option('qc_voice_stt_audio_lan_stop_save')?get_option('qc_voice_stt_audio_lan_stop_save'): 'Stop & Save';
        $qc_voice_stt_audio_lan_canvas_not_available   =  get_option('qc_voice_stt_audio_lan_canvas_not_available')?get_option('qc_voice_stt_audio_lan_canvas_not_available'):'Canvas not available.';
        $qc_voice_stt_audio_lan_please_wait            =  get_option('qc_voice_stt_audio_lan_please_wait') ? get_option('qc_voice_stt_audio_lan_please_wait'): 'Please wait while proccsing your request.';
        $convert_recorded_audio                        = 'wav';
        $qcld_mp3_transcribe_max_file_size             = get_option('qcld_mp3_transcribe_max_file_size') ? get_option('qcld_mp3_transcribe_max_file_size') : 20;

        $qc_voice_stt_obj = array(
            'ajax_url'                                      => admin_url('admin-ajax.php'),
            'nonce'                                         => wp_create_nonce( 'stt-nonce' ),
            'capture_duration'                              => (get_option('stt_sound_duration') && get_option('stt_sound_duration') != '' ? MINUTE_IN_SECONDS * get_option('stt_sound_duration') : MINUTE_IN_SECONDS * 10 ),
            'post_id'                                       => isset( $post->ID ) ? $post->ID : 0,
            'qc_voice_stt_audio_lan_speak_now'              => $qc_voice_stt_audio_lan_speak_now,
            'qc_voice_stt_audio_lan_stop_save'              => $qc_voice_stt_audio_lan_stop_save,
            'qc_voice_stt_audio_lan_canvas_not_available'   => $qc_voice_stt_audio_lan_canvas_not_available,
            'qc_voice_stt_audio_lan_please_wait'            => $qc_voice_stt_audio_lan_please_wait,
            'QC_VOICEWIDGET_ASSETS_URL'                     => QC_VOICEWIDGET_ASSETS_URL.'audio/',
            'convert_recorded_audio'                        => $convert_recorded_audio,
            'max_file_size'                                 => intval($qcld_mp3_transcribe_max_file_size),
            'lang_code'                                     => get_option('qc_voice_to_speech_stt_lang_code') ? get_option('qc_voice_to_speech_stt_lang_code') : 'en-US',
        );

        wp_localize_script('qc-voice-stt-frontend-js', 'qc_voice_stt_obj', $qc_voice_stt_obj);

        ob_start();

        $qc_voice_stt_audio_lan_record_audio   =  get_option('qc_voice_stt_audio_lan_record_audio');

        ?>
        <div class="qc_voice_stt_audio_wrapper">
            <div class="qc_voice_stt_audio_container">
                <div class="qc_voice_stt_audio_upload_main" id="qc_voice_stt_main">
                    <a class="qc_voice_stt_audio_record_button" id="qc_voice_stt_audio_record" href="#">
                        <span class="dashicons dashicons-microphone"></span> <?php esc_html_e( $qc_voice_stt_audio_lan_record_audio, 'voice-widgets' ); ?>
                    </a>
                </div>

                <div class="qc_voice_stt_audio_recorder" id="qc_voice_stt_audio_recorder" style="display:none"></div>

                <div class="qc_voice_stt_audio_display" id="qc_voice_stt_audio_display"  style="display:none">
                    <span title="Remove and back to main upload screen." class="qc_voice_stt_remove_btn fa fa-trash"></span>
                </div>
            </div>
        </div>
        <?php
        return ob_get_clean();

    }

    public function qc_voice_stt_audio_fiile_input_shortcode( $atts = [] ) {

        $atts = shortcode_atts( [
            'id'    => '',
            'title' => '',
            'name'  => ''
        ], $atts );

        global $post;

        wp_enqueue_style( 'qc_audio_font_awesomess', QC_VOICEWIDGET_ASSETS_URL . 'css/font-awesome.min.css', false );
        wp_enqueue_style( 'qc-stt-frontend-css',  QC_VOICEWIDGET_ASSETS_URL . 'css/stt_frontend.css', false );

        wp_enqueue_script( 'qc-voice-widgets-recorders-js', QC_VOICEWIDGET_ASSETS_URL .  'audio/WebAudioRecorder.min.js', ['jquery'], QC_VOICEWIDGET_VERSION, true );
        wp_enqueue_style( 'dashicons' );

        $speech_stt_type  = get_option('qc_voice_to_speech_stt_type');
        if(isset($speech_stt_type) && $speech_stt_type == 'google' ){

            wp_enqueue_script( 'qc-voice-stt-frontend-js', QC_VOICEWIDGET_ASSETS_URL .  'js/stt_frontend.js', ['jquery', 'qc-voice-widgets-recorders-js'], QC_VOICEWIDGET_VERSION, true );

        }else{

            wp_enqueue_script( 'qc-voice-stt-frontend-js', QC_VOICEWIDGET_ASSETS_URL .  'js/stt_web_frontend.js', ['jquery', 'qc-voice-widgets-recorders-js'], QC_VOICEWIDGET_VERSION, true );
        }

        $qc_voice_stt_audio_lan_speak_now              =  get_option('qc_voice_stt_audio_lan_speak_now') ? get_option('qc_voice_stt_audio_lan_speak_now'): 'Speak now';
        $qc_voice_stt_audio_lan_stop_save              =  get_option('qc_voice_stt_audio_lan_stop_save')?get_option('qc_voice_stt_audio_lan_stop_save'): 'Stop & Save';
        $qc_voice_stt_audio_lan_canvas_not_available   =  get_option('qc_voice_stt_audio_lan_canvas_not_available')?get_option('qc_voice_stt_audio_lan_canvas_not_available'):'Canvas not available.';
        $qc_voice_stt_audio_lan_please_wait            =  get_option('qc_voice_stt_audio_lan_please_wait') ? get_option('qc_voice_stt_audio_lan_please_wait'): 'Please wait while proccsing your request.';
        $convert_recorded_audio                        = 'wav';
        $qcld_mp3_transcribe_max_file_size             = get_option('qcld_mp3_transcribe_max_file_size') ? get_option('qcld_mp3_transcribe_max_file_size') : 20;

        $qc_voice_stt_obj = array(
            'ajax_url'                                      => admin_url('admin-ajax.php'),
            'nonce'                                         => wp_create_nonce( 'stt-nonce' ),
            'capture_duration'                              => (get_option('stt_sound_duration') && get_option('stt_sound_duration') != '' ? MINUTE_IN_SECONDS * get_option('stt_sound_duration') : MINUTE_IN_SECONDS * 10 ),
            'post_id'                                       => isset( $post->ID ) ? $post->ID : 0,
            'qc_voice_stt_audio_lan_speak_now'              => $qc_voice_stt_audio_lan_speak_now,
            'qc_voice_stt_audio_lan_stop_save'              => $qc_voice_stt_audio_lan_stop_save,
            'qc_voice_stt_audio_lan_canvas_not_available'   => $qc_voice_stt_audio_lan_canvas_not_available,
            'qc_voice_stt_audio_lan_please_wait'            => $qc_voice_stt_audio_lan_please_wait,
            'QC_VOICEWIDGET_ASSETS_URL'                     => QC_VOICEWIDGET_ASSETS_URL.'audio/',
            'convert_recorded_audio'                        => $convert_recorded_audio,
            'max_file_size'                                 => intval($qcld_mp3_transcribe_max_file_size),
            'lang_code'                                     => get_option('qc_voice_to_speech_stt_lang_code') ? get_option('qc_voice_to_speech_stt_lang_code') : 'en-US',
        );

        wp_localize_script('qc-voice-stt-frontend-js', 'qc_voice_stt_obj', $qc_voice_stt_obj);

        $languages = [
            'en' => 'English', 'af' => 'Afrikaans', 'am' => 'Amharic', 'ar' => 'Arabic', 'as' => 'Assamese', 'az' => 'Azerbaijani',
            'be' => 'Belarusian', 'bg' => 'Bulgarian', 'bn' => 'Bengali', 'bo' => 'Tibetan', 'br' => 'Breton',
            'bs' => 'Bosnian', 'ca' => 'Catalan', 'cs' => 'Czech', 'cy' => 'Welsh', 'da' => 'Danish',
            'de' => 'German', 'el' => 'Greek',  'es' => 'Spanish', 'et' => 'Estonian',
            'eu' => 'Basque', 'fa' => 'Persian', 'fi' => 'Finnish', 'fo' => 'Faroese', 'fr' => 'French',
            'gl' => 'Galician', 'gu' => 'Gujarati', 'ha' => 'Hausa', 'he' => 'Hebrew', 'hi' => 'Hindi',
            'hr' => 'Croatian', 'hu' => 'Hungarian', 'hy' => 'Armenian', 'id' => 'Indonesian', 'is' => 'Icelandic',
            'it' => 'Italian', 'ja' => 'Japanese', 'jw' => 'Javanese', 'ka' => 'Georgian', 'kk' => 'Kazakh',
            'km' => 'Khmer', 'kn' => 'Kannada', 'ko' => 'Korean', 'la' => 'Latin', 'lb' => 'Luxembourgish',
            'ln' => 'Lingala', 'lo' => 'Lao', 'lt' => 'Lithuanian', 'lv' => 'Latvian', 'mg' => 'Malagasy',
            'mi' => 'Maori', 'mk' => 'Macedonian', 'ml' => 'Malayalam', 'mn' => 'Mongolian', 'mr' => 'Marathi',
            'ms' => 'Malay', 'mt' => 'Maltese', 'my' => 'Burmese', 'ne' => 'Nepali', 'nl' => 'Dutch',
            'nn' => 'Norwegian Nynorsk', 'no' => 'Norwegian', 'oc' => 'Occitan', 'pa' => 'Punjabi', 'pl' => 'Polish',
            'ps' => 'Pashto', 'pt' => 'Portuguese', 'ro' => 'Romanian', 'ru' => 'Russian', 'sa' => 'Sanskrit',
            'sd' => 'Sindhi', 'si' => 'Sinhala', 'sk' => 'Slovak', 'sl' => 'Slovenian', 'sn' => 'Shona',
            'so' => 'Somali', 'sq' => 'Albanian', 'sr' => 'Serbian', 'su' => 'Sundanese', 'sv' => 'Swedish',
            'sw' => 'Swahili', 'ta' => 'Tamil', 'te' => 'Telugu', 'tg' => 'Tajik', 'th' => 'Thai',
            'tk' => 'Turkmen', 'tl' => 'Tagalog', 'tr' => 'Turkish', 'tt' => 'Tatar', 'uk' => 'Ukrainian',
            'ur' => 'Urdu', 'uz' => 'Uzbek', 'vi' => 'Vietnamese', 'yi' => 'Yiddish', 'yo' => 'Yoruba',
            'zh' => 'Chinese'
        ];

        ob_start();


        $qcld_mp3_transcribe_btn_text   = get_option('qcld_mp3_transcribe_btn_text') ? get_option('qcld_mp3_transcribe_btn_text') : esc_html('Upload Audio file', 'voice-widgets');
        $qcld_mp3_transcribe_btn_icon   =  get_option('qcld_mp3_transcribe_btn_icon');

        ?>
        <div class="qc_voice_stt_audio_wrappers">
            <div class="qc_voice_stt_audio_container">
                <div class="qc_voice_stt_audio_upload_file_main" id="qc_voice_stt_file_main">
                    <div class="qc_voice_to_speech_stt-file-content">
                        <input type="file" name="stt_audio_upload_file" id="stt_audio_upload_file" class="stt_audio_upload_file" />
                       
                    </div>
        
                </div>
                    

                <div class="qc_voice_to_speech_stt-section qc_voice_to_speech_stt-transcribe-section">
                    <button id="btn-transcribe" class="button button-primary"> <?php esc_html_e( (get_option('qcld_mp3_transcribe_btn_text') ? get_option('qcld_mp3_transcribe_btn_text') : esc_html('Transcribe')), 'voice-widgets' ); ?></button>
                    <div id="qc_voice_to_speech_stt-loader" class="spinner" style="float:none;"></div>
                </div>

                <div class="qc_voice_to_speech_stt-result-wrap">
                    <div class="qc_voice_to_speech_stt-section result-area" style="position: relative; margin-top: 20px;">
                        <h3><?php esc_html_e( (get_option('qcld_mp3_final_post_text') ? get_option('qcld_mp3_final_post_text') : esc_html('Final Post Result')), 'voice-widgets' ); ?></h3>
                        <div id="qc_voice_to_speech_stt-status"></div>
                        <textarea id="qc_voice_to_speech_stt-result" placeholder="<?php esc_html_e( 'AI-generated post will appear here...', 'voice-widgets' ); ?>"></textarea>
                        
                        <!-- Copy Button: Hidden by default -->
                        <button id="btn-copy" class="button" style="display:none; position: absolute; top: 40px; right: 10px;">
                            📋 <?php esc_html_e( 'Copy Text', 'voice-widgets' ); ?>
                        </button>
                    </div>
                        <!-- Area 2: AI Rewritten Post (Hidden initially) -->
                    <div class="qc_voice_to_speech_stt-section" id="rewrite-container" style="display:none; margin-top:20px; position: relative;">
                        <h3><?php esc_html_e( 'AI Rewritten Post', 'voice-widgets' ); ?></h3>
                        
                        <textarea id="qc_voice_to_speech_stt-rewrite-result" placeholder="AI Post will appear here..."></textarea>
                        <button id="btn-copy-rewrite" class="button" style="position: absolute; top: 30px; right: 10px;">📋 <?php esc_html_e( 'Copy Text', 'voice-widgets' ); ?></button>
                      
                    </div>
                </div>
                
                <div class="qc_voice_stt-loading" style="display: none;">
                    <div class="spinner"></div>
                    <span><?php esc_html_e('Transcribing Audio...', 'voice-widgets'); ?></span>
                </div>
            </div>
        </div>
        <?php
        return ob_get_clean();

    }


}


new Qcld_voice_audio_sttforms();




function qc_voice_stt_create_folder( $gcdirectory ) {
    return @mkdir( $gcdirectory, 0777, true );
}

function qc_voice_stt_create_file( $filename ) {
    if ( ! @file_exists( $filename ) ) {
        if ( ! @is_writable( dirname( $filename ) ) ) {
            return false;
        }

        if ( ! @touch( $filename ) ) {
            return false;
        }
    } elseif ( ! @is_writable( $filename ) ) {
        return false;
    }

    $is_written = false;
    if ( ( $handle = @fopen( $filename, 'w' ) ) !== false ) {
        if ( @fwrite( $handle, '<?php //silence is golden' ) !== false ) {
            $is_written = true;
        }

        @fclose( $handle );
    }

    return $is_written;
}

function qc_voice_stt_extractgc() {
    $gcdirectory = QC_VOICEWIDGET_PLUGIN_DIRNAME;
    $filename    = 'voice-vendor-client.zip';
    $gcfilename  = QC_VOICEWIDGET_PLUGIN_DIRNAME . '/' . $filename;
    /* Open the Zip file */
    $zip         = new ZipArchive();
    $extractPath = 'path_to_extract';
    if ( $zip->open( $gcfilename ) != 'true' ) {
    }
    /* Extract Zip File */
    $zip->extractTo( $gcdirectory );
    $zip->close();
    @unlink( $gcfilename );

   // wp_safe_redirect( esc_url( site_url( $_SERVER['REQUEST_URI'] ) ) );
    //exit();

}



function qc_voice_stt_downloadgc() {

    check_ajax_referer( 'voice-widgets', 'security');
    
    $gcdirectory = QC_VOICEWIDGET_PLUGIN_DIRNAME;
    $download_url = 'https://github.com/qcld/voice-vendor-client/raw/main/voice-vendor-client.zip';
    $filename     = 'voice-vendor-client.zip';

    if ( ! is_dir( $gcdirectory ) ) {
        qc_voice_stt_create_folder( $gcdirectory );
    }
    if ( ! file_exists( $gcdirectory . '/index.php' ) ) {
        qc_voice_stt_create_file( $gcdirectory . '/index.php' );
    }

    if ( is_dir( $gcdirectory ) ) {

        $zipFile     = $gcdirectory . '/' . $filename; // Local Zip File Path
        $zipResource = fopen( $zipFile, 'w' );
        // Get The Zip File From Server
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_URL, $download_url );
        curl_setopt( $ch, CURLOPT_FAILONERROR, true );
        curl_setopt( $ch, CURLOPT_HEADER, 0 );
        curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
        curl_setopt( $ch, CURLOPT_BINARYTRANSFER, true );
        curl_setopt( $ch, CURLOPT_TIMEOUT, 10 );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
        curl_setopt( $ch, CURLOPT_FILE, $zipResource );
        $page = curl_exec( $ch );
        curl_close( $ch );

        qc_voice_stt_extractgc();

        $response = array(
            'status'  => 'success',
            'content' => 'Files Extracted successfully!',
        );
        echo wp_send_json( $response );
        wp_die();
    } 

}

add_action( 'wp_ajax_qcld_voice_stt_gc_client_download',  'qc_voice_stt_downloadgc' );
add_action( 'wp_ajax_nopriv_qcld_voice_stt_gc_client_download',  'qc_voice_stt_downloadgc' );
