


<?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">Preview 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><br>
							
							<h4>Aadhaar Number</h4>
                            <input type="text" name="aadhaar_no" id="aadhaar_no" value="<?php echo e($aadharNumber); ?>" class="form-control"  readonly><br>

							<h4>Verification Code</h4>
							<input type="text" name="randomNo" id="randomNo" class="form-control" readonly="" ><br>
                             
                            <div id="video-container" style=""></div>


                            <div class="row">
                                <div class="col-md-6">
                                    <div class="btn-group">
                                        <!--<div id="startButton" class="btn btn-success"> Start Again </div>-->
                                         <a href="<?php echo e(url('/recordings-video')); ?>" class="btn btn-success"> Start Again </a>
                                        <div id="stopButton" class="btn btn-danger"  style="display:none;"> Stop </div>
                                        <div id="saveButton" class="btn btn-info"  style="display:none;"> Save Video</div>
                                        <button id="previewVideo" class="btn btn-primary" href="">Preview</button>
                                        <a id="retakeButton" class="btn btn-info" style="display: none;">Retake</a>
                                    </div><br><br>
                                    <!--<video id="preview" width="0" height="0" autoplay muted></video><br/><br/>-->
                                </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><br>


	                        <div class="row">
                                 <div class="col-lg-6">
                                      <a href="<?php echo e(url('/')); ?>" id="saveVideo" class="btn btn-warning mt-3 form-control">Submit</a>
                                 </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.style.display = "none";
            var videoContainer = document.getElementById("video-container");
            videoContainer.innerHTML = ''; // This empties the contents of the video container


            // Include audio constraint to capture audio
            navigator.mediaDevices.getUserMedia({
                video: true,
                audio: false // 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";
                })
                .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";
            saveButton.style.display = "inline-block";
            previewVideo.style.display = "none";
        }, false);
    }

 

// -------------- save ----------------

if (saveButton) {
    saveButton.addEventListener("click", function () {
        saveVideoAction(this); // Call the same function that handles video saving
    }, false);
}

// if (saveVideo) {
//     saveVideo.addEventListener("click", function () {
//         saveVideoAction(this); // Pass a reference to the clicked button
//     }, false);
// }




    function saveVideoAction(button) {
         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);

            $.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('aqqa');
                            if (button.id === 'saveButton') {
                                // alert('dd');
                                alert('Save Video'); 
                                window.location.reload();
                            } else if (button.id === 'saveVideo') {
                               alert(' Recorded  Video is Submited Successfully'); 
                               window.location.href = "<?php echo e(url('/')); ?>";
                            }
                    }
                }
            });
       
    }
    //-------------- 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) {
        preview.style.width = "500px";
        preview.style.height = "400px";
    } else {
        preview.style.width = "100%"; // Full width on mobile
        preview.style.height = "auto"; // Maintain aspect ratio
    }
}
window.addEventListener("load", setVideoSize);
window.addEventListener("resize", setVideoSize);
//----- Function to set the video size based on screen width




 let previewVideoClicked = false; // Flag to track if the preview video has been clicked
    // -------------- Preview video ----------------
    if (previewVideo) {
        previewVideo.addEventListener("click", function () {
       if (!previewVideoClicked) {
         previewVideoClicked = true; // Set the flag to true to prevent multiple openings
        
         var aadhaar_no = document.getElementById("aadhaar_no").value; 
         var projectPath = '/retirement/public/uploads'; // Replace with your actual project path

                $.ajax({
                    type: 'GET',
                    url: '<?php echo e(route('getVideoData', ['aadhaar_no' => ''])); ?>' + aadhaar_no,
                    dataType: 'json',
                    success: function (response) {
                        if (response.video_path) {
                            const videoURL = `${projectPath}/${response.video_path}`;
                            // Display the video using HTML5 video element
                            const videoElement = document.createElement('video');
                            videoElement.setAttribute('controls', 'controls');
                            
                        if (window.innerWidth > 768) { 
                            videoElement.setAttribute('width', '500'); // Set the desired width
                            videoElement.setAttribute('height', '400'); // Set the desired height
                        } else {
                            videoElement.setAttribute('width', '100%');
                            videoElement.setAttribute('height', 'auto');
                        }
                            videoElement.innerHTML = `<source src="${videoURL}" >`;
                            document.getElementById('video-container').appendChild(videoElement);
                        }
                    }
                });
            
      } else {
            alert("Video already opened");
      }
        
        
        
        }, false);
    }
    //-------------- Preview video ----------------

});

    // Add a click event listener to the button
 const submitButton = document.getElementById('saveVideo');
    submitButton.addEventListener('click', function (event) {
        event.preventDefault();
        alert('Your data has been submitted successfully.');
        window.location.href = submitButton.getAttribute('href');
    });

  //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/preview.blade.php ENDPATH**/ ?>