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


function qc_wpvoicemessage_stt_voice_api_ajax(){

    check_ajax_referer( 'stt-nonce', 'security' );

    $projectId  = get_option('qc_voice_to_speech_stt_project_id');
    $fileName   = $_FILES["audio_data"]["tmp_name"];
    $language   = ( get_option('qc_voice_to_speech_stt_lang_code') != '' ? get_option('qc_voice_to_speech_stt_lang_code') : 'en-US' );

    if ( empty( $_FILES['audio_data'] ) ) {
        wp_send_json_error( 'No file uploaded.' );
    }

    $file = $_FILES['audio_data'];

    if ( $file ) {
        $speech_stt_type  = get_option('qc_voice_to_speech_stt_type');
        if(isset($speech_stt_type) && $speech_stt_type == 'google' ){
            $transcription = qc_voice_stt_transcribe_audio( $file );
        }else{
            $transcription = qc_voice_stt_openai_transcribe_audio( $file );
        }

        if ( $transcription ) {
            wp_send_json_success( array( 'message' => $transcription ) );
        } else {
            wp_send_json_error( 'Transcription failed.' );
        }
    } else {
        wp_send_json_error( $file['error'] );
    }


}

add_action('wp_ajax_qc_wpvoicemessage_stt_voice_api_ajax', 'qc_wpvoicemessage_stt_voice_api_ajax' );
add_action('wp_ajax_nopriv_qc_wpvoicemessage_stt_voice_api_ajax', 'qc_wpvoicemessage_stt_voice_api_ajax' );

add_action( 'wp_ajax_qc_voice_stt_handle_upload', 'qc_voice_stt_handle_upload_callback' );
add_action( 'wp_ajax_nopriv_qc_voice_stt_handle_upload', 'qc_voice_stt_handle_upload_callback' );
function qc_voice_stt_handle_upload_callback() {
    check_ajax_referer( 'stt-nonce', 'security' );

    if ( empty( $_FILES['audio_file'] ) ) {
        wp_send_json_error( 'No file uploaded.' );
    }

    $file = $_FILES['audio_file'];

    if ( $file ) {
        $transcription = qc_voice_stt_openai_transcribe_audio( $file );
        
        if ( $transcription ) {
            wp_send_json_success( array( 'transcription' => $transcription ) );
        } else {
            wp_send_json_error( 'Transcription failed.' );
        }
    } else {
        wp_send_json_error( $move_file['error'] );
    }
    wp_die();

}

function qc_voice_stt_openai_transcribe_audio( $file ) {
    $api_key = get_option('qc_voice_to_speech_stt_openai_api_key');
    $language   = ( get_option('qc_voice_to_speech_stt_lang_code') != '' ? get_option('qc_voice_to_speech_stt_lang_code') : 'en-US' );
    $openai_lang = substr($language, 0, 2);

    if( isset($api_key) && empty($api_key) ){
        return "Please set your OpenAI Api key";
    }

    $model_name = 'whisper-1'; // Required model parameter

    // Use cURL for better multipart/form-data support with OpenAI
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/audio/transcriptions');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 300); // 5-minute timeout for large files

    $headers = array(
        'Authorization: Bearer ' . $api_key,
        'Content-Type: multipart/form-data'
    );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    // Build the request body with the file and the model
    $post_fields = array(
        'file'  => new CURLFile($file['tmp_name'], $file['type'], $file['name']),
        'model' => $model_name, // Fix: Explicitly send the model name
        'response_format' => 'verbose_json',
        'language' => $openai_lang,
        //'prompt'   => 'This is a nice conversation, separeate text according to each user specific voice. Please write it in own language.',
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);

    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code !== 200) {
        return ('API Error (' . $http_code . '): ' . $response);
    }

    $result = json_decode($response);

   // var_dump( $result );
   // wp_die();

    $result_data = isset($result->segments) ? $result->segments : '';

    return $result_data;
}