<?php
//Setup theme constant and default data

/**
*  Begin Global variables functions
*/

//Get default WordPress wpdb variable
function swap_get_wpdb() {
	global $wpdb;
	return $wpdb;
}

//Get default WordPress wp_query variable
function swap_get_wp_query() {
	global $wp_query;
	return $wp_query;
}
//Get default WordPress paged variable
function swap_get_paged() {
	global $paged;
	return $paged;
}

/*
	Get products list
*/
$args = array(
    'numberposts' => -1,
    'post_type' => array('products'),
);

$products_arr = get_posts($args);
$products_select = array();

foreach($products_arr as $product)
{
	$products_select[$product->ID] = $product->post_title;
}
//Get contact form 7 form list
$contactform7_arr = array();
$contactform7_arr[-1] = '';

//Check if contact form 7 plugin is installed	
$contactform7_plugin_path = 'contact-form-7/wp-contact-form-7.php';

if( !function_exists('is_plugin_active') ) {
	include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
}

$contactform7_activated = is_plugin_active($contactform7_plugin_path);
if($contactform7_activated)
{
	$contactform7_obj_arr = WPCF7_ContactForm::find($args);
	
	if(!empty($contactform7_obj_arr) && is_array($contactform7_obj_arr))
	{
		foreach($contactform7_obj_arr as $contactform7_obj)
		{
			$contactform7_id = $contactform7_obj->id();
			$contactform7_title = $contactform7_obj->title();
			
			$contactform7_arr[$contactform7_id] = $contactform7_title;
		}
	}
}
//add_filter( 'wpcf7_autop_or_not', '__return_false' );

$postmetas = 
	array (
	
		
	
	
		'gallery' => array(
		
		
	
			array(
				"section" 		=> "Gallery Attributes", 
				"id" 			=> "gallery_video", 
				"type" 			=> "file", 
				"title" 		=> esc_html__("Gallery Video", 'swap'), 
				"description" 	=> esc_html__("Upload Video", 'swap')
			),
		),
	
	
			'testimonials' => array(
		
		
	
			array(
				"section" 		=> "Testimonial Attributes", 
				"id" 			=> "testimonial_designation", 
				"type" 			=> "text", 
				"title" 		=> esc_html__("Testimonial Designation", 'swap'), 
				"description" 	=> esc_html__("Enter Testimonial Designation", 'swap')
			),
		),
			
				
				
				
				'drones' => array(
		array(
				"section" 		=> "Drone Attributes", 
				"id" 			=> "drone_price", 
				"type" 			=> "text", 
				"title" 		=> esc_html__("Drone Price", 'swap'), 
				"description" 	=> esc_html__("Enter Drone Price", 'swap')
			),
			
			
			
			array(
				"section" 		=> "Drone Attributes", 
				"id" 			=> "drone_image1", 
				"type" 			=> "file", 
				"title" 		=> esc_html__("Drone Image 1", 'swap'), 
				"description" 	=> esc_html__("Upload Drone Image 615X430", 'swap'),
                      
			),
			array(
				"section" 		=> "Drone Attributes", 
				"id" 			=> "drone_video", 
				"type" 			=> "file", 
				"title" 		=> esc_html__("Drone video", 'swap'), 
				"description" 	=> esc_html__("Upload Drone Video ", 'swap'),
                      
			),
			array(
				"section" 		=> "Drone Attributes", 
				"id" 			=> "drone_smallvideo", 
				"type" 			=> "file", 
				"title" 		=> esc_html__("Drone Gif", 'swap'), 
				"description" 	=> esc_html__("Upload Drone Gif ", 'swap'),
                      
			),
			
			array(
				"section" 		=> "Drone Attributes", 
				"id" 			=> "drone_speed", 
				"type" 			=> "text", 
				"title" 		=> esc_html__("Drone Speed", 'swap'), 
				"description" 	=> esc_html__("Enter Drone Speed ", 'swap'),
                      
			),
			
			array(
				"section" 		=> "Drone Attributes", 
				"id" 			=> "drone_flighttime", 
				"type" 			=> "text", 
				"title" 		=> esc_html__("Drone Flight Time", 'swap'), 
				"description" 	=> esc_html__("Enter Drone Flight Time ", 'swap'),
                      
			),
			
			
			array(
				"section" 		=> "Drone Attributes", 
				"id" 			=> "drone_range", 
				"type" 			=> "text", 
				"title" 		=> esc_html__("Drone Transmission Range", 'swap'), 
				"description" 	=> esc_html__("Enter Drone Transmission Range ", 'swap'),
                      
			),
			
			
			array(
				"section" 		=> "Drone Attributes", 
				"id" 			=> "drone_Triplechannel", 
				"type" 			=> "text", 
				"title" 		=> esc_html__("Drone Triple Channel Video", 'swap'), 
				"description" 	=> esc_html__("Enter Drone Triple Channel Video ", 'swap'),
                      
			),
			
				array(
				"section" 		=> "Drone Attributes", 
				"id" 			=> "drone_bgimage", 
				"type" 			=> "file", 
				"title" 		=> esc_html__("Drone Background Image", 'swap'), 
				"description" 	=> esc_html__("Upload Drone Background Image  ", 'swap'),
                      
			),
			
			array(
				"section" 		=> "Drone Attributes", 
				"id" 			=> "drone_features_img", 
				"type" 			=> "file", 
				"title" 		=> esc_html__("Drone Features Image", 'swap'), 
				"description" 	=> esc_html__("Upload Drone Features Image  ", 'swap'),
                      
			),
			
			
			array(
				"section" 		=> "Drone Attributes", 
				"id" 			=> "drone_features", 
				"type" 			=> "adding_list_group", 
				"title" 		=> esc_html__("Drone Features", 'swap'), 
				"description" 	=> esc_html__("Enter Drone Features", 'swap')
			),
					
		
				
					
			array(
				"section" 		=> "Drone Attributes", 
				"id" 			=> "drone_gallery_title", 
				"type" 			=> "text", 
				"title" 		=> esc_html__("Drone Gallery title", 'swap'), 
				"description" 	=> esc_html__("Enter Gallery title", 'swap')
			),
			
			array(
				"section" 		=> "Drone Attributes", 
				"id" 			=> "drone_gallery_description", 
				"type" 			=> "textarea", 
				"title" 		=> esc_html__("Drone Gallery Description", 'swap'), 
				"description" 	=> esc_html__("Enter Gallery Description", 'swap')
			),
			
			
				),
	
);

function create_meta_box() {

	global $postmetas;
	
	if(!isset($_GET['post_type']) OR empty($_GET['post_type']))
	{
		if(isset($_GET['post']) && !empty($_GET['post']))
		{
			$post_obj = get_post($_GET['post']);
			$_GET['post_type'] = $post_obj->post_type;
		}
		else
		{
			$_GET['post_type'] = 'post';
		}
	}
	
	if ( function_exists('add_meta_box') && isset($postmetas) && count($postmetas) > 0 ) {  
		foreach($postmetas as $key => $postmeta)
		{
			if($_GET['post_type']==$key && !empty($postmeta))
			{
				add_meta_box( 'metabox', ucfirst($key).' Options', 'new_meta_box', $key, 'normal', 'high' );
			}
		}
	}

}  

function new_meta_box() {
	global $post, $postmetas, $gallery_template_urls;
	
	if(!isset($_GET['post_type']) OR empty($_GET['post_type']))
	{
		if(isset($_GET['post']) && !empty($_GET['post']))
		{
			$post_obj = get_post($_GET['post']);
			$_GET['post_type'] = $post_obj->post_type;
		}
		else
		{
			$_GET['post_type'] = 'post';
		}
	}

	echo '<input type="hidden" name="pp_meta_form" id="pp_meta_form" value="' . wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
	
	//Get visual page template option
	$pp_visual_page_templates = get_option('pp_visual_page_templates');
	
	$meta_section = '';

	foreach ( $postmetas as $key => $postmeta ) {
	
		if($_GET['post_type'] == $key)
		{
		
			foreach ( $postmeta as $postmeta_key => $each_meta ) {
		
				$meta_id = $each_meta['id'];
				$meta_title = $each_meta['title'];
				$meta_description = $each_meta['description'];
				
				if(isset($postmeta['section']))
				{
					$meta_section = $postmeta['section'];
				}
				
				$meta_type = '';
				if(isset($each_meta['type']))
				{
					$meta_type = $each_meta['type'];
				}
				
				echo '<div id="post_option_'.strtolower($each_meta['id']).'" class="pp_meta_option key'.intval($postmeta_key+1).' '.$meta_type.'">';
				echo "<div class=\"meta_title_wrapper\">";
				echo "<strong>".$meta_title."</strong>";
				
				echo "<div class='pp_widget_description'>$meta_description</div>";
				
				echo "</div>";
				echo "<div class=\"meta_title_field\">";
				
				if ($meta_type == 'checkbox') {
					$checked = get_post_meta($post->ID, $meta_id, true) == '1' ? "checked" : "";
					echo "<input type='checkbox' name='$meta_id' id='$meta_id' class='iphone_checkboxes' value='1' $checked />";
				}
				else if ($meta_type == 'select') {
					echo "<select name='$meta_id' id='$meta_id'>";
					
					if(!empty($each_meta['items']))
					{
						foreach ($each_meta['items'] as $key => $item)
						{
							echo '<option value="'.$key.'"';
							
							if($key == get_post_meta($post->ID, $meta_id, true))
							{
								echo ' selected ';
							}
							
							echo '>'.$item.'</option>';
						}
					}
					
					echo "</select>";
				}
				else if ($meta_type == 'template') {
					$current_value = get_post_meta($post->ID, $meta_id, true);
					echo "<input type='hidden' name='$meta_id' id='$meta_id' value='$current_value' />";
					echo "<ul name=\"".$meta_id."_list\" id=\"".$meta_id."_list\" class=\"meta_template_list\">";
					
					if(!empty($each_meta['items']))
					{
						foreach ($each_meta['items'] as $key => $template_name)
						{
							echo '<li data-parent="'.$meta_id.'" data-value="'.esc_attr($key).'" ';
							
							if($key == $current_value)
							{
								echo 'class="checked"';
							}
							
							echo '>';
							
							//Check if use visual page templates
						    if(!empty($pp_visual_page_templates))
						    {
								if(isset($gallery_template_urls[$key]))
								{
									echo '<a href="'.esc_url($gallery_template_urls[$key]).'" target="_blank" title="View Sample" class="tooltipster meta_template_link"><i class="fa fa-external-link"></i></a>';
								}
							}
							echo '<div class="template_title">'.$template_name.'</div>';
							echo '</li>';
						}
					}
					
					echo "</ul>";
				}
				else if ($meta_type == 'checkboxes') {
					if(!empty($each_meta['items']))
					{
						$checkboxes_post_values = get_post_meta($post->ID, $meta_id, true);
						
						echo '<div class="wp-tab-panel"><ul id="'.$meta_id.'_checklist">';
					
						foreach ($each_meta['items'] as $key => $item)
						{
							echo '<li>';
							echo '<input name="'.$meta_id.'[]" id="'.$meta_id.'[]" type="checkbox"  value="'.$key.'"';
							
							if(is_array($checkboxes_post_values) && !empty($checkboxes_post_values) && in_array($key, $checkboxes_post_values))
							{
								echo ' checked ';
							}
							
							echo '/>'.$item;
							echo '</li>';
						}
						
						echo '</ul></div>';
					}
				}
				else if ($meta_type == 'adding_list') {
					
					echo '<table id="'.$meta_id.'_sortable" class="adding_list_sortable">';
		
					echo '<thead>';
					echo '<tr>';
					
					echo '<th width="5%"></th>';
					echo '<th width="90%">'.esc_html__("Title", 'swap').'</th>';
					echo '<th width="5%"></th>';
					
					echo '</tr>';
					echo '</thead>';
					
					echo '<tbody>';
					
					$adding_list_arr = get_post_meta($post->ID, $meta_id, true);
					
					if(!empty($adding_list_arr) && is_array($adding_list_arr))
					{
						foreach($adding_list_arr as $key => $adding_list_item)
						{
							echo '<tr>';
							echo '<td class="sortable_handle"><span class="dashicons dashicons-menu"></span></td>';
							echo '<td><input type="text" class="widefat" name="'.$meta_id.'[]" value="'.esc_attr($adding_list_item).'"></td>';
							echo '<td><a class="button adding_list_remove_row" href="javascript:;"><span class="dashicons dashicons-no-alt"></span></a></td>';
							echo '</tr>';
						}
					}
					else
					{
						echo '<tr>';
							echo '<td class="sortable_handle"><span class="dashicons dashicons-menu"></span></td>';
							echo '<td><input type="text" class="widefat" name="'.$meta_id.'[]" value=""></td>';
							echo '<td><a class="button adding_list_remove_row" href="javascript:;"><span class="dashicons dashicons-no-alt"></span></a></td>';
							echo '</tr>';
					}
					
					echo '</tbody>';
					echo '</table>';
		
					echo '<a id="'.$meta_id.'_add_row" class="button adding_list_add_row" data-target="'.$meta_id.'_sortable" data-metaid="'.$meta_id.'" href="javascript:;">'.esc_html__("Add another", 'swap').'</a>';
					
					echo '<script>';
					echo '
						jQuery("#'.$meta_id.'_add_row").on( "click", function(){
							var rowHTML = \'\';
							rowHTML+= \'<tr>\';
							rowHTML+= \'<td class="sortable_handle"><span class="dashicons dashicons-menu"></span></td>\';
							rowHTML+= \'<td><input type="text" class="widefat" name="'.$meta_id.'[]"></td>\';
							rowHTML+= \'<td><a class="button adding_list_remove_row" href="javascript:;"><span class="dashicons dashicons-no-alt"></span></a></td>\';
							rowHTML+= \'</tr>\';
							
							jQuery("#'.$meta_id.'_sortable").find("tbody:last").append(rowHTML);
							addingListRemoveEvent();
						});
						
	
					';
					echo '</script>';
					 echo '<script>
					 addingListRemoveEvent();
function addingListRemoveEvent()
{	
	jQuery(\'.adding_list_remove_row\').on( \'click\', function(){
		jQuery(this).parent(\'td\').parent(\'tr\').remove();
	});
}</script>';
			
				}
				
				
				else if ($meta_type == 'adding_list_group') {
					
					echo '<table id="'.$meta_id.'_sortable" class="adding_list_group_sortable">';
		
					echo '<thead>';
					echo '<tr>';
					
					echo '<th width="5%"></th>';
					echo '<th width="45%">'.esc_html__("Title", 'swap').'</th>';
					echo '<th width="45%">'.esc_html__("Content", 'swap').'</th>';
					echo '<th width="5%"></th>';
					
					echo '</tr>';
					echo '</thead>';
					
					echo '<tbody>';
					
					$adding_list_group_arr = get_post_meta($post->ID, $meta_id, true);
				
					
					if(!empty($adding_list_group_arr) && is_array($adding_list_group_arr))
					{
					    
						for ($i = 0; $i < count($adding_list_group_arr['title']); $i++) 
						{
						  
							echo '<tr>';
							echo '<td class="sortable_handle"><span class="dashicons dashicons-menu"></span></td>';
							echo '<td><input type="text" class="widefat" name="'.$meta_id.'[title][]" value="'.esc_attr($adding_list_group_arr['title'][$i]).'"></td>';
							echo '<td><input type="text" class="widefat" name="'.$meta_id.'[content][]" value="'.esc_attr($adding_list_group_arr['content'][$i]).'"></td>';
							echo '<td><a class="button adding_list_group_remove_row" href="javascript:;"><span class="dashicons dashicons-no-alt"></span></a></td>';
							echo '</tr>';
						
						}
					}
					else
					{
						echo '<tr>';
							echo '<td class="sortable_handle"><span class="dashicons dashicons-menu"></span></td>';
							echo '<td><input type="text" class="widefat" name="'.$meta_id.'[title][]" value=""></td>';
							echo '<td><input type="text" class="widefat" name="'.$meta_id.'[content][]" value=""></td>';
							echo '<td><a class="button adding_list_group_remove_row" href="javascript:;"><span class="dashicons dashicons-no-alt"></span></a></td>';
							echo '</tr>';
					}
					
					echo '</tbody>';
					echo '</table>';
		
					echo '<a id="'.$meta_id.'_add_row" class="button adding_list_group_add_row" data-target="'.$meta_id.'_sortable" data-metaid="'.$meta_id.'" href="javascript:;">'.esc_html__("Add another", 'swap').'</a>';
					
					echo '<script>';
					echo '
						jQuery("#'.$meta_id.'_add_row").on( "click", function(){
							var rowHTML = \'\';
							rowHTML+= \'<tr>\';
							rowHTML+= \'<td class="sortable_handle"><span class="dashicons dashicons-menu"></span></td>\';
							rowHTML+= \'<td><input type="text" class="widefat" name="'.$meta_id.'[title][]"></td>\';
							rowHTML+= \'<td><input type="text" class="widefat" name="'.$meta_id.'[content][]"></td>\';
							rowHTML+= \'<td><a class="button adding_list_group_remove_row" href="javascript:;"><span class="dashicons dashicons-no-alt"></span></a></td>\';
							rowHTML+= \'</tr>\';
							
							jQuery("#'.$meta_id.'_sortable").find("tbody:last").append(rowHTML);
							addingListRemoveEvent();
						});
						
	
					';
					echo '</script>';
					 echo '<script>
					 addingListRemoveEvent();
function addingListRemoveEvent()
{	
	jQuery(\'.adding_list_group_remove_row\').on( \'click\', function(){
		jQuery(this).parent(\'td\').parent(\'tr\').remove();
	});
}</script>';
			
				}

				
				else if ($meta_type == 'file') { 
				    echo "<input type='text' name='$meta_id' id='$meta_id' class='' value='".get_post_meta($post->ID, $meta_id, true)."' style='width:calc(100% - 75px)' /><input id='".$meta_id."_button' name='".$meta_id."_button' type='button' value='Upload' class='metabox_upload_btn button' readonly='readonly' rel='".$meta_id."' style='margin:0 0 0 5px' />";
				      	echo '<script>';
				       echo "var formfield = '';
	
	jQuery('.metabox_upload_btn').on( 'click', function() {
	    jQuery('.fancybox-overlay').css('visibility', 'hidden');
	    jQuery('.fancybox-wrap').css('visibility', 'hidden');
     	formfield = jQuery(this).attr('rel');
	    
	    var send_attachment_bkp = wp.media.editor.send.attachment;
	    wp.media.editor.send.attachment = function(props, attachment) {
	     	jQuery('#'+formfield).attr('value', attachment.url);
	
	        wp.media.editor.send.attachment = send_attachment_bkp;
	        jQuery('.fancybox-overlay').css('visibility', 'visible');
	     	jQuery('.fancybox-wrap').css('visibility', 'visible');
	    }
	
	    wp.media.editor.open();
     	return false;
    });";
    	echo '</script>';
				}
				else if ($meta_type == 'textarea') {
					if(isset($postmeta[$postmeta_key]['sample']))
					{
						echo "<textarea name='$meta_id' id='$meta_id' class=' hint' style='width:100%' rows='7' title='".$postmeta[$postmeta_key]['sample']."'>".get_post_meta($post->ID, $meta_id, true)."</textarea>";
					}
					else
					{
						echo "<textarea name='$meta_id' id='$meta_id' class='' style='width:100%' rows='7'>".get_post_meta($post->ID, $meta_id, true)."</textarea>";
					}
				}			
				else {
					if(isset($postmeta[$postmeta_key]['sample']))
					{
						echo "<input type='text' name='$meta_id' id='$meta_id' class='' title='".$postmeta[$postmeta_key]['sample']."' value='".get_post_meta($post->ID, $meta_id, true)."' style='width:100%' />";
					}
					else
					{
						echo "<input type='text' name='$meta_id' id='$meta_id' class='' value='".get_post_meta($post->ID, $meta_id, true)."' style='width:100%' />";
					}
				}
				
				echo "</div>";
				echo '</div>';
				
				
						
			}
		}
	}

}

function save_postdata( $post_id ) {

	global $postmetas;

	// verify this came from the our screen and with proper authorization,
	// because save_post can be triggered at other times

	if ( isset($_POST['pp_meta_form']) && !wp_verify_nonce( $_POST['pp_meta_form'], plugin_basename(__FILE__) )) {
		return $post_id;
	}

	// verify if this is an auto save routine. If it is our form has not been submitted, so we dont want to do anything

	if ((defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) || (defined('DOING_AJAX') && DOING_AJAX) || isset($_REQUEST['bulk_edit']))
        return;

	// Check permissions

	if ( isset($_POST['post_type']) && 'page' == $_POST['post_type'] ) {
		if ( !current_user_can( 'edit_page', $post_id ) )
			return $post_id;
		} else {
		if ( !current_user_can( 'edit_post', $post_id ) )
			return $post_id;
	}

	// OK, we're authenticated

	if ( $parent_id = wp_is_post_revision($post_id) )
	{
		$post_id = $parent_id;
	}
	
	if (isset($_POST['pp_meta_form'])) 
	{
		//If import page content builder
		if(is_admin() && isset($_POST['ppb_import_current']) && !empty($_POST['ppb_import_current']))
		{
			//If upload import builder file
			if(isset($_FILES['ppb_import_current_file']['name']) && !empty($_FILES['ppb_import_current_file']['name']))
			{
				//Check if zip file
				$import_filename = $_FILES['ppb_import_current_file']['name'];
				$import_type = $_FILES['ppb_import_current_file']['type'];
				$is_zip = FALSE;
				$new_filename = basename($import_filename, '_.zip');
				
				$accepted_types = array('application/zip', 
	                                'application/x-zip-compressed', 
	                                'multipart/x-zip', 
	                                'application/s-compressed');
	 
			    foreach($accepted_types as $mime_type) {
			        if($mime_type == $import_type) {
			            $is_zip = TRUE;
			            break;
			        } 
			    }
			}
			//If import demo pages
			else if(isset($_POST['ppb_import_demo_file']) && !empty($_POST['ppb_import_demo_file']))
			{
				$is_zip = FALSE;
			}
			//If import from saved template
			else if(isset($_POST['ppb_import_template_key']) && !empty($_POST['ppb_import_template_key']))
			{
				$is_zip = FALSE;
			}
			
			if($is_zip)
			{
				WP_Filesystem();
				$upload_dir = wp_upload_dir();
				$cache_dir = '';
				
				if(isset($upload_dir['basedir']))
				{
					$cache_dir = $upload_dir['basedir'].'/meteors';
				}
				
				move_uploaded_file($_FILES["ppb_import_current_file"]["tmp_name"], $cache_dir.'/'.$import_filename);
				//$unzipfile = unzip_file( $cache_dir.'/'.$import_filename, $cache_dir);
				
				$zip = new ZipArchive();
				$x = $zip->open($cache_dir.'/'.$import_filename);
				
				for($i = 0; $i < $zip->numFiles; $i++) {
			        $new_filename = $zip->getNameIndex($i);
			        break;
			    }  
				
				if ($x === true) {
					$zip->extractTo($cache_dir); 
					$zip->close();
				}

				$import_options_json = file_get_contents($cache_dir.'/'.$new_filename);
				unlink($cache_dir.'/'.$import_filename);
				unlink($cache_dir.'/'.$new_filename);
			}
			else
			{
				//If import demo pages
				if(isset($_POST['ppb_import_demo_file']) && !empty($_POST['ppb_import_demo_file']))
				{
					$import_options_json = file_get_contents(get_template_directory().'/cache/demos/pages/'.$_POST['ppb_import_demo_file']);
				}
				//If import from saved template
				else if(isset($_POST['ppb_import_template_key']) && !empty($_POST['ppb_import_template_key']))
				{
					$import_options_json = get_option( SHORTNAME."_template_".$_POST['ppb_import_template_key']);
				}
				else
				{
					//If .json file then import
					$import_options_json = $wp_filesystem->get_contents($_FILES["ppb_import_current_file"]["tmp_name"]);
					
					if(empty($import_options_json))
					{
						$import_options_json = file_get_contents($_FILES["ppb_import_current_file"]["tmp_name"]);
					}
				}
			}
			
			$import_options_arr = json_decode($import_options_json, true);
			
			if(isset($import_options_arr['ppb_form_data_order'][0]) && !empty($import_options_arr['ppb_form_data_order'][0]))
			{
				swap_page_update_custom_meta($post_id, $import_options_arr['ppb_form_data_order'][0], 'ppb_form_data_order');
			}
			
			$ppb_item_arr = explode(',', $import_options_arr['ppb_form_data_order'][0]);
			
			if(is_array($ppb_item_arr) && !empty($ppb_item_arr))
			{
				foreach($ppb_item_arr as $key => $ppb_item_arr)
				{
					if(isset($import_options_arr[$ppb_item_arr.'_data'][0]) && !empty($import_options_arr[$ppb_item_arr.'_data'][0]))
					{
						swap_page_update_custom_meta($post_id, $import_options_arr[$ppb_item_arr.'_data'][0], $ppb_item_arr.'_data');
					}
					
					if(isset($import_options_arr[$ppb_item_arr.'_size'][0]) && !empty($import_options_arr[$ppb_item_arr.'_size'][0]))
					{
						swap_page_update_custom_meta($post_id, $import_options_arr[$ppb_item_arr.'_size'][0], $ppb_item_arr.'_size');
					}
				}
			}
			
			header("Location: ".$_SERVER['HTTP_REFERER']);
			exit;
		}
	
		//If export page content builder
		if(is_admin() && isset($_POST['ppb_export_current']) && !empty($_POST['ppb_export_current']))
		{
			$page_title = get_the_title($post_id);
		
			$json_file_name = THEMENAME.'-Page-'.sanitize_title($page_title).'-Export-'.date('m-d-Y_hia');
			$json_file_name = strtolower($json_file_name);
	
			header('Content-disposition: attachment; filename='.$json_file_name.'.json');
			header('Content-type: application/json');
			
			//Get current content builder data
			$ppb_form_data_order = get_post_meta($post_id, 'ppb_form_data_order');
			$export_options_arr = array();
			
			if(!empty($ppb_form_data_order))
			{
				$export_options_arr['ppb_form_data_order'] = $ppb_form_data_order;

				//Get each builder module data
				$ppb_form_item_arr = explode(',', $ppb_form_data_order[0]);
			
				foreach($ppb_form_item_arr as $key => $ppb_form_item)
				{
					$ppb_form_item_data = get_post_meta($post_id, $ppb_form_item.'_data');
					$export_options_arr[$ppb_form_item.'_data'] = $ppb_form_item_data;
					
					$ppb_form_item_size = get_post_meta($post_id, $ppb_form_item.'_size');
					$export_options_arr[$ppb_form_item.'_size'] = $ppb_form_item_size;
				}
			}
		
			echo json_encode($export_options_arr);
			
			exit;
		}
	
		foreach ( $postmetas as $postmeta ) {
			foreach ( $postmeta as $each_meta ) {
				
				if (isset($_POST[$each_meta['id']]) && $_POST[$each_meta['id']]) {
					update_custom_meta($post_id, $_POST[$each_meta['id']], $each_meta['id']);
				}
				
				if (isset($_POST[$each_meta['id']]) && $_POST[$each_meta['id']] == "") {
					delete_post_meta($post_id, $each_meta['id']);
				}
				
				if (!isset($_POST[$each_meta['id']])) {
					delete_post_meta($post_id, $each_meta['id']);
				}
			
			}
		}
	
		// Saving Page Builder Data
		if(isset($_POST['ppb_enable']) && !empty($_POST['ppb_enable']))
		{
		    update_custom_meta($post_id, $_POST['ppb_enable'], 'ppb_enable');
		}
		else
		{
		    delete_post_meta($post_id, 'ppb_enable');
		}
		
		if(isset($_POST['ppb_form_data_order']) && !empty($_POST['ppb_form_data_order']))
		{
		    update_custom_meta($post_id, $_POST['ppb_form_data_order'], 'ppb_form_data_order');
		    
		    $ppb_item_arr = explode(',', $_POST['ppb_form_data_order']);
		    if(is_array($ppb_item_arr) && !empty($ppb_item_arr))
		    {
		    	foreach($ppb_item_arr as $key => $ppb_item_arr)
		    	{
		    		if(isset($_POST[$ppb_item_arr.'_data']) && !empty($_POST[$ppb_item_arr.'_data']))
		    		{
		    			update_custom_meta($post_id, $_POST[$ppb_item_arr.'_data'], $ppb_item_arr.'_data');
		    		}
		    		
		    		if(isset($_POST[$ppb_item_arr.'_size']) && !empty($_POST[$ppb_item_arr.'_size']))
		    		{
		    			update_custom_meta($post_id, $_POST[$ppb_item_arr.'_size'], $ppb_item_arr.'_size');
		    		}
		    	}
		    }
		}
		//If content builder is empty
		else
		{
		    update_custom_meta($post_id, '', 'ppb_form_data_order');
		}
		
		//If enable Content Builder then also copy its content to standard page content
		if (isset($_POST['ppb_enable']) && !empty($_POST['ppb_enable']) && ! wp_is_post_revision( $post_id ) )
		{
			//unhook this function so it doesn't loop infinitely
			remove_action('save_post', 'save_postdata');
		
			//update the post, which calls save_post again
			$ppb_page_content = swap_apply_builder($post_id, 'portfolios', FALSE);
			
			$current_post = array (
		      'ID'           => $post_id,
		      'post_content' => $ppb_page_content,
		    );
		    
		    wp_update_post($current_post);
		    if (is_wp_error($post_id)) {
				$errors = $post_id->get_error_messages();
				foreach ($errors as $error) {
					echo esc_html($error);
				}
			}
	
			//re-hook this function
			add_action('save_post', 'save_postdata');
		}
	}
}

function update_custom_meta($postID, $newvalue, $field_name) {

	if (isset($_POST['pp_meta_form'])) 
	{
		if (!get_post_meta($postID, $field_name)) {
			add_post_meta($postID, $field_name, $newvalue);
		} else {
			update_post_meta($postID, $field_name, $newvalue);
		}
	}

}

//init

add_action('admin_menu', 'create_meta_box'); 
add_action('save_post', 'save_postdata'); 

/**
 * Excerpt length
 */
function swap_excerpt_length( $length ) {

	if ( is_admin() ) {
		return $length;
	}

	$excerpt = get_theme_mod('swap_exc_length', '50');
	return $excerpt;
}
add_filter( 'excerpt_length', 'swap_excerpt_length', 999 );


?>