/**
 * Admin File Upload Functionality
 * This file contains the JavaScript for handling file uploads in the admin panel
 */

function setupFileUploader(inputId, previewId, uploadAreaId) {
    const fileInput = document.getElementById(inputId);
    const previewElement = document.getElementById(previewId);
    const uploadArea = document.getElementById(uploadAreaId);
    const placeholder = uploadArea.querySelector('.file-upload-placeholder');
    
    // Handle file selection
    fileInput.addEventListener('change', function() {
        handleFileSelect(this.files, previewElement, placeholder);
    });
    
    // Handle drag and drop
    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        this.classList.add('dragover');
    });
    
    uploadArea.addEventListener('dragleave', function(e) {
        e.preventDefault();
        this.classList.remove('dragover');
    });
    
    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        this.classList.remove('dragover');
        handleFileSelect(e.dataTransfer.files, previewElement, placeholder);
        fileInput.files = e.dataTransfer.files; // Update the file input
    });
}

function handleFileSelect(files, previewElement, placeholder) {
    if (files.length > 0) {
        const file = files[0];
        
        // Show preview
        const reader = new FileReader();
        reader.onload = function(e) {
            const previewImg = previewElement.querySelector('img');
            previewImg.src = e.target.result;
            
            const fileName = previewElement.querySelector('.file-name');
            fileName.textContent = file.name;
            
            placeholder.style.display = 'none';
            previewElement.style.display = 'block';
        };
        
        reader.readAsDataURL(file);
    }
}

// Setup remove buttons
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.remove-file').forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('data-target');
            const fileInput = document.getElementById(targetId);
            const previewId = targetId + 'Preview';
            const uploadAreaId = targetId + 'Upload';
            
            // Clear the file input
            fileInput.value = '';
            
            // Hide the preview and show the placeholder
            document.getElementById(previewId).style.display = 'none';
            const placeholder = document.querySelector(`#${uploadAreaId} .file-upload-placeholder`);
            placeholder.style.display = 'flex';
        });
    });
});