<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

require 'db.php'; // Include the database connection
require 'vendor/autoload.php'; // Ensure you have Guzzle installed

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

//fetch recently saved video from database
$pdo = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);

// $selectVideoFromDB = "SELECT video_id, youtube_url FROM tbl_video ORDER BY video_id DESC LIMIT 1 ";
$selectVideoFromDB = "SELECT video_id, youtube_url FROM tbl_videos ORDER BY video_id DESC LIMIT 1";
$stmt2 = $pdo->prepare($selectVideoFromDB);
$stmt2->execute();
$video = $stmt2->fetch(PDO::FETCH_ASSOC);

$videoId = $video['video_id'];
$youtubeUrlFetched = $video['youtube_url'];

// Function to extract YouTube Video ID from URL
function extractYouTubeID($url) {
    parse_str(parse_url($url, PHP_URL_QUERY), $query);
    return $query['v'] ?? '';
}

// Modified transcribeAudio function to handle URL downloads
function newTranscribeAudio(){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $assemblyKey = '8b2e22acc4704d8e8127d8bc360e2072';

    global $pdo;

    $fetchAudioLink = "SELECT server_audio_link, audio_link, video_id FROM tbl_videos ORDER BY video_id DESC LIMIT 1";
    $audio_stmt2 = $pdo->prepare($fetchAudioLink);
    $audio_stmt2->execute();
    $audioLinkers = $audio_stmt2->fetch(PDO::FETCH_ASSOC);

    $audio_link_fetched = $audioLinkers['server_audio_link'];
    $the_video_id_fetched = $audioLinkers['video_id'];
    $remote_audio_link = $audioLinkers['audio_link'];

    $full_audio_pathway = 'https://adhdlearnersapp.dextersolutionsltd.com/'. $audio_link_fetched;

    // AssemblyAI transcript endpoint (where we submit the file)
    $transcript_endpoint = "https://api.assemblyai.com/v2/transcript";

    // Request parameters 
    // $data = array(
    //     "audio_url" => $full_audio_pathway // audio file yetu
    // );
    //pass the remote link now
    // $remote_texters = "Remote URL is: ";
    // $final_remote_link = json_encode($remote_audio_link, JSON_UNESCAPED_SLASHES);
    // $data_debugging = array($remote_texters, $final_remote_link);
    // echo json_encode($data_debugging, JSON_FORCE_OBJECT);
    $data = array(
        "audio_url" => $full_audio_pathway // audio file yetu
    );

    // HTTP request headers
    $headers = array(
        "authorization: 8b2e22acc4704d8e8127d8bc360e2072",
        "content-type: application/json"
    );

    // submit for transcription via HTTP request
    $curl = curl_init($transcript_endpoint);

    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($curl);

    $response = json_decode($response, true);

    curl_close($curl);

    # polling for transcription completion
    $transcript_id = $response['id'];
    $polling_endpoint = "https://api.assemblyai.com/v2/transcript/" . $transcript_id;

    while (true) {
        $polling_response = curl_init($polling_endpoint);

        curl_setopt($polling_response, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($polling_response, CURLOPT_RETURNTRANSFER, true);

        $transcription_result = json_decode(curl_exec($polling_response), true);

        if ($transcription_result['status'] === "completed") {
            //lets debug here
            // $remote_texters = "Transcription Text : ";
            // //$final_remote_link = json_encode($remote_audio_link, JSON_UNESCAPED_SLASHES);
            // $trans_text = $transcription_result['text'];
            // $data_debugging = array($remote_texters, $trans_text);
            // echo json_encode($data_debugging, JSON_FORCE_OBJECT);

            //echo $transcription_result['text'];
            return $transcription_result['text'];
            break;
        } else if ($transcription_result['status'] === "error") {
            throw new Exception("Transcription failed: " . $transcription_result['error']);
        } else {
            sleep(3);
        }
    }

}

function SpicyLaika2() {
    global $youtubeUrlFetched;
    global $videoId;
    $nyuma = extractYouTubeID($youtubeUrlFetched);
    $final_url = 'https://youtube-mp3-audio-video-downloader.p.rapidapi.com/download-mp3/'.$nyuma;
    
    // Create folder path
    $folder_path = "audios/";
    
    // Create the directory if it doesn't exist
    if (!file_exists($folder_path)) {
        mkdir($folder_path, 0755, true);
    }
    
    // Generate a more unique filename using the YouTube ID
    $filename = $folder_path . "audio_" . $nyuma . ".mp3";
    
    $ch = curl_init($final_url);
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER => [
            "x-rapidapi-host: youtube-mp3-audio-video-downloader.p.rapidapi.com",
            "x-rapidapi-key: 63073389demshc2855675fcc3bb7p131e20jsn3c474ad5e1a1"
        ],
        CURLOPT_RETURNTRANSFER => true
    ]);
    
    $result = curl_exec($ch);
    
    if ($result === false) {
        // Handle curl error
        return ["error" => curl_error($ch)];
    }
    
    // Save the file and check if it was successful
    if (file_put_contents($filename, $result) === false) {
        return ["error" => "Failed to save file"];
    }
    
    curl_close($ch);

    // $remote_texters = "Spicy Laika is: ";
    // //$final_remote_link = json_encode($remote_audio_link, JSON_UNESCAPED_SLASHES);
    // $rev_ai_response = json_decode($filename);
    // $data_debugging = array($remote_texters, $rev_ai_response);
    // echo json_encode($data_debugging, JSON_FORCE_OBJECT);

    //naeka file path kwa server
    global $pdo;
    $upt_stmt = $pdo->prepare("UPDATE tbl_videos SET server_audio_link = ? WHERE video_id = ?");
    $upt_stmt->execute([$filename, $videoId]);
    
    return ["success" => true, "file_path" => $filename];
}


// Lets try to use Cohere for our summary
function summarizeText($text) {
    $client = new Client();
    $apiKey = 'jo1Ihz9lxKrGyIvvUaRJMCPRO0IAhWiFYO59B6ft';

    $response = $client->request('POST', 'https://api.cohere.ai/v1/summarize', [
        'headers' => [
            'Authorization' => 'Bearer ' . $apiKey,
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'text' => $text,
            'length' => 'medium', // Options: short, medium, long
            'format' => 'paragraph'
        ]
    ]);

    return json_decode($response->getBody(), true)['summary'] ?? '';
}

// Step 4: Save to MySQL database
function saveToDatabase($videoFetchedID, $videoUrl, $transcript, $summary) {
    global $pdo;
    $stmt = $pdo->prepare("INSERT INTO video_transcriptions (video_id, video_url, transcript, summary) VALUES (?, ?, ?, ?)");
    return $stmt->execute([$videoFetchedID, $videoUrl, $transcript, $summary]);
}


// Main execution
$videoID = $videoId;


//Tuanze by converting the youtube video to MP3
// $mp3TrueUrl = convertYTMP3($youtubeUrlFetched);
// $mp3TrueUrl = convertYTMP3();
// $mp3TrueUrl = AnotherConverter();
// $mp3TrueUrl = toMP3Audio();
$mp3TrueUrl = SpicyLaika2();
// $mp3TrueUrl = RevAI_transcribe();

// var_dump($mp3Url);
if ($mp3TrueUrl) {
    // $transcript = transcribeAudio($mp3TrueUrl);
    global $youtubeUrlFetched;
    global $videoId;
    
    //alafu tumake transcript ya io audio
    $transcript = newTranscribeAudio();
    
    //kumalizia ni ku create summary ya audio
    $summary = summarizeText($transcript);

    if (saveToDatabase($videoId, $youtubeUrlFetched, $transcript, $summary)) {
        echo "Transcription and Summary Saved Successfully.";
    } else {
        echo "Failed to save data.";
    }
} else {
    echo "Failed to fetch MP3.";
}
?>