<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Record Audio</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body class="bg-light py-4">
    <div class="container">
        <h1 class="text-center mb-4">Record Audio</h1>
        <div class="text-center">
            <button id="toggleRecording" class="btn btn-primary">
                <i class="bi bi-mic-fill"></i> Start Recording
            </button>
        </div>
        <div class="text-center mt-4">
            <audio id="audioPreview" controls style="display: none;"></audio>
        </div>
        <div id="recordingIndicator" class="text-center mt-3 text-danger fw-bold d-none">
            <i class="bi bi-record-circle-fill"></i> Recording...
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.js"></script>
    <script>
        let mediaRecorder;
        let audioChunks = [];
        let isRecording = false;

        $(document).ready(function () {
            const toggleButton = $("#toggleRecording");
            const audioPreview = $("#audioPreview");
            const recordingIndicator = $("#recordingIndicator");

            // Toggle Recording
            toggleButton.on("click", async function () {
                if (!isRecording) {
                    // Start Recording
                    try {
                        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                        mediaRecorder = new MediaRecorder(stream);

                        mediaRecorder.ondataavailable = (event) => {
                            audioChunks.push(event.data);
                        };

                        mediaRecorder.onstop = () => {
                            const audioBlob = new Blob(audioChunks, { type: "audio/wav" }); // or 'audio/ogg' if preferred
                            audioChunks = [];

                            // Create an object URL for the audio blob
                            const audioUrl = URL.createObjectURL(audioBlob);
                            audioPreview.attr("src", audioUrl).show();

                            // Play the audio after recording
                            audioPreview[0].play().catch(error => {
                                console.error("Audio playback failed:", error);
                                alert("Failed to play the audio.");
                            });

                            uploadAudio(audioBlob); // Upload audio to server
                        };

                        mediaRecorder.start();
                        isRecording = true;
                        updateButtonState();
                        recordingIndicator.removeClass("d-none"); // Show recording indicator
                    } catch (error) {
                        console.error("Error accessing microphone:", error);
                        alert("Microphone access is required to record voice notes.");
                    }
                } else {
                    // Stop Recording
                    mediaRecorder.stop();
                    isRecording = false;
                    updateButtonState();
                    recordingIndicator.addClass("d-none"); // Hide recording indicator
                }
            });

            // Update Button State
            function updateButtonState() {
                if (isRecording) {
                    toggleButton
                        .removeClass("btn-primary")
                        .addClass("btn-danger")
                        .html('<i class="bi bi-stop-circle"></i> Stop Recording');
                } else {
                    toggleButton
                        .removeClass("btn-danger")
                        .addClass("btn-primary")
                        .html('<i class="bi bi-mic-fill"></i> Start Recording');
                }
            }

            // Upload Audio
            function uploadAudio(audioBlob) {
                const formData = new FormData();
                formData.append("audio", audioBlob, "voice_note.wav"); // You can also use 'voice_note.ogg' or another format

                $.ajax({
                    url: "{{ route('audio.upload') }}", // Replace with your API route
                    type: "POST",
                    data: formData,
                    processData: false,
                    contentType: false,
                    headers: {
                        "X-CSRF-TOKEN": "{{ csrf_token() }}"
                    },
                    success: function (response) {
                        alert("Audio uploaded successfully!");
                        console.log(response);
                    },
                    error: function (error) {
                        alert("Failed to upload audio.");
                        console.error(error);
                    }
                });
            }
        });
    </script>
</body>
</html>
