<?php

///////////////////////////////////
// ADMIN IMPLEMENTATION


// get affected post types for WP gall management
function gg_affected_wp_gall_ct() {
	$basic = array('post','page');	
	$cpt = get_option('gg_extend_wp_gall'); 

	if(is_array($cpt)) {
		$pt = array_merge((array)$basic, (array)$cpt);	
	}
	else {$pt = $basic;}

	return $pt;
}


// add a meta box for affected post types
function gg_wp_gall_metabox() {
	
    // get affected post types for WP gall management
    $basic = array('post','page');	
	$cpt = get_option('gg_extend_wp_gall', array()); 

    $pt = $basic;
	if(is_array($cpt)) {
		$pt = array_merge((array)$basic, (array)$cpt);	
	}
    
    foreach(gg_affected_wp_gall_ct() as $type){
		add_meta_box('gg_wp_gall_settings', esc_html__('Global Gallery', 'gg_ml'), 'gg_wp_gall_settings', $type, 'normal', 'default');
	}  
}
add_action('admin_init', 'gg_wp_gall_metabox');



// create metabox
function gg_wp_gall_settings() {
    if(!dike_lc('lcweb', 'gg')) {
        echo 'License not validated';
        return false;    
    }
    
	include_once(GG_DIR .'/settings/field_options.php');
	global $post;
	
    get_post_meta($post->ID); // use only one query
    
	$use_it 		= get_post_meta($post->ID, 'gg_affect_wp_gall', true);
	$show_as 		= get_post_meta($post->ID, 'gg_layout', true); 
    if(!$show_as) {
        $show_as = 'default';
    }
	
	
	$thumb_w 		= (int)get_post_meta($post->ID, 'gg_thumb_w', true);
	$thumb_h 		= (int)get_post_meta($post->ID, 'gg_thumb_h', true);
	
	$colnzd_max_w 	= (int)get_post_meta($post->ID, 'gg_colnzd_thumb_max_w', true);
	$colnzd_h 		= (int)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 	= (int)get_post_meta($post->ID, 'gg_masonry_cols', true);
	$masonry_min_w 	= (int)get_post_meta($post->ID, 'gg_masonry_min_width', true);;
	
	$ps_height 		= (int)get_post_meta($post->ID, 'gg_photostring_h', true);
	$ps_min_w 		= (int)get_post_meta($post->ID, 'gg_photostring_min_width', true);
	
    $slider_w       = (int)get_post_meta($post->ID, 'gg_slider_w', true);
    $slider_w_type  = get_post_meta($post->ID, 'gg_slider_w_type', true);
    $slider_h       = (int)get_post_meta($post->ID, 'gg_slider_h', true);
    $slider_h_type  = get_post_meta($post->ID, 'gg_slider_h_type', true);
	$slider_autop 	= get_post_meta($post->ID, 'gg_slider_autoplay', true);
	
	$car_img_h		= (int)get_post_meta($post->ID, 'gg_car_img_h', true);
	$car_cols		= (int)get_post_meta($post->ID, 'gg_car_cols', true); if(!$car_cols) {$car_cols = 3;}
	$car_rows		= (int)get_post_meta($post->ID, 'gg_car_rows', true); if(!$car_rows) {$car_rows = 1;}
	$car_nocrop 	= get_post_meta($post->ID, 'gg_car_nocrop', true);
	
	$itg_w			= (int)get_post_meta($post->ID, 'gg_itg_w', true); if(!$itg_w) {$itg_w = 100;}
	$itg_w_type 	= get_post_meta($post->ID, 'gg_itg_w_type', true);
	$itg_h			= (int)get_post_meta($post->ID, 'gg_itg_h', true); if(!$itg_h) {$itg_h = 75;}
	$itg_h_type 	= get_post_meta($post->ID, 'gg_itg_h_type', true);
	$itg_layout 	= get_post_meta($post->ID, 'gg_itg_layout', true);
	$itg_img_num 	= (int)get_post_meta($post->ID, 'gg_itg_img_num', true);
	$itg_font_size 	= get_post_meta($post->ID, 'gg_itg_font_size', true);
	$itg_cust_txt	= get_post_meta($post->ID, 'gg_itg_cust_txt', true);
	
	$paginate 		= get_post_meta($post->ID, 'gg_paginate', true); if(!$paginate) {$paginate = 'default';}
	$per_page 		= (int)get_post_meta($post->ID, 'gg_per_page', true);
	$pag_system 	= get_post_meta($post->ID, 'gg_pag_system', true);
	
	
	// retrocompatibility
	if(get_post_meta($post->ID, 'gg_use_slider', true)) {
        $show_as = 'slider';
    }
	
	if($paginate == 'default') {
		$per_page = get_option('gg_img_per_page', 10);	
	}
    
	// switches
	$hide = 'gg_displaynone';
	$standard_show 	= ($show_as != 'standard') ? $hide : '';
	$colnzd_show 	= ($show_as != 'columnized') ? $hide : '';
	$masonry_show 	= ($show_as != 'masonry') ? $hide : '';
	$ps_show 		= ($show_as != 'string') ? $hide : '';
	
	$slider_show 	= ($show_as != 'slider') ? $hide : '';
	$carousel_show 	= ($show_as != 'carousel') ? $hide : '';
	$itg_show		= ($show_as != 'itg') ? $hide : '';
	
	$pag_show 		= (in_array($show_as, array('slider', 'carousel', 'itg'))) ? $hide : '';
	$per_page_show 	= ($paginate != '1') ? $hide : '';
	
	// info icon
	$info_icon = '<span class="dashicons dashicons-info" title="'. esc_attr__('Leave fields empty to use global setup', 'gg_ml') .'"></span>';

	?>
    <div class="gg_mainbox_meta gg_wp_gall_manag_form">
        <table class="widefat gg_table gg_metabox_table">
          <tr>
            <td class="gg_label_td"><?php esc_html_e("Use Global Gallery with wordpress galleries in this page?", 'gg_ml'); ?></td>
            <td class="gg_field_td">
                <select name="gg_affect_wp_gall" id="gg_affect_wp_gall" autocomplete="off">
                  <option value="default"><?php esc_html_e('As default', 'gg_ml') ?></option>
                  <option value="1" <?php selected($use_it, '1') ?>><?php esc_html_e('Yes', 'gg_ml') ?></option>
                  <option value="0" <?php selected($use_it, '0') ?>><?php esc_html_e('No', 'gg_ml') ?></option>
                </select>
            </td>    
          </tr>
			
          <tbody id="gg_wp_gall_opts" class="gg_form <?php if($use_it == '0') {echo $hide;} ?>">
            <tr><td class="gg_field_td" colspan="2">
                <div>
                    <label><?php esc_html_e('Display as', 'gg_ml') ?></label>
                    
                    <select name="gg_layout" id="gg_show_as" autocomplete="off">
                        <option value="default"><?php esc_html_e('Gallery', 'gg_ml') ?> - <?php esc_html_e('Default layout', 'gg_ml') ?></option>  
                        <option value="standard" <?php selected($show_as, 'standard') ?>><?php esc_html_e('Gallery', 'gg_ml') ?> - Standard layout</option> 
                        <option value="columnized" <?php selected($show_as, 'columnized') ?>><?php esc_html_e('Gallery', 'gg_ml') ?> - Columnized layout</option>   
                        <option value="masonry" <?php selected($show_as, 'masonry') ?>><?php esc_html_e('Gallery', 'gg_ml') ?> -  Masonry layout</option>
                        <option value="string" <?php selected($show_as, 'string') ?>><?php esc_html_e('Gallery', 'gg_ml') ?> -  PhotoString layout</option>  
                        
                        <option value="slider" <?php selected($show_as, 'slider') ?>><?php esc_html_e('Slider', 'gg_ml') ?></option> 
                        <option value="carousel" <?php selected($show_as, 'carousel') ?>><?php esc_html_e('Carousel', 'gg_ml') ?></option>   
                        <option value="itg" <?php selected($show_as, 'itg') ?>><?php esc_html_e('Image-to-gallery', 'gg_ml') ?></option>   
                    </select>
                </div>
                
                
                
                <div id="gg_tt_sizes" class="<?php echo $standard_show; ?>">
                    <label><?php esc_html_e('Images size', 'gg_ml') ?> <?php echo $info_icon ?></label>
                   
                    <input type="number" name="gg_thumb_w" value="<?php echo (int)$thumb_w ?>" min="0" max="3000" step="1" /> x 
                    <input type="number" name="gg_thumb_h" value="<?php echo (int)$thumb_h ?>" min="0" max="3000" step="1" /> px
                </div>    
                 
                
                
                <div class="gg_colnzd_fields <?php echo $colnzd_show; ?>">
                    <label><?php esc_html_e('Maximum thumbnails width', 'gg_ml') ?> <?php echo $info_icon ?></label>
                    
                    <input type="number" value="<?php echo (int)$colnzd_max_w ?>" name="gg_colnzd_thumb_max_w" min="40" max="3000" step="1" data-unit="px" data-respect-limits="0" class="gg_slider_input" autocomplete="off" />
                </div>
                <div class="gg_colnzd_fields <?php echo $colnzd_show; ?>">
                    <label><?php esc_html_e('Thumbnails height', 'gg_ml') ?> <?php echo $info_icon ?></label>
                    
                    <input type="number" name="gg_colnzd_thumb_h" value="<?php echo (int)$colnzd_h ?>" min="0" max="3000" step="1" autocomplete="off" />
            
                    <select name="gg_colnzd_thumb_h_type" autocomplete="off">
                        <option value="px">px</option>
                        <option value="%" <?php selected($colnzd_h_type, '%') ?>>%</option>
                    </select>
                </div>
            
            
            
                <div class="gg_masonry_fields <?php echo $masonry_show; ?>">
                    <label><?php esc_html_e('How many columns?', 'gg_ml') ?> <?php echo $info_icon ?></label>
                    
                    <input type="number" value="<?php echo (int)$masonry_cols ?>" name="gg_masonry_cols" min="1" max="30" step="1" data-unit="" data-respect-limits="1" class="gg_slider_input" autocomplete="off" />
                </div>
                <div class="gg_masonry_fields <?php echo $masonry_show; ?>">
                    <label><?php esc_html_e('Minimum images width', 'gg_ml') ?></label>
                    
                    <input type="number" value="<?php echo (int)$masonry_min_w ?>" name="gg_masonry_min_width" min="40" max="2000" step="1" data-unit="px" data-respect-limits="0" class="gg_slider_input" autocomplete="off" />
                </div>
                
                
                
                <div class="gg_ps_fields <?php echo $ps_show; ?>">
                    <label><?php esc_html_e('Images height', 'gg_ml') ?> <?php echo $info_icon ?></label>
                    
                    <input type="number" value="<?php echo (int)$ps_height ?>" name="gg_photostring_h" min="20" max="500" step="1" data-unit="px" data-respect-limits="1" class="gg_slider_input" autocomplete="off" />
                </div>
                <div class="gg_ps_fields <?php echo $ps_show; ?>">
                    <label><?php esc_html_e('Minimum thumbnails width', 'gg_ml') ?></label>
                    
                    <input type="number" value="<?php echo (int)$ps_min_w ?>" name="gg_photostring_min_width" min="20" max="700" step="1" data-unit="px" data-respect-limits="1" class="gg_slider_input" autocomplete="off" />
                </div>
                
                
                
                <div class="gg_slider_opts gg_slider_numtype_opt <?php echo $slider_show; ?>">
                    <label><?php esc_html_e('Slider width', 'gg_ml') ?></label>
                    
                    <input type="text" name="gg_slider_w" value="<?php echo (int)$slider_w ?>" min="0" max="4000" step="1" /> 
                    <select name="gg_slider_w_type" autocomplete="off">
                        <option value="%">%</option>
                        <option value="px" <?php selected('px', $slider_w_type) ?>>px</option>
                    </select>
                </div>     
                <div class="gg_slider_opts <?php echo $slider_show; ?>">
                    <label><?php esc_html_e('Slider height', 'gg_ml') ?></label>
                    
                    <input type="text" name="gg_slider_h" value="<?php echo (int)$slider_h ?>" min="0" max="3000" step="1" /> 
                    <select name="gg_slider_h_type" autocomplete="off">
                        <option value="%">%</option>
                        <option value="px" <?php selected('px', $slider_h_type) ?>>px</option>
                    </select>
                </div>
                <div class="gg_slider_opts <?php echo $slider_show; ?>">
					<label><?php esc_html_e("Autoplay slideshow?", 'gg_ml'); ?></label> 
                    
                    <select name="gg_slider_autoplay" autocomplete="off">
                      <option value="auto"><?php esc_html_e('As default', 'gg_ml') ?></option>
                      <option value="1" <?php selected($slider_autop, '1') ?>><?php esc_html_e('Yes', 'gg_ml') ?></option>
                      <option value="0" <?php selected($slider_autop, '0') ?>><?php esc_html_e('No', 'gg_ml') ?></option>
                    </select>
                </div>
                
                
                
                <div class="gg_carousel_opts <?php echo $carousel_show; ?>">
                    <label><?php esc_html_e('Images height', 'gg_ml') ?></label>
                    
                    <input type="number" value="<?php echo (int)$car_img_h ?>" name="gg_car_img_h" min="20" max="500" step="1" data-unit="px" data-respect-limits="0" class="gg_slider_input" autocomplete="off" />
                </div>
                <div class="gg_carousel_opts <?php echo $carousel_show; ?>">
                    <label><?php esc_html_e('Images per time', 'gg_ml') ?></label>
                    
                    <input type="number" value="<?php echo (int)$car_cols ?>" name="gg_car_cols" min="1" max="10" step="1" data-unit="" data-respect-limits="0" class="gg_slider_input" autocomplete="off" />
                </div>
                <div class="gg_carousel_opts <?php echo $carousel_show; ?>">
                    <label><?php esc_html_e('Rows', 'gg_ml') ?></label>
                    
                    <input type="number" value="<?php echo (int)$car_rows ?>" name="gg_car_rows" min="1" max="4" step="1" data-unit="" data-respect-limits="0" class="gg_slider_input" autocomplete="off" />
                </div>
                <div class="gg_carousel_opts <?php echo $carousel_show; ?>">
					<label><?php esc_html_e("Use multiscroll?", 'gg_ml'); ?></label> 
                    
                    <?php  $sel = (get_post_meta($post->ID, 'gg_car_multiscroll', true) == 1) ? 'checked="checked"' : ''; ?>
                    <input type="checkbox" value="1" name="gg_car_multiscroll" class="gg_lc_switch" <?php echo $sel; ?> />
                </div>   
                <div class="gg_carousel_opts <?php echo $carousel_show; ?>">
					<label><?php esc_html_e("Center mode?", 'gg_ml'); ?></label> 
                    
                    <?php  $sel = (get_post_meta($post->ID, 'gg_car_centermode', true) == 1) ? 'checked="checked"' : ''; ?>
                    <input type="checkbox" value="1" name="gg_car_centermode" class="gg_lc_switch" <?php echo $sel; ?> />
                </div> 
                <div class="gg_carousel_opts <?php echo $carousel_show; ?>">
					<label><?php esc_html_e("Avoid images crop?", 'gg_ml'); ?></label> 
                    
                    <?php  $sel = (get_post_meta($post->ID, 'gg_car_nocrop', true) == 1) ? 'checked="checked"' : ''; ?>
                    <input type="checkbox" value="1" name="gg_car_nocrop" class="gg_lc_switch" <?php echo $sel; ?> />
                </div>  
                              
                            
                
                <div class="gg_itg_opts <?php echo $itg_show; ?>">
               		<label><?php esc_html_e("Box width", 'gg_ml') ?></label>
                    <input type="number" name="gg_itg_w" value="<?php echo (int)$itg_w ?>" min="0" max="1000" step="1" autocomplete="off" />
                    
                    <select name="gg_itg_w_type" autocomplete="off">
                    	<option value="%">%</option>
                        <option value="px" <?php selected($itg_w_type, 'px') ?>>px</option>
                    </select>
                </div>
                <div class="gg_itg_opts <?php echo $itg_show; ?>">
                    <label><?php esc_html_e("Images height", 'gg_ml') ?> <em>(<?php esc_html_e('% is proportional to width', 'gg_ml') ?>)</em></label>
                    
                    <input type="number" name="gg_itg_h" value="<?php echo (int)$itg_h ?>" min="0" max="1000" step="1" autocomplete="off" />
                    
                    <select name="gg_itg_h_type" autocomplete="off">
                    	<option value="%">%</option>
                        <option value="px" <?php selected($itg_h_type, 'px') ?>>px</option>
                    </select>
                </div>
                <div class="gg_itg_opts <?php echo $itg_show; ?>">
                    <label><?php esc_html_e("Layout", 'gg_ml') ?></label>

                    <select name="gg_itg_layout" autocomplete="off">
                    	<option value="">(<?php esc_html_e('default one', 'gg_ml') ?>)</option>
                       	<?php
						include_once(GG_DIR .'/settings/field_options.php');
						foreach(gg_itg_layouts() as $key => $val) {
							echo '<option value="'. $key .'" '. selected($itg_layout, $key, false) .'>'. $val .'</option>';	
						}
						?>
                    </select>
                </div>
                <div class="gg_itg_opts <?php echo $itg_show; ?>">
                    <label><?php esc_html_e("How many images to display?", 'gg_ml') ?> <span class="dashicons dashicons-info" title="<?php esc_attr_e('This will be ignored if chosen layout is "main image + two on sides"', 'gg_ml') ?>"></span></label>

                    <select name="gg_itg_img_num" autocomplete="off">
                    	<option value="1">1</option>
                        <option value="2" <?php selected($itg_img_num, '2') ?>>2</option>
                        <option value="4" <?php selected($itg_img_num, '4') ?>>4</option>
                    </select>
                </div>
                <div class="gg_itg_opts <?php echo $itg_show; ?>">
					<label><?php esc_html_e("Custom font size", 'gg_ml') ?> <span class="dashicons dashicons-info" title="<?php esc_attr_e('Leave empty to use default one', 'gg_ml') ?>"></span></label>

                     <input type="number" name="gg_itg_font_size" value="<?php echo (int)$itg_font_size ?>" max="5" min="0" step="0.1" autocomplete="off" /> rem
                </div>   
                <div class="gg_itg_opts <?php echo $itg_show; ?>">
					<label><?php esc_html_e("Custom overlay text", 'gg_ml') ?> <span class="dashicons dashicons-info" title="<?php esc_attr_e('Remember you can use placeholders and FontAwesome icons as explained in settings', 'gg_ml') ?>"></span></label>
                    
                	<textarea name="gg_itg_cust_txt"><?php echo $itg_cust_txt ?></textarea>
                </div>  
            </td>
            </tr>
            
            
            
            <tr id="gg_pagination"><td class="gg_field_td <?php echo $pag_show ?>" colspan="2">
                <div>
                    <label><?php esc_html_e('Use pagination?', 'gg_ml') ?></label>
                    <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', 'gg_ml') ?></option>  
                        <option value="0" <?php selected($paginate, '0') ?>><?php esc_html_e('No', 'gg_ml') ?></option>  
                    </select>
                </div>     
                <div id="gg_per_page" class="<?php echo $per_page_show; ?>">
                    <label><?php esc_html_e('Images per page', 'gg_ml') ?> <?php echo $info_icon ?></label>
                    
                    <input type="number" value="<?php echo (int)$per_page ?>" name="gg_per_page" min="2" max="100" step="1" data-unit="" data-respect-limits="0" class="gg_slider_input" autocomplete="off" />
                </div>
            	<div>
                    <label><?php esc_html_e('Pagination System', 'gg_ml') ?></label>
                    <select name="gg_pag_system" id="gg_pag_system" autocomplete="off">
                        <option value=""><?php esc_html_e('auto - follow global settings', 'gg_ml') ?></option>
                        
                        <?php
						foreach(gg_pag_sys() as $id => $val) {
							echo '<option value="'. $id .'" '. selected($pag_system, $id, false) .'>'. $val .'</option>';
						}
						?>
                    </select>
                </div>
            </td>
            </tr>
            <tr>
              <td colspan="2">
			  	<div>
					<label><?php esc_html_e("Use watermark?", 'gg_ml'); ?></label> 
                    <?php  $sel = (get_post_meta($post->ID, 'gg_watermark', true) == 1) ? 'checked="checked"' : ''; ?>
                    <input type="checkbox" value="1" name="gg_watermark" class="gg_lc_switch" <?php echo $sel; ?> />
                </div>    
              </td>   
            </tr>
          </tbody>
        </table>  
        
        <input type="hidden" name="lcwp_nonce" value="<?php echo wp_create_nonce('lcwp') ?>" />
    </div>

    
    <?php // SCRIPTS ?>
    <script type="text/javascript">
    (function($) { 
        "use strict";       
        
        $(document).ready(function($) {

            // sliders
            new lc_range_n_num('.gg_wp_gall_manag_form .gg_slider_input', {
                unit_width: 17    
            });

            // lc switch
            lc_switch('.gg_wp_gall_manag_form .gg_lc_switch', {
                on_txt      : "<?php echo strtoupper(esc_html__('yes', 'gg_ml')) ?>",
                off_txt     : "<?php echo strtoupper(esc_html__('no', 'gg_ml')) ?>",   
            });


            // check min values to not have troubles with page saving
            $('.gg_wp_gall_manag_form input[type=number]').each(function() {

                const val = parseFloat($(this).val()),
                      min = parseFloat($(this).attr('min')),
                      max = parseFloat($(this).attr('max'));

                if(val < min) {
                    $(this).val(min);    
                }
                else if(val > max) {
                    $(this).val(max);
                }
            });


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


            // settings toggle
            $(document).on('change', '#gg_affect_wp_gall', function() {
                ($(this).val() != '0') ? $('#gg_wp_gall_opts').slideDown() : $('#gg_wp_gall_opts').slideUp();		
            });


            $(document).on('change', '#gg_show_as', function() {
                var sa = $(this).val();
                $('#gg_tt_sizes, .gg_colnzd_fields, .gg_masonry_fields, .gg_ps_fields, .gg_slider_opts, .gg_carousel_opts').hide();

                if(sa == 'standard') {
                    $('#gg_tt_sizes').show();
                }
                else if (sa == 'columnized') {
                    $('.gg_colnzd_fields').show();
                }
                else if (sa == 'masonry') {
                    $('.gg_masonry_fields').show();
                }
                else if (sa == 'string') {
                    $('.gg_ps_fields').show();
                }
                else if (sa == 'slider') {
                    $('.gg_slider_opts').show();
                }
                else if (sa == 'carousel') {
                    $('.gg_carousel_opts').show();
                }
                else if (sa == 'itg') {
                    $('.gg_itg_opts').show();
                }


                if (sa == 'slider' || sa == 'carousel' || sa == 'itg') {
                    $('#gg_pagination').hide();
                } else {
                    $('#gg_pagination').show();	
                }


                if (sa == 'slider' || sa == 'itg') {
                    $('#gg_cust_ol').hide();
                } else {
                    $('#gg_cust_ol').show();	
                }
            });


            $(document).on('change', '#gg_paginate', function() {
                ($(this).val() == '1') ? $('#gg_per_page').show() : $('#gg_per_page').hide();		
            });
        });
    })(jQuery);   
	</script>
    <?php
}





// save metabox
function gg_wp_gall_meta_save($post_id) {
	if(isset($_POST['gg_affect_wp_gall'])) {
		if (!wp_verify_nonce($_POST['lcwp_nonce'], 'lcwp')) { 
            return $post_id;
        }
        
		include_once(GG_DIR.'/classes/simple_form_validator.php');	
		$validator = new simple_fv(GG_ML);
		$indexes = array();
		
		$indexes[] = array('index'=>'gg_affect_wp_gall', 'label'=>'Affect WP galleries');
		
		
		$to_save = array(
			'gg_affect_wp_gall',
			'gg_layout',
			
			'gg_thumb_w',
			'gg_thumb_h',
			
			'gg_colnzd_thumb_max_w',
			'gg_colnzd_thumb_h',
			'gg_colnzd_thumb_h_type',
			
			'gg_masonry_cols',
			'gg_masonry_min_width',
			
			'gg_photostring_h',
			'gg_photostring_min_width',
			
			'gg_paginate',
			'gg_per_page',
		);
		foreach($to_save as $ts) {
			$indexes[] = array('index'=>$ts, 'label'=>'foo');	
		}
		
		$indexes[] = array('index'=>'gg_pag_system', 'label'=>'pagination system');
		
		$indexes[] = array('index'=>'gg_slider_w', 'label'=>'slider width');
		$indexes[] = array('index'=>'gg_slider_w_type', 'label'=>'slider width type');
		$indexes[] = array('index'=>'gg_slider_h', 'label'=>'slider height');
		$indexes[] = array('index'=>'gg_slider_h_type', 'label'=>'slider height type');
		$indexes[] = array('index'=>'gg_slider_autoplay', 'label'=>'autoplay slider');
		
		$indexes[] = array('index'=>'gg_car_img_h', 'label'=>'carousel image height');
		$indexes[] = array('index'=>'gg_car_cols', 'label'=>'carousel columns');
		$indexes[] = array('index'=>'gg_car_rows', 'label'=>'carousel rows');
		$indexes[] = array('index'=>'gg_car_multiscroll', 'label'=>'carousel multiscroll');
		$indexes[] = array('index'=>'gg_car_centermode', 'label'=>'carousel center mode');
		$indexes[] = array('index'=>'gg_car_nocrop', 'label'=>'no images crop mode');
		
		$indexes[] = array('index'=>'gg_itg_w', 'label'=>'');
		$indexes[] = array('index'=>'gg_itg_w_type', 'label'=>'');
		$indexes[] = array('index'=>'gg_itg_h', 'label'=>'');
		$indexes[] = array('index'=>'gg_itg_h_type', 'label'=>'');
		$indexes[] = array('index'=>'gg_itg_layout', 'label'=>'');
		$indexes[] = array('index'=>'gg_itg_img_num', 'label'=>'');
		$indexes[] = array('index'=>'gg_itg_font_size', 'label'=>'');
		$indexes[] = array('index'=>'gg_itg_cust_txt', 'label'=>'');
		
		$indexes[] = array('index'=>'gg_watermark', 'label'=>'use watermark');
		
		$validator->formHandle($indexes);
		$fdata = $validator->form_val;
		$error = $validator->getErrors();

		// clean data
		foreach($fdata as $key=>$val) {
			if(!is_array($val)) {
				$fdata[$key] = stripslashes($val);
			}
			else {
				$fdata[$key] = array();
				foreach($val as $arr_val) {$fdata[$key][] = stripslashes($arr_val);}
			}
		}

		// save data
		foreach($fdata as $key=>$val) {
			update_post_meta($post_id, $key, $fdata[$key]); 
		}
		
		// be sure old meta is deleted
		delete_post_meta($post_id, 'gg_use_slider');
	}

    return $post_id;
}
add_action('save_post','gg_wp_gall_meta_save');







/**************************************************************/






///////////////////////////////////
// FRONTEND IMPLEMENTATION

function gg_wp_gallery_manag_frontend($foo, $atts) {
	global $post;
	
	extract(shortcode_atts( array(
		'ids' => '',
		'orderby' => ''
	), $atts ) );
	
    get_post_meta($post->ID); // use only one query
    
	$use_it 	= gg_gall_static::check_default_val($post->ID, 'gg_affect_wp_gall', false);
	$random 	= ($orderby == 'rand') ? '1' : 0; 
	$wm 		= (get_post_meta($post->ID, 'gg_watermark', true)) ? '1' : '0';

	if($use_it && !empty($ids)) {
		gg_wp_gall_images($post->ID, $ids); // get and cache
		$layout = get_post_meta($post->ID, 'gg_layout', true);
		
		
		// slider
		if($layout == 'slider') {
			$w = (int)get_post_meta($post->ID, 'gg_slider_w', true) . get_post_meta($post->ID, 'gg_slider_w_type', true);
			$h = (int)get_post_meta($post->ID, 'gg_slider_h', true) . get_post_meta($post->ID, 'gg_slider_h_type', true);
			$autop = get_post_meta($post->ID, 'gg_slider_autoplay', true);
			
			$code = do_shortcode('[g-slider gid="'.$post->ID.'" width="'.$w.'" height="'.$h.'" random="'.$random.'" autoplay="'.$autop.'" watermark="'.$wm.'" wp_gall_hash="'.'-'. md5($ids) .'"]');	
		}
		
		
		// carousel
		else if($layout == 'carousel') {
			$h = get_post_meta($post->ID, 'gg_car_img_h', true);
			$cols = get_post_meta($post->ID, 'gg_car_cols', true);
			$rows = get_post_meta($post->ID, 'gg_car_rows', true);
			$ms = get_post_meta($post->ID, 'gg_car_multiscroll', true);
			$center = get_post_meta($post->ID, 'gg_car_centermode', true);
			$nocrop = (int)get_post_meta($post->ID, 'gg_car_nocrop', true);

			$code = do_shortcode('[g-carousel gid="'.$post->ID.'" height="'.$h.'" per_time="'.$cols.'" rows="'.$rows.'" multiscroll="'.$ms.'" center="'.$center.'" 
									nocrop="'.$nocrop.'" random="'.$random.'" watermark="'.$wm.'" wp_gall_hash="'.'-'.md5($ids).'"]');	
		}
		
		
		// image-to-gallery
		else if($layout == 'itg') {
			$itg_w			= (int)get_post_meta($post->ID, 'gg_itg_w', true); if(!$itg_w) {$itg_w = 100;}
			$itg_w_type 	= get_post_meta($post->ID, 'gg_itg_w_type', true);
			$itg_h			= (int)get_post_meta($post->ID, 'gg_itg_h', true); if(!$itg_h) {$itg_h = 75;}
			$itg_h_type 	= get_post_meta($post->ID, 'gg_itg_h_type', true);
			$itg_layout 	= get_post_meta($post->ID, 'gg_itg_layout', true);
			$itg_img_num 	= get_post_meta($post->ID, 'gg_itg_img_num', true);
			$itg_font_size 	= get_post_meta($post->ID, 'gg_itg_font_size', true);
			$itg_cust_txt	= get_post_meta($post->ID, 'gg_itg_cust_txt', true);

			$code = do_shortcode('[g-itg gid="'.$post->ID.'" width="'.$itg_w.$itg_w_type.'" img_h="'.$itg_h.$itg_h_type.'" layout="'.$itg_layout.'" img_num="'.$itg_img_num.'" 
									font_size="'.$itg_font_size.'" random="'.$random.'" watermark="'.$wm.'" wp_gall_hash="'.'-'.md5($ids).'"]'. $itg_cust_txt .'[/g-itg]');	
		}
		
		
		// gallery
		else {
			$pag_system = get_post_meta($post->ID, 'gg_pag_system', true);
			$overlay = '';
			
			if(!is_string($ids)) {
				$ids = implode(',', $ids);	
			}
			
			$code = do_shortcode('[g-gallery gid="'.$post->ID.'" random="'.$random.'" watermark="'.$wm.'" pagination="'.$pag_system.'" overlay="'.$overlay.'" wp_gall_hash="'.'-'.md5($ids).'"]');
		}
		
		return $code;
	}
	else {
        return $foo;
    }
}
add_filter('post_gallery', 'gg_wp_gallery_manag_frontend', 999, 2);




// Wordpress gallery images - get and cache
function gg_wp_gall_images($post_id, $img_list, $use_captions = false) {
	if(!is_string($img_list)) {
		$img_list = implode(',', $img_list);	
	}
	
	$new_gall_hash = '-'.md5($img_list); 
	$cached_list = get_post_meta($post_id, 'gg_new_wp_gall_img_list'.$new_gall_hash, true); 
	
	// if equal to the cached - do anything
	if($img_list == $cached_list) {return true;}
	
	
	// otherwise fetch everything and compose the gallery array
	else {
		$args = array(
			'post_type' => 'attachment', 
			'post_mime_type' =>'image', 
			'post_status' => 'inherit', 
			'posts_per_page' => -1,
			'orderby' => 'post__in',
			'post__in' => explode(',', $img_list)
		);
		$query = new WP_query($args);

		$images = array();
		foreach($query->posts as $image) {
			if(trim($image->guid) != '') {
				$images[] = array(
					'img_src'	=> $image->ID,
					'thumb' 	=> 'c',
					'author'	=> '',  
					'title'		=> $image->post_title,
					'descr'		=> $image->post_content,
					'link_opt'	=> '', 
					'link'		=> ''
				);
			}
		} 
	
		gg_gall_static::save_data($post_id, $images, $autopop = false, $new_gall_hash);
		update_post_meta($post_id, 'gg_new_wp_gall_img_list'.$new_gall_hash, $img_list); 
	}
	
	return true;
}





// WP 5+ - Gutenberg needs contents to be scanned in order to create a workaround
function gg_on_guten_gallery($block_content, $block) {
    
    // is this post affected?
	global $post;
	if(!is_object($post) || !gg_gall_static::check_default_val($post->ID, 'gg_affect_wp_gall', false)) {
		return $block_content;		
	}
    
    if($block['blockName'] !== "core/gallery") {
        return $block_content;
    }

    $ids = array();

    // WP 5.9+
    if(array_key_exists('innerBlocks', $block) && is_array($block['innerBlocks'])) {
        foreach($block['innerBlocks'] as $inner_block) {
            
            if(isset($inner_block['blockName']) && $inner_block['blockName'] === 'core/image') {
                $ids[] = $inner_block['attrs']['id'];
            }
        }
    }

    // older WP
    elseif(array_key_exists('attrs', $block) && is_array($block['attrs']) && array_key_exists('ids', $block['attrs']) && is_array($block['attrs']['ids'])) {
        $ids = $block['attrs']['ids'];
    }
    
    if(empty($ids)) {
        return $block_content;
    }

    return do_shortcode('[gallery ids="'. implode(',', $ids) .'"]');
}
add_filter('render_block', 'gg_on_guten_gallery', 11, 2);


