<?php

/**
 * AIT Theme Admin
 *
 * Copyright (c) 2011, AIT s.r.o (http://ait-themes.com)
 *
 */

function aitDirItemPostType() {
	register_post_type( 'ait-dir-item',
		array(
			'labels' => array(
				'name'			=> 'Items',
				'singular_name' => 'Item',
				'add_new'		=> 'Add new',
				'add_new_item'	=> 'Add new item',
				'edit_item'		=> 'Edit item',
				'new_item'		=> 'New item',
				'not_found'		=> 'No items found',
				'not_found_in_trash' => 'No items found in Trash',
				'menu_name'		=> 'Items',
			),
			'description' => 'Manipulating with Items',
			'public' => true,
			'show_in_nav_menus' => true,
			'supports' => array(
				'title',
				'thumbnail',
				'author',
				'editor',
				'excerpt',
				'page-attributes',
				'comments',
			),
			'show_ui' => true,
			'show_in_menu' => true,
			'menu_icon' => AIT_FRAMEWORK_URL . '/CustomTypes/dir-item-tour/dir-item-tour.png',
			'menu_position' => $GLOBALS['aitThemeCustomTypes']['dir-item-tour'],
			'has_archive' => true,
			'query_var' => 'dir-item',
			'rewrite' => array('slug' => 'item'),
			'capability_type' => 'ait-dir-item',
			'map_meta_cap' => true
		)
	);
	aitDirItemTaxonomies();

	register_post_type( 'ait-dir-item-offer',
		array(
			'labels' => array(
				'name'			=> 'Item Offers',
				'singular_name' => 'Offer',
				'add_new'		=> 'Add new',
				'add_new_item'	=> 'Add new offer',
				'edit_item'		=> 'Edit offer',
				'new_item'		=> 'New offer',
				'not_found'		=> 'No offers found',
				'not_found_in_trash' => 'No offers found in Trash',
				'menu_name'		=> 'Item Offers',
			),
			'description' => 'Manipulating with tour offers',
			'public' => true,
			'show_in_nav_menus' => true,
			'supports' => array(
				'title',
				'editor'
			),
			'show_ui' => true,
			'show_in_menu' => true,
			'menu_icon' => AIT_FRAMEWORK_URL . '/CustomTypes/dir-item-tour/dir-item-tour.png',
			'menu_position' => $GLOBALS['aitThemeCustomTypes']['dir-item-tour'] + 1,
			'publicly_queryable' => false,
			'capability_type' => 'ait-dir-item-offer',
			'map_meta_cap' => true
		)
	);

	flush_rewrite_rules(false);
}

function aitDirItemTaxonomies() {

	register_taxonomy( 'ait-dir-item-category', array( 'ait-dir-item' ), array(
		'hierarchical' => true,
		'labels' => array(
			'name'			=> 'Item Types',
			'singular_name' => _x( 'Type', 'taxonomy singular name', 'ait'),
			'search_items'	=> __( 'Search Type', 'ait'),
			'all_items'		=> __( 'All Types', 'ait'),
			'parent_item'	=> __( 'Parent Type', 'ait'),
			'parent_item_colon' => __( 'Parent Type:', 'ait'),
			'edit_item'		=> __( 'Edit Type', 'ait'),
			'update_item'	=> __( 'Update Type', 'ait'),
			'add_new_item'	=> __( 'Add New Type', 'ait'),
			'new_item_name' => __( 'New Type Name', 'ait'),
		),
		'show_ui' => true,
		'rewrite' => array( 'slug' => 'type' ),
		'capabilities' => array(
			'assign_terms' => 'assign_dir_category'
		)
	));

	register_taxonomy( 'ait-dir-item-location', array( 'ait-dir-item' ), array(
		'hierarchical' => true,
		'labels' => array(
			'name'			=> 'Item Destinations',
			'singular_name' => _x( 'Destination', 'taxonomy singular name', 'ait'),
			'search_items'	=> __( 'Search Destination', 'ait'),
			'all_items'		=> __( 'All Destinations', 'ait'),
			'parent_item'	=> __( 'Parent Destination', 'ait'),
			'parent_item_colon' => __( 'Parent Destination:', 'ait'),
			'edit_item'		=> __( 'Edit Destination', 'ait'),
			'update_item'	=> __( 'Update Destination', 'ait'),
			'add_new_item'	=> __( 'Add New Destination', 'ait'),
			'new_item_name' => __( 'New Destination Name', 'ait'),
		),
		'show_ui' => true,
		'rewrite' => false,
		'capabilities' => array(
			'assign_terms' => 'assign_dir_location'
		)
	));

	register_taxonomy( 'ait-dir-item-amenities', array( 'ait-dir-item' ), array(
		'hierarchical' => true,
		'labels' => array(
			'name'			=> 'Item Amenities',
			'singular_name' => _x( 'Amenities', 'taxonomy singular name', 'ait'),
			'search_items'	=> __( 'Search Amenities', 'ait'),
			'all_items'		=> __( 'All Amenities', 'ait'),
			'parent_item'	=> __( 'Parent Amenities', 'ait'),
			'parent_item_colon' => __( 'Parent Amenities:', 'ait'),
			'edit_item'		=> __( 'Edit Amenities', 'ait'),
			'update_item'	=> __( 'Update Amenities', 'ait'),
			'add_new_item'	=> __( 'Add New Amenities', 'ait'),
			'new_item_name' => __( 'New Amenities Name', 'ait'),
		),
		'show_ui' => true,
		'rewrite' => false,
		'capabilities' => array(
			'assign_terms' => 'assign_dir_amenities'
		)
	));

}
add_action( 'init', 'aitDirItemPostType');

function aitDirItemFeaturedImageMetabox() {
	global $wp_meta_boxes;
	// only if exist
	if(isset($wp_meta_boxes['ait-dir-item'])){
		foreach ($wp_meta_boxes['ait-dir-item'] as $contextName => $context) {
			foreach ($context as $boxesName => $boxes) {
				foreach ($boxes as $boxName => $box) {
					if($boxName == 'postimagediv'){
						remove_meta_box( 'postimagediv', 'ait-dir-item', 'side' );
						add_meta_box('postimagediv', 'Image for item', 'post_thumbnail_meta_box', 'ait-dir-item', 'normal', 'high');
					}
				}
			}
		}
	}
}
add_action('do_meta_boxes', 'aitDirItemFeaturedImageMetabox',1);

$dirItemOptions = new WPAlchemy_MetaBox(array(
	'id' => '_ait-dir-item',
	'title' => __('Item\'s details', 'ait'),
	'types' => array('ait-dir-item'),
	'context' => 'normal',
	'priority' => 'core',
	'config' => dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '.neon',
	'js' => dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '.js',
	'save_action' => 'tourSaveMetaAction'
));

$dirItemofferOptions = new WPAlchemy_MetaBox(array(
	'id' => '_ait-dir-item-offer',
	'title' => __('Offer\'s details', 'ait'),
	'types' => array('ait-dir-item-offer'),
	'context' => 'normal',
	'priority' => 'core',
	'config' => dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '-offer.neon',
	'js' => dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '-offer.js',
	'save_action' => 'offerSaveMetaAction'
));

function offerSaveMetaAction($meta,$postId) {
	update_post_meta( $postId, 'ait_item_id', $meta['itemId'] );
	update_post_meta( $postId, 'ait_date_from', date('Ymd',strtotime($meta['from'])) );
	update_post_meta( $postId, 'ait_date_to', date('Ymd',strtotime($meta['to'])) );
	update_post_meta( $postId, 'ait_date_price', $meta['price'] );
}

function tourSaveMetaAction($meta,$postId) {
	if (!empty($meta['featured'])) {
		update_post_meta( $postId, 'dir_featured', 'yes' );
	} else {
		delete_post_meta( $postId, 'dir_featured' );
	}
	$currentMeta = get_post_meta($postId, '_ait-dir-item', true);
	// check if lat and lng already exist and move new item
	if (!(empty($meta['gpsLatitude']) && empty($meta['gpsLongitude']))) {
		global $wpdb;
		$itemsMeta = $wpdb->get_results("SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_ait-dir-item'", OBJECT_K );
		foreach ($itemsMeta as $id => $metaDb) {
			$options = unserialize($metaDb->meta_value);
			if ($options && ($postId != $id) && ($options['gpsLatitude'] === $meta['gpsLatitude']) && ($options['gpsLongitude'] === $meta['gpsLongitude'])) {
				// calculate new position -> move
				if (function_exists("movePointByMeters")) {
					$movedPosition = movePointByMeters($meta['gpsLatitude'],$meta['gpsLongitude'],0,10);
					// save
					$currentMeta['gpsLatitude'] = (string) $movedPosition['lat'];
					$currentMeta['gpsLongitude'] = (string) $movedPosition['lng'];
					update_post_meta($postId, '_ait-dir-item', $currentMeta);
				}
			}
		}
	}
	if (empty($currentMeta['gpsLatitude'])) {
		$currentMeta['gpsLatitude'] = '0';
	}
	if (empty($currentMeta['gpsLongitude'])) {
		$currentMeta['gpsLongitude'] = '0';
	}
	update_post_meta($postId, '_ait-dir-item', $currentMeta);
}

function aitDirItemChangeColumns($cols) {

	global $aitThemeOptions, $current_user;
	if( isset($aitThemeOptions->members->easyAdminEnable) && isset( $current_user->roles ) && is_array( $current_user->roles ) && ( in_array('directory_1', $current_user->roles) || in_array('directory_2', $current_user->roles) || in_array('directory_3', $current_user->roles) || in_array('directory_4', $current_user->roles) || in_array('directory_5', $current_user->roles) ) ) {
		// easy admin columns
		$cols = array(
			'title'			=> __( 'Title', 'ait'),
			'tour_offers'	=> __( 'Offers', 'ait'),
			'thumbnail'		=> __( 'Image', 'ait'),
			'address' 		=> __( 'Address', 'ait'),
			'category'		=> __( 'Types', 'ait'),
			'ait-dir-item-location'	=> __( 'Destinations', 'ait'),
			'ait-dir-item-amenities' => __( 'Amenities', 'ait'),
			'date'			=> __( 'Modification date', 'ait')
		);
	} else {
		$cols = array(
			'cb'			=> '<input type="checkbox" />',
			'title'			=> __( 'Title', 'ait'),
			'tour_offers'	=> __( 'Offers', 'ait'),
			'author'		=> __( 'Author', 'ait'),
			'thumbnail'		=> __( 'Image', 'ait'),
			'address' 		=> __( 'Address', 'ait'),
			'category'		=> __( 'Types', 'ait'),
			'ait-dir-item-location'	=> __( 'Destinations', 'ait'),
			'ait-dir-item-amenities' => __( 'Amenities', 'ait'),
			'date'			=> __( 'Modification date', 'ait')
		);
	}
	return $cols;

}
add_filter( "manage_ait-dir-item_posts_columns", "aitDirItemChangeColumns" );

function aitDirItemOfferChangeColumns($cols) {
	
	global $aitThemeOptions, $current_user;
	if( isset($aitThemeOptions->members->easyAdminEnable) && isset( $current_user->roles ) && is_array( $current_user->roles ) && ( in_array('directory_1', $current_user->roles) || in_array('directory_2', $current_user->roles) || in_array('directory_3', $current_user->roles) || in_array('directory_4', $current_user->roles) || in_array('directory_5', $current_user->roles) ) ) {
		// easy admin columns
		$cols = array(
			'title'				=> __( 'Title', 'ait'),
			'offer_item'		=> __( 'Offer is for item', 'ait'),
			'offer_date_from'	=> __( 'From', 'ait'),
			'offer_date_to'		=> __( 'To', 'ait'),
			'offer_price'	=> __( 'Price', 'ait'),
			'offer_special'		=> __( 'Special', 'ait'),
			'offer_capacity'	=> __( 'Capacity', 'ait'),
			'date'				=> __( 'Modification date', 'ait')
		);
	} else {
		$cols = array(
			'cb'				=> '<input type="checkbox" />',
			'title'				=> __( 'Title', 'ait'),
			'offer_item'		=> __( 'Offer is for item', 'ait'),
			'author'			=> __( 'Author', 'ait'),
			'offer_date_from'	=> __( 'From', 'ait'),
			'offer_date_to'		=> __( 'To', 'ait'),
			'offer_price'	=> __( 'Price', 'ait'),
			'offer_special'		=> __( 'Special', 'ait'),
			'offer_capacity'	=> __( 'Capacity', 'ait'),
			'date'				=> __( 'Modification date', 'ait')
		);
	}
	return $cols;

}
add_filter( "manage_ait-dir-item-offer_posts_columns", "aitDirItemOfferChangeColumns" );

function aitDirItemCustomColumns($column, $postId) {
	global $dirItemOptions;
	$options = $dirItemOptions->the_meta();

	switch($column){

		case "tour_offers":
			$offers = getTourOffers($postId);
			if (!empty($offers)) {
				foreach ($offers as $key => $offer) {
					echo "<a href='".get_edit_post_link($offer->ID)."'>{$offer->post_title}</a><br>";
				}
			}
			break;

		case "ait-dir-item-location":
			$terms = get_the_terms($postId, 'ait-dir-item-location');
			if (!empty($terms)) {
				foreach($terms as $term){
					echo "<a href='".get_term_link($term, 'ait-dir-item-location')."' rel='tag'>{$term->name}</a>, ";
				}
			}
			break;

		case "ait-dir-item-amenities":
			$terms = get_the_terms($postId, 'ait-dir-item-amenities');
			if (!empty($terms)) {
				foreach($terms as $term){
					echo "<a href='".get_term_link($term, 'ait-dir-item-amenities')."' rel='tag'>{$term->name}</a>, ";
				}
			}
			break;

		case "address":
			if(isset($options['address'])){
				echo $options['address'];
			}
			break;

		case "offer_item":
			$itemId = get_post_meta( $postId, 'ait_item_id', true );
			if (!empty($itemId)) {
				$item = get_post( $itemId );
				if (isset($item)) {
					echo "<a href='".get_edit_post_link($item->ID)."'>{$item->post_title}</a>";
				}
			}
			break;

		case "offer_date_from":
			$options = get_post_meta( $postId, '_ait-dir-item-offer', true );
			$dateFormat = get_option( 'date_format', 'F j, Y' );
			if (!empty($options['from'])) {
				echo date($dateFormat,strtotime($options['from']));
			}
			break;

		case "offer_date_to":
			$options = get_post_meta( $postId, '_ait-dir-item-offer', true );
			$dateFormat = get_option( 'date_format', 'F j, Y' );
			if (!empty($options['to'])) {
				echo date($dateFormat,strtotime($options['to']));
			}
			break;

		case "offer_price":
			$options = get_post_meta( $postId, '_ait-dir-item-offer', true );
			$currency = (isset($GLOBALS['aitThemeOptions']->directory->currency)) ? $GLOBALS['aitThemeOptions']->directory->currency : '';
			if (!empty($options['price'])) {
				echo $currency . ' ' . $options['price'];
			}
			break;

		case "offer_special":
			$options = get_post_meta( $postId, '_ait-dir-item-offer', true );
			if (isset($options['special'])) {
				_e( 'Yes', 'ait' );
			} else {
				_e( 'No', 'ait' );
			}
			break;

		case "offer_capacity":
			$options = get_post_meta( $postId, '_ait-dir-item-offer', true );
			$currency = (isset($GLOBALS['aitThemeOptions']->directory->currency)) ? $GLOBALS['aitThemeOptions']->directory->currency : '';
			if (!empty($options['capacity'])) {
				echo $options['capacity'];
			} else {
				echo '0';
			}
			break;

	}
}
add_action( "manage_posts_custom_column", "aitDirItemCustomColumns", 10, 2);


/************************** Add meta ICON *****************************************/
add_action( 'ait-dir-item-category_edit_form_fields', 'edit_dir_item_category', 10, 2);
add_action( 'ait-dir-item-category_add_form_fields', 'add_dir_item_category', 10, 2);
function edit_dir_item_category($tag, $taxonomy) {
	$icon = get_option( 'ait_dir_item_category_'.$tag->term_id.'_icon', '' );
	$thumbnail = get_option( 'ait_dir_item_category_'.$tag->term_id.'_thumbnail', '' );
	$excerpt = get_option( 'ait_dir_item_category_'.$tag->term_id.'_excerpt', '' );

	?>
	<tr class="form-field">
		<th scope="row" valign="top"><label for="ait_dir_item_category_excerpt">Excerpt</label></th>
		<td>
			<textarea name="ait_dir_item_category_excerpt" id="ait_dir_item_category_excerpt" cols="30" rows="5"><?php echo $excerpt; ?></textarea>
		</td>
	</tr>
	<tr class="form-field">
		<th scope="row" valign="top"><label for="ait_dir_item_category_icon">Icon</label></th>
		<td>
			<input type="text" name="ait_dir_item_category_icon" id="ait_dir_item_category_icon" value="<?php echo $icon; ?>" style="width: 80%;"/>
			<input type="button" value="Select Image" class="media-select" id="ait_dir_item_category_icon_selectMedia" name="ait_dir_item_category_icon_selectMedia" style="width: 15%;">
			<br />
			<p class="description">Icon for category</p>
		</td>
	</tr>
	<tr class="form-field">
		<th scope="row" valign="top"><label for="ait_dir_item_category_thumbnail">Thumbnail</label></th>
		<td>
			<input type="text" name="ait_dir_item_category_thumbnail" id="ait_dir_item_category_thumbnail" value="<?php echo $thumbnail; ?>" style="width: 80%;"/>
			<input type="button" value="Select Image" class="media-select" id="ait_dir_item_category_thumbnail_selectMedia" name="ait_dir_item_category_thumbnail_selectMedia" style="width: 15%;">
			<br />
			<p class="description">Thumbnail for category</p>
		</td>
	</tr>
	<?php
}
function add_dir_item_category($tag) {
	?>
	<div class="form-field">
		<label for="ait_dir_item_category_excerpt">Excerpt</label>
		<textarea name="ait_dir_item_category_excerpt" id="ait_dir_item_category_excerpt" cols="30" rows="5"></textarea>
	</div>
	<div class="form-field">
		<label for="ait_dir_item_category_icon">Icon</label>
		<input type="text" name="ait_dir_item_category_icon" id="ait_dir_item_category_icon" value="" style="width: 80%;"/>
		<input type="button" value="Select Image" class="media-select" id="ait_dir_item_category_icon_selectMedia" name="ait_dir_item_category_icon_selectMedia" style="width: 15%;">
			<br />
			<p class="description">Icon for category</p>
	</div>
	<div class="form-field">
		<label for="ait_dir_item_category_thumbnail">Thumbnail</label>
		<input type="text" name="ait_dir_item_category_thumbnail" id="ait_dir_item_category_thumbnail" value="" style="width: 80%;"/>
		<input type="button" value="Select Image" class="media-select" id="ait_dir_item_category_thumbnail_selectMedia" name="ait_dir_item_category_thumbnail_selectMedia" style="width: 15%;">
			<br />
			<p class="description">Thumbnail for category</p>
	</div>
	<?php
}
add_action( 'created_ait-dir-item-category', 'save_dir_item_category', 10, 2);
add_action( 'edited_ait-dir-item-category', 'save_dir_item_category', 10, 2);
function save_dir_item_category($term_id, $tt_id) {
	if (!$term_id) return;

	if (isset($_POST['ait_dir_item_category_excerpt'])){
		$name = 'ait_dir_item_category_' .$term_id. '_excerpt';
		update_option( $name, stripslashes($_POST['ait_dir_item_category_excerpt']) );
	}

	if (isset($_POST['ait_dir_item_category_icon'])){
		$name = 'ait_dir_item_category_' .$term_id. '_icon';
		update_option( $name, $_POST['ait_dir_item_category_icon'] );
	}

	if (isset($_POST['ait_dir_item_category_thumbnail'])){
		$name = 'ait_dir_item_category_' .$term_id. '_thumbnail';
		update_option( $name, $_POST['ait_dir_item_category_thumbnail'] );
	}

}

add_action( 'deleted_term_taxonomy', 'delete_dir_item_category' );
function delete_dir_item_category($id) {
	delete_option( 'ait_dir_item_category_'.$id.'_excerpt' );
	delete_option( 'ait_dir_item_category_'.$id.'_icon' );
	delete_option( 'ait_dir_item_category_'.$id.'_thumbnail' );
}


// TABLE COLUMNS
add_filter("manage_edit-ait-dir-item-category_columns", 'dir_item_category_columns');
function dir_item_category_columns($category_columns) {
	$new_columns = array(
		'cb'        		=> '<input type="checkbox" />',
		'name'      		=> __('Name', 'ait'),
		'description'     	=> __('Description', 'ait'),
		'item_excerpt'	    => __('Excerpt', 'ait'),
		'icon' 				=> __('Icon', 'ait'),
		'item_thumbnail'    => __('Thumbnail', 'ait'),
		'slug'      		=> __('Slug', 'ait'),
		'posts'     		=> __('Items', 'ait'),
		);
	return $new_columns;
}

add_filter("manage_ait-dir-item-category_custom_column", 'manage_dir_item_category_columns', 10, 3);
function manage_dir_item_category_columns($out, $column_name, $cat_id) {

	$icon = get_option( 'ait_dir_item_category_'.$cat_id.'_icon', '' );
	$thumbnail = get_option( 'ait_dir_item_category_'.$cat_id.'_thumbnail', '' );
	$excerpt = get_option( 'ait_dir_item_category_'.$cat_id.'_excerpt', '' );

	switch ($column_name) {
		case 'item_excerpt':
			if($excerpt && !empty($excerpt)){
				$out .= $excerpt;
			}
			break;
		case 'icon':
			if(!empty($icon)){
				$out .= '<img src="'.$icon.'" alt="" width="50" height="50">';
			}
			break;
		case 'item_thumbnail':
			if(!empty($thumbnail)){
				$out .= '<img src="'.$thumbnail.'" alt="" width="50" height="50">';
			}
			break;
		default:
			break;
	}
	return $out;
}

function aitDirItemSortableColumns() {
	return array(
		'title'=> 'title',
		'category'=> 'category'
	);
}
add_filter( "manage_edit-ait-dir-item_sortable_columns", "aitDirItemSortableColumns" );

?>