<style>

    .list-group {
        display: flex;
        flex-direction: column;        
        padding-left: 0; 
        margin-bottom: 0;
        
      }
      
    .me-3 {
        margin-right: 1.5rem!important;
        font-size: 20px; 
    }
    
    .float-start {
        float: left!important;
    }
    #qrcode{
        display:flex;
        justify-content:center;
    }
    img[src^="data:image/png"] {
        max-width: 100%;
    }
</style>
<div class="wrapper">
    <div class="container">
        <div class="row m-t-20">
            <div class="col-md-12">
                <div class="panel panel-default m-t-20">
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-md-12" style="text-align: center;">
                                <h1 style="font-weight: bold;">Mark Your Attendance</h1>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-4" style="text-align: center;">
                                <h3>QR Scan</h3>
                                <span id="qrcode" style="text-align: center;"></span>
                                <button onclick="refreshqr();" class="btn btn-pink waves-effect waves-light m-t-10">Refresh QR Code</button>
                            </div>
                            <div class="col-md-4" style="text-align: center;">
                                <ul class="list-group mb-0 user-list">
                                    <li class="list-group-item">
                                        <a href="#" class="user-list-item">
                                            <div class="user float-start me-3">
                                                <i class="zmdi zmdi-circle  text-primary"></i>
                                            </div>
                                            <div class="user-desc overflow-hidden">
                                                <h5 class="name mt-0 mb-1">Use your registered Mobile Device only</h5>
                                                <span class="desc text-muted font-12 text-truncate d-block">&nbsp</span>
                                            </div>
                                        </a>
                                    </li>

                                    <li class="list-group-item">
                                        <a href="#" class="user-list-item">
                                            <div class="user float-start me-3">
                                                <i class="zmdi zmdi-circle text-success"></i>
                                            </div>
                                            <div class="user-desc overflow-hidden">
                                                <h5 class="name mt-0 mb-1">You can only mark your time in once per day</h5>
                                                <span class="desc text-muted font-12 text-truncate d-block">&nbsp</span>
                                            </div>
                                        </a>
                                    </li>

                                    <li class="list-group-item">
                                        <a href="#" class="user-list-item">
                                            <div class="user float-start me-3">
                                                <i class="zmdi zmdi-circle text-pink"></i>
                                            </div>
                                            <div class="user-desc overflow-hidden">
                                                <h5 class="name mt-0 mb-1">Your time is automatically synchronized with the central HR system</h5>
                                                <span class="desc text-muted font-12 text-truncate d-block">&nbsp</span>
                                            </div>
                                        </a>
                                    </li>

                                    <li class="list-group-item">
                                        <a href="#" class="user-list-item">
                                            <div class="user float-start me-3">
                                                <i class="zmdi zmdi-circle text-muted"></i>
                                            </div>
                                            <div class="user-desc overflow-hidden">
                                                <h5 class="name mt-0 mb-1">In case your device fails to scan, contact your administrator</h5>
                                                <span class="desc text-muted font-12 text-truncate d-block">&nbsp</span>
                                            </div>
                                        </a>
                                    </li>
                                    <li class="list-group-item">
                                        <a href="#" class="user-list-item">
                                            <div class="user float-start me-3">
                                                <i class="zmdi zmdi-circle text-warning"></i>
                                            </div>
                                            <div class="user-desc overflow-hidden">
                                                <h5 class="name mt-0 mb-1">QR Code will update in:</h5>
                                                <span class="desc text-muted font-12 text-truncate d-block" id="timer">30 seconds</span>
                                            </div>
                                        </a>
                                    </li>
                                </ul>
                            </div>
                            <div class="col-md-4" style="text-align: center;">
                                <h3>Fingerprint Scan</h3>
                                <div class="row">
                                    <div class="col-md-12" style="text-align: center;">
                                        <input type='hidden' id=quality size=10 value="100">
                                        <input type="hidden" name="staff_id" id="staff_id_for_fingerprint" >
                                        <input type="hidden" name="staff_fingerprint_template_base64" id="staff_fingerprint_template_base64" >
                                        <img id ="FPImage" src="<?php echo base_url() . 'assets/images/staff_fingerprint/'; ?>fingerprint_placeholder.jpg"  style="width: 300px !important; max-width:100%"/>
                                    </div>
                                </div>
                                <button id="fingerprint_scan_button" type="button" class="btn btn-icon waves-effect waves-light btn-info m-t-10" onclick="matchFinger()">Click to Scan</button> 
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="<?php echo base_url();?>assets/plugins/qrcode/qrcode.js"></script>
    
    <script type="text/javascript">
        new QRCode(document.getElementById("qrcode"), {
                    text:  "<?php echo $key_code->current_key;?>",
                    width: 300,
                    height: 300,
                    colorDark: "#000000",
                    colorLight: "#ffffff",
                    correctLevel: QRCode.CorrectLevel.H,
                });
    
        $('document').ready(function(){
            countDown(30);
        });

        function countDown(i) {
            var int = setInterval(function () {
                $("#timer").html(i + " seconds");
                if(i == 0){
                    i=30;
                    refreshqr();  //if i is 0, then stop the interval
                }else{
                    i-- ;
                }
            }, 1000);
        }
        

        function refreshqr(){

            $("#qrcode").html('');

            $.ajax({
                type: "GET",
                url: "<?php echo base_url();?>/attendance_controller/update_qr",
                data: {},
                dataType: "json",
                cache: false,            
                success: function (data) {
                    new QRCode(document.getElementById("qrcode"), {
                        text: data.current_key,
                        width: 300,
                        height: 300,
                        colorDark: "#000000",
                        colorLight: "#ffffff",
                        correctLevel: QRCode.CorrectLevel.H,
                    });
                    $("#qrcode").addClass('style', 'text-align: center');
                    // location.reload();
                }
            });

        }
    </script>

    <!-- Fingerprint -->
<script src="<?php echo base_url(); ?>assets/plugins/fingerprint/js/modernizr-2.6.2.js"></script>
<script type="text/javascript">
    async function matchFinger() {
        var button = document.getElementById('fingerprint_scan_button');
        button.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Scanning';
        button.disabled = true;
        var uri = "https://localhost:8443/SGIFPCapture";
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = async function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var fpobject = JSON.parse(xmlhttp.responseText);
                var match_found = 0; // Flag to track if a match is found
                var fingerprint_to_be_matched = fpobject.TemplateBase64;
                if (fingerprint_to_be_matched) {
                    $.ajax({
                        type: 'POST',
                        url: '<?php echo base_url(); ?>attendance_controller/get_all_staff_fingerprints',
                        dataType: "json",
                        cache: false,
                        async: true,
                        success: function(result) {
                            var requests = [];  // Array to hold all AJAX promises
                            result.forEach(function(item) {
                                var current_fingerprint = item.staff_fingerprint_template_base64;
                                var staff_id = item.id_staff;
                                var staffFCM = item.fcm_id;
                                var staff = item.staff_firstname;
                                var staffCell = item.staff_cell;
                                var businessid = item.business_id;
                                var uri = "https://localhost:8443/SGIMatchScore";
                                // Create a Promise for each AJAX request
                                let request = new Promise(function(resolve, reject) {
                                    var xmlhttp = new XMLHttpRequest();
                                    xmlhttp.onreadystatechange = async function () {
                                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                                            var result = JSON.parse(xmlhttp.responseText);
                                            
                                            var idQuality = document.getElementById("quality").value;
                                            if (result.ErrorCode == 0) {
                                                if (result.MatchingScore >= idQuality) {
                                                    match_found = 1;
                                                    var currentDate = new Date();
                                                    var date = currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getDate();
                                                    var time = currentDate.getHours() + ':' + currentDate.getMinutes() +':'+ currentDate.getSeconds();
                                                    const result = await getLocationAndAddress();
                                                    var lat = result.latitude;
                                                    var lng = result.longitude;
                                                    var add = result.address;
                                                    $.ajax({
                                                        type: 'POST',
                                                        url: 'attendance_controller/mark_staff_attendance_fingerprint',
                                                        data: {id_staff: staff_id, staff_fcm:staffFCM, staff_cell: staffCell, attendance_date: date, attendance_time: time, businessId: businessid, latitude: lat, longitude: lng, address: add },
                                                        success: function(data) {
                                                            let parsedData = JSON.parse(data);
                                                            var status = parsedData[0]['status'][0];
                                                            var message = parsedData[0]['message'][0];
                                                            swal({
                                                                type:status?'success':'error',
                                                                title: 'Hi '+staff+'!',
                                                                text: message,
                                                                timer: 5000
                                                                });
                                                            speak("Hi "+staff+"! "+message);
                                                            enableFingerPrintScanningButton();
                                                        }
                                                    });

                                                }
                                            } else {
                                                swal({
                                                    type:"error",
                                                    title: "Error!",
                                                    text: "Error Scanning Fingerprint ErrorCode = " + result.ErrorCode
                                                    });
                                                enableFingerPrintScanningButton();
                                            }
                                            resolve();  // Resolve the promise when the request completes
                                        } else if (xmlhttp.status == 404) {
                                            swal({
                                                type:"error",
                                                title: "Error!",
                                                text: "Error: Not Found"
                                                });
                                            reject("Error: Not Found");
                                            enableFingerPrintScanningButton();
                                        }
                                    };
                                    xmlhttp.onerror = function () {
                                        swal({
                                            type:"error",
                                            title: "Error!",
                                            text: "Error: Network issue"
                                            });
                                        reject("Error: Network issue");
                                        enableFingerPrintScanningButton();
                                    };
                                    var params = "template1=" + encodeURIComponent(fingerprint_to_be_matched);
                                    params += "&template2=" + encodeURIComponent(current_fingerprint);
                                    params += "&licstr=" + encodeURIComponent(secugen_lic);
                                    params += "&templateFormat=" + "ISO";
                                    xmlhttp.open("POST", uri, true);  // Use async true here
                                    xmlhttp.send(params);
                                });

                                requests.push(request);  // Add the request promise to the array
                            });

                            // After all requests complete, check if a match was found
                            Promise.all(requests).then(function() {
                                if (match_found === 0) {
                                    swal({
                                        type:"warning",
                                        title: "Not Found!",
                                        text: "No match found"
                                        });
                                    speak("No match found");
                                    enableFingerPrintScanningButton();
                                }
                            }).catch(function(error) {
                                console.log(error);  // Handle any errors that might occur in the AJAX requests
                                enableFingerPrintScanningButton();
                            });
                        }
                    });
                }
                else{
                    enableFingerPrintScanningButton();
                    alert("Fingerprint Capture Error Code:  55.\nDescription:  Fingerprint Device Not Found.");
                }
            } else if (xmlhttp.status == 404) {
                console.log(xmlhttp.status);
                enableFingerPrintScanningButton();
                // failCall(xmlhttp.status)
            }
        };

        xmlhttp.onerror = function () {
            console.log(xmlhttp.status);
            enableFingerPrintScanningButton();
        };

        var params = "Timeout=" + "10000";
        params += "&Quality=" + "50";
        params += "&licstr=" + encodeURIComponent(secugen_lic);
        params += "&templateFormat=" + "ISO";
        xmlhttp.open("POST", uri, true);
        xmlhttp.send(params);
    }
    function speak(text) {
        var msg = new SpeechSynthesisUtterance(text);
        var voices = window.speechSynthesis.getVoices(); // Get list of voices
        msg.voice = voices[0]; // Set voice (optional, you can choose any voice you want)
        window.speechSynthesis.speak(msg);  // Speak the message
    }
    function getLocationAndAddress() {
        return new Promise((resolve, reject) => {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    const latitude = position.coords.latitude;
                    const longitude = position.coords.longitude;
    
                    // Call reverse geocoding to get the address
                    const url = `https://nominatim.openstreetmap.org/reverse?lat=${latitude}&lon=${longitude}&format=json`;
    
                    fetch(url)
                        .then(response => response.json())
                        .then(data => {
                            let address = null;
                            if (data && data.address) {
                                address = `${data.display_name || ''}`;
                            }
    
                            // Resolve with the location and address
                            resolve({
                                latitude: latitude,
                                longitude: longitude,
                                address: address || 'Address not found'
                            });
                        })
                        .catch(error => {
                            // reject('Error fetching address: ' + error);
                            console.log('Error fetching address: ' + error);
                            resolve({
                                latitude: '',
                                longitude: '',
                                address: ''
                            });
                        });
                }, function(error) {
                    // reject('Geolocation error: ' + error.message);
                    console.log('Geolocation error: ' + error.message);
                    resolve({
                            latitude: '',
                            longitude: '',
                            address: ''
                        });
                });
            } else {
                // reject('Geolocation is not supported by this browser.');
                console.log('Geolocation is not supported by this browser.');
                resolve({
                        latitude: '',
                        longitude: '',
                        address: ''
                    });
            }
        });
    }

</script>



<script src="<?php echo base_url(); ?>assets/plugins/fingerprint/js/MsAjaxJs.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/plugins/fingerprint/js/respond.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/plugins/fingerprint/js/WebFormsJs.js" type="text/javascript"></script>

<script type="text/javascript">
    var template_1 = "";
    var template_2 = "";
    function enableFingerPrintScanningButton(){
        var button = document.getElementById('fingerprint_scan_button');
        button.innerHTML = 'Click to Scan';
        button.disabled = false;
    }
    function SuccessFunc(result) {
        if (result.ErrorCode == 0) {
            /* 	Display BMP data in image tag
                BMP data is in base 64 format 
            */
            if (result != null && result.BMPBase64.length > 0) {
                document.getElementById('FPImage').src = "data:image/bmp;base64," + result.BMPBase64;
                document.getElementById('staff_fingerprint_template_base64').value = result.TemplateBase64;
                
                var element = document.getElementById('fingerprint_save_button');
                if (element && element.style.display === 'none') {
                    element.style.display = '';  // Reset to default display value (usually block or inline)
                }
            }
            template_1 = result.TemplateBase64;
        }
        else {
            alert("Fingerprint Capture Error Code:  " + result.ErrorCode + ".\nDescription:  " + ErrorCodeToString(result.ErrorCode) + ".");
            enableFingerPrintScanningButton();
        }
    }

    function ErrorFunc(status) {
        /* 	
            If you reach here, user is probabaly not running the 
            service. Redirect the user to a page where he can download the
            executable and install it. 
        */
        //alert("Check if SGIBIOSRV is running; status = " + status + ":");
        swal({
            title: "Check if SGIBIOSRV is running; ",
            text: "status = " + status + ":",
            type: "info",
            confirmButtonText: 'OK!'
        });
        enableFingerPrintScanningButton();
    }

    function CallSGIFPGetData(successCall, failCall) {
        var uri = "https://localhost:8443/SGIFPCapture";
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                fpobject = JSON.parse(xmlhttp.responseText);
                successCall(fpobject);
                enableFingerPrintScanningButton();
            }
            else if (xmlhttp.status == 404) {
                failCall(xmlhttp.status)
                enableFingerPrintScanningButton();
            }
        }
        xmlhttp.onerror = function () {
            failCall(xmlhttp.status);
            enableFingerPrintScanningButton();
        }
        var params = "Timeout=" + "10000";
        params += "&Quality=" + "50";
        params += "&licstr=" + encodeURIComponent(secugen_lic);
        params += "&templateFormat=" + "ISO";
        xmlhttp.open("POST", uri, true);
        xmlhttp.send(params);
    }

    function matchScore(succFunction, failFunction) {
        if (template_1 == "" || template_2 == "") {
           // alert("Please scan two fingers to verify!!");
            swal({
                title: "Please scan two fingers to verify!!",
                text: "",
                type: "info",
                confirmButtonText: 'OK!'
            });
            
            return;
        }
        var uri = "https://localhost:8443/SGIMatchScore";

        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                fpobject = JSON.parse(xmlhttp.responseText);
                succFunction(fpobject);
            }
            else if (xmlhttp.status == 404) {
                failFunction(xmlhttp.status)
            }
        }

        xmlhttp.onerror = function () {
            failFunction(xmlhttp.status);
        }
        var params = "template1=" + encodeURIComponent(template_1);
        params += "&template2=" + encodeURIComponent(template_2);
        params += "&licstr=" + encodeURIComponent(secugen_lic);
        params += "&templateFormat=" + "ISO";
        xmlhttp.open("POST", uri, false);
        xmlhttp.send(params);
    }

    function succMatch(result) {
        var idQuality = document.getElementById("quality").value;
        if (result.ErrorCode == 0) {
            if (result.MatchingScore >= idQuality)
                //alert("MATCHED ! (" + result.MatchingScore + ")");
                swal({
                    title: "MATHED !",
                    text: result.MatchingScore,
                    type: "info",
                    confirmButtonText: 'OK!'
                });
            
            else
               // alert("NOT MATCHED ! (" + result.MatchingScore + ")");
                swal({
                    title: "NOT MATHED !",
                    text: result.MatchingScore,
                    type: "info",
                    confirmButtonText: 'OK!'
                });
        }
        else {
           // alert("Error Scanning Fingerprint ErrorCode = " + result.ErrorCode);
            swal({
                title: "ERROR !",
                text: result.ErrorCode,
                type: "error",
                confirmButtonText: 'OK!'
            });
        }
    }

    function failureFunc(error) {
        alert ("On Match Process, failure has been called");
    }
</script>
<script type="text/javascript">
    // nice global area, so that only 1 location, contains this information
    // var secugen_lic = "hE/78I5oOUJnm5fa5zDDRrEJb5tdqU71AVe+/Jc2RK0=";   // webapi.secugen.com
    var secugen_lic = "";

    function ErrorCodeToString(ErrorCode) {
        var Description;
        switch (ErrorCode) {
            // 0 - 999 - Comes from SgFplib.h
            // 1,000 - 9,999 - SGIBioSrv errors 
            // 10,000 - 99,999 license errors
            case 51:
                Description = "System file load failure";
                break;
            case 52:
                Description = "Sensor chip initialization failed";
                break;
            case 53:
                Description = "Device not found";
                break;
            case 54:
                Description = "Fingerprint image capture timeout";
                break;
            case 55:
                Description = "No device available";
                break;
            case 56:
                Description = "Driver load failed";
                break;
            case 57:
                Description = "Wrong Image";
                break;
            case 58:
                Description = "Lack of bandwidth";
                break;
            case 59:
                Description = "Device Busy";
                break;
            case 60:
                Description = "Cannot get serial number of the device";
                break;
            case 61:
                Description = "Unsupported device";
                break;
            case 63:
                Description = "SgiBioSrv didn't start; Try image capture again";
                break;
            default:
                Description = "Unknown error code or Update code to reflect latest result";
                break;
        }
        return Description;
    }

</script>
<!-- Fingerprint End-->



<script src="assets/plugins/switchery/switchery.min.js"></script>
   