<?php 
dike_lc('lcweb', 'gg', true);
?>
<div class="wrap gg_form">  
    <h2 class="gg_page_title"><?php esc_html_e('Collections Manager', 'gg_ml') ?></h2>  

    <div id="poststuff" class="metabox-holder has-right-sidebar">
    	
        
        
        <?php // SIDEBAR ?>
        <div id="side-info-column" class="inner-sidebar">
            <form class="form-wrap">	
                
                <div id="add_coll_box" class="postbox gg_sidebox_meta">
                    <h3 class="hndle"><?php esc_html_e('Add Collection', 'gg_ml') ?></h3> 
                    <div class="inside">
                        <div class="misc-pub-section-last">
                            <input type="text" name="gg_coll_name" value="" maxlenght="150" placeholder="<?php esc_attr_e('Collection name', 'gg_ml') ?>" autocomplete="off" />
                            <input type="button" name="add_coll_btn" value="<?php esc_attr_e('Add', 'gg_ml') ?>" class="button-primary" />
                        </div>  
                    </div>
                </div>

                <div id="man_coll_box" class="postbox gg_sidebox_meta">
                    <h3 class="hndle"><?php esc_html_e('Collections List', 'gg_ml') ?></h3> 
                    
                    <div class="gg_coll_search">
                        <input type="text" name="gg_coll_search" value="" placeholder="🔎 <?php esc_attr_e('search collections', 'gg_ml') ?>" autocomplete="off" />
                        <span class="dashicons dashicons-no-alt" title="<?php esc_attr_e('clear search', 'gg_ml') ?>"></span>
                    </div>
                    <div class="inside"></div>
                </div>

                <div id="save_coll_box" class="postbox gg_sidebox_meta">
                    <input type="button" name="save-coll" value="<?php esc_attr_e('Save Collection', 'gg_ml') ?>" class="button-primary" />

                    <?php if(get_option('gg_preview_pag')) : ?>
                    <input type="button" name="preview-coll" value="<?php esc_attr_e('Preview', 'gg_ml') ?>" data-baseurl="<?php echo esc_attr(get_permalink(get_option('gg_preview_pag'))) ?>?gg_cid=" class="button-secondary" />
                    <?php endif; ?>

                    <div class="gg_save_coll_spinner_box"></div>
                </div>
            </form>	
        </div>
    	
        
        
        <?php // PAGE CONTENT ?>
        <form class="form-wrap" id="coll_items_list">  
          <div id="post-body">
          <div id="post-body-content" class="gg_coll_content">
              <p><?php esc_html_e('Select a collection', 'gg_ml') ?> ..</p>
          </div>
          </div>
        </form>
        
        <br class="clear">
    </div>
    
</div>  



<?php // SCRIPTS ?>
<script type="text/javascript">
(function($) {
    "use strict"; 
    
    const gg_nonce = '<?php echo esc_js(wp_create_nonce('gg_coll_builder')) ?>';
    let gg_sel_coll = 0;
    
    
    $(document).ready(function($) {
        gg_load_colls();

        
        // add collection
        $('input[name="add_coll_btn"]').click(function() {
            var coll_name = $('input[name="gg_coll_name"]').val();

            if($.trim(coll_name)) {
                var data = {
                    action      : 'gg_add_coll',
                    coll_name   : coll_name,
                    nonce       : gg_nonce,
                };

                $.post(ajaxurl, data, function(response) {
                    var resp = $.trim(response); 

                    if(resp == 'success') {
                        lc_wp_popup_message('success', `<?php esc_html_e('Collection added', 'gg_ml') ?>`);
                        $('#add_coll').val('');
                        
                        gg_load_colls();
                    }
                    else {
                        lc_wp_popup_message('error', resp);
                    }
                });	
            }
        });
        
        
        
        // search collection
        let coll_search_tout = false;
        $(document).on('keyup', ".gg_coll_search input", function(e) {
            if(e.keyCode === 13) {
                e.preventDefault();
                return false;
            }
            const val = $(this).val().trim();
            
            if(coll_search_tout) {
                clearTimeout(coll_search_tout);
            }
            coll_search_tout = setTimeout(function() {
                
                if(val.length < 2) {
                    $('#man_coll_box .inside > div').removeClass('gg_displaynone');
                    $('.gg_coll_search .dashicons').addClass('gg_displaynone');
                }
                else {
                    $('.gg_coll_search .dashicons').removeClass('gg_displaynone');
                    
                    $('#man_coll_box .inside > div').each(function() {
                        const to_match = $(this).find('.gg_coll_tit').text().trim().toLowerCase();    
                        let matching = false;
                        
                        $.each( val.toLowerCase().split(' '), function(i, word) {
                            if(to_match.indexOf(word) !== -1) {
                                matching = true;
                                return true;    
                            }
                        });
                        
                        (matching) ? $(this).removeClass('gg_displaynone') : $(this).addClass('gg_displaynone');
                    });
                }
            }, 500); 
        });
                
        
        // clear search
        $(document).on('click', ".gg_coll_search .dashicons", function(e) {
            $('.gg_coll_search input').val('').trigger('keyup');    
        });
        
        
        
        // select collection
        $(document).on("click", '#man_coll_box input[type=radio]', function() {

            const val = parseInt($(this).val(), 10);
            if(gg_sel_coll == val) {
                return false;    
            }
            
            gg_sel_coll = val;
            var coll_title = $(this).parent().siblings('.gg_coll_tit').text();

            $('.gg_coll_content').html('<div class="gg_spinner gg_spinner_big"></div>');

            var data = {
                action  : 'gg_coll_builder',
                coll_id : gg_sel_coll,
                nonce   : gg_nonce,
            };

            $.post(ajaxurl, data, function(response) {
                $('.gg_coll_content').html(response);

                // add the title
                $('.gg_coll_content > h2').html(coll_title);

                // save coll box
                $('#save_coll_box').fadeIn();

                gg_live_lc_select();
                gg_live_lc_switch();
                gg_live_sort();
            });	
        });
        
        
        
        // delete collection
        $(document).on('click', '.gg_del_coll', function() {
            const $target_coll_wrap = $(this).parent(); 
            var coll_id  = parseInt($(this).data('id'), 10);

            if(confirm(`<?php esc_html_e('Definitively delete collection?', 'gg_ml') ?>`)) {
                $target_coll_wrap.fadeTo(200, 0.6);
                
                var data = {
                    action  : 'gg_del_coll',
                    coll_id : coll_id,
                    nonce   : gg_nonce
                };

                $.post(ajaxurl, data, function(response) {
                    var resp = $.trim(response); 

                    if(resp == 'success') {
                        // if is this one opened
                        if(gg_sel_coll == coll_id) {
                            $('.gg_coll_content').html(`<p><?php esc_html_e('Select a collection', 'gg_ml') ?> ..</p>`);
                            gg_sel_coll = 0;

                            // savecoll box
                            $('#save_coll_box').fadeOut();
                        }

                        $target_coll_wrap.slideUp(function() {
                            $(this).remove();

                            if( !$('#man_coll_box .inside .misc-pub-section-last').length) {
                                $('#man_coll_box .inside').html(`<p><?php esc_html_e('No existing collections', 'gg_ml') ?></p>`);
                            }
                        });	
                    }
                    else {
                        $target_coll_wrap.fadeTo(200, 1);
                        lc_wp_popup_message('error', resp);
                    }
                });
            }
        });
        
        
        
        
        //////////////////////////////////////////////////////////////////
        

        
        
        // custom main image - media image  manager 
        let file_frame = false;

        $(document).on('click', '.gg_coll_cust_img_btn', function(e) {
            if($(e.target).hasClass('gg_coll_del_cust_img_btn')) {
                return false;
            }

            var $wrap = $(this).parents('td');
            var $btn = $(this);

            // Create the media frame
            file_frame = wp.media.frames.file_frame = wp.media({
              title: `Global Gallery - <?php esc_html_e("custom main image", 'gg_ml') ?>`,
              button: {
                text: `<?php esc_html_e('Select', 'gg_ml') ?>`,
              },
              library : {type : 'image'},
              multiple: false
            });

            // When an image is selected, run a callback.
            file_frame.on('select', function() {
                var img_data = file_frame.state().get('selection').first().toJSON();

                $wrap.find('.gg_coll_cust_img').val(img_data.id);
                $wrap.css('background-image', 'url('+ img_data.url +')');
                $btn.addClass('gg_coll_cust_img_sel');
            });

            file_frame.open();
        });



        // custom main image removal
        $(document).on('click', '.gg_coll_del_cust_img_btn', function() {
            var $wrap = $(this).parents('td');
            var $btn = $(this).parents('.gg_coll_cust_img_btn');

            if(confirm(`<?php esc_html_e("Remove custom gallery main image?", 'gg_ml') ?>`)) {
                $wrap.find('.gg_coll_cust_img').val('');
                $btn.removeClass('gg_coll_cust_img_sel');
                $wrap.css('background-image', 'url('+ $(this).attr('orig-img') +')');
            }

            return false;
        });

        


        /////////////////////////////////////////////////////////////

        


        // galleries cat choose
        $(document).on("change", 'select[name="gg_gall_cats"]', function() {
            var item_cats = $(this).val();	
            var data = {
                action      : 'gg_cat_galleries_code',
                gallery_cat : item_cats,
                nonce       : gg_nonce,
            };

            $('.gg_dd_galls_preview').remove();
            $('#gg_coll_gall_picker').html('<div class="gg_spinner"></div>');

            $.post(ajaxurl, data, function(response) {
                if($.trim(response)) {
                    $('#gg_coll_gall_picker').html(response);
                } else {
                    $('#gg_coll_gall_picker').html(`<span><?php esc_html_e('No galleries found', 'gg_ml') ?> ..</span>`);
                }
            });	
        });
        
        
        
        // galleries search
        let gg_cgs_acting_tout = false;

        $(document).on('keyup', 'input[name="gg_coll_gall_search"]', function() {
            let src_string = $(this).val().trim();
                src_string = src_string.replace(',', '').replace('.', '').replace('?', ''); 
            
            if(gg_cgs_acting_tout) {
                clearTimeout(gg_cgs_acting_tout);
            }
            gg_cgs_acting_tout = setTimeout(function() {

                if(src_string.length > 2) {
                    $('.gg_cgs_del').removeClass('gg_displaynone');

                    var src_arr = src_string.toLowerCase().split(' ');
                    var matching = [];

                    // cyle and check eac searched term 
                    $('#gg_coll_gall_picker li').each(function(i, elem) {
                        $.each(src_arr, function(i, word) {	
                            ( $(elem).find('div').attr('title').toLowerCase().indexOf(word) !== -1 ) ? $(elem).removeClass('gg_displaynone') : $(elem).addClass('gg_displaynone');
                        });
                    });
                }
                else {
                    $('.gg_cgs_del').addClass('gg_displaynone');
                    $('#gg_coll_gall_picker li').removeClass('gg_displaynone');
                }
            }, 300);
        });
        
        
        // clear gallery search
        $(document).on('click', '.gg_cgs_del', function() {
            $('input[name="gg_coll_gall_search"]').val('').trigger('keyup');
        });



        // galleries picker - expand/compress
        $(document).on("click", '.gg_cgs_show_all', function() {	
            if($(this).hasClass('shown')) {
                $(this).removeClass('shown').text(`(<?php esc_html_e('expand', 'gg_ml') ?>)`);

                $('#gg_coll_gall_picker').css('max-height', '113px');
            }
            else {
                $(this).addClass('shown').text(`(<?php esc_html_e('collapse', 'gg_ml') ?>)`);
                $('#gg_coll_gall_picker').css('max-height', 'none');	
            }
        });


        
        // add gallery
        $(document).on("click", '#gg_coll_gall_picker li', function() {
            let gall_id       = $(this).data('id'),
                gall_title    = $(this).find('div').text(),
                gall_cats     = $.trim($(this).data('gg-cats')),
                gall_img      = $(this).data('gg-img');

            // check for already existing galleries
            if($('#gg_coll_builder tr#gg_coll_'+gall_id).length) {
                lc_wp_popup_message('error', gall_title +` - <?php esc_html_e('gallery already in collection', 'gg_ml') ?>`);
            }
            else {
                if(!$('#gg_coll_builder .gg_coll_gall_imgbox').length) {$('#gg_coll_builder > tbody').empty();}

                gall_cats = (gall_cats) ? `<em class="dashicons dashicons-tag gg_coll_gall_cats_icon" title="<?php esc_html_e('Categories', 'gg_ml') ?>"></em> `+gall_cats : `<em><?php esc_html_e('No associated categories', 'gg_ml') ?> ..</em>`;


                let new_tr = `<?php echo gg_coll_static::manual_gall_code_block() ?>`;
                    new_tr = new_tr
                                .replaceAll('%%GALL_ID%%', gall_id)
                                .replaceAll('%%THUMB_TO_USE%%', gall_img) 
                                .replaceAll('%%CUST-ICON_SEL_CLASS%%', '')
                                .replaceAll('%%CUST_IMG_ID%%', '')
                                .replaceAll('%%ORIG_THUMB%%', gall_img) 
                                .replaceAll('%%GALL_CATS%%', gall_cats) 
                                .replaceAll('%%GALL_TITLE%%', gall_title) 
                                .replaceAll('%%RANDOM_CHECK%%', '') 
                                .replaceAll('%%FILTER_CHECK%%', '')
                                .replaceAll('%%SEARCH_CHECK%%', '') 
                                .replaceAll('%%WATERM_CHECK%%', '')
                                .replaceAll('%%DESCR%%', '');
                
                $('#gg_coll_builder > tbody').append(new_tr);
                gg_live_lc_switch();
            }
        });



        // coll images linking management
        $(document).on('change', 'select.gg_linking_dd', function() {
            const link_opt = $(this).val();
            let link_field;

            if(link_opt == 'page') {
                link_field = `<?php echo gg_static::wp_kses_ext(gg_static::link_field('page')) ?>`;
            }
            else if(link_opt == 'custom') {
                link_field = `<?php echo gg_static::wp_kses_ext(gg_static::link_field('custom')) ?>`;
            }
            else {
                link_field = `<?php echo gg_static::wp_kses_ext(gg_static::link_field('none')) ?>`;	
            }

            $(this).parent().find('.gg_link_wrap').html(link_field);
            gg_live_lc_select();
        });



        // remove collection's gallery
        $(document).on("click", '.gg_del_gall', function() {
            if(!confirm(`<?php esc_html_e("Do you really want to remove this gallery from the collection?", 'gg_ml') ?>`)) {
                return false;
            }
                
            $(this).parents('.coll_component').fadeOut(function() {

                $(this).remove();
                if(!$('#gg_coll_builder tbody tr').length) {
                    $('#gg_coll_builder tbody').append(`<tr><td colspan="5"><?php esc_html_e("No galleries selected", 'gg_ml') ?> ..</td></tr>`);		
                }
            });
        });



        // save collection
        $(document).on("click", '#save_coll_box input', function() {
            const $btn = $(this);
            
            let gall_list 	= [],
                cust_img	= [],
                random_flag = [],
                filters_flag= [],
                search_flag	= [],
                wmark_flag 	= [],
                link_subj 	= [],
                link_val 	= [],
                coll_descr 	= [];

            // catch data
            $('#gg_coll_builder tr.coll_component').each(function() {
                var gid = parseInt($(this).data('id'), 10);

                gall_list.push(gid);
                cust_img.push( $(this).find('.gg_coll_cust_img').val() )
                coll_descr.push( $(this).find('.coll_descr').val() );

                var rand = ($(this).find('input[name=random]').is(':checked')) ? 1 : 0; 
                random_flag.push(rand);

                var filters = ($(this).find('input[name=tags_filter]').is(':checked')) ? 1 : 0; 
                filters_flag.push(filters);

                var search = ($(this).find('input[name=search]').is(':checked')) ? 1 : 0; 
                search_flag.push(search);

                var wmark = ($(this).find('input[name=watermark]').is(':checked')) ? 1 : 0; 
                wmark_flag.push(wmark);

                link_subj.push( $(this).find('.gg_linking_dd').val() );
                link_val.push( 
                    ($(this).find('.gg_linking_dd').val() != 'none') ? $(this).find('.gg_link_field').val() : '' 
                );
            });

            // ajax
            var data = {
                action: 		'gg_save_coll',
                nonce:          gg_nonce,
                
                coll_id: 		gg_sel_coll,
                gall_list: 		gall_list,
                cust_img:		cust_img,
                random_flag: 	random_flag,
                filters_flag: 	filters_flag,
                search_flag:	search_flag,
                wmark_flag:		wmark_flag,
                link_subj: 		link_subj,
                link_val:		link_val,
                coll_descr:		coll_descr
            };
            $btn.fadeTo(200, 0.5);

            $.post(ajaxurl, data, function(response) {
                var resp = $.trim(response); 			

                if(resp == 'success') {
                    lc_wp_popup_message('success', `<?php esc_html_e('Collection saved', 'gg_ml') ?>`);
                } else {
                    lc_wp_popup_message('error', resp);
                }
            })
            .always(function() {
                $btn.fadeTo(200, 1);    
            });	
        });

        // bind enter key
        $(document).on("keypress", "#add_coll", function(e) { 
            if(e.keyCode === 13){
                e.preventDefault();	
                $('#add_coll_btn').trigger('click');

                return false;
            }

        });



        
        /////////////////////////////////////////////////////////



        
        // collection preview
        $(document).on("click", 'input[name=preview-coll]', function(e) {
            const url = $(this).data('baseurl') + gg_sel_coll;
            window.open(url, '_blank', null);
        });



        // keep sidebar visible
        $(window).scroll(function() {
            var $subj = $('#side-info-column');

            if($subj.find('.postbox').length) {
                var side_h = $subj.outerHeight();
                var top_pos = $subj.parent().offset().top;
                var top_scroll = $(window).scrollTop();

                // if is higher that window - ignore
                if((top_pos + side_h + 44) >= $(window).height() || top_scroll <= top_pos) {
                    $subj.css('margin-top', 0);	
                }
                else {
                    $subj.css('margin-top', (top_scroll - top_pos + 44)); 	
                }	
            }
            else {
                $subj.css('margin-top', 0);	
            }
        });
    });
    
    
    
    
    
    /////////////////////////////////////////////////////////////////
    // FUNCTIONS
    
    // load collection list
    const gg_load_colls = function() {
        $('#man_coll_box .inside').html('<div class="gg_spinner"></div>');

        $.ajax({
            type: "POST",
            url: ajaxurl,
            data: "action=gg_get_colls&nonce="+ gg_nonce,
            dataType: "json",
            success: function(response){	
                $('#man_coll_box .inside').empty();
                $('.gg_coll_search input').val('');
                
                // no collections
                if(!response.length) {
                    $('#man_coll_box .inside').html(`<p><?php esc_html_e("No collections found", 'gg_ml') ?> ..</p>`);  
                    $(".gg_coll_search").addClass('gg_displaynone');
                    return false;
                }
                if(response.length > 10) {
                    $(".gg_coll_search").removeClass('gg_displaynone');
                }
                
                $.each(response, function(k, v) {	
                    var sel = (gg_sel_coll == v.id) ? 'checked="checked"' : '';

                    $('#man_coll_box .inside').append(
                    `<div class="misc-pub-section-last">
                        <span><input type="radio" name="gl" value="${ v.id }" ${ sel } /></span>
                        <span class="gg_coll_tit" title="<?php esc_attr_e('Collection', 'gg_ml') ?> #${ v.id }">${ v.name }</span>
                        <span class="gg_del_coll dashicons dashicons-no-alt" data-id="${ v.id }" title="<?php esc_attr_e('Delete collection', 'gg_ml') ?>"></span>
                    </div>`);
                });
            }
        });	
    };
    
    
    
    // sort opt
    const gg_live_sort = function() {
        $('#gg_coll_builder tbody').sortable({ 
            handle: '.gg_move_row',
            items: "> tr",
            axis: "y",
            placeholder: "gg-coll-sort-placeholder",
        });
        $('#gg_coll_builder').find('.gg_move_row').disableSelection();
    };

    

    // init lc select for live elements
    const gg_live_lc_select = function() {
        new lc_select('.gg_lc_select_dd', {
            wrap_width : '300px',
            addit_classes : ['lcslt-lcwp'],
        });    
    };

    

    // dynamic lc switch
    const gg_live_lc_switch = function() {
        lc_switch('.gg_lc_switch', {
            on_txt      : `<?php echo strtoupper(esc_html__('yes', 'gg_ml')) ?>`,
            off_txt     : `<?php echo strtoupper(esc_html__('no', 'gg_ml')) ?>`,   
        });
    };
    
    
})(jQuery);    
</script>