{% extends "users/base.html" %}
{% block title %}Import Database{% endblock title %}
{% block content %}

 <div class="card card-default">
      <div class="card-header">
        <h2>Import Database ({{db}})</h2>
		
        

      </div>
    
   <div class="card-body">
   <div class="row">
   

	</div>
<div class="table-responsive">
    
	
	
	</div>
   <div class="form-group">
            <label for="exampleFormControlFile1">Sql file</label>
            <input type="file" class="form-control-file" id="file-input">
          </div>
		  <div class="form-group">
		   <div id="file-preview" class="file-preview"></div>
		   </div>
	<div class="form-group">	   
<button type="submit" class="btn btn-primary btn-sm" id="upload-button">Import</button>
</div>
</div>
</div>
<style>

.progress-container {
    margin-top: 5px;
    height: 20px;
    background: #e0e0e0; /* Default grey background */
    border: 1px solid #ddd;
    border-radius: 3px;
    position: relative;
    overflow: hidden;
    width: 200px; /* Default width for PC */
}

.progress-bar {
    height: 100%;
    width: 0%; /* Starts empty */
    background: #4CAF50; /* Green by default for success */
    border-radius: 3px;
    transition: width 0.4s ease; /* Smooth width transition */
}

.progress-bar.failed {
    background: #f44336; /* Red for failure */
}

.progress-percentage {
    position: absolute;
    top: 2px;
    right: 5px;
    font-size: 12px;
    color: #fff;
}
@media (max-width: 768px) {
    .progress-container {
        width: 70px; /* Reduced width for mobile */
    }
}

</style>
<script>
const csrfToken = "{{ csrf_token }}";
const actionUrl = "{% url 'upload_db' db %}";
const fileInput = document.getElementById('file-input');
fileInput.addEventListener('change', handleFiles);
function uploadFile(file, index) {
     const formData = new FormData();
    formData.append('file', file);
   
    const fileId = `file-${file.name.replace(/[^a-zA-Z0-9]/g, '-')}`;
    const progressBar = $(`#${fileId} .progress-bar`);
    const progressPercentage = $(`#${fileId} .progress-percentage`);

    $.ajax({
        url: actionUrl, // Django URL name for the upload view
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        headers: { "X-CSRFToken": csrfToken },
        xhr: function () {
            const xhr = new window.XMLHttpRequest();
            xhr.upload.addEventListener('progress', function (e) {
                if (e.lengthComputable) {
                    const percentComplete = Math.round((e.loaded / e.total) * 100);
                    progressBar.css('width', `${percentComplete}%`);
                    progressPercentage.text(`${percentComplete}%`);
                }
            }, false);
            return xhr;
        },
        success: function (response) {
            progressBar.css('background', 'green'); // Set to green on success
            progressPercentage.text('Complete'); // Optionally update text
			
        },
        error: function (xhr, status, error) {
            progressBar.addClass('failed'); // Set to red on failure
            progressPercentage.text('Failed'); // Optionally update text
            
           
        }
    });
}


$('#upload-button').on('click', function () {
    const files = $('#file-input')[0].files;
    if (files.length === 0) {
        alert('Please select files to upload.');
        return;
    }

    Array.from(files).forEach((file, index) => {
        uploadFile(file, index);
    });
});


// Function to handle files selected or dropped
function handleFiles(event) {
    const files = event.target.files || event.dataTransfer.files;
    const filePreview = document.getElementById('file-preview');
    filePreview.innerHTML = Array.from(files)
        .map(file => {
            const fileId = `file-${file.name.replace(/[^a-zA-Z0-9]/g, '-')}`;
            return `
                <div class="file-item" id="${fileId}">
                    <p>${file.name} (${Math.round(file.size / 1024)} KB)</p>
                    <div class="progress-container">
                        <div class="progress-bar" style="width: 0%;"></div>
                        <span class="progress-percentage">0%</span>
                    </div>
                </div>
            `;
        })
        .join('');
}
</script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
{% endblock content %}

{% include "users/footer.html" %}