// Initialize Dropzone for image upload
Dropzone.autoDiscover = false; // Prevent Dropzone from auto-attaching to all elements

const dropzone = new Dropzone("#image-upload", {
    url: "<?= $this->Url->build(['controller' => 'Contents', 'action' => 'uploadImage']) ?>", // URL for uploading new images
    addRemoveLinks: true,
    init: function() {
        let dropzoneInstance = this;

        // Load existing images
        <?php foreach ($images as $image): ?>
            let mockFile = { 
                name: "<?= h($image->image_path) ?>", 
                size: 12345, // Estimated size if you don’t know it
                serverId: <?= $image->id ?> // Pass server ID for AJAX removal
            };

            // Add the mock file to Dropzone
            dropzoneInstance.emit("addedfile", mockFile);
            dropzoneInstance.emit("thumbnail", mockFile, "<?= Cake\Core\Configure::read('IMAGE_PREPATH') . $image->image_path ?>");
            dropzoneInstance.emit("complete", mockFile);
        <?php endforeach; ?>

        // Handle file removal
        dropzoneInstance.on("removedfile", function(file) {
            if (file.serverId) { // Only make AJAX call for files with a server ID
                removeImage(file.serverId);
            }
        });
    }
});

// AJAX function to remove image from server
function removeImage(imageId) {
    $.ajax({
        url: "<?= $this->Url->build(['controller' => 'Contents', 'action' => 'removeImage']) ?>/" + imageId,
        type: 'GET',
        success: function() {
            console.log('Image deleted from server.');
        },
        error: function(xhr, status, error) {
            console.error('Error deleting image:', error);
            alert('Failed to delete the image. Please try again.');
        }
    });
}
