// Edocman Lite Admin JavaScript

jQuery(document).ready(function($) {
    
    // Media Uploader for Category Image
    var categoryImageFrame;
    $('#upload_category_image_button').on('click', function(e) {
        e.preventDefault();
        
        if (categoryImageFrame) {
            categoryImageFrame.open();
            return;
        }
        
        categoryImageFrame = wp.media({
            title: 'Select Category Image',
            button: {
                text: 'Use this image'
            },
            multiple: false
        });
        
        categoryImageFrame.on('select', function() {
            var attachment = categoryImageFrame.state().get('selection').first().toJSON();
            $('#category_image').val(attachment.url);
            $('#category_image_preview').html('<img src="' + attachment.url + '" style="max-width: 150px;">');
        });
        
        categoryImageFrame.open();
    });
    
    // Media Uploader for Document Image
    var documentImageFrame;
    $('#upload_document_image_button').on('click', function(e) {
        e.preventDefault();
        
        if (documentImageFrame) {
            documentImageFrame.open();
            return;
        }
        
        documentImageFrame = wp.media({
            title: 'Select Document Thumbnail',
            button: {
                text: 'Use this image'
            },
            multiple: false
        });
        
        documentImageFrame.on('select', function() {
            var attachment = documentImageFrame.state().get('selection').first().toJSON();
            $('#document_image').val(attachment.url);
            $('#document_image_preview').html('<img src="' + attachment.url + '" style="max-width: 150px;">');
        });
        
        documentImageFrame.open();
    });
    
    // Confirm delete actions
    $('.delete-category, .delete-document').on('click', function(e) {
        if (!confirm('Are you sure you want to delete this item?')) {
            e.preventDefault();
            return false;
        }
    });
    
    // Form validation
    $('form').on('submit', function(e) {
        var title = $('#title').val();
        if (title.trim() === '') {
            alert('Please enter a title.');
            e.preventDefault();
            return false;
        }
    });
});
