<?php

//Registering Sub Menu for Ordering
add_action( 'admin_menu', 'qcpd_register_pd_item_assign' );

function qcpd_register_pd_item_assign() {
	add_submenu_page(
		'edit.php?post_type=pd',
		esc_html('Assign Listing Owner'),
		esc_html('Assign Listing Owner'),
		'edit_pages', 'pd-item-assign',
		'qcpd_pd_item_assign_page'
	);
}

//Submenu Callback to show ordering page contents
function qcpd_pd_item_assign_page() {
	global $wpdb;
?>
	<div class="wrap">

		<style>

		.filter-sld-tax .filter-btn {
		  background-color: #fff;
		  border-color: #ccc;
		  color: #333;
		  -moz-user-select: none;
		  background-image: none;
		  border: 1px solid #ccc;
		  border-radius: 4px;
		  cursor: pointer;
		  display: inline-block;
		  font-size: 14px;
		  font-weight: 400;
		  line-height: 1.42857;
		  margin-bottom: 0;
		  padding: 6px 12px;
		  text-align: center;
		  vertical-align: middle;
		  white-space: nowrap;
		  -moz-border-radius: 3px;
		  -webkit-border-radius: 3px;
		  border-radius: 3px;
		  -ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=0, Direction=90, Color=#ffffff)";
			-moz-box-shadow: 0px 0px 0px #ffffff;
			-webkit-box-shadow: 0px 0px 0px #ffffff;
			box-shadow: 0px 0px 0px #ffffff;
			filter: progid:DXImageTransform.Microsoft.Shadow(Strength=0, Direction=90, Color=#ffffff);  
		  -webkit-transition: all 0.3s ease;
		  -moz-transition: all 0.3s ease;
		  -o-transition: all 0.3s ease;
		  transition: all 0.3s ease;
		  text-decoration: none;
		}

		.filter-sld-tax .filter-btn:hover{
		  background-color: #e6e6e6;
		  border-color: #adadad;
		  color: #333;
		}

		.filter-btn {
		  margin-bottom: 10px !important;
		  margin-right: 10px;
		  text-decoration: none !important;
		}
		</style>

		<h2>Assign Directory List Item to a User or List</h2>
		
		<form action="<?php echo admin_url('edit.php?post_type=pd&page=pd-item-assign'); ?>" method="POST">
			
				<b>Select a List to Assigning Listings from</b> <select name="pd_list_name">
					<option value="">None</option>
					<?php $sld = new WP_Query( array( 'post_type' => 'pd', 'posts_per_page' => -1, 'order' => 'ASC', 'orderby' => 'menu_order' ) ); ?>
					<?php if( $sld->have_posts() ) : ?>
						<?php while( $sld->have_posts() ) : $sld->the_post(); ?>
							<option value="<?php the_ID(); ?>" <?php echo (isset($_POST['pd_list_name']) && $_POST['pd_list_name']==get_the_ID()?'selected="selected"':''); ?>><?php the_title(); ?></option>
						<?php endwhile; ?>
					<?php endif; ?>
				</select>
				<input type="submit" name="submit" value="Go" />
			
		</form>
		<br>
		<hr>
		<br>
	
	<?php
	
		if(isset($_POST['pd_list_name']) && $_POST['pd_list_name']!=''):
			$post = get_post($_POST['pd_list_name']);
			$userentry = $wpdb->prefix.'pd_user_entry';
			
			if(isset($_POST['assign']) && $_POST['pd_list_item']!=''){
				$item_id = $_POST['pd_list_item'];
				$items = get_post_meta($post->ID, 'qcpd_list_item01');
				
				if($_POST['pd_user_id']!=''){
					
					
					$user_id = $_POST['pd_user_id'];
					
					$get_data = $wpdb->get_row("Select * from $userentry where 1 and `pd_list`='".$post->ID."' and `custom` = '".$item_id."'");
					
					if(empty($get_data)){
					
						
						
						$category = get_the_terms($post->ID,'pd_cat');
						if(!empty($category)){
							$catslug = $category[0]->slug;
						}else{
							$catslug = '';
						}
						

						$datetime = date('Y-m-d H:i:s');
						
						foreach($items as $item){
							if($item['qcpd_timelaps']==$item_id){
								
								$wpdb->insert(
									$userentry,
									array(
										'item_title'  	=> $item['qcpd_item_title'],
										'item_link'   	=> $item['qcpd_item_link'],
										'item_subtitle' => $item['qcpd_item_subtitle'],
										'category'   	=> $catslug,
										'pd_list'  		=> $post->ID,
										'user_id' 		=>  $user_id,
										'image_url' 	=> ($item['qcpd_item_img']==''?$item['qcpd_item_img_link']:@wp_get_attachment_image_src($item['qcpd_item_img'])[0]),
										'time' 			=> $datetime,
										'nofollow' 		=> ($item['qcpd_item_nofollow']==''?0:$item['qcpd_item_nofollow']),
										'custom' 		=>$item['qcpd_timelaps'],
										'approval' 		=>1,
										'item_phone'	=> $item['qcpd_item_phone'],
										'location'		=> $item['qcpd_item_location'],
										'full_address'	=> $item['qcpd_item_full_address'],
										'latitude'		=> $item['qcpd_item_latitude'],
										'longitude'		=> $item['qcpd_item_longitude'],
										'linkedin'		=> $item['qcpd_item_linkedin'],
										'twitter'		=> $item['qcpd_item_twitter'],
										'facebook'		=> $item['qcpd_item_facebook'],
										'yelp'			=> $item['qcpd_item_yelp'],
										'business_hour'	=> $item['qcpd_item_business_hour'],
										'email'			=> $item['qcpd_item_email'],
										'description'	=> $item['qcpd_description'],
										'qcpd_field_1' 	=> (isset($item['qcpd_field_1'])?$item['qcpd_field_1']:''),
										'qcpd_field_2' 	=> (isset($item['qcpd_field_2'])?$item['qcpd_field_2']:''),
										'qcpd_field_3' 	=>(isset($item['qcpd_field_3'])?$item['qcpd_field_3']:''),
										'qcpd_field_4' 	=>(isset($item['qcpd_field_4'])?$item['qcpd_field_4']:''),
										'qcpd_field_5' 	=>(isset($item['qcpd_field_5'])?$item['qcpd_field_5']:''),
										'tags' 			=>$item['qcpd_tags'],
										
									)
								);
								if($wpdb->last_error !== ''):
									echo $wpdb->last_error;
								else:
									echo '<p style="color:green;">'.esc_html('Item has been successfully assigned to your selected user!').'</p>';
								endif;
								break;

							}
						}
						
						
						
					}else{
						echo '<p style="color:red;">'.esc_html('This item is already assigned to another user!').'</p>';
					}
				}
				
				if(!empty($_POST['pd_list_id'])){
					
					$list_ids = $_POST['pd_list_id'];
					
					foreach($items as $item){
						if($item['qcpd_timelaps']==$item_id){
							
							$item['qcpd_timelaps'] = time();
							
							foreach($list_ids as $lid){
								add_post_meta( $lid, 'qcpd_list_item01', $item );
							}
							
							echo '<p style="color:green;">'.esc_html('Item has been successfully assigned to your selected lists!').'</p>';
							break;

						}
					}
					
					
				}
				
				
			}
			
			
		
	?>
		<form action="<?php echo admin_url('edit.php?post_type=pd&page=pd-item-assign'); ?>" method="POST">
			<table class="wp-list-table">
				
				<tbody id="sld_item_sort" class="tbl-body" data-post-type="sld" data-list-id="<?php echo $post->ID; ?>">
					<?php 
						$tti3e = get_post_meta($post->ID, 'qcpd_list_item01');
						$cnt = 0;
						
					?>

					<tr>
						<td>
							<label style="width:100px;display: inline-block;">Select List Item</label>
							<select name="pd_list_item" required>
								<option value="">None</option>
								<?php 
									foreach($tti3e as $item):
										echo '<option value="'.$item['qcpd_timelaps'].'">'.$item['qcpd_item_title'].'</option>';
									endforeach;
								?>
							</select>
							<span class="description">Select a list item to assign a user or list</span>
						</td>
						
					</tr>
					
					<tr>
						<td>
							<label style="width:100px;display: inline-block;">Select User</label>
							<?php 
								$users = get_users();
								//print_r($users);exit;
							?>
							<select name="pd_user_id">
								<option value="">None</option>
								<?php 
									foreach($users as $user):
										echo '<option value="'.$user->ID.'">'.$user->data->user_login.' ('.$user->roles[0].')</option>';
									endforeach;
								?>
							</select>
							<span class="description">Select a user for assigning your selected item.</span>
						</td>
						
					</tr>
					<tr>
						<td>
							<label style="width:100px;display: inline-block;">Copy List Item to Another List</label>
							
							<select name="pd_list_id[]" multiple style="width: 200px;">
								<option value="">None</option>
								<?php $sld = new WP_Query( array( 'post_type' => 'pd', 'posts_per_page' => -1, 'order' => 'ASC', 'orderby' => 'menu_order' ) ); ?>
								<?php if( $sld->have_posts() ) : ?>
									<?php while( $sld->have_posts() ) : $sld->the_post(); ?>
										<option value="<?php the_ID(); ?>"><?php the_title(); ?></option>
									<?php endwhile; ?>
								<?php endif; ?>
							</select>
							<span class="description">Select lists to copy your selected item. You can select multiple list at a time by pressing ctrl.</span>
						</td>
						
					</tr>
					<tr>
						<td>
							<label style="width:100px;display: inline-block;"></label>
							<input type="hidden" name="pd_list_name" value="<?php echo $_POST['pd_list_name']; ?>" />
							<input type="submit" name="assign" value="Assign" />
							
						</td>
						
					</tr>
					
				</tbody>
				

			</table>
		</form>
		<?php endif; ?>
	
	<?php wp_reset_postdata(); // Don't forget to reset again! ?>

	<style>
		#sortable-table td { background: white; }
		#sortable-table .column-order { padding: 3px 10px; width: 50px; }
			#sortable-table .column-order img { cursor: move; }
		#sortable-table td.column-order { vertical-align: middle; text-align: center; }
		#sortable-table .column-thumbnail { width: 160px; }
	</style>

	</div><!-- .wrap -->

<?php

}



//Registering ajax for saving sort order
add_action( 'wp_ajax_sld_update_post_item_order', 'sld_update_post_item_order' );

function sld_update_post_item_order() {

	global $wpdb;

	$post_type     = $_POST['postType'];
	$listid = $_POST['listID'];
	$orders        = $_POST['order'];
	
	//update_post_meta( $listid, 'qcopd_list_item01', $order );
	delete_post_meta( $listid, 'qcopd_list_item01' );
	
	foreach($orders as $order){
		add_post_meta( $listid, 'qcopd_list_item01', $order );
	}

	die( '1' );
	
}


