jQuery(document).ready(function($) {

    var custom_uploader;

    $('.upload-propdb-media').click(function(e) {
        e.preventDefault();

        // If the uploader object has already been created, reopen the dialog
        if (custom_uploader) {
            custom_uploader.open();
            return;
        }

        // Extend the wp.media object
        custom_uploader = wp.media.frames.file_frame = wp.media({
            title: 'Select or Upload Media',
            button: {
                text: 'Use this media'
            },
            multiple: true  // Set this to true if you want to allow multiple file selections
        });

        // When a file is selected, grab the URL and set it as the text field's value
        custom_uploader.on('select', function() {
            var attachment = custom_uploader.state().get('selection').first().toJSON();
            
            var data = {
                action: 'associate_media_with_post',
                media_id: attachment.id,
                post_id: YOUR_POST_ID_HERE // Replace with your post ID or fetch dynamically
            };

            $.post(ajaxurl, data, function(response) {
                alert('Media associated with the post!');
            });

        });

        // Open the uploader dialog
        custom_uploader.open();
    });

});
