let mediaRecorder;
let audioChunks = [];
let audioBlob;

function change_radio(val, type){
	$("." + type).addClass('showHide');	
	$("#" + val).removeClass('showHide');
}

async function start_audio(startBtnId, stopBtnId, audioPlaybackId, audioDataId) {
    try {
        mediaRecorder = "";
        audioChunks = [];
        audioBlob = "";
    	audioChunks = [];
        const startBtn = document.getElementById(startBtnId);
        const stopBtn = document.getElementById(stopBtnId);
        const audioPlayback = document.getElementById(audioPlaybackId);
        const audioDataInput = document.getElementById(audioDataId);
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        mediaRecorder = new MediaRecorder(stream);

        mediaRecorder.start();
        startBtn.disabled = true;
        stopBtn.disabled = false;

        mediaRecorder.addEventListener('dataavailable', event => {
            audioChunks.push(event.data);
        });
    } catch (error) {
        console.error('Error accessing microphone:', error);
    }
}

function stop_audio(startBtnId, stopBtnId, audioPlaybackId, audioDataId) {
    $("#" + audioPlaybackId).removeClass('showHide');
    const startBtn = document.getElementById(startBtnId);
    const stopBtn = document.getElementById(stopBtnId);
    const audioPlayback = document.getElementById(audioPlaybackId);
    const audioDataInput = document.getElementById(audioDataId);
    
    mediaRecorder.stop();
    stopBtn.disabled = true;
    startBtn.disabled = false;

    mediaRecorder.addEventListener('stop', () => {
        const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
        const audioUrl = URL.createObjectURL(audioBlob);
        audioPlayback.src = audioUrl;

        // Convert audioBlob to a Base64 string for form submission
        const reader = new FileReader();
        reader.readAsDataURL(audioBlob);
        reader.onloadend = () => {
            audioDataInput.value = reader.result;
        };
    });
}

function upload_file_call_flow(audioFileId, audioMessageId){

    const fileInput = document.getElementById(audioFileId);
    const file = fileInput.files[0];
    const messageDiv = document.getElementById(audioMessageId);
    messageDiv.innerHTML = "";
    if (file) {

        const fileName = file.name;
        const fileExtension = fileName.split('.').pop().toLowerCase();
        
        // Check if the file extension is either .wav or .mp4
        if (fileExtension === 'wav' || fileExtension === 'mp4') {

        	// messageDiv.innerHTML = "<p class = 'badge badge-success'>Correct file format.</p>";
        }
        else{
            messageDiv.innerHTML = "<p class = 'badge badge-danger'>Invalid file format. Please upload a .wav or .mp4 file.</p>";
        }
    } else {
        messageDiv.innerHTML = "<p class = 'badge badge-danger'>Please select a file.</p>";
    }
}

function upload_file_validate(fileId, messageId, update_call_flow, file_hidden){
    const fileInput = document.getElementById(fileId);
    const file = fileInput.files[0];
    if(file === undefined){
        var chk = $("#"+file_hidden).val();
        if(chk !== ""){
            return 1;
        }
    }
    const messageDiv = document.getElementById(messageId);
    messageDiv.innerHTML = "";
    if (file) {

        const fileName = file.name;
        const fileExtension = fileName.split('.').pop().toLowerCase();
        
        // Check if the file extension is either .wav or .mp4
        if (fileExtension === 'wav' || fileExtension === 'mp4') {

            // messageDiv.innerHTML = "<p class = 'badge badge-success'>Correct file format.</p>";
            return 1;
        }
        else{
            messageDiv.innerHTML = "<p class = 'badge badge-danger'>Invalid file format. Please upload a .wav or .mp4 file.</p>";
            return 0;
        }
    } else {
        messageDiv.innerHTML = "<p class = 'badge badge-danger'>Please select a file.</p>";
        return 0;
    }
}

function record_file_validate(recordId, messId, update_call_flow, rec_hid){
    var rec_hid = $('#'+rec_hid).val();
    var rec = $("#"+recordId).val();
    if(update_call_flow == 1){
        if((rec === "") && (rec_hid === "")){
            $("#"+messId).html("<p class = 'badge badge-danger'>Please record audio file.</p>");
            return 0;
        }
        else{
            return 1;   
        }
    }
    else if(rec == ""){
        $("#"+messId).html("<p class = 'badge badge-danger'>Please record audio file.</p>");
        return 0;
        
    }
    else{
        return 1;
    }
}

function textto_speech_validate(txtId, txtMsgId){
    var txtVal = $("#"+txtId).val();
    if(txtVal == ""){
        $("#"+txtMsgId).html("<p class = 'badge badge-danger'>Please enter your message.</p>");
        return 0;
    }
    else return 1;
}

function addNewCallFlow(){
    $("#add_call_flow_btn").addClass('showHide'); 
    $("#my_call_flow_content").removeClass('showHide');
    // $("#status_call_flow_message").hide();
    // $.ajax({
    //     url: 'include/signalwire/numbers.php',
    //     type: 'post',
    //     data: { checkPropertyDoorHardware: 'yes'},
    //     success: function(response) {
    //         if(response == 0){
    //             $("#status_call_flow_message").show();
    //             $("#status_call_flow_message").html("<h5 class='alert alert-danger'>Please add door for this property</h5>")
    //         }
    //         else if(response == 1){
    //             $("#add_call_flow_btn").addClass('showHide'); 
    //             $("#my_call_flow_content").removeClass('showHide'); 
    //         }
    //         else if(response == 2){
    //             $("#status_call_flow_message").show();
    //             $("#status_call_flow_message").html("<h5 class='alert alert-danger'>Please add Hardware to a door of this property</h5>")   
    //         }
            
    //         setInterval(function(){ 
    //             $("#status_call_flow_message").hide();
    //         }, 5000);
    //     },
    //     error: function(xhr, status, error) {
    //         console.error('Failed to fetch data:', status, error);
    //     }
    // });   
}

function save_call_flow(){
    $(".error_message_call_flow").html("");
    var is_valid = 1;
    var check_upload_audio;
    var check_record_audio;
    var check_txtto_speech;
    var first_checkbox = $('input[name="call_flow_first_message"]:checked').val();
    var update_call_flow = $("#update_call_flow").val();
    if(first_checkbox == "is_first_upload_audio"){
        check_upload_audio = upload_file_validate('is_first_upload_audio_field', 'call_flow_first_audio_message', update_call_flow, 'is_first_upload_audio_field_hidden');
        if(check_upload_audio == 0){
            is_valid = 0;
        }
    }
    else if(first_checkbox == "is_first_record_audio"){
        check_record_audio = record_file_validate('is_first_record_audio_field', 'is_first_record_audio_message', update_call_flow, 'update_first_record_audio_field');
        if(check_record_audio == 0){
            is_valid = 0;   
        }
    }
    else if(first_checkbox == "is_first_textto_speech"){
        check_txtto_speech = textto_speech_validate('is_first_textto_speech_field', 'is_first_textto_speech_message');   
        if(check_txtto_speech == 0){
            is_valid = 0;   
        }
    }

    var first_end_message = $('input[name="call_flow_first_end_message"]:checked').val();
    if(first_end_message == "is_no_response_upload_audio"){
        check_upload_audio = upload_file_validate('is_no_response_upload_audio_field', 'call_flow_first_end_audio_message', update_call_flow, 'is_no_response_upload_audio_field_hidden');
        if(check_upload_audio == 0){
            is_valid = 0;
        }
    }
    else if(first_end_message == "is_no_response_record_audio"){
        check_record_audio = record_file_validate('is_no_response_record_audio_field', 'is_no_response_record_audio_message', update_call_flow, 'is_no_response_record_audio_field_hidden');
        if(check_record_audio == 0){
            is_valid = 0;   
        }
    }
    else if(first_end_message == "is_no_response_textto_speech"){
        check_txtto_speech = textto_speech_validate('is_no_response_textto_speech_field', 'is_no_response_textto_speech_message');   
        if(check_txtto_speech == 0){
            is_valid = 0;   
        }      
    }

    var press2_check = $('input[name="press2_message"]:checked').val();
    if(press2_check == "press2_upload_audio"){
        check_upload_audio = upload_file_validate('press2_upload_audio_field', 'press2_audio_message', update_call_flow, 'press2_upload_audio_field_hidden');
        if(check_upload_audio == 0){
            is_valid = 0;
        }
    }
    else if(press2_check == "press2_record_audio"){
        check_record_audio = record_file_validate('press2_record_audio_field', 'press2_record_audio_message', update_call_flow, 'press2_record_audio_field_hidden');
        if(check_record_audio == 0){
            is_valid = 0;   
        }
    }
    else if(press2_check == "press2_textto_speech"){
        check_txtto_speech = textto_speech_validate('press2_textto_speech_field', 'press2_textto_speech_message');   
        if(check_txtto_speech == 0){
            is_valid = 0;   
        }      
    }

    var press2_auth_code_check = $('input[name="press2_auth_code_message"]:checked').val();

    if(press2_auth_code_check == "press2_auth_code_upload_audio"){
        check_upload_audio = upload_file_validate('press2_auth_code_upload_audio_field', 'press2_auth_code_audio_message', update_call_flow, 'press2_auth_code_upload_audio_field_hidden');
        if(check_upload_audio == 0){
            is_valid = 0;
        }
    }
    else if(press2_auth_code_check == "press2_auth_code_record_audio"){
        check_record_audio = record_file_validate('press2_auth_code_record_audio_field', 'press2_auth_code_record_audio_message', update_call_flow, 'press2_auth_code_record_audio_field_hidden');
        if(check_record_audio == 0){
            is_valid = 0;   
        }
    }
    else if(press2_auth_code_check == "press2_auth_code_textto_speech"){
        check_txtto_speech = textto_speech_validate('press2_auth_code_textto_speech_field', 'press2_auth_code_textto_speech_message');   
        if(check_txtto_speech == 0){
            is_valid = 0;   
        }      
    }

    var press2_auth_code_ack_check = $('input[name="press2_auth_code_ack_message"]:checked').val();
    if(press2_auth_code_ack_check == "press2_auth_code_ack_upload_audio"){
        check_upload_audio = upload_file_validate('press2_auth_code_ack_upload_audio_field', 'press2_auth_code_ack_audio_message', update_call_flow, 'press2_auth_code_ack_upload_audio_field_hidden');
        if(check_upload_audio == 0){
            is_valid = 0;
        }
    }
    else if(press2_auth_code_ack_check == "press2_auth_code_ack_record_audio"){
        check_record_audio = record_file_validate('press2_auth_code_ack_record_audio_field', 'press2_auth_code_ack_record_audio_message', update_call_flow, 'press2_auth_code_ack_record_audio_field_hidden');
        if(check_record_audio == 0){
            is_valid = 0;   
        }
    }
    else if(press2_auth_code_ack_check == "press2_auth_code_ack_textto_speech"){
        check_txtto_speech = textto_speech_validate('press2_auth_code_ack_textto_speech_field', 'press2_auth_code_ack_textto_speech_message');   
        if(check_txtto_speech == 0){
            is_valid = 0;   
        }      
    }

    var press2_auth_code_access_check = $('input[name="press2_auth_code_access_message"]:checked').val();
    if(press2_auth_code_access_check == "press2_auth_code_access_upload_audio"){
        check_upload_audio = upload_file_validate('press2_auth_code_access_upload_audio_field', 'press2_auth_code_access_audio_message', update_call_flow, 'press2_auth_code_access_upload_audio_field_hidden');
        if(check_upload_audio == 0){
            is_valid = 0;
        }
    }
    else if(press2_auth_code_access_check == "press2_auth_code_access_record_audio"){
        check_record_audio = record_file_validate('press2_auth_code_access_record_audio_field', 'press2_auth_code_access_record_audio_message', update_call_flow, 'press2_auth_code_access_record_audio_field_hidden');
        if(check_record_audio == 0){
            is_valid = 0;   
        }
    }
    else if(press2_auth_code_access_check == "press2_auth_code_access_textto_speech"){
        check_txtto_speech = textto_speech_validate('press2_auth_code_access_textto_speech_field', 'press2_auth_code_access_textto_speech_message');   
        if(check_txtto_speech == 0){
            is_valid = 0;   
        }      
    }

    var press2_auth_code_denied_check = $('input[name="press2_auth_code_denied_message"]:checked').val();
    if(press2_auth_code_denied_check == "press2_auth_code_denied_upload_audio"){
        check_upload_audio = upload_file_validate('press2_auth_code_denied_upload_audio_field', 'press2_auth_code_denied_audio_message', update_call_flow, 'press2_auth_code_denied_upload_audio_field_hidden');
        if(check_upload_audio == 0){
            is_valid = 0;
        }
    }
    else if(press2_auth_code_denied_check == "press2_auth_code_denied_record_audio"){
        check_record_audio = record_file_validate('press2_auth_code_denied_record_audio_field', 'press2_auth_code_denied_record_audio_message', update_call_flow, 'press2_auth_code_denied_record_audio_field_hidden');
        if(check_record_audio == 0){
            is_valid = 0;   
        }
    }
    else if(press2_auth_code_denied_check == "press2_auth_code_denied_textto_speech"){
        check_txtto_speech = textto_speech_validate('press2_auth_code_denied_textto_speech_field', 'press2_auth_code_denied_textto_speech_message');   
        if(check_txtto_speech == 0){
            is_valid = 0;   
        }     
    }

    var advertisement_check = $('input[name="advertisement_first_message"]:checked').val();
    
    if(advertisement_check == "is_advertisement_upload_audio"){
        check_upload_audio = upload_file_validate('is_advertisement_upload_audio_field', 'advertisement_first_audio_message', update_call_flow, 'adv_aud_file_hidden');
        if(check_upload_audio == 0){
            is_valid = 0;
        }
    }
    else if(advertisement_check == "is_advertisement_record_audio"){
        check_record_audio = record_file_validate('is_advertisement_record_audio_field', 'is_advertisement_record_audio_message', update_call_flow, 'adv_rec_hidden');
        if(check_record_audio == 0){
            is_valid = 0;   
        }
    }
    else if(advertisement_check == "is_advertisement_textto_speech"){
        check_txtto_speech = textto_speech_validate('is_advertisement_textto_speech_field', 'is_advertisement_textto_speech_message');   
        if(check_txtto_speech == 0){
            is_valid = 0;   
        }      
    }

    var connect_to_me_check = $('input[name="connect_to_me_message"]:checked').val();
    if(connect_to_me_check == "is_connected_no_answer_upload_audio"){
        check_upload_audio = upload_file_validate('is_connected_no_answer_upload_audio_field', 'connect_me_first_audio_message', update_call_flow, 'connect_aud_file_hidden');
        if(check_upload_audio == 0){
            is_valid = 0;
        }
    }
    else if(connect_to_me_check == "is_connected_no_answer_record_audio"){
        check_record_audio = record_file_validate('is_connected_no_answer_record_audio_field', 'is_connected_no_answer_record_audio_message', update_call_flow, 'connect_rec_hidden');
        if(check_record_audio == 0){
            is_valid = 0;   
        }
    }
    else if(connect_to_me_check == "is_connected_no_answer_textto_speech"){
        check_txtto_speech = textto_speech_validate('is_connected_no_answer_textto_speech_field', 'is_connected_no_answer_textto_speech_message');   
        if(check_txtto_speech == 0){
            is_valid = 0;   
        }      
    }
    
    var hang_up_call_check = $('input[name="is_connected_hangeup_message"]:checked').val();
    
    if(hang_up_call_check == "hang_up_message_play"){
        var hang_up_record_audio = $('input[name="hang_up_record_audio"]:checked').val();
        if(hang_up_record_audio == "is_connected_hangeup_upload_audio"){
            check_upload_audio = upload_file_validate('is_connected_hangeup_upload_audio_field', 'hang_up_first_audio_message', update_call_flow, 'hang_aud_file_hidden');
            if(check_upload_audio == 0){
                is_valid = 0;
            }
        }
        else if(hang_up_record_audio == "is_connected_hangeup_record_audio"){
            check_record_audio = record_file_validate('is_connected_hangeup_record_audio_field', 'is_connected_hangeup_record_audio_message', update_call_flow, 'hang_rec_aud_hidden');
            if(check_record_audio == 0){
                is_valid = 0;   
            }
        }
        else if(hang_up_record_audio == "is_connected_hangeup_textto_speech"){
            check_txtto_speech = textto_speech_validate('is_connected_hangeup_textto_speech_field', 'is_connected_hangeup_textto_speech_message');   
            if(check_txtto_speech == 0){
                is_valid = 0;
            }      
        }
    }
    
    var open_command_check = $('input[name="open_command_first_check"]:checked').val();

    if(open_command_check == "is_beep_upload_audio"){
        check_upload_audio = upload_file_validate('is_beep_upload_audio_field', 'open_command_first_audio_message', update_call_flow, 'beep_aud_file_hidden');
        if(check_upload_audio == 0){
            is_valid = 0;
        }
    }
    else if(open_command_check == "is_beep_record_audio"){
        check_record_audio = record_file_validate('is_beep_record_audio_field', 'is_beep_record_audio_message', update_call_flow, 'beep_aud_rec_hidden');
        if(check_record_audio == 0){
            is_valid = 0;   
        }
    }
    else if(open_command_check == "is_beep_textto_speech"){
        check_txtto_speech = textto_speech_validate('is_beep_textto_speech_field', 'is_beep_textto_speech_message');   
        if(check_txtto_speech == 0){
            is_valid = 0;   
        }      
    }

    var access_check_opt = $('input[name="access_first_options"]:checked').val();
    if(access_check_opt == "is_access_upload_audio"){
        check_upload_audio = upload_file_validate('is_access_upload_audio_field', 'access_first_audio_message', update_call_flow, 'access_aud_file_hidden');
        if(check_upload_audio == 0){
            is_valid = 0;
        }
    }
    else if(access_check_opt == "is_access_record_audio"){
        check_record_audio = record_file_validate('is_access_record_audio_field', 'is_access_record_audio_message', update_call_flow, 'access_rec_hidden');
        if(check_record_audio == 0){
            is_valid = 0;   
        }
    }
    else if(access_check_opt == "is_access_textto_speech"){
        check_txtto_speech = textto_speech_validate('is_access_textto_speech_field', 'is_access_textto_speech_message');   
        if(check_txtto_speech == 0){
            is_valid = 0;   
        }      
    }   

    var end_call_time = $('input[name="is_hang_up_call_terminate"]:checked').val();
    if(end_call_time == 0){
        var check_time_end = $("#end_call_time_seconds").val();
        if(check_time_end == "" || check_time_end < 60){
            is_valid = 0;
            $("#end_call_time_message").html("<p class = 'badge badge-danger'>You can add minimum 60 seconds</p>");
        }
        else{
            $("#end_call_time_message").html('');
        }
    }
    else{
        $("#end_call_time_seconds").val('');
    }
    
    var call_duration_after_user_connect = $("#call_duration_after_user_connect").val();

    if(call_duration_after_user_connect == "" || call_duration_after_user_connect < 60){
        is_valid = 0;
        $("#error_message_call_duration_after_user_connect").html("<p class = 'badge badge-danger'>You can add minimum 60 seconds.</p>");   
    }
    else{
        $("#error_message_call_duration_after_user_connect").html("");      
    }

    if(is_valid == 1){
        $("#call_flow_form").submit();
    }
}
