<?php
// SAVING GALLERY METAS (manual images saved via ajax)


function gg_gallery_meta_save($post_id) {
	if(!isset($_POST['gg_gallery_noncename']) || !wp_verify_nonce($_POST['gg_gallery_noncename'], 'gg_gall_builder')) {
        return;
    }
    include_once(GG_DIR.'/classes/simple_form_validator.php');

    $validator = new simple_fv(GG_ML);
    $indexes = array();

    $to_save = array(
        'gg_type',
        'gg_username',
        'gg_psw',
        'gg_connect_id',

        'gg_wp_cat',
        'gg_cpt_tax',
        'gg_cpt_tax_term',
        'gg_album',
        'gg_fb_album',
        'gg_gdrive_album',
        'gg_onedrive_album',
        'gg_rml_folder',
        'gg_ngg_gallery',

        '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',

        'gg_orderby',
        'gg_sitemap_page_url'
    );
    foreach($to_save as $ts) {
        $indexes[] = array('index'=>$ts, 'label'=>'foo');	
    }


    $indexes[] = array('index'=>'gg_autopop', 'label'=>'Gallery auto population');
    $indexes[] = array('index'=>'gg_auto_author', 'label'=>'Catch authors');
    $indexes[] = array('index'=>'gg_auto_title', 'label'=>'Catch titles');
    $indexes[] = array('index'=>'gg_auto_descr', 'label'=>'Catch descriptions');
    $indexes[] = array('index'=>'gg_auto_link', 'label'=>'Auto link');

    $indexes[] = array('index'=>'gg_forced_author', 'label'=>'Custom author');
    $indexes[] = array('index'=>'gg_cache_interval', 'label'=>'Cache interval');
    $indexes[] = array('index'=>'gg_auto_random', 'label'=>'Random Catching');
    $indexes[] = array('index'=>'gg_max_images', 'label'=>'Max images in gallery');

    $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) {

        // skip google drive folder if empty
        if($key == 'gg_gdrive_album' && empty($val)) {
            continue;   
        }

        update_post_meta($post_id, $key, $fdata[$key]);
    }
}
add_action('save_post','gg_gallery_meta_save');
