/**
 * Sifency CPT Select2 Quick Category Update Script
 * Handles select2 initialization and taxonomy terms updating via AJAX.
 *
 * @package Sifency
 * @since 1.0.4
 */

jQuery(window).on('load', function() {
    var $ = jQuery;
    
    $('.sifency-select2-update').each(function(){
        $(this).select2({ 
            placeholder: 'Select Category', 
            tags: true, 
            tokenSeparators: [','], 
            allowClear: true, 
            width: '100%' 
        });
    });

    $('.sifency-select2-update').on('change', function(e) {
        var select = $(this);
        select.prop('disabled', true);
        $.ajax({
            url: sifency_cpt_select2.ajax_url, 
            type: 'POST',
            data: {
                action: 'sifency_update_cpt_terms',
                post_id: select.data('post-id'), 
                taxonomy: select.data('tax'), 
                terms: select.val(),
                nonce: sifency_cpt_select2.nonce
            },
            success: function(response) {
                select.prop('disabled', false);
                if(response.success) {
                    var container = select.next('.select2-container').find('.select2-selection');
                    container.css('border-color', '#46b450');
                    setTimeout(function(){ container.css('border-color', '#e2e4e7'); }, 1500);
                }
            },
            error: function() { 
                select.prop('disabled', false); 
            }
        });
    });
});
