const dropArea=document.querySelector(".drop-area");
const dragText=dropArea.querySelector("h2");
const button=dropArea.querySelector("button");
const input=dropArea.querySelector("#input-file");
let files;

function simula_inputfile(idInput){
    document.getElementById(idInput).click();
}

input.addEventListener("change",(e)=>{
    files= this.files;
    dropArea.classList.add("active");
    showFiles(files);
    dropArea.classList.remove("active");
})

dropArea.addEventListener("dragover",(e)=>{
    e.preventDefault();
    dropArea.classList.add("active");
    dragText.textContent="Suelta para subir archivos"
})
dropArea.addEventListener("dragleave",(e)=>{
    e.preventDefault();
    dropArea.classList.remove("active");
    dragText.textContent="Arrastra y suelta archivos"
})
dropArea.addEventListener("drop",(e)=>{
    e.preventDefault();
    files=e.dataTransfer.files;
    showFiles(files);
    dropArea.classList.remove("active");
    dragText.textContent="Arrastra y suelta archivos"
})
function showFiles(files){
    if(files.length === undefined){
        processFile(files);
    }else{
        for (const file of files){
            processFile(file);
        }  
    }
}

function readFile(input) {
    console.log(input)
    let file = input.files[0];
  
    let reader = new FileReader();
  
    reader.readAsText(file);
  
    reader.onload = function() {
      console.log(reader.result);
    };
  
    reader.onerror = function() {
      console.log(reader.error);
    };
  
  }

  function processFile(file) {
    const docType = file.type;
    const validaExtensions = [
        'image/jpeg', 'image/jpg', 'image/png', 'image/gif',
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ];

    if (validaExtensions.includes(docType)) {
        const fileReader = new FileReader();
        const id = `file-${Math.random().toString(32).substring(7)}`;

        fileReader.addEventListener("load", (e) => {
            const fileUrl = fileReader.result;

            let previewContent = '';
            if (docType.startsWith('image/')) {
                previewContent = `<img src="${fileUrl}" alt="${file.name}" width="50">`;
            } else {
                previewContent = `<span>${file.name}</span>`;
            }

            const fileContainer = `
                <div id="${id}" class="file-container">
                    ${previewContent}
                    <div class="status">
                        <span>${file.name}</span>
                        <span class="status-text">Loading...</span>
                    </div>
                </div>
            `;

            const html = document.querySelector("#preview").innerHTML;
            document.querySelector("#preview").innerHTML = fileContainer + html;
        });

        fileReader.readAsDataURL(file);
        uploadFile(file, id);
    } else {
        alert("Tipo de archivo no válido");
    }
}

function uploadFile(file, id) {
    const XHR = new XMLHttpRequest();
    const formData = new FormData();

    formData.append("archivos", file);
    formData.append("empresa", VGempresa.toLowerCase());
    formData.append("ruta", "varios");
    formData.append("modulo", sessionStorage.getItem('modulo').toLowerCase());
    formData.append("tipo", sessionStorage.getItem('tipo'));

    if (sessionStorage.getItem('tipo') === "p" || sessionStorage.getItem('tipo') === "d") {
        formData.append("ide", file.name);
    }

    XHR.upload.addEventListener("progress", progressHandler, false);
    XHR.addEventListener("load", completeHandler, false);
    XHR.addEventListener("error", errorHandler, false);
    XHR.addEventListener("abort", abortHandler, false);

    XHR.open("POST", "subir.php");
    XHR.send(formData);

    XHR.onreadystatechange = function () {
        console.log(this.responseText);
    };
}

function progressHandler(event) {
    _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
    const percent = (event.loaded / event.total) * 100;
    _("progressBar").value = Math.round(percent);
    _("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
}

function completeHandler(event) {
    _("status").innerHTML = event.target.responseText;
    _("progressBar").value = 0;
}

function errorHandler(event) {
    _("status").innerHTML = "Upload Failed";
}

function abortHandler(event) {
    _("status").innerHTML = "Upload Aborted";
}

function _(el) {
    return document.getElementById(el);
}