$(document).ready(function () {
    let webcamStream;
    let imageData;

    $('#attendance-btn').on('click', async function () {
        try {
            webcamStream = await navigator.mediaDevices.getUserMedia({
                video: true
            });
            $('#webcam').prop('srcObject', webcamStream);
            $('#webcam-container').removeClass('d-none');
            $('#webcam').removeClass('d-none');
            $('#btn-capture').removeClass('d-none');
            $('#canvas-preview').addClass('d-none');
            $('#action-buttons').addClass('d-none');
        } catch (error) {
            Swal.fire({
                icon: 'error',
                title: 'Webcam Error',
                text: 'Tidak dapat mengakses webcam Anda. Silakan periksa izin kamera Anda.',
                confirmButtonText: 'Tutup'
            });
        }
    });

    $('#btn-capture').on('click', function () {
        const canvas = document.createElement('canvas');
        const webcam = $('#webcam')[0];
        canvas.width = webcam.videoWidth;
        canvas.height = webcam.videoHeight;
        const context = canvas.getContext('2d');

        context.translate(canvas.width, 0);
        context.scale(-1, 1);
        context.drawImage(webcam, 0, 0, canvas.width, canvas.height);

        imageData = canvas.toDataURL('image/png');

        const previewCanvas = $('#canvas-preview')[0];
        const previewContext = previewCanvas.getContext('2d');
        previewCanvas.width = canvas.width;
        previewCanvas.height = canvas.height;
        previewContext.drawImage(canvas, 0, 0);

        $('#webcam').addClass('d-none');
        $('#btn-capture').addClass('d-none');

        $('#canvas-preview').removeClass('d-none');
        $('#action-buttons').removeClass('d-none');

        webcamStream.getTracks().forEach(track => track.stop());
    });

    $('#btn-retry').on('click', async function () {
        try {
            webcamStream = await navigator.mediaDevices.getUserMedia({
                video: true
            });
            $('#webcam').prop('srcObject', webcamStream);
            $('#webcam').removeClass('d-none');
            $('#btn-capture').removeClass('d-none');
            $('#canvas-preview').addClass('d-none');
            $('#action-buttons').addClass('d-none');
        } catch (error) {
            Swal.fire({
                icon: 'error',
                title: 'Webcam Error',
                text: 'Gagal membuka kembali webcam. Silakan coba lagi.',
                confirmButtonText: 'Tutup'
            });
            console.error(error);
        }
    });

    $('#btn-save').on('click', function () {
        if (!imageData) {
            Swal.fire({
                icon: 'warning',
                title: 'Tidak Ada Gambar yang Diambil',
                text: 'Silakan ambil gambar sebelum disimpan.',
                confirmButtonText: 'Tutup'
            });
            return;
        }

        $.ajax({
            url: '/dashboard/manage/attendance/store',
            type: 'POST',
            data: {
                _token: $('meta[name="csrf-token"]').attr('content'),
                image: imageData
            },
            success: function (response) {
                Swal.fire({
                    icon: 'success',
                    title: 'Gambar Disimpan',
                    text: 'Gambar Anda telah berhasil disimpan!',
                    confirmButtonText: 'OK'
                }).then(() => {
                    $('#webcam-container').addClass('d-none');
                    window.location.reload();
                });
            },
            error: function (error) {
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal Menyimpan',
                    text: 'Ada masalah saat menyimpan gambar Anda. Silakan coba lagi.',
                    confirmButtonText: 'Tutup'
                });

            }
        });
    });
});
