


<?php $__env->startSection('content'); ?>

<div class="wizard-main">
	<div id="particles-js"></div>
	<div class="container">
		<div class="row">
		
			<div class="col-lg-6 login-sec mx-auto">
				<div class="login-sec-bg">
					<h2 class="text-center">Online Life Verification </h2>
					
                        <!--<h3 class="text-center p-2">Recording</h3>-->
						<fieldset class="form-input">

                            <?php echo $__env->make('includes.alerts', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
                            
                            <h4>Full Name</h4>
							<input type="text" name="full_name" id="full_name" value"<?php echo e($user->first_name .' '.$user->middle_name .' '.$user->last_name); ?>"  class="form-control" readonly="">
							
							<h4>Aadhaar Number</h4>
                            <input type="text" name="aadhaar_no" id="aadhaar_no" value="<?php echo e($aadharNumber); ?>" class="form-control" ><br>

							<h4>Verification Code</h4>
							<input type="text" name="randomNo" id="randomNo" class="form-control" readonly="" >
                         
                         	

                               
                            <div class="row">
                                    <div class="col-md-6">
                                        <!-- <h2>Preview</h2> -->
                                       
                                        <div class="btn-group">
                                            <div id="startButton" class="btn btn-success"> <i class="fa fa-play-circle" aria-hidden="true"></i> Start </div>
                                            <div id="stopButton" class="btn btn-danger"  style="display:none;"> <i class="fa fa-stop" aria-hidden="true"></i> Stop </div>
                                            <a id="retakeButton" class="btn btn-info" style="display: none;">Retake</a>
                                        </div><br><br>

                                         <video id="preview" autoplay muted></video>
                                    </div>
                                    <div class="col-md-6" id="recorded"  style="display:none">
                                        <h2>Recording</h2><br>
                                        <video id="recording" width="450" height="350" controls></video><br/><br/>
                                        <a id="downloadButton" class="btn btn-primary" data-url="">save</a>
                                        <a id="downloadLocalButton" class="btn btn-primary">Download</a>
                                    </div>
                                </div>

		                        <div class="row">
		                         <div class="col-lg-6">
		                              <button id="saveVideo" class="btn btn-warning mt-3 form-control">Recording Save</button>
		                         </div>
		                         <div class="col-lg-6">
		                              <a href="<?php echo e(url('/')); ?>" class="btn btn-warning mt-3 form-control">Cancel</a>
		                         </div>
		                        </div>
	                       
						</fieldset>
				
				</div>
			</div>			
		</div>
	</div>
</div>


<?php $__env->stopSection(); ?>
<?php $__env->startSection('js'); ?>
<script src="<?php echo e(asset('wizard/js/jquery.min.js')); ?>"></script>

<script>

function generateRandomFiveDigitNumber() {
    let randomNumber = Math.floor(Math.random() * 100000);
    let randomFiveDigitNumber = randomNumber.toString().padStart(5, '0');
    return randomFiveDigitNumber;
}

  var randomNoInput = document.getElementById("randomNo");
    randomNoInput.value = generateRandomFiveDigitNumber();


$(document).ready(function () {
     navigator.mediaDevices.getUserMedia({
        video: true,
        audio: false
    })
    let preview = document.getElementById("preview");
    let recording = document.getElementById("recording");
    let startButton = document.getElementById("startButton");
    let stopButton = document.getElementById("stopButton");
    let retakeButton = document.getElementById("retakeButton"); // New Retake button
    let downloadButton = document.getElementById("downloadButton");
    let logElement = document.getElementById("log");
    let recorded = document.getElementById("recorded");
    let downloadLocalButton = document.getElementById("downloadLocalButton");

    let recordingTimeMS = 60000; // Video limit 60 seconds
    var localstream;
    var mediaRecorder;
    var recordedChunks = [];

    window.log = function (msg) {
        console.log(msg);
    }

    window.wait = function (delayInMS) {
        return new Promise(resolve => setTimeout(resolve, delayInMS));
    }

    window.startRecording = function (stream, lengthInMS) {
        mediaRecorder = new MediaRecorder(stream);
        recordedChunks = [];

        mediaRecorder.ondataavailable = event => {
            if (event.data.size > 0) {
                recordedChunks.push(event.data);
            }
        };

        mediaRecorder.start();
        log(mediaRecorder.state + " for " + (lengthInMS / 1000) + " seconds...");

        let stopped = new Promise((resolve, reject) => {
            mediaRecorder.onstop = resolve;
            mediaRecorder.onerror = event => reject(event.name);
        });

        let recorded = wait(lengthInMS).then(
            () => mediaRecorder.state == "recording" && mediaRecorder.stop()
        );

        return Promise.all([
            stopped,
            recorded
        ])
            .then(() => recordedChunks);
    }

    var formData = new FormData();

    if (startButton) {
        startButton.addEventListener("click", function () {
            startButton.innerHTML = "Recording...";
            recorded.style.display = "none";
            stopButton.style.display = "inline-block";
            // downloadButton.innerHTML = "Please wait some time...";
            downloadButton.style.display = "none";

            // Include audio constraint to capture audio
            navigator.mediaDevices.getUserMedia({
                video: true,
                audio: true // Enable audio recording
            }).then(stream => {
                preview.srcObject = stream;
                localstream = stream;
                preview.captureStream = preview.captureStream || preview.mozCaptureStream;
                return new Promise(resolve => preview.onplaying = resolve);
            }).then(() => startRecording(preview.captureStream(), recordingTimeMS))
                .then(recordedChunks => {
                    let recordedBlob = new Blob(recordedChunks, {
                        type: "video/webm"
                    });
                    recording.src = URL.createObjectURL(recordedBlob);

                    formData.append('_token', document.querySelector('meta[name="csrf-token"]').getAttribute('content'));
                    formData.append('video', recordedBlob);

                    downloadLocalButton.href = recording.src;
                    downloadLocalButton.download = "RecordedVideo.webm";
                    log("Successfully recorded " + recordedBlob.size + " bytes of " +
                        recordedBlob.type + " media.");
                    startButton.innerHTML = "Start";
                    stopButton.style.display = "none";
                    // recorded.style.display = "block";
                    // downloadButton.innerHTML = "Save";
                })
                .catch(log);
        }, false);
    }

    if (stopButton) {
        stopButton.addEventListener("click", function () {
            mediaRecorder.stop();
            localstream.getTracks().forEach(track => track.stop());
            startButton.style.display = "none";
            stopButton.style.display = "none";
            // recorded.style.display = "block";
            // downloadButton.style.display = "inline-block";
            // retakeButton.style.display = "inline-block"; // Display the Retake button
        }, false);
    }

    if (retakeButton) {
        retakeButton.addEventListener("click", function () {
            // Hide the Retake button and reset the UI
            startButton.innerHTML = "Start again...";
            retakeButton.style.display = "none";
            startButton.style.display = "inline-block";
            recorded.style.display = "none";
            downloadButton.style.display = "none";
            recording.src = ""; // Clear the recorded video
        }, false);
    }

    if (downloadButton) {
        downloadButton.addEventListener("click", function () {
            $.ajax({
                url: this.getAttribute('data-url'),
                method: 'POST',
                data: formData,
                cache: false,
                processData: false,
                contentType: false,
                success: function (res) {
                    if (res.success) {
                        location.reload();
                    }
                }
            });
        }, false);
    }

     // -- save
    if (saveVideo) {
        saveVideo.addEventListener("click", function () {
             if (recordedChunks.length === 0) {
               alert('Please record a video before saving.');
             } else {
                 var recordedVideoBlob = new Blob(recordedChunks, { type: "video/webm" });
                 var recordedVideoFile = new File([recordedVideoBlob], "recordedVideo.webm");
                 var aadhaar_no = document.getElementById("aadhaar_no").value; 
                 var randomNo = document.getElementById("randomNo").value; 
                 formData.append('aadhaar_no', aadhaar_no);
                 formData.append('randomNo', randomNo);
                 formData.append('video', recordedVideoFile);
                 var aadhaar_no = localStorage.getItem('aadhaar_no');

                $.ajax({
                    url: '<?php echo e(route('saveVideo')); ?>', // Use the named route
                    type: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: formData,
                    cache: false,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        if (res.success) {
                            alert('Video saved successfully.'); // Display a success message
                            var url = '<?php echo e(route('preview-video')); ?>' + '?aadhaar_no=' + aadhaar_no;
                            window.location.href = url;
                        }
                    }
                });  //ajax close
             }
            
        }, false);
    }
    //--save close



// Function to set the video size based on screen width
function setVideoSize() {
    const screenWidth = window.innerWidth;
    const screenHeight = window.innerHeight;
    const preview = document.getElementById("preview");

    if (screenWidth >= 768) {
        // For desktop or larger screens
        preview.style.width = "500px";
        preview.style.height = "400px";
    } else {
        // For mobile or smaller screens
        preview.style.width = "100%"; // Full width on mobile
        preview.style.height = "auto"; // Maintain aspect ratio
    }
}
// Call the function when the page loads and when it's resized
window.addEventListener("load", setVideoSize);
window.addEventListener("resize", setVideoSize);
// Function to set the video size based on screen width




});

  //alert message
var successMessage = $(".alert-success,.alert-danger");
if (successMessage.length) {
    successMessage.fadeIn();
    setTimeout(function () {
        successMessage.fadeOut();
    }, 3000); // 3000 milliseconds = 3 seconds
}

</script>
<?php $__env->stopSection(); ?>


<?php echo $__env->make('includes.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/kart/retirement.creatorkart.com/retirement/resources/views/pages/recording.blade.php ENDPATH**/ ?>