<style>
#dropZone {
    border: 2px dashed #007BFF;
    padding: 30px;
    text-align: center;
    color: #6C757D;
    cursor: pointer;
}

#dropZone.dragover {
    background-color: #E9F5FF;
}

.preview {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.preview-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    border: 1px solid #ccc;
    padding: 5px;
    border-radius: 5px;
}

.preview-item img {
    max-width: 100px;
    max-height: 100px;
    margin-bottom: 5px;
}

.preview-item button {
    background-color: #f44336;
    color: white;
    border: none;
    padding: 4px 8px;
    border-radius: 4px;
    cursor: pointer;
}

.preview-item button:hover {
    background-color: #d32f2f;
}
</style>
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <div class="img-profile ml-3">

                </div>
                <h1 class="m-0 text-dark">Add Images (<?=$label?>)</h1>

            </div><!-- /.col -->
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?= base_url(); ?>dashboard/userimages">User Images</a></li>
                    <li class="breadcrumb-item active">Add Images</li>
                </ol>
            </div><!-- /.col -->
        </div><!-- /.row -->
    </div><!-- /.container-fluid -->
</div>
<!-- <form method="post" id="userImages" class="card" action="<?php echo base_url() . "dashboard/saveimages"?>" enctype="multipart/form-data"> -->
<form id="userImages" class="card" enctype="multipart/form-data">
    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="card-body">


                <div class="row">

                    <div class="col-12">
                        <label class="form-label"><?=$label?></label>
                        <div class="form-group">
                            <div id="dropZone" class="mb-3">
                                Drag & drop files here or click to browse
                                <input type="file" id="<?=$type?>" name="<?=$type?>" multiple hidden />
                            </div>
                            <div id="imageList" class="mb-3 preview"></div>
                            <!-- <div id="preview" class="mb-3 list-group"></div> -->
                        </div>
                    </div>


                </div>

            </div>

        </div>
    </section>
    <!-- /.content -->


    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">

            <div class="card-footer text-right">

                <button type="submit" class="btn btn-primary">Add Images</button>
            </div>
        </div>
    </section>
    <!-- /.content -->
</form>
<script>
const dropZone = document.getElementById("dropZone");
const fileInput = document.getElementById("<?=$type?>");
const imageList = document.getElementById("imageList");
let selectedFiles = [];

function renderPreview() {
    imageList.innerHTML = '';

    selectedFiles.forEach((file, index) => {
        const reader = new FileReader();
        const item = document.createElement('div');
        item.className = 'preview-item';

        reader.onload = (e) => {
            const img = document.createElement('img');
            img.src = e.target.result;
            item.appendChild(img);
        };

        reader.readAsDataURL(file);

        const caption = document.createElement('div');
        caption.textContent = file.name;
        item.appendChild(caption);

        const removeBtn = document.createElement('button');
        removeBtn.textContent = 'Remove';
        removeBtn.onclick = () => {
            selectedFiles.splice(index, 1);
            renderPreview();
        };

        item.appendChild(removeBtn);
        imageList.appendChild(item);
    });
}
// Click to open file dialog
dropZone.addEventListener("click", () => fileInput.click());
// Files selected via file input
fileInput.addEventListener("change", (e) => {
    const files = Array.from(e.target.files);
    if (files.length >= 5) {
        alert('You can only select up to 5 images.');
        return;
    }
    let error = false;
    files.forEach(file => {
        if (!file.type.startsWith('image/')) {
            error = true;
            alert(`File "${file.name}" is not an image.`);
            return;
        }
    });
    if (error) {
        return;
    }
    selectedFiles = files;
    renderPreview();
});
// Drag & drop events
dropZone.addEventListener("dragover", (e) => {
    e.preventDefault();
    dropZone.classList.add("dragover");
});
dropZone.addEventListener("dragleave", () => {
    dropZone.classList.remove("dragover");
});
dropZone.addEventListener("drop", (e) => {
    e.preventDefault();

    dropZone.classList.remove("dragover");
    const files = Array.from(e.dataTransfer.files);
    if (files.length > 10) {
        alert('You can only select up to 5 images.');
        return;
    }

    let error = false;
    files.forEach(file => {
        if (!file.type.startsWith('image/')) {
            error = true;
            alert(`File "${file.name}" is not an image.`);
            return;
        }
    });
    if (error) {
        return;
    }
    // selectedFilesMaleLight = selectedFilesMaleLight.concat(files);
    selectedFiles = files;
    renderPreview();
});

// Form submit
document
    .getElementById("userImages")
    .addEventListener("submit", function(e) {
        e.preventDefault();

        if (
            selectedFiles.length === 0

        ) {
            alert("Please select or drop at least one file.");
            return;
        }

        const formData = new FormData();
        selectedFiles.forEach((file, index) => {
            formData.append("<?=$type?>[]", file);
        });

        $("body").addClass("loading");

        fetch('<?=base_url('dashboard/saveimages')?>', {
                method: 'POST',
                body: formData
            }).then(res => res.json())
            .then(data => {

                $("body").removeClass("loading");

                selectedFiles = [];

                renderPreview();

                const Toast = Swal.mixin({
                    toast: true,
                    position: 'top',
                    showConfirmButton: false,
                    timer: 5000
                });
                Toast.fire({
                    type: 'success',
                    title: 'New images added successfully'
                });
            })
            .catch(err => console.error('Error:', err));
    });
</script>