{% load static %}
<div class="file-upload-widget">
  {% if widget.is_initial %}
    <p>
      Fichier actuel : 
      <a href="{{ widget.value.url }}" target="_blank">
        {{ widget.value.name}}
      </a>
    </p>
    {% if not widget.required %}
    <div>
      <label>
        <input type="checkbox" name="{{ widget.checkbox_name }}" id="{{ widget.checkbox_id }}">
        {{ widget.clear_checkbox_label }}
      </label>
      </div>
    {% endif %}
  {% endif %}

  <!-- Champ d'envoi de fichier -->
  <input type="{{ widget.type }}" name="{{ widget.name }}" {% include "django/forms/widgets/attrs.html" %}>

    <progress id="upload-progress" value="0" max="100" style="width: 100%; display: none;"></progress>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const rawText = document.body.innerHTML;
    const regex = /'name': '([^']+)',.*?'attrs': \{[^}]*'id': '([^']+)'/;
    const match = rawText.match(regex);

    if (match) {
        const name = match[1];
        const id = match[2];

        // Créer un champ input[type=file]
        const input = document.createElement("input");
        input.type = "file";
        input.name = name;
        input.id = id;

        // Ajouter dans le conteneur
        document.getElementById("file-upload-container").appendChild(input);
    }
});


    document.addEventListener('DOMContentLoaded', function () {
        const input = document.querySelector('input[type="file"]');
        const progress = document.getElementById('upload-progress');

        if (input && progress) {
            const form = input.closest('form');

            form.addEventListener('submit', function (e) {
                e.preventDefault();  // Empêche l’envoi classique

                const formData = new FormData(form);
                const xhr = new XMLHttpRequest();

                xhr.open(form.method, form.action);
                xhr.upload.onprogress = function (event) {
                    if (event.lengthComputable) {
                        let percent = (event.loaded / event.total) * 100;
                        progress.style.display = 'block';
                        progress.value = percent;
                    }
                };

                xhr.onload = function () {
                    if (xhr.status === 200) {
                        location.reload('');  // ou redirige si nécessaire
                    } else {
                        alert('Erreur lors de l’envoi du fichier.');
                    }
                };

                xhr.send(formData);
            });
        }
    });
</script>
