<?php

namespace App\Http\Controllers;

use Session;
use App\Helper\Helper;
use Illuminate\Http\Request;
use App\Events\IncomingLead;
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;

class VoiceAiExtensionUserController extends Controller {

    function voiceAudio(Request $request)
    {
        try
        {
            if(isset($_GET['client_id']))
            {
                $clientId = $_GET['client_id'];
            }
            else
            {
                echo "invalid request";die;
            }

            $uniqueId = rand(1000,9999);

            $voice = "en-US ## en-US-Neural2-C ## FEMALE";//$request->voice_name_ddl;
            $voice_name_ddl = explode("##", $voice);

            $langCode = trim($voice_name_ddl[0]);
            $stand_wave = trim($voice_name_ddl[1]);
            $gender = trim($voice_name_ddl[2]);

            $client = new TextToSpeechClient(['credentials' => env('GOOGLE_JSON_KEY')]);

            $DB_DATABASE = env('DB_DATABASE');
            $DB_USERNAME = env('DB_USERNAME');
            $DB_PASSWORD = env('DB_PASSWORD');
            $DB_HOST     = env('DB_HOST');

            $conn = mysqli_connect($DB_HOST,$DB_USERNAME,$DB_PASSWORD,$DB_DATABASE);
            if (!$conn) {
                echo mysqli_connect_errno() . ":" . mysqli_connect_error();
                exit;
            }

            $sqlUser = mysqli_fetch_all(mysqli_query($conn,"SELECT first_name,last_name,extension,id FROM users  WHERE base_parent_id='".$clientId."' and is_deleted='0'"));

            foreach($sqlUser as $key =>$user)
            {
                $first_name = $user[0];
                $last_name  = $user[1];
                $extension  = $user[2];
                $id  = $user[3];



                $text = "Hello, You have reached ".$first_name." ".$last_name." Voice mail. Currently ".$first_name." is unavailable to take your call. Please leave your name, number and brief message after the beep and ".$first_name." will get back to you."; 


$sql = "SELECT id,extension FROM user_wise_voice_ai  WHERE user_id=".$id."";
$result = mysqli_query($conn,$sql);

// Associative array
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
//printf ("%s (%s)\n", $row["extension"], $row["id"]);
//die;

if(empty($row["extension"]))
{
                 $insert = "insert into user_wise_voice_ai set user_id='".$id."',extension='".$user[2]."',speech_text='".$text."',language='".$langCode."',voice_name='".$stand_wave."',file_name='-'";

                mysqli_query($conn,$insert);

}



                $input_text = (new SynthesisInput())->setSsml("<speak>".$text."</speak>");

                if($gender == 'FEMALE')
                {
                    $voice = (new VoiceSelectionParams())->setLanguageCode($langCode)->setName($stand_wave)->setSsmlGender(SsmlVoiceGender::FEMALE);
                }
                else
                {
                    $voice = (new VoiceSelectionParams())->setLanguageCode($langCode)->setName($stand_wave)->setSsmlGender(SsmlVoiceGender::MALE);
                }

                $effectsProfileId = "telephony-class-application";

                $audioConfig = (new AudioConfig())->setAudioEncoding(AudioEncoding::MP3)->setEffectsProfileId(array($effectsProfileId));
                $response = $client->synthesizeSpeech($input_text, $voice, $audioConfig);
                
                $audioContent = $response->getAudioContent();
                $file = $extension.".mp3";

                $filePath = '/var/www/html/branch/backend/public/upload/voice_ai_users/'.$file;

                if(file_exists($filePath))
                {
                    unlink($filePath);
                }

                file_put_contents($filePath, $audioContent);
                $client->close();

                $rootPath = '/var/www/html/branch/backend/public/upload/voice_ai_users/'.$file;
                $convertedFilename = '/var/www/html/branch/backend/public/upload/voice_ai_users/'.$extension.'.wav';
                $res  = shell_exec("sox $rootPath -r 8000 -c 1 $convertedFilename -q");

                $arrAstriskServers = mysqli_fetch_all(mysqli_query($conn,"SELECT * FROM asterisk_server"));
                $strModuleDirectory = null;

                if(!empty($arrAstriskServers)) {
                    foreach ($arrAstriskServers as $arrAsteriskServer) {
                        $strAsteriskPath = "root@" . $arrAsteriskServer[2] . ":" . env('ASTERISK_UPLOAD_PATH') . "audio/agent_voicemail_greetings/" . $strModuleDirectory . "/";
                        shell_exec("scp -P 10347 $convertedFilename $strAsteriskPath");
                    }
                }

                if(file_exists($filePath))
                {
                    unlink($filePath);
                }
            }
            return response()->json(['file' => $file]);
            $textToSpeechClient->close();
        }
        catch(Exception $e)
        {
            echo $e->getMessage();
        }
    }
}


