
document.addEventListener('DOMContentLoaded', function() {
    fetch('list_data/get_upload_file.php')
        .then(response => response.json())
        .then(data => {
            data.forEach(item => {
                const uploadImage = document.querySelector(`.uploadImage[data-id="${item.formId}"]`);
                if (uploadImage) {
                    const preview = uploadImage.querySelector('img');
                    const spanText = uploadImage.querySelector('span');
                    preview.src = `img/user/${item.fileName}`;
                    preview.style.display = 'block';
                    spanText.style.display = 'none';
                }
            });
        });
});

// upload.js
document.querySelectorAll('.uploadImage').forEach(uploadImage => {
    uploadImage.addEventListener('click', function() {
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = 'image/*';
        fileInput.style.display = 'none';

        fileInput.addEventListener('change', function() {
            const file = this.files[0];
            const preview = uploadImage.querySelector('img');
            const spanText = uploadImage.querySelector('span');

            // Menampilkan preview gambar
            const reader = new FileReader();
            reader.onload = function(e) {
                preview.src = e.target.result;
                preview.style.display = 'block';
                spanText.style.display = 'none';

                compressAndUploadImage(file, uploadImage.dataset.id, uploadImage);
            };
            reader.readAsDataURL(file);
        });

        document.body.appendChild(fileInput);
        fileInput.click();
    });
});

function compressAndUploadImage(file, formId, uploadImage) {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(event) {
        const img = new Image();
        img.src = event.target.result;
        img.onload = function() {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');

            const maxWidth = img.width;
            const maxHeight = img.height;
            canvas.width = maxWidth;
            canvas.height = maxHeight;
            ctx.drawImage(img, 0, 0, maxWidth, maxHeight);

            let quality = 0.9;
            let dataUrl = canvas.toDataURL('image/jpeg', quality);

            // Mengurangi kualitas sampai ukuran gambar kurang dari 200KB
            while (dataUrl.length > 200 * 1024) {
                quality -= 0.05;
                dataUrl = canvas.toDataURL('image/jpeg', quality);
            }

            fetch(dataUrl)
                .then(res => res.blob())
                .then(blob => {
                    const formData = new FormData();
                    formData.append('file', blob, file.name);
                    formData.append('formId', formId);

                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', 'list_data/upload_file.php', true);

                    // Menangani proses upload dan persentase
                    xhr.upload.onprogress = function(event) {
                        if (event.lengthComputable) {
                            const percentComplete = (event.loaded / event.total) * 100;
                            const progressBar = uploadImage.querySelector('.progressBar');
                            progressBar.style.width = percentComplete + '%';
                            uploadImage.querySelector('.progressContainer').style.display = 'block';
                        }
                    };

                    xhr.onload = function() {
                        if (xhr.status === 200) {
                            console.log('Success:', xhr.responseText);
                            showUploadAnimation(uploadImage);
                        } else {
                            console.error('Error:', xhr.responseText);
                        }
                    };

                    xhr.send(formData);
                });
        };
    };
}

function showUploadAnimation(uploadImage) {
    const uploaded = document.createElement('div');
    uploaded.innerText = 'Uploaded!';
    uploaded.style.position = 'absolute';
    uploaded.style.top = '0';
    uploaded.style.left = '0';
    uploaded.style.width = '100%';
    uploaded.style.height = '100%';
    uploaded.style.background = 'rgba(0, 128, 0, 0.5)';
    uploaded.style.color = 'white';
    uploaded.style.fontSize = '24px';
    uploaded.style.display = 'flex';
    uploaded.style.alignItems = 'center';
    uploaded.style.justifyContent = 'center';
    uploadImage.appendChild(uploaded);

    setTimeout(() => {
        uploaded.style.animation = 'fadeOut 2s forwards';
        setTimeout(() => {
            uploadImage.removeChild(uploaded);
        }, 2000);
    }, 1000); // Menampilkan teks "Uploaded!" selama 1 detik sebelum memulai animasi
}




// // upload.js
// document.getElementById('uploadImage').addEventListener('click', function() {
//     document.getElementById('fileInput').click();
// });

// document.getElementById('fileInput').addEventListener('change', function() {
//     var file = this.files[0];
//     var preview = document.getElementById('preview');
//     var spanText = document.querySelector('#uploadImage span');

//     // Menampilkan preview gambar
//     var reader = new FileReader();
//     reader.onload = function(e) {
//         preview.src = e.target.result;
//         preview.style.display = 'block';
//         spanText.style.display = 'none';
        
//         compressAndUploadImage(file);
//     };
//     reader.readAsDataURL(file);
// });

// function compressAndUploadImage(file) {
//     var reader = new FileReader();
//     reader.readAsDataURL(file);
//     reader.onload = function(event) {
//         var img = new Image();
//         img.src = event.target.result;
//         img.onload = function() {
//             var canvas = document.createElement('canvas');
//             var ctx = canvas.getContext('2d');

//             var maxWidth = img.width;
//             var maxHeight = img.height;
//             canvas.width = maxWidth;
//             canvas.height = maxHeight;
//             ctx.drawImage(img, 0, 0, maxWidth, maxHeight);

//             var quality = 0.9;
//             var dataUrl = canvas.toDataURL('image/jpeg', quality);
            
//             // Mengurangi kualitas sampai ukuran gambar kurang dari 200KB
//             while (dataUrl.length > 200 * 1024) {
//                 quality -= 0.05;
//                 dataUrl = canvas.toDataURL('image/jpeg', quality);
//             }

//             fetch(dataUrl)
//             .then(res => res.blob())
//             .then(blob => {
//                 var formData = new FormData();
//                 formData.append('file', blob, file.name);

//                 var xhr = new XMLHttpRequest();
//                 xhr.open('POST', 'list_data/upload_file.php', true);

//                 // Menangani proses upload dan persentase
//                 xhr.upload.onprogress = function(event) {
//                     if (event.lengthComputable) {
//                         var percentComplete = (event.loaded / event.total) * 100;
//                         var progressBar = document.getElementById('progressBar');
//                         progressBar.style.width = percentComplete + '%';
//                         document.getElementById('progressContainer').style.display = 'block';
//                     }
//                 };

//                 xhr.onload = function() {
//                     if (xhr.status === 200) {
//                         console.log('Success:', xhr.responseText);
//                         showUploadAnimation();
//                     } else {
//                         console.error('Error:', xhr.responseText);
//                     }
//                 };

//                 xhr.send(formData);
//             });
//         };
//     };
// }

// function showUploadAnimation() {
//     var uploadImage = document.getElementById('uploadImage');
//     var uploaded = document.createElement('div');
//     uploaded.innerText = 'Loading...!';
//     uploaded.style.position = 'absolute';
//     uploaded.style.top = '0';
//     uploaded.style.left = '0';
//     uploaded.style.width = '100%';
//     uploaded.style.height = '100%';
//     uploaded.style.background = 'rgba(212, 212, 212, 0.7)';
//     uploaded.style.color = 'black';
//     uploaded.style.fontSize = '24px';
//     uploaded.style.display = 'flex';
//     uploaded.style.alignItems = 'center';
//     uploaded.style.justifyContent = 'center';
//     uploadImage.appendChild(uploaded);

//     setTimeout(() => {
//         uploaded.style.animation = 'fadeOut 2s forwards';
//         setTimeout(() => {
//             uploadImage.removeChild(uploaded);
//         }, 2000);
//     }, 1000); // Menampilkan teks "Uploaded!" selama 1 detik sebelum memulai animasi
// }