<?php
if (!defined('ABSPATH')) exit;

// 1. Add Admin Menu
add_action('admin_menu', 'qc_voice_to_speech_stt_add_menu', 99 );
function qc_voice_to_speech_stt_add_menu() {

    add_submenu_page(
        'edit.php?post_type=wp_voicemsg_record',
        __( 'Voice Transcription', 'voice-widgets' ),
        __( 'Voice Transcription', 'voice-widgets' ),
        'manage_options',
        'qcld-voice-stt',
        'qc_voice_to_speech_stt_admin_page'
    );
}

// 2. Enqueue Assets
add_action('admin_enqueue_scripts', 'qc_voice_to_speech_stt_enqueue_assets');
function qc_voice_to_speech_stt_enqueue_assets($hook) {
    // var_dump( $hook );
    // wp_die();
    if ($hook !== 'wp_voicemsg_record_page_qcld-voice-stt') return;
    wp_enqueue_script('qc_voice_to_speech_stt-script', plugins_url('assets/js/transcribe-script.js', __FILE__), array('jquery'), '1.0', true);
    wp_enqueue_style('qc_voice_to_speech_stt-style', plugins_url('assets/css/transcribe-style.css', __FILE__));
    wp_localize_script('qc_voice_to_speech_stt-script', 'qc_voice_to_speech_stt_ajax', array('ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('qc_voice_to_speech_stt_nonce')));
}

// 3. Admin Page HTML
function qc_voice_to_speech_stt_admin_page() {
    // Codes follow ISO-639-1 (e.g., 'en', 'es', 'fr').
    $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'
    ];
    ?>
    <div class="wrap qc_voice_to_speech_stt-plugin-wrapper">
        <h1>🎙️ <?php esc_html_e( 'OpenAI Voice Transcriber', 'voice-widgets' ); ?></h1>
        <div id="qc_voice_to_speech_stt-container">
            <div class="qc_voice_to_speech_stt-card">
                    <h3><?php esc_html_e( 'Upload or Record', 'voice-widgets' ); ?></h3>
                    <p><b><?php esc_html_e( 'Transcription service requires ', 'voice-widgets' ); ?> <a href="<?php echo esc_url(admin_url('edit.php?post_type=wp_voicemsg_record&page=wpvoice_speech_to_text')); ?>"><?php esc_html_e( 'OpenAI integration.', 'voice-widgets' ); ?></a> <?php esc_html_e( ' Add your API key in the setting and fund your OpenAI account.', 'voice-widgets' ); ?></b> </p>
                    <p><b><?php esc_html_e( 'In the Free version, only MP3 file type is supported for transcription. WAV, M4A, AAC, OGG, MP4 etc. are available with the Pro versions.', 'voice-widgets' ); ?></b></p>
                
                <div class="qc_voice_to_speech_stt-section">
                    
                    <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" />
                            <span class="or-divider"><?php esc_html_e( 'OR', 'voice-widgets' ); ?></span>
                            <div class="record-controls">
                                <button id="record-btn" class="button">🔴 <?php esc_html_e( 'Start Recording', 'voice-widgets' ); ?></button>
                                <span id="recording-timer" style="display:none; color:red;">00:00</span>
                            </div>
                        </div>

                        <div class="qc_voice_to_speech_stt-lan">
                            <label><strong><?php esc_html_e( 'Select Language:', 'voice-widgets' ); ?></strong></label>
                            <select id="qc_voice_to_speech_stt-lang">
                                <?php foreach ($languages as $code => $name) : ?>
                                    <option value="<?php echo $code; ?>"><?php echo $name; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
            
                    </div>
                    
                    <!-- NEW: Audio Preview Container -->
                    <div id="audio-preview-container" style="display:none; margin-top:15px;">
                        <p><strong><?php esc_html_e( 'Review Recording:', 'voice-widgets' ); ?></strong></p>
                        <audio id="audio-preview" controls style="width:100%;"></audio>
                        <div style="margin-top:10px;">
                            <button type="button" id="btn-reset-recording" class="button button-link-delete">🗑️ <?php esc_html_e( 'Reset & Re-record', 'voice-widgets' ); ?></button>
                        </div>
                    </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( '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-container">
                    <!-- Desktop Navigation -->
                    <ul class="qc_voice_to_speech_stt-list">
                        <li class="active" data-tab="qc_voice_to_speech_stt-1"><?php esc_html_e( 'YouTube Transcribe', 'voice-widgets' ); ?> <span class="qc_voice_pro"><?php esc_html_e( 'Pro Feature', 'voice-widgets' ); ?></span></li>
                        <li data-tab="qc_voice_to_speech_stt-2"><?php esc_html_e( 'Vimeo Transcribe', 'voice-widgets' ); ?> <span class="qc_voice_pro"><?php esc_html_e( 'Pro Feature', 'voice-widgets' ); ?></span></li>
                    </ul>

                    <!-- Content Sections -->
                    <div class="qc_voice_to_speech_stt-wrapper">
                        <!-- Tab 1 -->
                        <h3 class="qc_voice_to_speech_stt-header active" data-tab="qc_voice_to_speech_stt-1"><?php esc_html_e( 'YouTube Transcribe', 'voice-widgets' ); ?></h3>
                        <div id="qc_voice_to_speech_stt-1" class="qc_voice_to_speech_stt-content active">
                            <div class="qc_voice_to_speech_stt-section">
                                <label><strong><?php esc_html_e( 'YouTube Video ID', 'voice-widgets' ); ?></strong></label>
                                <input type="text" id="qcld_youtube_video_id" placeholder="<?php esc_html_e( 'Write YouTube Video ID', 'voice-widgets' ); ?>">
                                <p><?php esc_html_e( 'EX: https://www.youtube.com/watch?v=', 'voice-widgets' ); ?> <code>20eebO8zBYk</code></p>
                                <button id="qc_voice_stt_youtube_subtitle_generate" class="button button-primary" ><?php esc_html_e('Get Transcript', 'voice-widgets'); ?></button>
                            </div>
                        </div>

                        <!-- Tab 2 -->
                        <h3 class="qc_voice_to_speech_stt-header" data-tab="qc_voice_to_speech_stt-2"><?php esc_html_e( 'Vimeo Transcribe', 'voice-widgets' ); ?></h3>
                        <div id="qc_voice_to_speech_stt-2" class="qc_voice_to_speech_stt-content">
                            <div class="qc_voice_to_speech_stt-section">
                                <label><strong><?php esc_html_e( 'Vimeo Video ID', 'voice-widgets' ); ?></strong></label>
                                <input type="text" id="qcld_vimeo_video_id" placeholder="<?php esc_html_e( 'Write Vimeo Video ID', 'voice-widgets' ); ?>">
                                <p><?php esc_html_e( 'https://vimeo.com/', 'voice-widgets' ); ?> <code>1147325999</code></p>
                                <button id="qc_voice_stt_vimeo_subtitle_generate" class="button button-primary" ><?php esc_html_e('Get Transcript', 'voice-widgets'); ?></button>
                            </div>
                        </div>

                    </div>
                </div>

                <div class="qc_voice_to_speech_stt-section">
                    <h3><?php esc_html_e( 'Rewrite', 'voice-widgets' ); ?></h3>
                    <div class="rewrite-prompt-content">
                    <label><strong><?php esc_html_e( 'Rewrite Prompt', 'voice-widgets' ); ?></strong> <?php esc_html_e( '( You can change prompt )', 'voice-widgets' ); ?></label>
                    <input type="text" id="qcld_rewrite_prompt" class="regular-text" value="<?php esc_html_e( 'Convert this raw transcript into a structured WordPress post without any HTML heading or other tags.', 'voice-widgets' ); ?>">
                    </div>
                    <button id="btn-rewrite" class="button button-secondary" disabled> <?php esc_html_e( 'AI Rewrite', 'voice-widgets' ); ?> <span class="qc_voice_pro"><?php esc_html_e( 'Pro Feature', 'voice-widgets' ); ?></span></button>
                    <div id="qc_voice_to_speech_stt-loader" class="spinner" style="float:none;"></div>
                </div>

                <div class="qc_voice_to_speech_stt-section result-area" style="position: relative; margin-top: 20px;">
                    <h3><?php esc_html_e( '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: 30px; right: 10px;">
                        📋 <?php esc_html_e( 'Copy Text', 'voice-widgets' ); ?>
                    </button>
                </div>
                <button id="create-post-btn" class="button button-hero" style="margin-top:10px;"><?php esc_html_e( 'Create WordPress Post', 'voice-widgets' ); ?> <span class="qc_voice_pro"><?php esc_html_e( 'Pro Feature', 'voice-widgets' ); ?></span></button>
            </div>
        </div>





            <div class="qcld-accordion-box">
                <?php $action = 'edit.php?post_type=wp_voicemsg_record&page=qcld-voice-stt';  ?>
        <form  action="<?php echo esc_attr(admin_url($action)); ?>" method="POST" enctype="multipart/form-data">
            <div class="wppt-settings-section text_to_speech_wrap">
                <h4><?php echo esc_html__('Audio to Text Transcription', 'voice-widgets' ); ?> <i style="color:indianred; font-weight:bold"> ( <?php echo esc_html__(' The Audio Transcription feature requires OpenAI Api integration. Please Enable OpenAI and add the API key', 'voice-widgets' ); ?> ) </i></h4>
                <table class="form-table">
                    <tr valign="top">
                        <th scope="row"><?php echo esc_html__('MP3 to Text Transcribe', 'voice-widgets' ); ?></th>
                        <td>
                            <input type="text" name="qcld_mp3_transcribe_form" class="regular-text" value="[qcld_mp3_transcribe_form]" />
                            <br>
                            <i><?php echo esc_html__('Paste this shortcode anywhere on a page where you want the MP3 To Text Transcribe button to show', 'voice-widgets' ); ?> </i>
                        </td>
                    </tr>
                    <tr valign="top">
                        <th scope="row"><?php echo esc_html__('Transcribe', 'voice-widgets' ); ?></th>
                        <td>
                            <input type="text" name="qcld_mp3_transcribe_btn_text" class="regular-text" value="<?php echo (get_option('qcld_mp3_transcribe_btn_text') ? get_option('qcld_mp3_transcribe_btn_text') : esc_html('Transcribe')); ?>" />
                            <i><?php echo esc_html__('You can change the text "Transcribe" button text from here', 'voice-widgets' ); ?></i>
                        </td>
                    </tr>
                    <tr valign="top">
                        <th scope="row"><?php echo esc_html__('Final Post Result', 'voice-widgets' ); ?></th>
                        <td>
                            <input type="text" name="qcld_mp3_final_post_text" class="regular-text" value="<?php echo (get_option('qcld_mp3_final_post_text') ? get_option('qcld_mp3_final_post_text') : esc_html('Final Post Result')); ?>" />
                            <i><?php echo esc_html__('You can change the text "Final Post Result" button text from here', 'voice-widgets' ); ?></i>
                        </td>
                    </tr>
                    <tr valign="top">
                        <th scope="row"><?php echo esc_html__('Max File Size', 'voice-widgets' ); ?></th>
                        <td>
                            <input type="number" name="qcld_mp3_transcribe_max_file_size" value="<?php echo (get_option('qcld_mp3_transcribe_max_file_size') ? get_option('qcld_mp3_transcribe_max_file_size') : 20); ?>" /><?php echo esc_html__(' ( MB ) ', 'voice-widgets' ); ?>
                                <i><?php echo esc_html__('You can change the Max File Size', 'voice-widgets' ); ?></i>
                        </td>
                    </tr>
                    <tr valign="top">
                        <th scope="row">
                            
                            <?php submit_button(); ?>
                            <?php wp_nonce_field('voice-speech-to-text'); ?>
                        </th>
                        <td>
                            
                        </td>
                    </tr>

                </table>
            </div>
        </form>
            </div>
    </div>
    <?php
}


// Hook for Transcription
add_action('wp_ajax_qc_voice_to_speech_stt_transcribe_only', 'qc_voice_to_speech_stt_handle_transcription');
function qc_voice_to_speech_stt_handle_transcription() {
    check_ajax_referer('qc_voice_to_speech_stt_nonce', 'nonce');
    
    $api_key    = get_option('qc_voice_to_speech_stt_openai_api_key');
    $language   = isset($_POST['language']) ? sanitize_text_field($_POST['language']) :'en';
    $file       = $_FILES['audio_file'];

    if(empty($api_key)){
        wp_send_json_error('The Audio Transcription feature requires OpenAI Api integration. Please Enable OpenAI and add the API key.');
    }

    // Call OpenAI Whisper with language parameter
    $url = 'https://api.openai.com/v1/audio/transcriptions';
    $headers = ['Authorization: Bearer ' . $api_key];
    $data = [
        'file' => new CURLFile($file['tmp_name'], $file['type'], $file['name']),
        'model' => 'whisper-1',
        'response_format' => 'verbose_json',
        'language' => $language // Whisper 2025 supports 99+ languages
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = json_decode(curl_exec($ch), true);
    curl_close($ch);

    if (isset($response['segments'])) {
        wp_send_json_success($response['segments']);
    } else {
        wp_send_json_error('Transcription failed.');
    }
}

