
function loading() {
    $('.btn-save').prop("disabled", true);
    // add spinner to button
    $('.btn-save').html(
        '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading...'
    );
    window.setTimeout(function () {
        $('.btn-save').prop("disabled", false);
        $('.btn-save').html('<i class="far fa-save"></i> Simpan'
        );
    }, 2000);
}

$('.timepicker').timepicker({
    showInputs: false,
    showMeridian: false,
    use24hours: true,
    format: 'HH:mm'
})

function loadDropdown() {
    $.ajax({
        type: 'POST',
        url: './sw-mod/recognition-pegawai/sw-proses.php?action=dropdown',
        cache: false,
        dataType: 'json',
        success: function (data) {
            const $dropdown = $(".pegawai");
            $dropdown.empty();
            data.forEach(item => {
                $dropdown.append(`<option value="${item.id}">${item.text}</option>`);
            });
        },
        error: function (err) {
            console.error("Gagal load dropdown:", err);
        }
    });
}
loadDropdown();

loadData();
function loadData() {
    var table;
    var modifikasi = $('.modifikasi').html();
    var hapus = $('.hapus').html();
    $(document).ready(function () {
        //datatables
        table = $('.datatable').DataTable({
            "scrollY": false,
            "scrollX": false,
            "processing": true,
            "serverSide": false,
            "bAutoWidth": true,
            "bSort": true,
            "bStateSave": true,
            "bDestroy": true,
            "paging": true,
            "ssSorting": [[0, 'desc']],
            "iDisplayLength": 15,
            "aLengthMenu": [
                [15, 30, 50, -1],
                [15, 30, 50, "All"]
            ],
            language: {
                paginate: {
                    previous: "<i class='fas fa-angle-left'>",
                    next: "<i class='fas fa-angle-right'>"
                }
            },
            "ajax": {
                "url": "./sw-mod/recognition-pegawai/sw-datatable.php",
                "type": "POST",
                "data": {
                    modifikasi: modifikasi,
                    hapus: hapus,
                },
            },
            "columnDefs": [{
                "targets": [0],
                "orderable": false,
            },],
        });
    });
}


const video = document.getElementById("video");
const guide = document.querySelector('.overlay-recognition');
const statusText = document.getElementById("status");
const captureBtn = document.getElementById("capture");

const CENTER = {
    x: 160,
    y: 120
};
const MAX_OFFSET = 60;
const MIN_SIZE = 90;

Promise.all([
    faceapi.nets.tinyFaceDetector.loadFromUri("../template/vendor/webcame/models"),
    faceapi.nets.faceLandmark68Net.loadFromUri("../template/vendor/webcame/models"),
    faceapi.nets.faceRecognitionNet.loadFromUri("../template/vendor/webcame/models"),
]).then(startVideo);

function startVideo() {
    navigator.mediaDevices.getUserMedia({
        video: {
            facingMode: "user",
            width: 320,
            height: 240
        }
    }).then(s => video.srcObject = s);
}

new faceapi.TinyFaceDetectorOptions({
    inputSize: 160,   // PENTING untuk HP low-end
    scoreThreshold: 0.5
});

setInterval(checkFace, 400);

async function checkFace() {
    const detection = await faceapi
        .detectSingleFace(video, new faceapi.TinyFaceDetectorOptions());

    if (!detection) {
        statusText.innerText = "Wajah tidak terdeteksi";
        $(".result-label").addClass("error");
        $(".result-label").removeClass("success");
        guide.style.borderColor = "red";
        captureBtn.disabled = true;
        return;
    }

    const box = detection.box;
    const faceCenterX = box.x + box.width / 2;
    const faceCenterY = box.y + box.height / 2;

    const offset = Math.hypot(
        faceCenterX - CENTER.x,
        faceCenterY - CENTER.y
    );

    if (box.width < MIN_SIZE) {
        statusText.innerText = "Wajah terlalu jauh";
        $(".result-label").addClass("error");
        $(".result-label").removeClass("success");
        guide.style.borderColor = "danger";
        captureBtn.disabled = true;
        return;
    }

    if (offset > MAX_OFFSET) {
        statusText.innerText = "Posisikan wajah di tengah";
        $(".result-label").addClass("error");
        $(".result-label").removeClass("success");
        guide.style.borderColor = "danger";
        captureBtn.disabled = true;
        return;
    }

    statusText.innerText = "Posisi wajah OK";
    $(".result-label").addClass("success");
    $(".result-label").removeClass("error")
    guide.style.borderColor = "white";
    captureBtn.disabled = false;
}


async function capture() {
    $('.btn-save').html(
        '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading...'
    );
    window.setTimeout(function () {
        $('.btn-save').prop("disabled", false);
        $('.btn-save').html('<i class="fas fa-camera"></i> Take Photo');
    }, 2000);

    var pegawai_id = $('.pegawai').val();

    const result = await faceapi
        .detectSingleFace(video, new faceapi.TinyFaceDetectorOptions())
        .withFaceLandmarks()
        .withFaceDescriptor();

    if (!result) {
        swal({ title: 'Wajah Gagal diambil!', text: data, icon: 'error', timer: 2500, });
        return;
    }

    const data = {
        pegawai_id: pegawai_id,
        descriptor: Array.from(result.descriptor)
    };
  
    fetch("./sw-mod/recognition-pegawai/sw-proses.php?action=add", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data)
    })
        .then(async res => {
            const text = await res.text();
            try {
                return JSON.parse(text);
            } catch {
                throw new Error("Response bukan JSON: " + text);
            }
        })
        .then(res => {
            swal({
                title: res.status ? "Berhasil" : "Gagal",
                text: res.msg || "Terjadi kesalahan",
                icon: res.status ? "success" : "error",
                timer: 2500,
                buttons: false
            });

            if (res.status == true) {
                loadDropdown();
                loadData();
            }
        })
        .catch(err => {
            swal({
                title: "Error",
                text: err.message,
                icon: "error",
                timer: 2500,
                buttons: false
            });
        });
}


$(document).on('click', '.btn-delete', function () {
    var id = $(this).attr("data-id");

    swal({
        text: "Anda yakin ingin menghapus data ini?",
        icon: "warning",
        buttons: {
            cancel: true,
            confirm: true,
        }
    }).then((value) => {
        if (value) {
            loading();
            $.ajax({
                url: './sw-mod/recognition-pegawai/sw-proses.php?action=delete',
                type: 'POST',
                dataType: 'json',
                data: { id: id },
                success: function (res) {
                    loadData();

                    if (res.status) {
                        swal({
                            title: 'Berhasil!',
                            text: res.msg,
                            icon: 'success',
                            timer: 2500,
                            buttons: false
                        });
                    } else {
                        swal({
                            title: 'Error!',
                            text: res.msg + "\n\n" + res.error,
                            icon: 'error'
                        });
                        console.error(res.error); 
                    }
                },
                error: function (xhr, status, error) {
                    swal({
                        title: 'AJAX Error!',
                        text: error,
                        icon: 'error'
                    });
                    console.error(xhr.responseText);
                }
            });
        }
    });
});