<?php
// CLLBACKD FOR GALLERY BUILDER SIDE BOXES



//////////////////////////
// GALLERY TYPE
function gg_gb_gallery_type() {
	include_once(GG_DIR . '/classes/gg_connections_hub.php');
    
	global $post;
    get_post_meta($post->ID); // use only one query
    
	$type 		= get_post_meta($post->ID, 'gg_type', true);
	$username 	= get_post_meta($post->ID, 'gg_username', true);
	$psw 		= get_post_meta($post->ID, 'gg_psw', true);
	
	$conn_hub 	= new gg_connection_hub($post->ID);
	$usern_vis 	= (!$type || in_array($type, array_merge($conn_hub->to_consider, array('wp', 'wp_cat', 'cpt_tax', 'gg_album', 'rml', 'ngg')))) ? 'gg_displaynone' : '';
	?>
    <div class="gg_sidebox_meta">
        <div class="misc-pub-section">
          <select name="gg_type" id="gg_type_dd" autocomplete="off">
            <?php
			foreach(gg_gall_static::sources() as $id => $name) {
				$sel = ($id == $type) ? 'selected="selected"' : '';
                
                $disabled = '';
                if(in_array($id, array('picasa', 'fb', 'instagram', 'twitter'))) {
                    if($sel) {
                        $disabled = 'disabled="disabled"';    
                    } else {
                        continue;    
                    }
                }
                   
				echo '<option value="'. $id .'" '. $sel .' '. $disabled .'>'. $name .'</option>';
			}
			?>
          </select>
        </div>

		<div class="misc-pub-section <?php if(!in_array($type, $conn_hub->to_consider)) {echo 'gg_displaynone';} ?>" id="gg_connect_id_wrap">
            <?php echo $conn_hub->src_connections_dd(); ?>
        </div>   

        <div class="misc-pub-section <?php echo $usern_vis ?>" id="gg_username_wrap">
            <label><?php echo gg_gall_static::username_label($type); ?></label>
            <textarea name="gg_username" id="gg_username" autocomplete="off" /><?php echo esc_textarea($username) ?></textarea>
        </div>

        <?php  
        // DEC 2024 - allow Google Drive re-connect because of the new Google requirements
        $first_gall_imgs = get_post_meta($post->ID, 'gg_first_imgs_data', true);
        if($type == 'g_drive' && (get_post_meta($post->ID, 'gg_gdrive_album', true) || !empty($first_gall_imgs))) :
        ?>
            <input type="button" name="gg_handle_user" value="<?php esc_attr_e('Update connection', 'gg_ml') ?>" id="gg_handle_user_btn" class="button-secondary gg_gdrive_reconnect" />

        <?php else : ?>
            <input type="button" name="gg_handle_user" value="<?php esc_attr_e('Connect', 'gg_ml') ?>" id="gg_handle_user_btn" class="button-secondary <?php if(!$type || in_array($type, array('wp', 'wp_cat', 'cpt_tax', 'gg_album', 'rml', 'ngg'))) {echo 'gg_displaynone';} ?>" />

        <?php endif; ?>
    </div>
    

    
    <script type="text/javascript">
    (function($) { 
        "use strict";      
        
        // NB: lc-lightbox enqueued in builder.php file - as well as blocks visibility
        
        const gid = <?php echo absint($post->ID) ?>,
              gg_nonce = '<?php echo esc_js(wp_create_nonce('gg_gall_builder')) ?>';
        
        let gg_conn_hub_acting = false,
            refresh_dd_on_close = false;


        // lightbox on wizard link click
        $(document).on('click', '#gg_launch_conn_wizard', function(e) {
            e.preventDefault();

            var obj = [{
                type	: 'html',
                src		: '#gg_conn_hub_wizard_outer_wrap'
            }];

            var instance = lc_lightbox(obj, {
                wrap_class	: 'lcl_zoomin_oc',
                max_width	: 450,
                modal		: true,

                ins_close_pos	: 'corner',
                open_close_time	: 250,
                fading_time		: 0,
                animation_time	: 0,

                // populate lightbox on open
                on_open	: function () {
                    conn_hub_fill_lightbox();
                },

                // reload connections dropdown on close
                on_close : function() {
                    if(gg_conn_hub_acting) {return false;}
                    gg_conn_hub_acting = true;

                    // if something changed - refresh
                    if(refresh_dd_on_close) {
                        gg_reload_conn_hub_dd();
                    }
                }
            });
            lcl_open(instance, 0); // direct lightbox opening showing first element
        });



        // populate lightbox
        const conn_hub_fill_lightbox = function() {
            gg_conn_hub_acting = true;

            // populate with ajax
            $('.lcl_html_elem #gg_conn_hub_wizard_wrap').html('<div class="gg_spinner"></div>');

            var data = {
                action		: 'gg_connect_wizard_show',
                gg_type		: $('#gg_type_dd').val(),
                gallery_id	: gid,
                nonce		: gg_nonce,
            };
            $.post(ajaxurl, data, function(response) {
                $('.lcl_html_elem #gg_conn_hub_wizard_wrap').html(response);
                gg_conn_hub_acting = false;
            });	
        };



        // load connections dropdown
        window.gg_reload_conn_hub_dd = function() {
            // reload connection's dropdown
            $('#gg_connect_id_wrap').html('<div class="gg_spinner"></div>');

            var data = {
                action		: 'gg_connect_dd_reload',
                gg_type		: $('#gg_type_dd').val(),
                gallery_id	: gid,
                nonce		: gg_nonce,
            };
            $.post(ajaxurl, data, function(response) {
                $('#gg_connect_id_wrap').html(response);

                refresh_dd_on_close = false;
                gg_conn_hub_acting = false;
            });	
        };



        // submit connection trial
        $(document).on('click', '#gg_conn_hub_submit', function() {
            var $subj = $('#gg_add_conn_form');
            $subj.find('section').empty();

            // check that every field has been filled up
            var js_check = true;
            $subj.find('input').each(function() {
                if(!$(this).val() && $(this).parents('p').is(':visible')) {
                    $subj.find('section').html(`<div class="gch_error"><?php esc_html_e('One or more fields are empty', 'gg_ml') ?></div>`);
                    js_check = false;
                    return false;	
                }
            });

            if(!js_check || gg_conn_hub_acting) {
                return false;
            }
            gg_conn_hub_acting = true;

            // ajax submission
            $('#gg_conn_hub_submit').css('opacity', 0.5);

            var data = 'action=gg_save_type_connect&gg_type='+ $('#gg_type_dd').val() +'&gallery_id='+ gid +'&nonce='+ gg_nonce +'&'+ $subj.serialize();
            $.post(ajaxurl, data, function(response) {
                $('#gg_conn_hub_submit').css('opacity', 1);

                if($.trim(response) != 'success') {
                    $subj.find('section').html('<div class="gch_error">'+ response +'</div>');	
                    gg_conn_hub_acting = false;
                }
                else {
                    $subj.find('section').html(`<div class="gch_success"><?php esc_html_e('Successfully connected!', 'gg_ml') ?></div>`);
                    refresh_dd_on_close = true;

                    // successfully added - reload lightbox contents
                    setTimeout(function() {
                        conn_hub_fill_lightbox();	
                    }, 1700);
                }
            }).fail(function() {
                // handle eventual 500 server errors (eg. dropbox on bad token)
                $subj.find('section').html(`<div class='gch_error'><?php esc_html_e('Connection error - check credentials', 'gg_ml') ?></div>`);	

                $('#gg_conn_hub_submit').css('opacity', 1);
                gg_conn_hub_acting = false;
            });
        });



        // delete connections
        $(document).on('click', '#gg_conn_hub_wizard_wrap .gg_del_row', function(e) {
            if(gg_conn_hub_acting) {
                return false;
            }
            var $subj = $(this).parents('tr');

            if(confirm(`<?php esc_html_e("Do you really want to remove this connection?", 'gg_ml') ?>`)) {
                gg_conn_hub_acting = true;
                $(this).parents('tr').fadeTo(100, 0.7);

                var data = {
                    action	: 'gg_remove_connection',
                    conn_id	: $subj.attr('rel'),
                    nonce	: gg_nonce,
                };
                $.post(ajaxurl, data, function(response) {
                    if($.trim(response) == 'success') {
                        $subj.slideUp();
                        refresh_dd_on_close = true;	
                    } 
                    else {
                        alert(response);	
                    }

                    gg_conn_hub_acting = false;
                });	
            }
        });
        
    })(jQuery);    
    </script>
    
    <?php
	// create a custom nonce for submit verification later
    echo '<input type="hidden" name="gg_gallery_noncename" value="' . wp_create_nonce('gg_gall_builder') . '" />';
	return true;
}








//////////////////////////
// GALLERY MAIN SETTINGS
function gg_gb_main_settings() {
	global $post;

	$layout 		= get_post_meta($post->ID, 'gg_layout', true);
	$thumb_w 		= get_post_meta($post->ID, 'gg_thumb_w', true);
	$thumb_h 		= get_post_meta($post->ID, 'gg_thumb_h', true);
	
	$colnzd_max_w 	= get_post_meta($post->ID, 'gg_colnzd_thumb_max_w', true);
	$colnzd_h 		= get_post_meta($post->ID, 'gg_colnzd_thumb_h', true);
	$colnzd_h_type 	= get_post_meta($post->ID, 'gg_colnzd_thumb_h_type', true);

	$masonry_cols 	= get_post_meta($post->ID, 'gg_masonry_cols', true);
	$masonry_min_w 	= get_post_meta($post->ID, 'gg_masonry_min_width', true);;
	
	$ps_height 		= get_post_meta($post->ID, 'gg_photostring_h', true);
	$ps_min_w 		= get_post_meta($post->ID, 'gg_photostring_min_width', true);

	$paginate 		= get_post_meta($post->ID, 'gg_paginate', true);
	$per_page 		= get_post_meta($post->ID, 'gg_per_page', true);
	
	$orderby 		= get_post_meta($post->ID, 'gg_orderby', true);
	
	if(!$paginate || $paginate == 'default') {
		$per_page = get_option('gg_img_per_page');
	}

	// switches
	$hide = 'gg_displaynone';
	$standard_show 	= ($layout != 'standard') ? $hide : '';
	$columnized_show= ($layout != 'columnized') ? $hide : '';
	$masonry_show 	= ($layout != 'masonry') ? $hide : '';
	
	$ps_show 		= ($layout != 'string') ? $hide :  '';
	$per_page_show 	= ($paginate != '1') ? $hide : '';
	?>
    <div class="gg_sidebox_meta gg_form">
      <div class="misc-pub-section">
      	<div>
        	<select name="gg_layout" id="gg_layout" autocomplete="off">
                <option value="default"><?php esc_html_e('As default', 'gg_ml') ?></option>
                <option value="standard" <?php selected($layout, 'standard') ?>>Standard</option>
                <option value="columnized" <?php selected($layout, 'columnized') ?>>Columnized</option>
                <option value="masonry" <?php selected($layout, 'masonry') ?>>Masonry</option>
                <option value="string" <?php selected($layout, 'string') ?>>PhotoString</option>
            </select>
        </div>
        
        <label><?php esc_html_e('Gallery layout', 'gg_ml') ?></label>
      </div>


      <div class="misc-pub-section <?php echo $standard_show ?>" id="gg_tt_sizes">
          <label><?php esc_html_e('Thumbnail sizes', 'gg_ml') ?></label>
          <div class="gg_sbm_nofloat">
              <input type="number" name="gg_thumb_w" value="<?php echo gg_static::empty_or_number_val($thumb_w) ?>" max="3000" step="1" min="0" class="gg_sbm_num_f" autocomplete="off" placeholder="<?php echo (int)get_option('gg_thumb_w') ?>" /> x
              <input type="number" name="gg_thumb_h" value="<?php echo gg_static::empty_or_number_val($thumb_h) ?>" max="3000" step="1" min="0" class="gg_sbm_num_f" autocomplete="off" placeholder="<?php echo (int)get_option('gg_thumb_h') ?>" /> px
        </div>
      </div>
      
      <div class="misc-pub-section gg_columnized_fields <?php echo $columnized_show ?>">
        <div class="gg_sbm_numtype_f">
            <input type="number" name="gg_colnzd_thumb_max_w" value="<?php echo gg_static::empty_or_number_val($colnzd_max_w) ?>" max="3000" step="1" min="0" class="gg_sbm_num_f" autocomplete="off" placeholder="<?php echo (int)get_option('gg_colnzd_thumb_max_w') ?>" /><span>px</span>
        </div>
        
        <label><?php esc_html_e('Max thumbs width', 'gg_ml') ?></label>
      </div>
      <div class="misc-pub-section gg_columnized_fields <?php echo $columnized_show ?>">
        <div>
            <input type="number" name="gg_colnzd_thumb_h" value="<?php echo gg_static::empty_or_number_val($colnzd_h) ?>" max="3000" step="1" min="0" class="gg_sbm_num_f" autocomplete="off" placeholder="<?php echo (int)get_option('gg_colnzd_thumb_h') ?>" />
            
            <select name="gg_colnzd_thumb_h_type" autocomplete="off">
                <option value="px">px</option>
                <option value="%" <?php selected($colnzd_h_type, '%') ?>>%</option>
            </select>
        </div>
        
        <label><?php esc_html_e('Thumbnails height', 'gg_ml') ?></label>
      </div>
      
      
      <div class="misc-pub-section gg_masonry_fields <?php echo $masonry_show ?>">
        <div>
            <select name="gg_masonry_cols" autocomplete="off">
                <option value="default"><?php esc_html_e('As default', 'gg_ml') ?></option>
                <?php
                for($a=1; $a<=20; $a++) {
                    echo '<option value="'.$a.'" '. selected((int)$masonry_cols, $a, false) .'>'. $a .'</option>';
                }
                ?>
            </select>
        </div>
        
        <label><?php esc_html_e('Image columns', 'gg_ml') ?></label>
      </div>
      
      <div class="misc-pub-section gg_masonry_fields <?php echo $masonry_show ?>" >
        <div class="gg_sbm_numtype_f">
            <input type="number" name="gg_masonry_min_width" value="<?php echo gg_static::empty_or_number_val($masonry_min_w) ?>" max="2000" step="1" min="0" class="gg_sbm_num_f" autocomplete="off" placeholder="<?php echo (int)get_option('gg_masonry_min_width') ?>" /><span>px</span>
        </div>
        
        <label><?php esc_html_e('Min thumbs width', 'gg_ml') ?></label>
      </div>
      
      
      <div class="misc-pub-section gg_ps_fields <?php echo $ps_show ?>">
        <div class="gg_sbm_numtype_f">
        	<input type="number" name="gg_photostring_h" value="<?php echo gg_static::empty_or_number_val($ps_height) ?>" max="2000" step="1" min="0" class="gg_sbm_num_f" autocomplete="off" placeholder="<?php echo (int)get_option('gg_photostring_h') ?>" /><span>px</span>
        </div>
        
        <label><?php esc_html_e('Thumbs height', 'gg_ml') ?></label>
      </div>
      
      <div class="misc-pub-section gg_ps_fields <?php echo $ps_show ?>">
        <div class="gg_sbm_numtype_f">
            <input type="number" name="gg_photostring_min_width" value="<?php echo gg_static::empty_or_number_val($ps_min_w) ?>" max="2000" step="1" min="0" class="gg_sbm_num_f" autocomplete="off" placeholder="<?php echo (int)get_option('gg_photostring_min_width') ?>" /><span>px</span>
        </div>
        
        <label><?php esc_html_e('Min thumbs width', 'gg_ml') ?></label>
      </div>
      

      <div class="misc-pub-section">
        <div>
        	<select name="gg_paginate" id="gg_paginate" autocomplete="off">
                <option value="default"><?php esc_html_e('As default', 'gg_ml') ?></option>
                <option value="1" <?php selected($paginate, '1') ?>><?php esc_html_e('Yes') ?></option>
                <option value="0" <?php selected($paginate, '0') ?>><?php esc_html_e('No') ?></option>
            </select>
        </div>
        
        <label><?php esc_html_e('Use pagination?', 'gg_ml') ?></label>
      </div>
      <div class="misc-pub-section <?php echo $per_page_show ?>" id="gg_per_page">
          <div>
              <input type="number" name="gg_per_page" value="<?php echo gg_static::empty_or_number_val($per_page) ?>" max="500" step="1" min="0" class="gg_sbm_num_f" autocomplete="off" placeholder="<?php echo (int)get_option('gg_per_page') ?>" />
          </div>
        
          <label><?php esc_html_e('Images per page', 'gg_ml') ?></label>
      </div>
      
      
      <div class="misc-pub-section">
        <div>
        	<select name="gg_orderby" autocomplete="off">
                <option value="default"><?php esc_html_e('As in builder', 'gg_ml') ?></option>
                <option value="title_asc" <?php selected($orderby, 'title_asc') ?>><?php esc_html_e('By title (A to Z)', 'gg_ml') ?></option>
                <option value="title_desc" <?php selected($orderby, 'title_desc') ?>><?php esc_html_e('By title (Z to A)', 'gg_ml') ?></option>
                <option value="author_asc" <?php selected($orderby, 'author_asc') ?>><?php esc_html_e('By author (A to Z)', 'gg_ml') ?></option>
                <option value="author_desc" <?php selected($orderby, 'author_desc') ?>><?php esc_html_e('By author (Z to A)', 'gg_ml') ?></option>
                <option value="id_asc" <?php selected($orderby, 'id_asc') ?>><?php esc_html_e('By date (A to Z)', 'gg_ml') ?></option>
                <option value="id_desc" <?php selected($orderby, 'id_desc') ?>><?php esc_html_e('By date (Z to A)', 'gg_ml') ?></option>
            </select>
        </div>
        
        <label><?php esc_html_e('Images sorting', 'gg_ml') ?></label>
      </div>
    </div>


	<script type="text/javascript">
    (function($) { 
        "use strict";     
        
		// main settings toggle
		$(document).on('change', '#gg_layout', function() {
			var layout = $(this).val();

			if(layout == 'standard') {
				$('#gg_tt_sizes').removeClass('gg_displaynone');
				$('.gg_columnized_fields, .gg_masonry_fields, .gg_ps_fields').addClass('gg_displaynone');;
			}
			else if (layout == 'columnized') {
				$('.gg_columnized_fields').removeClass('gg_displaynone');
				$('#gg_tt_sizes, .gg_masonry_fields, .gg_ps_fields').addClass('gg_displaynone');;
			}
			else if (layout == 'masonry') {
				$('.gg_masonry_fields').removeClass('gg_displaynone');
				$('.gg_columnized_fields, #gg_tt_sizes, .gg_ps_fields').addClass('gg_displaynone');;
			}
			else if (layout == 'string') {
				$('.gg_ps_fields').removeClass('gg_displaynone');
				$('#gg_tt_sizes, .gg_masonry_fields').addClass('gg_displaynone');;
			}
			else { 
				$('#gg_tt_sizes, .gg_columnized_fields, .gg_masonry_fields, .gg_ps_fields').addClass('gg_displaynone');; 
			}
		});

		
		// paginate toggle
		$(document).on('change', '#gg_paginate', function() {	
			($(this).val() == '1') ? $('#gg_per_page').removeClass('gg_displaynone') : $('#gg_per_page').addClass('gg_displaynone');;
		});
		
		
		// toggle WP-restricted sorting
		$(document).on('change', '#gg_type_dd', function() {
			switch($(this).val()) {
				case 'wp' :
				case 'wp_cat' :
				case 'cpt_tax' :
				case 'rml' :
					$('select[name=gg_orderby]').find('option[value="id_asc"], option[value="id_desc"]').removeAttr('disabled');
					break;  
				
				default :
					$('select[name=gg_orderby]').find('option[value="id_asc"], option[value="id_desc"]').prop('disabled', 'disabled');
					break;  
			}
		});
        
        $(document).ready(function() {
		  $('#gg_layout').trigger('change'); // on init
        });
        
    })(jQuery);    
	</script>
    <?php
	return true;
}






//////////////////////////
// PAGE URL FOR SITEMAP
function gg_gb_sitemap() {
	global $post;
	$type = get_post_meta($post->ID, 'gg_type', true);
	
	// only for local images
	if(!$type || !in_array($type, array('wp', 'wp_cat', 'cpt_tax', 'gg_album', 'rml', 'ngg'))) {
		?>
        <style type="text/css">
		#gg_gb_sitemap {
			display: none;	
		}
		</style>
        <?php
		return false;
	}
	
	$url = get_post_meta($post->ID, 'gg_sitemap_page_url', true);
	?>
    <div class="gg_sidebox_meta">
        <div class="misc-pub-section">
            <input type="text" name="gg_sitemap_page_url" value="<?php echo esc_attr($url) ?>" placeholder="<?php echo site_url() ?> ..." />
        </div>
    </div>
    
    <script type="text/javascript">
	(function($) { 
        "use strict";
        
        $('#gg_type_dd').on('change', function() {
			( $.inArray($(this).val(), ['wp', 'wp_cat', 'cpt_tax', 'gg_album', 'rml', 'ngg']) !== -1) ? $('#gg_gb_sitemap').slideDown() : $('#gg_gb_sitemap').slideUp(); 
		});
    })(jQuery); 
	</script>
    <?php
}








//////////////////////////
// CREATE WATERMARK CACHE
function gg_gb_wmark_cache() {
	global $post;
    ?>
    <div class="gg_mainbox_meta gg_mbm_create_wm">
        <div>
            <a class="gg_mbm_create_wm_btn" href="javascript:void(0);">
                <i class="dashicons dashicons-shield"></i> <?php esc_html_e('Create watermark cache', 'gg_ml') ?>
            </a> 
            <span></span>
        </div>
    </div>

    <script type="text/javascript">
    (function($) { 
        "use strict"; 

        const wmark_box = $('#gg_gb_wmark_cache .gg_mainbox_meta > div');

        $(document).on('click', '#gg_gb_wmark_cache .gg_mainbox_meta a', function(e) {
            e.preventDefault();
            $wmark_box.find('small, div').remove();

            $wmark_box.find('span').html('<div class="gg_spinner gg_spinner_inline"></div>');
            $wmark_box.append(`<small>(<?php esc_html_e('might take very long having many images to manage', 'gg_ml') ?>)</small>`);

            const data = {
                action	: 'gg_create_wm_cache',
                gid		: <?php echo absint($post->ID) ?>,
                nonce	: '<?php echo esc_js(wp_create_nonce('lcwp_nonce')) ?>',
            };
            $.post(ajaxurl, data, function(response) {
                var resp = $.trim(response);

                $wmark_box.find('span').empty();
                $wmark_box.find('small').remove();

                if(resp == 'success') {
                    $wmark_box.append(`<div><?php esc_html_e('Cache created succesfully!', 'gg_ml') ?></div>`);
                }
                else {
                    console.error(resp);

                    if(resp.indexOf("Maximum execution") != -1) {
                        $wmark_box.append(`<div><?php esc_html_e('Process took too much time for your server. Try again', 'gg_ml' ) ?></div>`);
                    }
                    else if(resp.indexOf("bytes exhausted") != -1) {
                        $wmark_box.append(`<div><?php esc_html_e('The process requires too much memory for your server. Try using smaller images', 'gg_ml' ) ?></div>`);
                    }
                    else {
                        $wmark_box.append(`<div><?php esc_html_e('Error during the cache creation', 'gg_ml' ) ?></div>`);
                    }
                }
            })
            .fail(function(e) {
                if(e.status) {
                    console.error(e);
                    $wmark_box.append(`<div><?php esc_html_e('Error creating watermarks cache!', 'gg_ml') ?></div>`);
                }
            });;
        });
    })(jQuery); 
    </script>
    <?php
}