<?php
/**
 * Wiaas Linked Packages Editor
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
?>

<script type="text/javascript">
    jQuery(document).ready(function ($) {

        $( '.wiaas-search-documents' ).each(function() {
            var element = $( this );
            var searchTarget = $('#' + element.data('target'));

            element.autocomplete({
                source: function(request, response) {
                    $.get( window.ajaxurl, {
                        action: 'wiaas_json_search_documents',
                        query: request.term,
                        _ajax_nonce: '<?php echo wp_create_nonce('wiaas_json_search_documents') ?>'
                    } ).done( function( documents ) {
                            response( documents || []);
                        }
                    );
                },
                select: function(event, ui) {
                    if (!searchTarget || $('#wiaas_attached_document_' + ui.item.id).length) {
                        return;
                    }

                    $.get(window.ajaxurl, {
                        action: 'wiaas_link_document',
                        _ajax_nonce: '<?php echo wp_create_nonce('wiaas_link_document') ?>',
                        id: ui.item.id
                    }).done( function (document) {
                        searchTarget.find('tbody').append(document);
                    });

                }
            })
                .autocomplete( 'instance' )._renderItem = function( ul, item ) {
                return $( '<li role="option" id="wiaas-document-autocomplete-' + item.id + '">' )
                    .text( item.name )
                    .appendTo( ul );
            };
        });

        $('#wiaas_attached_documents').delegate('.wiaas-remove-attached-document', 'click', function (e) {
            e.preventDefault();

            var id = $(this).data('id');

            $('#wiaas_attached_document_' + id).remove();
        });

    });
</script>

<div id="wiaas_documents" class="panel woocommerce_options_panel">
    <div class="options_group">
        <p class="form-field">
            <label style="font-weight: bold;" for="wiaas_addon_packages"><?php esc_html_e( 'Search documents:', 'wiaas' ); ?></label>
            <input type="text" data-target="wiaas_attached_documents" class="wiaas-search-documents"/>
        </p>
    </div>
    <div class="options_group">
        <div class="form-field">
            <div style="margin:20px">
                <table id="wiaas_attached_documents" class="widefat wp-list-table">
                    <tbody>
                    <?php
                        foreach ($documents_ids as $id) {
                            require 'html-attached-document.php';
                        }
                    ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
