// Edocman Lite Media Uploader

jQuery(document).ready(function($) {
    var mediaUploader;
    
    $('.upload-media-button, #upload_category_image_button, #upload_document_image_button').on('click', function(e) {
        e.preventDefault();
        
        var button = $(this);
        var buttonId = button.attr('id');
        var targetInput, previewDiv;
        
        // Determine target input and preview based on button
        if (buttonId === 'upload_category_image_button') {
            targetInput = '#category_image';
            previewDiv = '#category_image_preview';
        } else if (buttonId === 'upload_document_image_button') {
            targetInput = '#document_image';
            previewDiv = '#document_image_preview';
        } else {
            targetInput = button.data('target');
            previewDiv = button.data('preview');
        }
        
        // Create media uploader
        if (mediaUploader) {
            mediaUploader.open();
            return;
        }
        
        mediaUploader = wp.media({
            title: 'Select Image',
            button: {
                text: 'Use This Image'
            },
            multiple: false
        });
        
        mediaUploader.on('select', function() {
            var attachment = mediaUploader.state().get('selection').first().toJSON();
            $(targetInput).val(attachment.url);
            
            // Update preview
            if (previewDiv) {
                $(previewDiv).html('<img src="' + attachment.url + '" style="max-width: 150px;">');
            }
        });
        
        mediaUploader.open();
    });
});
