<?php
// Add custom columns to the media library table
function custom_media_columns($columns) {
    $columns['assign_media_category'] = 'Assign_media_category';
    return $columns;
}
add_filter('manage_media_columns', 'custom_media_columns');
// Populate custom column with data
function custom_media_column_content($column_name, $post_id) {
    if ($column_name == 'assign_media_category') {
        $terms = get_the_terms($post_id, 'media-category');
        $media_category_list = '';
        // Get top-level media categories
        $top_level_categories = get_terms('media-category', array('parent' => 0, 'hide_empty' => false));



        if (!empty($top_level_categories)) {
          foreach ($top_level_categories as $top_category) {
            $checked_top = in_array($top_category->term_id, wp_list_pluck($terms, 'term_id')) ? 'checked' : '';

            $media_category_list .= '<div class="term">';
            $media_category_list .= '<label><input type="checkbox" name="media_category[]" value="' . $top_category->term_id . '" ' . $checked_top . ' />' . esc_html($top_category->name) . '</label>';
            $media_category_list .= nest_terms($top_category->term_id, $all_categories, $terms);
            $media_category_list .= '</div>';
          }
        }
		

        // Output the accordion
        echo '<div class="accordion">';
        echo '<h3 class="accordion-title">Update Media Categories</h3>';
        echo '<div class="accordion-content">';
        echo '<div class="media_category_list">' . $media_category_list . '</div>';
        // echo '<button class="button" data-post-id="' . esc_attr($post_id) . '">Save</button>';
        echo '<a href="#" class="button xyz" data-post-id="' . esc_attr($post_id) . '">Save</a>';
        echo '</div>'; // close accordion-content
        echo '</div>'; // close accordion
    }
}
// Recursive function to nest terms
function nest_terms($term_id, $terms, $checked_terms) {
    $nested_terms = '';

    $child_terms = get_terms('media-category', array('parent' => $term_id, 'hide_empty' => false));

    if (!empty($child_terms)) {
        foreach ($child_terms as $child_term) {
            $checked_child = in_array($child_term->term_id, wp_list_pluck($checked_terms, 'term_id')) ? 'checked' : '';
            $nested_terms .= '<div class="term child">';
            $nested_terms .= '<label><input type="checkbox" name="media_category[]" value="' . $child_term->term_id . '" ' . $checked_child . ' />' . esc_html($child_term->name) . '</label>';
            $nested_terms .= nest_terms($child_term->term_id, $terms, $checked_terms);
            $nested_terms .= '</div>';
        }
    }

    return $nested_terms;
}
add_action('manage_media_custom_column', 'custom_media_column_content', 10, 2);

// Add AJAX action in your theme's functions.php
function save_post_data() {
    // Check nonce for security
    if (isset($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], 'ajax-nonce')) {
        // Get and sanitize the post ID
        $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;

        // Get the selected media category term IDs
        $selected_categories = isset($_POST['media_category']) ? array_map('absint', $_POST['media_category']) : array();

        // Update the post with the new terms
        wp_set_post_terms($post_id, $selected_categories, 'media-category', false);

        // Send a response (you can modify this based on your needs)
        echo json_encode(array('success' => true));
    } else {
        // Send a response for failed nonce verification (you can modify this based on your needs)
        echo json_encode(array('success' => false, 'message' => 'Nonce verification failed.'));
    }

    // Always exit to avoid extra output
    exit();
}
add_action('wp_ajax_save_post_data', 'save_post_data');


// Output the script in the admin footer
function output_custom_script_in_admin_footer() {
    ?>
	<style>
		h3.accordion-title {
    font-size: 13px;
    text-decoration: underline;
    text-align: center;
    display: inline;
    cursor: pointer;
}

.accordion {
    border: 1px solid black;
    padding: 5px;
    background: #ebcfcf;
}
		.term.child {
    margin-left: 10px;
}
	</style>
    <script>
        jQuery(document).ready(function($) {
			$('.accordion-content').hide();
			$('.accordion-title').click(function() {
        		$(this).next('.accordion-content').slideToggle();
    		});
        // Attach click event to the button
        $('.button.xyz').on('click', function(e) {
            e.preventDefault();

            // Get the post ID from the data attribute
            var post_id = $(this).data('post-id');

            // Get the selected media category term IDs
            var selected_categories = [];
            $(this).parent().find('input[name="media_category[]"]:checked').each(function() {
                selected_categories.push($(this).val());
            });

            // AJAX request
            $.ajax({
                type: 'POST',
                url: '<?php echo admin_url('admin-ajax.php'); ?>',
                data: {
                    action: 'save_post_data',
                    nonce: '<?php echo wp_create_nonce('ajax-nonce'); ?>',
                    post_id: post_id,
                    media_category: selected_categories
                },
                success: function(response) {
                    // Handle the response (you can modify this based on your needs)
                    var data = JSON.parse(response);
                    if (data.success) {
                        alert('Data saved successfully!');
                    } else {
                        alert('Failed to save data. ' + data.message);
                    }
                },
                error: function(error) {
                    console.log(error);
                }
            });
        });
    });
    </script>
    <?php
}
add_action('admin_footer', 'output_custom_script_in_admin_footer');

?>