<?php


////////////////////////////////////////////////
////// SET PREDEFINED STYLES ///////////////////
////////////////////////////////////////////////

function gg_set_predefined_style() {
	if(!isset($_POST['lcwp_nonce']) || !gg_static::verify_nonce($_POST['lcwp_nonce'], 'lcwp_nonce')) {
        wp_die('Cheating?');
    }
	if(!isset($_POST['style'])) {
        wp_die('data is missing');
    }
	require_once(GG_DIR .'/settings/preset_styles.php');

	$style_data = gg_preset_styles_data( sanitize_text_field(wp_unslash($_POST['style'])) );
	if(empty($style_data)) {
        wp_die('Style not found');
    }
	
	
	// override values
	foreach($style_data as $key => $val) {
		update_option($key, $val);		
	}


	// if is not forcing inline CSS - create static file
	if(!get_option('gg_force_inline_css')) {
		gg_static::create_frontend_css();
	}
	
	wp_die('success');
}
add_action('wp_ajax_gg_set_predefined_style', 'gg_set_predefined_style');




////////////////////////////////////////////////
////// CREATE WATERMARK CACHE //////////////////
////////////////////////////////////////////////

function gg_create_wm_cache() {
    if(!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'lcwp_nonce')) {
        wp_die('Cheating?');
    }
    
	// specific gallery or any gallery?
	$gid = (isset($_POST['gid'])) ? absint($_POST['gid']) : false;
	
	if(!$gid) {
		$args = array(
			'post_type' => 'gg_galleries',
			'numberposts' => -1,
			'post_status' => 'publish'
		);
		$galleries = get_posts($args);
	}
	else {
		$galleries = array( get_post($gid));	
	}
	
	
	// perform
	foreach($galleries as $gallery) {
		$gid = $gallery->ID;
		$type = get_post_meta($gid, 'gg_type', true);
		$images = gg_gall_static::get_data($gid);
	
		if(is_array($images)) {
			foreach($images as $img) { 
				$full_src = gg_static::img_src_on_type($img['img_src'], $type);
				gg_static::watermark_image($full_src);
			}
		}	
	}

	wp_die('success');
}
add_action('wp_ajax_gg_create_wm_cache', 'gg_create_wm_cache');




////////////////////////////////////////////////
////// CLEAN WATERMARK CACHE ///////////////////
////////////////////////////////////////////////

function gg_clean_wm_cache() {
	if(!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'lcwp_nonce')) {
        wp_die('Cheating?');
    }
    
    $wp_dirs = wp_upload_dir();
	$cache_dir = trailingslashit($wp_dirs['basedir']) . 'gg_watermarked';
	
	// folder exists?
	if(!@file_exists($cache_dir)) {
		wp_die('success');	
	}
	
	// clean
	foreach(scandir($cache_dir) as $file) {
		$ext = gg_static::stringToExt($file);
		$accepted = array('.jpg', '.jpeg', '.gif', '.png', '.webp', '.avif');
		
		if(in_array($ext, $accepted) && file_exists($cache_dir.'/'.$file)) {
			unlink($cache_dir.'/'.$file);
		}	
	}

	wp_die('success');
}
add_action('wp_ajax_gg_clean_wm_cache', 'gg_clean_wm_cache');





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





////////////////////////////////////////////////
////// ADD COLLECTION TERM /////////////////////
////////////////////////////////////////////////

function gg_add_coll() {
    if(!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'gg_coll_builder')) {
        wp_die('cheating?');
    }
    
	if(!isset($_POST['coll_name'])) {
        wp_die('missing data');
    }
	$name = sanitize_text_field(wp_unslash($_POST['coll_name']));
	
	$resp = wp_insert_term(
        $name, 
        'gg_collections', 
        array(
            'slug' => sanitize_title($name)
        )
    );
	
	if(is_array($resp)) {
        wp_die('success');
    }
	else {
		$err_mes = $resp->errors['term_exists'][0];
		wp_die($err_mes);
	}
}
add_action('wp_ajax_gg_add_coll', 'gg_add_coll');



////////////////////////////////////////////////
////// LOAD COLLECTIONS LIST ///////////////////
////////////////////////////////////////////////

function gg_coll_list() {
    if(!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'gg_coll_builder')) {
        wp_die('cheating?');
    }
    
	$colls = get_terms(array(
        'taxonomy'   => 'gg_collections',
        'hide_empty' => false,
    ));
    $to_return = array();
    
	foreach($colls as $coll) {
		$to_return[] = array('id' => $coll->term_id, 'name' => $coll->name);
	}

	echo json_encode($to_return);
	wp_die();
}
add_action('wp_ajax_gg_get_colls', 'gg_coll_list');




////////////////////////////////////////////////
////// DELETE THE COLLECTION TERM //////////////
////////////////////////////////////////////////

function gg_del_coll() {
	if(!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'gg_coll_builder')) {
        wp_die('cheating?');
    }
    
    if(!isset($_POST['coll_id'])) {
        wp_die('missing data');
    }
	$id = absint($_POST['coll_id']);
	
	$resp = wp_delete_term($id, 'gg_collections');
	($resp) ? wp_die('success') : wp_die('error during the collection deletion');
}
add_action('wp_ajax_gg_del_coll', 'gg_del_coll');




////////////////////////////////////////////////
////// DISPLAY COLLECTION BUILDER //////////////
////////////////////////////////////////////////

function gg_coll_builder() {
	if(!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'gg_coll_builder')) {
        wp_die('cheating?');
    }
    
    if(!isset($_POST['coll_id'])) {
        wp_die('missing data');
    }
	$coll_id = absint($_POST['coll_id']);
			
	// item categories list
	$item_cats = get_terms(array(
        'taxonomy'   => 'gg_collections',
        'hide_empty' => false,
    ));
	
	// cat and page selector
	?>
    <h2></h2>

    <div id="gg_grid_builder_cat" class="postbox">
        <h3 class="hndle"><?php esc_html_e("Galleries Picker", 'gg_ml'); ?></h3>
        <div class="inside">

            <div class="gg_mainbox_meta">
                <table class="widefat gg_table gg_metabox_table gg_bordernone">
                    <tr>
                        <td>
                            <label><?php esc_html_e("Gallery Categories", 'gg_ml'); ?></label>

                            <select name="gg_gall_cats" class="gg_lc_select_dd" autocomplete="off">
                                <option value="all"><?php esc_html_e('Any category', 'gg_ml') ?></option>

                                <?php 
            foreach($item_cats as $cat) {
                // WPML fix - get original ID
                if (function_exists('icl_object_id') && isset($GLOBALS['sitpress'])) {
                    global $sitepress;
                    $term_id = icl_object_id($cat->term_id, 'gg_gall_categories', true, $sitepress->get_default_language());
                }
                else {
                    $term_id = $cat->term_id;
                }

                echo '<option value="'. absint($term_id) .'">'. esc_html($cat->name) .'</option>';
            }
                                ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <div>
                                <label><?php esc_html_e("Select galleries", 'gg_ml'); ?></label>

                                <input type="text" name="gg_coll_gall_search" placeholder="🔎 <?php esc_attr_e('search galleries', 'gg_ml') ?>" autocomplete="off" />
                                <i class="gg_cgs_del dashicons dashicons-no-alt" title="<?php esc_attr_e('clear search', 'gg_ml') ?>"></i>

                                <a href="javascript:void(0)" class="gg_cgs_show_all">(<?php esc_html_e('expand', 'gg_ml') ?>)</a>
                            </div>

                            <ul id="gg_coll_gall_picker">
                                <?php 
                                    $post_list = gg_cat_galleries_code('all'); 
        echo (!$post_list) ? '<span>'. esc_html__('No galleries found', 'gg_ml') .' ..</span>' : gg_static::wp_kses_ext($post_list);
                                ?>
                            </ul>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>


    <div class="postbox">
        <h3 class="hndle"><?php esc_html_e("Collection Builder", 'gg_ml') ?></h3>
        <div class="inside">

            <div id="visual_builder_wrap">
                <table id="gg_coll_builder">
                    <tbody>	
                        <?php
                        $coll_data = get_term($coll_id, 'gg_collections');
                        $coll_composition = unserialize($coll_data->description);
                        $coll_galleries = (array)$coll_composition['galleries'];
                        $has_a_gallery = false;

                        foreach( $coll_galleries as $gdata) {
                            $gid = $gdata['id'];
                            $gall_img = gg_coll_static::get_gall_first_img($gid);	

                            if(get_post_status($gid) == 'publish' && $gall_img) {

                                $rand_check 	= (isset($gdata['rand']) && $gdata['rand'] != 0) ? 'checked="checked"' : '';
                                $wmark_check 	= (isset($gdata['wmark']) && $gdata['wmark'] != 0) ? 'checked="checked"' : '';  
                                $filter_check	= (isset($gdata['filters']) && $gdata['filters'] != 0) ? 'checked="checked"' : ''; 
                                $search_check	= (isset($gdata['search']) && $gdata['search'] != 0) ? 'checked="checked"' : ''; 	

                                $link_subj 	= (isset($gdata['link_subj'])) ? $gdata['link_subj'] : 'none'; 
                                $link_val 	= (isset($gdata['link_val'])) ? $gdata['link_val'] : '';
                                $descr 		= (isset($gdata['descr'])) ? $gdata['descr'] : ''; 

                                // custom image
                                $cust_img = '';
                                $cust_img_id = '';
                                $ci_icon_sel_class = '';  

                                if(isset($gdata['cust_img']) && $gdata['cust_img']) {
                                    $cust_img = gg_static::inline_thumb_src($gdata['cust_img'], 500, 500, 70);
                                    $cust_img_id = $gdata['cust_img'];
                                    $ci_icon_sel_class = 'gg_coll_cust_img_sel';   
                                } 

                                $orig_thumb = gg_static::inline_thumb_src($gall_img, 500, 500, 70);
                                $thumb_to_use = (empty($cust_img)) ? $orig_thumb : $cust_img;

                                // categories
                                $gall_cats = gg_coll_static::gallery_cats($gid, 'list', ', ');
                                $gall_cats = (empty($gall_cats)) ? '<em>'. esc_html__('No associated categories', 'gg_ml') .' ..</em>' : '<em class="dashicons dashicons-tag gg_coll_gall_cats_icon" title="'. esc_attr__('Categories', 'gg_ml') .'"></em> '.$gall_cats;

                                $has_a_gallery = true;
                                echo gg_static::wp_kses_ext(str_replace(
                                    array(
                                        '%%GALL_ID%%',
                                        '%%THUMB_TO_USE%%', 
                                        '%%CUST-ICON_SEL_CLASS%%', 
                                        '%%CUST_IMG_ID%%', 
                                        '%%ORIG_THUMB%%', 
                                        '%%GALL_CATS%%', 
                                        '%%GALL_TITLE%%', 
                                        '%%RANDOM_CHECK%%', 
                                        '%%FILTER_CHECK%%',
                                        '%%SEARCH_CHECK%%', 
                                        '%%WATERM_CHECK%%',
                                        '%%DESCR%%'
                                    ),
                                    array(
                                        $gid,
                                        $thumb_to_use,
                                        $ci_icon_sel_class,
                                        $cust_img_id,
                                        $orig_thumb,
                                        $gall_cats,
                                        get_the_title($gid),
                                        (isset($gdata['rand']) && $gdata['rand'] != 0) ? 'checked="checked"' : '',
                                        (isset($gdata['filters']) && $gdata['filters'] != 0) ? 'checked="checked"' : '',
                                        (isset($gdata['search']) && $gdata['search'] != 0) ? 'checked="checked"' : '',	
                                        (isset($gdata['wmark']) && $gdata['wmark'] != 0) ? 'checked="checked"' : '',  
                                        esc_textarea($descr),
                                    ),
                                    gg_coll_static::manual_gall_code_block($link_subj, $link_val)
                                ));
                            }
                        }
    
                        if(!$has_a_gallery) {
                            echo '
                              <tr>
                                <td colspan="5">
                                    <p>'.esc_html__('No selected galleries', 'gg_ml').' ..</p>
                                </td>
                              </tr>';
                        }
                        ?>
                    </tbody>
                </table>
            </div> 

        </div>
    </div>
	<?php
	wp_die();
}
add_action('wp_ajax_gg_coll_builder', 'gg_coll_builder');






////////////////////////////////////////////////
////// GET GALLERIES FOR A CATEGORY ////////////
////////////////////////////////////////////////

function gg_cat_galleries_code($fnc_cat = false) {	
	if(!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'gg_coll_builder')) {
        wp_die('cheating?');
    }
    
    $cat = $fnc_cat;
	$code = '';
	
	// if is not called directly
	if(!$cat) {
		if(!isset($_POST['gallery_cat'])) {wp_die('missing data');}
		$cat = sanitize_text_field(wp_unslash($_POST['gallery_cat']));
	}

	$post_list = gg_coll_static::cat_galleries($cat);	
	if(!$post_list) {
        return false;
    }
	
	foreach($post_list as $post) {
		$code .= '
		<li style="background-image: url('. esc_attr(gg_static::inline_thumb_src($post['img'], 200, 170, 70)) .');" data-id="'. absint($post['id']) .'" title="'. esc_attr__('add to collection', 'gg_ml') .'" data-gg-cats="'. esc_attr($post['cats']) .'" data-gg-img="'. esc_attr(gg_static::inline_thumb_src($post['img'], 500, 500, 70)) .'">
			
            <div title="'. esc_attr($post['title']) .'">'. esc_html($post['title']) .'</div>
		</li>';
	}

	
	if($fnc_cat == false) {
        wp_die( $code );
    } else {
        return $code;
    }
}
add_action('wp_ajax_gg_cat_galleries_code', 'gg_cat_galleries_code');






////////////////////////////////////////////
////// SAVE COLLECTION CONTENTS ////////////
////////////////////////////////////////////

function gg_save_coll() {	
	if(!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'gg_coll_builder')) {
        wp_die('cheating?');
    }
    
    if(!isset($_POST['coll_id'])) {
        wp_die('missing data');
    }
	$coll_id = absint($_POST['coll_id']);
	
	$data = array();
	$to_check = array('gall_list', 'cust_img', 'random_flag', 'filters_flag', 'search_flag', 'wmark_flag', 'link_subj', 'link_val', 'coll_descr');
	foreach($to_check as $tc) {
		$data[$tc] = (!isset($_POST[$tc])) ? '' : sanitize_text_field(wp_unslash($_POST[$tc]));	
	}
	
	// create the categories array
	$terms_array = array();
	if(is_array($data['gall_list'])) {
		foreach($data['gall_list'] as $post_id) {
			$pid_terms = wp_get_post_terms($post_id, 'gg_gall_categories', array("fields" => "ids"));
			
			foreach($pid_terms as $pid_term) { 
				$terms_array[] = $pid_term;
			}	
		}
		$terms_array = array_unique($terms_array);
	}
	
	// create the galleries array
	$galleries = array();
	if(is_array($data['gall_list'])) {
		$a = 0;
		foreach($data['gall_list'] as $gid) {
			$galleries[] = array(
				'id' 		=> $gid,
				'cust_img'	=> $data['cust_img'][$a],
				'rand'		=> $data['random_flag'][$a],
				'filters'	=> $data['filters_flag'][$a],
				'search'	=> $data['search_flag'][$a],
				'wmark' 	=> $data['wmark_flag'][$a],
				'link_subj' => $data['link_subj'][$a],
				'link_val' 	=> esc_attr(wp_unslash($data['link_val'][$a])),
				'descr'		=> esc_attr(wp_unslash($data['coll_descr'][$a])) 
			);	
			$a++;
		}
	}

	// final array
	$coll_arr = array(
		'galleries' => $galleries,
		'categories' => $terms_array
	);
	
	// update the collection term
	$result = wp_update_term($coll_id, 'gg_collections', array(
	  'slug' => uniqid(),
	  'description' => serialize($coll_arr)
	));
	
	
	if(is_wp_error($result)) {
        echo 'error';
    }
	else {
        gg_coll_static::wpml_dynamic_txt_sync($coll_id, $galleries);
        echo 'success';
    }	

	wp_die();
}
add_action('wp_ajax_gg_save_coll', 'gg_save_coll');






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






////////////////////////////////////////////////
//// SAVE WP FILESYSTEM CREDENTIALS (for no "direct" methods) 
////////////////////////////////////////////////

function gg_save_wp_filesys_data() {
	if (!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'lcwp_ajax')) {
        wp_die('Cheating?');
    };
	
	include_once(GG_DIR .'/classes/gg_local_images.php');
	$fm = new gg_local_images();
	
	// save credentials
	$data = array(
		'hostname',
		'username',
		'password',
		'public_key',
		'private_key',
		'connection_type'
	);
	
	foreach($data as $key) {
		$data[$key] = (isset($_POST[$key])) ? sanitize_text_field(wp_unslash($_POST[$key])) : '';
	}

	// try connecting
	$response = $fm->is_ready();
	if($response === true) {
        echo 'success';
        update_option('gg_filesys_creds', $data);
    }
    else {
        echo $response;
    }
	wp_die();
}
add_action('wp_ajax_gg_save_wp_filesys_data', 'gg_save_wp_filesys_data');






////////////////////////////////////////////////
//// SAVE GG ALBUMS BASEPATHS ////////////////// 
////////////////////////////////////////////////

function gg_save_gg_album_basepaths() {
	if (!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'lcwp_ajax')) {
        wp_die('Cheating?');
    };

	include_once(GG_DIR .'/classes/gg_local_images.php');
	$fm = new gg_local_images();
	
	// get and validate data
    if(
        !isset($_POST['basepath']) || !isset($_POST['baseurl']) || 
        empty($_POST['basepath']) || empty($_POST['baseurl']) ||
        !preg_match('/^(\.\.\/(?:\.\.\/)*)?(?!.*?\/\/)(?!(?:.*\/)?\.+(?:\/|$)).+$/', wp_unslash($_POST['basepath'])) || 
        !filter_var(wp_unslash($_POST['baseurl']), FILTER_VALIDATE_URL)
    ) {
        wp_die( esc_html__('Please insert valid values', 'gg_ml'));
    }

    $basepath   = untrailingslashit(sanitize_text_field(wp_unslash($_POST['basepath'])));
    $baseurl    = untrailingslashit(sanitize_text_field(wp_unslash($_POST['baseurl'])));
    
	
    // check path existence
    $fm->folder_path = $basepath;
    
    if($fm->is_ready()) {
        update_option('gg_albums_basepath', $basepath);
        update_option('gg_albums_baseurl', $baseurl);
        
        wp_die('success');
    }
    else {
        wp_die('Folder not found', 'gg_ml');       
    }
}
add_action('wp_ajax_gg_save_gg_album_basepaths', 'gg_save_gg_album_basepaths');






////////////////////////////////////////////////
////// LIM - CREATE FOLDER ///////////////////// 
////////////////////////////////////////////////

function gg_lim_create_folder() {
	if (!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'gg_files_manager')) {
        wp_die('Cheating?');
    };
    
	include_once(GG_DIR .'/classes/gg_local_images.php');
	$fm = new gg_local_images();
	
    // startup engine
    $fm_response = $fm->is_ready();
    if($fm_response !== true) {
        wp_die($fm_response);     
    }
    
    // get and validate folder name
    $f_name = (isset($_POST['f_name'])) ? sanitize_text_field(wp_unslash($_POST['f_name'])) : '';

    if(empty($f_name) || !preg_match('/^[a-zA-Z0-9_-]+$/', $f_name)) {
        wp_die( esc_html__('Invalid format', 'gg_ml'));        
    }
    elseif(strlen($f_name) > 150) {
        wp_die( esc_html__('Too long', 'gg_ml'));          
    }
    elseif($fm->folder_exists($f_name)) {
        wp_die( esc_html__("A folder with same name already exists", 'gg_ml'));          
    }
    
    
    // create
    if($fm->create_folder($f_name)) {
        wp_die('success');    
    } else {
        wp_die( esc_html__('Error creating the folder', 'gg_ml') );    
    }
}
add_action('wp_ajax_gg_lim_create_folder', 'gg_lim_create_folder');






////////////////////////////////////////////////
////// LIM -  DELETE FOLDER //////////////////// 
////////////////////////////////////////////////

function gg_lim_delete_folder() {
	if(!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'gg_files_manager')) {
        wp_die('Cheating?');
    };
    
	include_once(GG_DIR .'/classes/gg_local_images.php');
	$fm = new gg_local_images();
	
    // startup engine
    $fm_response = $fm->is_ready();
    if($fm_response !== true) {
        wp_die($fm_response);     
    }
    
    // get and validate folder name
    $f_name = (isset($_POST['f_name'])) ? sanitize_text_field(wp_unslash($_POST['f_name'])) : '';
    if(empty($f_name)) {
        wp_die( esc_html__('Folder name missing', 'gg_ml'));        
    }
    
    
    // delete
    $response = $fm->delete($f_name);
    
    if($response === true) {
        wp_die('success');    
    } else {
        wp_die( esc_html__('Error creating the folder', 'gg_ml') );    
    }
}
add_action('wp_ajax_gg_lim_delete_folder', 'gg_lim_delete_folder');






////////////////////////////////////////////////
////// LIM - GET IMAGES //////////////////////// 
////////////////////////////////////////////////

function gg_lim_get_images() {
	if(!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'gg_files_manager')) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => 'Cheating?'
        )));
    };

	include_once(GG_DIR .'/classes/gg_local_images.php');
	$fm = new gg_local_images();
	
    // startup engine
    $fm_response = $fm->is_ready();
    if($fm_response !== true) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => $fm_response
        )));
    }
    
    // get and validate folder name
    $f_name = (isset($_POST['f_name'])) ? sanitize_text_field(wp_unslash($_POST['f_name'])) : '';
    if(empty($f_name)) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => esc_html__('Folder name missing', 'gg_ml')
        )));   
    }
    
    
    // get
    $response = $fm->list_files($f_name);
    
    if(is_array($response)) {
        wp_die(json_encode(array(
            'status'   => 'success',
            'images'   => $response
        )));   
    } 
    else {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => $response
        )));   
    }
}
add_action('wp_ajax_gg_lim_get_images', 'gg_lim_get_images');





////////////////////////////////////////////////
////// LIM - MOVE FILES INTO ANOTHER FOLDER //// 
////////////////////////////////////////////////

function gg_lim_move_files() {
	if (!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'gg_files_manager')) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => 'Cheating?'
        )));
    };
    
	include_once(GG_DIR .'/classes/gg_local_images.php');
	$fm = new gg_local_images();
	
    // startup engine
    $fm_response = $fm->is_ready();
    if($fm_response !== true) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => $fm_response
        ))); 
    }
    
    
    // get and validate folder name
    $old_f_name = (isset($_POST['old_f_name'])) ? sanitize_text_field(wp_unslash($_POST['old_f_name'])) : '';
    $new_f_name = (isset($_POST['new_f_name'])) ? sanitize_text_field(wp_unslash($_POST['new_f_name'])) : '';

    if(
        empty($old_f_name) || !preg_match('/^[a-zA-Z0-9_-]+$/', $old_f_name) ||
        empty($new_f_name) || !preg_match('/^[a-zA-Z0-9_-]+$/', $new_f_name)
    ) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => esc_html__('Please choose the destination folder', 'gg_ml')
        )));     
    }
    elseif(!$fm->folder_exists($new_f_name)) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => esc_html__("Destination folder not found", 'gg_ml')
        )));         
    }
    elseif($old_f_name == $new_f_name) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => esc_html__("Current and destination folders coincide", 'gg_ml')
        )));             
    }
    
    
    // get files to move
    $files = (isset($_POST['files']) && is_array($_POST['files'])) ? array_map('sanitize_text_field', $_POST['files']) : array();
    if(empty($files)) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => esc_html__("No files to move", 'gg_ml')
        )));          
    }
    
    $problems = array();
    
    foreach($files as $filename) {
        $old_path = $fm->folder_path .'/'. $old_f_name .'/'. $filename;
        $new_path = $fm->folder_path .'/'. $new_f_name .'/'. $filename;
        
        if(!$fm->fs->move($old_path, $new_path)) {
            $problems[] = $filename;    
        }
    }
    
    wp_die(json_encode(array(
        'status'   => 'success',
        'problems' => $problems
    )));
}
add_action('wp_ajax_gg_lim_move_files', 'gg_lim_move_files');





////////////////////////////////////////////////
////// LIM - DELETE FILES ////////////////////// 
////////////////////////////////////////////////

function gg_lim_delete_files() {
	if (!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'gg_files_manager')) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => 'Cheating?'
        )));
    };
    
	include_once(GG_DIR .'/classes/gg_local_images.php');
	$fm = new gg_local_images();
	
    // startup engine
    $fm_response = $fm->is_ready();
    if($fm_response !== true) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => $fm_response
        )));       
    }


    // get and validate folder name
    $f_name = (isset($_POST['f_name'])) ? sanitize_text_field(wp_unslash($_POST['f_name'])) : '';
    if(empty($f_name) || !preg_match('/^[a-zA-Z0-9_-]+$/', $f_name)) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => esc_html__('Target folder missing', 'gg_ml')
        )));     
    }

    // get files to delete
    $files = (isset($_POST['files']) && is_array($_POST['files'])) ? array_map('sanitize_text_field', $_POST['files']) : array();
    if(empty($files)) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => esc_html__("No files to delete", 'gg_ml')
        )));           
    }
    
    
    $problems = array();
    foreach($files as $filename) {
        if($fm->delete($f_name, $filename) !== true) {
           $problems[] = $filename;
        }
    }
    
    wp_die(json_encode(array(
        'status'   => 'success',
        'problems' => $problems
    )));
}
add_action('wp_ajax_gg_lim_delete_files', 'gg_lim_delete_files');





////////////////////////////////////////////////
////// LIM - UPDATE IMAGES IPTC DATA /////////// 
////////////////////////////////////////////////

function gg_lim_update_images_data() {
	if (!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'gg_files_manager')) {
        wp_die('Cheating?');
    };

	include_once(GG_DIR .'/classes/gg_local_images.php');
	$fm = new gg_local_images();
	
    // startup engine
    $fm_response = $fm->is_ready();
    if($fm_response !== true) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => $fm_response
        )));   
    }
    
    // get and validate folder name
    $f_name = (isset($_POST['f_name'])) ? sanitize_text_field(wp_unslash($_POST['f_name'])) : '';
    if(empty($f_name)) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => esc_html__('Folder name missing', 'gg_ml')
        )));   
    }
    
    
    // get images data (multidimensional array(filename => array(author, title, ec) ) )
    $data = (isset($_POST['img_data']) && is_array($_POST['img_data'])) ? array_map('sanitize_text_field', $_POST['img_data']) : array();
    if(empty($data)) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => esc_html__('Images data missing', 'gg_ml')
        )));       
    }
    
    
    // perform
    foreach($data as $filename => $file_data) {
        include_once(GG_DIR .'/classes/iptc.php');
        
        // only JPEG
        if(!in_array( gg_static::stringToExt($filename), array('.jpg', '.jpeg') )) {
            continue;   
        }
        
        $img_path = $fm->folder_path .'/'. $f_name .'/'. $filename;
        $iptc = new Iptc($img_path, $fm->fs);
        
        $iptc->apply_tags(array(
            '080' => $file_data['author'],
            '005' => $file_data['title'],
            '120' => $file_data['descr'],
            '025' => explode(',', $file_data['tags'])
        ));
    }
    
    wp_die(json_encode(array(
        'status'   => 'success',
    )));
}
add_action('wp_ajax_gg_lim_update_images_data', 'gg_lim_update_images_data');





////////////////////////////////////////////////
//// LIM - IMAGE UPLOAD ////////////////////////
////////////////////////////////////////////////

function gg_lim_upload() {
	if (!isset($_POST['nonce']) || !gg_static::verify_nonce($_POST['nonce'], 'gg_files_manager')) {
		wp_die(json_encode(array(
            'status'    => 'error', 
            'message'   => "Cheating?"
        )));
	};

    include_once(GG_DIR .'/classes/gg_local_images.php');
	$fm = new gg_local_images();
	
    // startup engine
    $fm_response = $fm->is_ready();
    if($fm_response !== true) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => $fm_response
        )));      
    }
    
    
    // get and validate folder name
    $f_name = (isset($_POST['f_name'])) ? sanitize_text_field(wp_unslash($_POST['f_name'])) : '';
    if(empty($f_name) || !preg_match('/^[a-zA-Z0-9_-]+$/', $f_name)) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => esc_html__('Target folder missing', 'gg_ml')
        )));     
    }
	
    
    // get and validate file
	if(!isset($_FILES['gg_lim_image'])) {
		wp_die(json_encode(array(
            'status'    =>'error', 
            'message'   => esc_html__("File not found", 'gg_ml')
        )));	
	}
	$file = $_FILES['gg_lim_image'];
	
	$result = $fm->validate_file($file);
	if($result !== true) {
		wp_die(json_encode(array(
            'status'    =>'error', 
            'message'   => $result
        ))); 	
	}
	
	
	// upload file
	$response = $fm->upload_file($f_name, $file);
	if($response !== true) {
        wp_die(json_encode(array(
            'status'    => 'error',
            'message'   => $response
        )));
	}
	
	wp_die(json_encode(array(
        'status'    => 'success', 
        'img_data'  => $fm->get_file($f_name, $fm->last_uploaded_filename)
    )));	
}
add_action('wp_ajax_gg_lim_upload', 'gg_lim_upload');