<?php
/**
 * =====================================================
 * SIMPAS v2.0
 * Modul : Scan QR Absensi
 * =====================================================
 */

include "../../config/koneksi.php";
include "../../config/session.php";

include "../../templates/header.php";
include "../../templates/navbar.php";
include "../../templates/sidebar.php";
?>

<div class="content-wrapper">

<section class="content-header">

<div class="container-fluid">

<div class="row">

<div class="col-sm-6">

<h1>

<i class="fas fa-qrcode"></i>

SCAN QR ABSENSI SISWA

</h1>

</div>

<div class="col-sm-6 text-right">

<h4 id="jamDigital" class="font-weight-bold text-primary"></h4>

</div>

</div>

</div>

</section>

<section class="content">

<div class="container-fluid">

<div class="row">

<!-- =========================
     KOLOM SCANNER
========================== -->

<div class="col-lg-8">

<div class="card card-primary shadow">

<div class="card-header">

<h3 class="card-title">

<i class="fas fa-camera"></i>

Scanner QR Code

</h3>

</div>

<div class="card-body">

<div class="form-group">

<label>

Pilih Kamera

</label>

<select
id="pilihKamera"
class="form-control">

<option value="">Memuat kamera...</option>

</select>

</div>

<div
id="reader"
style="width:100%;min-height:420px;border:2px dashed #007bff;border-radius:10px;padding:10px;">

</div>

</div>

</div>

</div>

<!-- =========================
     KOLOM KANAN
========================== -->

<div class="col-lg-4">

<div class="card card-info shadow">

<div class="card-header">

<h3 class="card-title">

<i class="fas fa-info-circle"></i>

Hasil Scan

</h3>

</div>

<div class="card-body">

<div
id="hasil"
class="alert alert-info text-center">

<h4>

Silakan arahkan QR Code ke kamera

</h4>

<p>

Scanner siap digunakan

</p>

</div>

</div>

</div>

<div class="card card-success shadow">

<div class="card-header">

<h3 class="card-title">

<i class="fas fa-chart-line"></i>

Dashboard Live

</h3>

</div>

<div class="card-body">

<div id="dashboardLive">

<div class="text-center">

<i class="fas fa-spinner fa-spin fa-2x"></i>

<br><br>

Memuat Dashboard...

</div>

</div>

</div>

</div>

</div>

</div>

</div>

</section>

</div>

<?php
include "../../templates/footer.php";
?>

<script src="../../assets/plugins/html5-qrcode/html5-qrcode.min.js"></script>

<script>

/* ===========================================================
   VARIABEL GLOBAL
=========================================================== */

let html5QrCode = null;

let kameraAktif = "";

let daftarKamera = [];

let scannerAktif = false;

let sedangProses = false;
/* ===========================================================
   JAM DIGITAL
=========================================================== */

function updateJam(){

    let now = new Date();

    let jam =
        String(now.getHours()).padStart(2,'0') + ":" +
        String(now.getMinutes()).padStart(2,'0') + ":" +
        String(now.getSeconds()).padStart(2,'0');

    $("#jamDigital").text(jam);

}

updateJam();

setInterval(updateJam,1000);


/* ===========================================================
   TAMPILKAN PESAN
=========================================================== */

function tampilPesan(html,type="info"){

    $("#hasil").html(

        '<div class="alert alert-'+type+' text-center mb-0">'+
        html+
        '</div>'

    );

}


/* ===========================================================
   BUNYI BEEP
=========================================================== */

function beep(){

    try{

        let ctx =
        new(window.AudioContext || window.webkitAudioContext)();

        let osc = ctx.createOscillator();

        let gain = ctx.createGain();

        osc.connect(gain);

        gain.connect(ctx.destination);

        osc.type="sine";

        osc.frequency.value=1200;

        gain.gain.value=0.20;

        osc.start();

        osc.stop(ctx.currentTime+0.15);

    }catch(e){}

    if(navigator.vibrate){

        navigator.vibrate(150);

    }

}


/* ===========================================================
   DASHBOARD LIVE
=========================================================== */

function loadDashboard(){

    $.ajax({

        url:"dashboard_live.php",

        type:"GET",

        cache:false,

        success:function(res){

            $("#dashboardLive").html(res);

        },

        error:function(xhr){

            $("#dashboardLive").html(

                '<div class="alert alert-danger">'+
                '<b>Dashboard gagal dimuat</b><br>'+
                xhr.status+' - '+xhr.statusText+
                '</div>'

            );

            console.log(xhr.responseText);

        }

    });

}

loadDashboard();

setInterval(loadDashboard,5000);
/* ===========================================================
   LOAD DAFTAR KAMERA
=========================================================== */

async function loadCamera(){

    try{

        daftarKamera = await Html5Qrcode.getCameras();

        if(!daftarKamera || daftarKamera.length===0){

            tampilPesan(
                "<h4><i class='fas fa-camera'></i></h4>Kamera tidak ditemukan.",
                "danger"
            );

            return;
        }

        let option = "";

        daftarKamera.forEach(function(cam,index){

            let nama = cam.label;

            if(!nama || nama===""){

                nama = "Kamera " + (index+1);

            }

            option += '<option value="'+cam.id+'">'+nama+'</option>';

        });

        $("#pilihKamera").html(option);

        // Pilih kamera belakang jika ada
        let belakang = daftarKamera.find(function(cam){

            let label = (cam.label || "").toLowerCase();

            return label.includes("back") ||
                   label.includes("rear") ||
                   label.includes("belakang");

        });

        if(belakang){

            kameraAktif = belakang.id;

        }else{

            kameraAktif = daftarKamera[0].id;

        }

        $("#pilihKamera").val(kameraAktif);

        mulaiScanner();

    }catch(err){

        console.error(err);

        tampilPesan(

            "<b>Kamera gagal dibuka</b><br>"+err,

            "danger"

        );

    }

}


/* ===========================================================
   GANTI KAMERA
=========================================================== */

$("#pilihKamera").on("change",function(){

    kameraAktif = $(this).val();

    if(html5QrCode){

        html5QrCode.stop()

        .then(function(){

            scannerAktif = false;

            html5QrCode.clear()

            .then(function(){

                html5QrCode = null;

                mulaiScanner();

            });

        })

        .catch(function(){

            scannerAktif = false;

            html5QrCode = null;

            mulaiScanner();

        });

    }

});


/* ===========================================================
   MULAI SCANNER
=========================================================== */

function mulaiScanner(){

    if(scannerAktif){
        return;
    }

    if(!kameraAktif){

        tampilPesan(
            "Kamera belum dipilih.",
            "warning"
        );

        return;
    }

    scannerAktif = true;

    if(html5QrCode==null){

        html5QrCode = new Html5Qrcode("reader");

    }

    html5QrCode.start(

        kameraAktif,

        {

            fps:10,

            qrbox:{
                width:250,
                height:250
            }

        },

        function(decodedText){

            if(sedangProses){
                return;
            }

            sedangProses = true;

            beep();

            html5QrCode.stop()

            .then(function(){

                scannerAktif = false;

                kirimQR(decodedText);

            })

            .catch(function(err){

                console.error(err);

                scannerAktif = false;

                sedangProses = false;

            });

        },

        function(errorMessage){

            // abaikan

        }

    )

    .catch(function(err){

        scannerAktif = false;

        console.error(err);

        tampilPesan(

            "<b>Kamera gagal dijalankan</b><br>"+err,

            "danger"

        );

    });

}
/* ===========================================================
   KIRIM QR KE SERVER
=========================================================== */

function kirimQR(qr){

    tampilPesan(

        '<i class="fas fa-spinner fa-spin fa-2x"></i><br><br>Memproses absensi...',

        'warning'

    );

    $.ajax({

        url:"proses_scan.php",

        type:"POST",

        data:{
            qr:qr
        },

        cache:false,

        timeout:10000,

        success:function(res){

            $("#hasil").html(res);

            sedangProses=false;

            // Refresh dashboard setelah scan
            loadDashboard();

            // Aktifkan kembali scanner
            setTimeout(function(){

                if(html5QrCode){

                    html5QrCode.clear()

                    .then(function(){

                        html5QrCode=null;

                        scannerAktif=false;

                        loadCamera();

                    })

                    .catch(function(){

                        html5QrCode=null;

                        scannerAktif=false;

                        loadCamera();

                    });

                }else{

                    scannerAktif=false;

                    loadCamera();

                }

            },3000);

        },

        error:function(xhr){

            sedangProses=false;

            scannerAktif=false;

            tampilPesan(

                "<b>SERVER ERROR</b><hr>"+xhr.responseText,

                "danger"

            );

            console.error(xhr.responseText);

            setTimeout(function(){

                loadCamera();

            },3000);

        }

    });

}


/* ===========================================================
   HALAMAN DIBUKA
=========================================================== */

$(document).ready(function(){

    loadDashboard();

    loadCamera();

});

</script>