<?php 
if ( ! defined( 'ABSPATH' ) ) exit;
class Sbd_User_entry_list extends WP_List_Table {

	/** Class constructor */
	public function __construct() {

		parent::__construct( array(
			'singular' => esc_html( 'Profile', 'sp' ), //singular name of the listed records
			'plural'   => esc_html( 'Profiles', 'sp' ), //plural name of the listed records
			'ajax'     => false //should this table support ajax?

        ) );
	}
	/**
	 * Delete a Subscriber Profile record.
	 *
	 * @param int $id Subscriber Profile
	 */
	public static function get_subscriber_profiles( $per_page = 5, $page_number = 1 ) {

	  global $wpdb;
		
		
		
	  $sql = "SELECT * FROM {$wpdb->prefix}pd_user_entry where 1";
	  
	  if(isset($_GET['stat']) and $_GET['stat']!=''){
			switch($_GET['stat']){
				case 'approved':
					$sql .= " and approval = 1";
					break;
				case 'pending':
					$sql .=" and (approval = 0 or approval = 3)";
					break;
				case 'denied':
					$sql .=" and approval = 2";
					break;
                case 'paid':
                    $sql .= " and package_id!=0";
                    break;
                case 'free':
                    $sql .=" and package_id=0";
                    break;
			}
	  }
	  if(isset($_POST['s']) and $_POST['s']!=''){
		  $sql .= " and (item_title like '%".$_POST['s']."%' or item_subtitle like '%".$_POST['s']."%')";
	  }
	  
	  if ( ! empty( $_REQUEST['orderby'] ) ) {
		$sql .= ' ORDER BY ' . esc_sql( $_REQUEST['orderby'] );
		$sql .= ! empty( $_REQUEST['order'] ) ? ' ' . esc_sql( $_REQUEST['order'] ) : ' ASC';
	  }else{
		   $sql .=' ORDER BY `time` DESC';
	  }
	 

	  $sql .= " LIMIT $per_page";

	  $sql .= ' OFFSET ' . ( $page_number - 1 ) * $per_page;
	  
	 
	  $result = $wpdb->get_results( $sql, 'ARRAY_A' );

	  return $result;
	}
	
	/**
	 * Delete Subscriber profile.
	 *
	 * @return null
	*/
	
	public static function delete_subscriber_profile( $id ) {
	  global $wpdb;
	
		$sql = "SELECT * FROM {$wpdb->prefix}pd_user_entry where 1 and id = ".$id;
		$pdata = $wpdb->get_row($sql);
		
		if(@$pdata->approval==1){
			self::deny_subscriber_profile($id);
		}

		$wpdb->delete(
		"{$wpdb->prefix}pd_user_entry",
			array( 'id' => $id ),
			array( '%d' )
		);
	
 
	}
	
	/**
	 * Approve Subscriber profile.
	 *
	 * @return null
	*/
	 
	public static function approve_subscriber_profile($id){
		global $wpdb;
		
		$package_purchase_table = $wpdb->prefix.'pd_package_purchased';
		$sql = "SELECT * FROM {$wpdb->prefix}pd_user_entry where 1 and id = ".$id;
		$identifier = time().rand(1,100);
		$pdata = $wpdb->get_row($sql);
		$featured = 0;
		$exp_date = '';
		if($pdata->package_id > 0){
			$featured = 1;
			$package_purchase = $wpdb->get_row("SELECT DATE_FORMAT(`expire_date`,'%Y-%m-%d') as exp_date FROM $package_purchase_table where 1 and id = ".$pdata->package_id);
			$exp_date = $package_purchase->exp_date;
		}
		

		if(pd_ot_get_option('sbd_paid_item_featured')!='on'){
			$featured = 0;
		}
		
		
		if( $pdata->approval==0 || $pdata->approval==2){
			
			$prepare = array( //preparing Meta
				'qcpd_item_title' 			=> sanitize_text_field($pdata->item_title),
				'qcpd_item_link' 			=> trim($pdata->item_link),
				'qcpd_item_subtitle' 		=> sanitize_text_field($pdata->item_subtitle),
				'qcpd_description' 		=> ($pdata->description),
				'qcpd_item_img' 		=> trim($pdata->image_url),
				'qcpd_item_phone' 		=> trim($pdata->item_phone),
				'qcpd_item_location' 		=> trim($pdata->location),
				'qcpd_item_full_address' 		=> trim($pdata->full_address),
				'qcpd_item_latitude' 		=> trim($pdata->latitude),
				'qcpd_item_longitude' 		=> trim($pdata->longitude),
				'qcpd_item_email' 		=> trim($pdata->email),
				'qcpd_item_twitter' 		=> trim($pdata->twitter),
				'qcpd_item_linkedin' 		=> trim($pdata->linkedin),
				'qcpd_item_facebook' 		=> trim($pdata->facebook),
				'qcpd_item_yelp' 		=> trim($pdata->yelp),
				'qcpd_item_business_hour' 		=> trim($pdata->business_hour),
				'qcpd_fa_icon' 			=> '',
				'qcpd_item_nofollow' 		=> ($pdata->nofollow==1?1:0),
				'qcpd_item_newtab' 		=> 1,
				'qcpd_upvote_count' 		=> 0,
				'qcpd_entry_time' 			=> date('Y-m-d H:i:s'),
				'qcpd_ex_date'				=> $exp_date,
				'qcpd_timelaps' 			=> $identifier,
				'qcpd_is_bookmarked' 			=> 0,
				'qcpd_featured'			=> $featured,
				'qcpd_field_1'		=> trim($pdata->qcpd_field_1),
				'qcpd_field_2'		=> trim($pdata->qcpd_field_2),
				'qcpd_field_3'		=> trim($pdata->qcpd_field_3),
				'qcpd_field_4'		=> trim($pdata->qcpd_field_4),
				'qcpd_field_5'		=> trim($pdata->qcpd_field_5),
				'qcpd_tags'		=> trim($pdata->tags),
				'qcpd_paid'		=> ($pdata->package_id>0?'1':''),
				'qcpd_verified' => $pdata->verified,
			);
			
			//echo '<pre>'.print_r($prepare).'</pre>';exit;
			$meta_data = serialize($prepare);
			add_post_meta( trim($pdata->pd_list), 'qcpd_list_item01', $prepare );

			$wpdb->update(
				$wpdb->prefix.'pd_user_entry',
				array(
					'custom'  => $identifier,
					'approval'=> 1
				),
				array( 'id' => $id),
				array(
					'%s',
					'%d',
				),
				array( '%d')
			);			
		}elseif($pdata->approval==3){
			
			$sql = "SELECT * FROM {$wpdb->prefix}pd_user_entry where 1 and id = ".$id;
			$pdata = $wpdb->get_row($sql);
			$identifier = time();
			if($pdata->custom!=''){
				self::deny_subscriber_profile($id);
			}
			
			$prepare = array( //preparing Meta
			
				'qcpd_item_title' 			=> sanitize_text_field($pdata->item_title),
				'qcpd_item_link' 			=> trim($pdata->item_link),
				'qcpd_item_subtitle' 		=> sanitize_text_field($pdata->item_subtitle),
				'qcpd_description' 		=> ($pdata->description),
				'qcpd_item_img' 		=> trim($pdata->image_url),
				'qcpd_item_phone' 		=> trim($pdata->item_phone),
				'qcpd_item_location' 		=> trim($pdata->location),
				'qcpd_item_full_address' 		=> trim($pdata->full_address),
				'qcpd_item_latitude' 		=> trim($pdata->latitude),
				'qcpd_item_longitude' 		=> trim($pdata->longitude),
				'qcpd_item_email' 		=> trim($pdata->email),
				'qcpd_item_twitter' 		=> trim($pdata->twitter),
				'qcpd_item_linkedin' 		=> trim($pdata->linkedin),
				'qcpd_item_facebook' 		=> trim($pdata->facebook),
				'qcpd_item_yelp' 		=> trim($pdata->yelp),
				'qcpd_item_business_hour' 		=> trim($pdata->business_hour),
				'qcpd_fa_icon' 			=> '',
				'qcpd_item_nofollow' 		=> ($pdata->nofollow==1?1:0),
				'qcpd_item_newtab' 		=> 1,
				'qcpd_upvote_count' 		=> 0,
				'qcpd_entry_time' 			=> date('Y-m-d H:i:s'),
				'qcpd_ex_date'				=> $exp_date,
				'qcpd_timelaps' 			=> $identifier,
				'qcpd_is_bookmarked' 			=> 0,
				'qcpd_featured'			=> $featured,
				'qcpd_field_1'		=> trim($pdata->qcpd_field_1),
				'qcpd_field_2'		=> trim($pdata->qcpd_field_2),
				'qcpd_field_3'		=> trim($pdata->qcpd_field_3),
				'qcpd_field_4'		=> trim($pdata->qcpd_field_4),
				'qcpd_field_5'		=> trim($pdata->qcpd_field_5),
				'qcpd_tags'		=> trim($pdata->tags),
				'qcpd_paid'		=> ($pdata->package_id>0?'1':''),
				'qcpd_verified' => $pdata->verified,

			);
			
			//echo '<pre>'.print_r($prepare).'</pre>';exit;
			$meta_data = serialize($prepare);
			add_post_meta( trim($pdata->pd_list), 'qcpd_list_item01', $prepare );

			$wpdb->update(
				$wpdb->prefix.'pd_user_entry',
				array(
					'custom'  => $identifier,
					'approval'=> 1
				),
				array( 'id' => $id),
				array(
					'%s',
					'%d',
				),
				array( '%d')
			);	
		}

	}

	
	public static function clean($string) {
		$string = str_replace(' ', '-', trim($string)); // Replaces all spaces with hyphens.

		return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
	}
	/**
	 * Deny Subscriber profile.
	 *
	 * @return null
	*/
	 
	public static function deny_subscriber_profile($id){
		global $wpdb;
		
		$sql = "SELECT * FROM {$wpdb->prefix}pd_user_entry where 1 and id = ".$id;
		$identifier = time().rand(1,100);
		$pdata = $wpdb->get_row($sql);
		
		if( $pdata->approval==1 || $pdata->approval==3 ){

            $searchQuery = "SELECT * FROM ".$wpdb->prefix."postmeta WHERE 1 and `post_id` = ".$pdata->pd_list." and `meta_key` = 'qcpd_list_item01'";
            $results = @$wpdb->get_results($searchQuery);
			
			foreach($results as $result){
				
				$unserialize = unserialize($result->meta_value);
				if($pdata->custom == $unserialize['qcpd_timelaps']){
					
					$meta_id = @$result->meta_id;

					@$wpdb->delete(
						"{$wpdb->prefix}postmeta",
						array( 'meta_id' => $meta_id ),
						array( '%d' )
					);

				}
				
				
			}
			
			$wpdb->update(
				$wpdb->prefix.'pd_user_entry',
				array(
					'custom'  => '',
					'approval'=> 2
				),
				array( 'id' => $id),
				array(
					'%s',
					'%d',
				),
				array( '%d')
			);

        }

	}


	public static function edit_subscriber_profile($id){
				if(!function_exists('wp_get_current_user')) {
					include(ABSPATH . "wp-includes/pluggable.php"); 
				}
				global $wpdb;
				$table             = $wpdb->prefix.'pd_user_entry';
				$current_user = wp_get_current_user();

				//form submit section code
				if(isset($_POST['uid']) and $_POST['uid']!=''){
					$uid = $_POST['uid'];
					$item_title = sanitize_text_field($_POST['item_title']);
					$item_link = sanitize_text_field($_POST['item_link']);
					$item_subtitle = sanitize_text_field(stripcslashes($_POST['item_subtitle']));
					$imageurl = sanitize_text_field($_POST['pd_pf_image_url']);
					$qc_pd_category = sanitize_text_field($_POST['qc_pd_category']);
					$qc_pd_list = sanitize_text_field($_POST['qc_pd_list']);
					
					if(isset($_POST['item_no_follow']) and $_POST['item_no_follow']==1){
						$item_no_follow = 1;
					}else{
						$item_no_follow = 0;
					}
					
							$item_phone = sanitize_text_field(stripcslashes($_POST['item_phone']));
							$item_location = sanitize_text_field(stripcslashes($_POST['item_location']));
							$item_full_address = sanitize_text_field(stripcslashes($_POST['item_full_address']));
							$item_latitude = sanitize_text_field(stripcslashes($_POST['item_latitude']));
							$item_longitude = sanitize_text_field(stripcslashes($_POST['item_longitude']));
							$item_linkedin = sanitize_text_field(stripcslashes($_POST['item_linkedin']));
							$item_twitter = sanitize_text_field(stripcslashes($_POST['item_twitter']));
							$item_facebook = sanitize_text_field(stripcslashes($_POST['item_facebook']));
							$item_yelp = sanitize_text_field(stripcslashes($_POST['item_yelp']));
							$item_business_hour = sanitize_text_field(stripcslashes($_POST['item_business_hour']));
							$item_email = sanitize_text_field(stripcslashes($_POST['item_email']));
							$item_description = stripcslashes($_POST['item_long_description']);
					

					$wpdb->update(
						$table,
						array(
							'item_title'  => $item_title,
							'item_link'   => $item_link,
							'item_subtitle' => $item_subtitle,
							'image_url'=> $imageurl,
							'nofollow'=> $item_no_follow,
							'category'   => $qc_pd_category,
							'pd_list'  => $qc_pd_list,
							'item_phone'	=> $item_phone,
							'location'		=> $item_location,
							'full_address'	=> $item_full_address,
							'latitude'		=> $item_latitude,
							'longitude'		=> $item_longitude,
							'linkedin'		=> $item_linkedin,
							'twitter'		=> $item_twitter,
							'facebook'		=> $item_facebook,
							'yelp'			=> $item_yelp,
							'business_hour'	=> $item_business_hour,
							'email'			=> $item_email,	
							'description'=>$item_description,
							'approval'=> 3
						),
						array( 'id' => $uid),
						array(
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%d',
							'%s'
						),
						array( '%d')
					);
					if(isset($_POST['approve']) and $_POST['approve']=='1'){
						self::approve_subscriber_profile($uid);
					}

					echo '<div style="color: green;border: 1px solid green;margin: 2px;padding: 2px;text-align: center;margin-bottom: 8px;font-size: 18px;margin-top: 10px;">Link has been edited successfully! <a href="edit.php?post_type=pd&page=qcpd_user_entry_list">Click to go back</a></div>';
				}
				
				
				
				$recid = sanitize_text_field($id);
				$s = 1;
				
				$rows     = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $table WHERE %d and id=%s", $s, $recid ) );
				
				$taxonomy = 'pd_cat';
				$terms = get_terms($taxonomy); //
				
				foreach($rows as $row){
				?>
			<h1>Edit Item</h1>
			<form method="post" action="">
				<table class="form-table">
									
					<tr>
						<th><label for="qc_pd_item_title"><?php _e( 'Listings Title', 'qc-pd' ); ?></label>
						</th>

						<td>
							<input type="text" id="qc_pd_item_title" name="item_title" value="<?php echo $row->item_title; ?>" required />
							
						</td>
					</tr>

					<tr>
						<th><label for="qc_pd_item_link"><?php _e( 'Listings Link', 'qc-pd' ); ?></label>
						</th>

						<td>
							<input type="text" id="qc_pd_item_link" name="item_link" value="<?php echo $row->item_link; ?>" required/>
							
						</td>
					</tr>

					<tr>
						<th><label for="qc_pd_item_subtitle"><?php _e( 'Listings Subtitle', 'qc-pd' ); ?></label>
						</th>

						<td>
							<textarea name="item_subtitle" id="qc_pd_item_subtitle" rows="2" cols="40" required><?php echo $row->item_subtitle; ?></textarea>

						</td>
					</tr>
					
					<tr>
						<th><label for="qc_pd_item_subtitle"><?php _e( 'Listings Long Description', 'qc-pd' ); ?></label>
						</th>

						<td>
							<textarea name="item_long_description" id="qc_pd_item_subtitle" rows="2" cols="40" required><?php echo ($row->description); ?></textarea>
						</td>
					</tr>
					
					<tr>
						<th><label for="qc_pd_item_subtitle"><?php _e( 'Main Phone Number (For call)', 'qc-pd' ); ?></label>
						</th>

						<td>
							<input type="text" name="item_phone" class="field-long pd_text_width" value="<?php echo esc_html($row->item_phone); ?>"  />
						</td>
					</tr>
					<tr>
						<th><label for="qc_pd_item_subtitle"><?php _e( 'Short Address', 'qc-pd' ); ?></label>
						</th>

						<td>
							<input type="text" name="item_location" class="field-long pd_text_width" value="<?php echo esc_html($row->location); ?>"  />
						</td>
					</tr>
					<tr>
						<th><label for="qc_pd_item_subtitle"><?php _e( 'Full Address (For google map)', 'qc-pd' ); ?></label>
						</th>

						<td>
							<input type="text" name="item_full_address" id="sbd_full_address" class="field-long pd_text_width" value="<?php echo esc_html($row->full_address); ?>"  />
						</td>
					</tr>
					<tr>
						<th><label for="qc_pd_item_subtitle"><?php _e( 'Latitude', 'qc-pd' ); ?></label>
						</th>

						<td>
							<input type="text" name="item_latitude" id="sbd_lat" class="field-long pd_text_width" value="<?php echo esc_html($row->latitude); ?>"  />
						</td>
					</tr>
					<tr>
						<th><label for="qc_pd_item_subtitle"><?php _e( 'Longitude', 'qc-pd' ); ?></label>
						</th>

						<td>
							<input type="text" name="item_longitude" id="sbd_long" class="field-long pd_text_width" value="<?php echo esc_html($row->longitude); ?>"  />
						</td>
					</tr>
					
					<tr>
						<th><label for="qc_pd_item_subtitle"><?php _e( 'Linkedin Address', 'qc-pd' ); ?></label>
						</th>

						<td>
							<input type="text" name="item_linkedin" class="field-long pd_text_width" value="<?php echo esc_html($row->linkedin); ?>"  />
						</td>
					</tr>
					
					<tr>
						<th><label for="qc_pd_item_subtitle"><?php _e( 'Twitter Address', 'qc-pd' ); ?></label>
						</th>

						<td>
							<input type="text" name="item_twitter" class="field-long pd_text_width" value="<?php echo esc_html($row->twitter); ?>"  />
						</td>
					</tr>
					
					<tr>
						<th><label for="qc_pd_item_subtitle"><?php _e( 'Email Address', 'qc-pd' ); ?></label>
						</th>

						<td>
							<input type="email" name="item_email" class="field-long pd_text_width" value="<?php echo esc_html($row->email); ?>" placeholder="email@example.com"  />
						</td>
					</tr>
					
					<tr>
						<th><label for="qc_pd_item_subtitle"><?php _e( 'Business Hour', 'qc-pd' ); ?></label>
						</th>

						<td>
							<input type="text" name="item_business_hour" class="field-long pd_text_width" value="<?php echo esc_html($row->business_hour); ?>" placeholder="Mon - Fri 10:00am - 05:00pm"  />
						</td>
					</tr>
					
					<tr>
						<th><label for="qc_pd_item_subtitle"><?php _e( 'Yelp Address', 'qc-pd' ); ?></label>
						</th>

						<td>
							<input type="text" name="item_yelp" class="field-long pd_text_width" value="<?php echo esc_html($row->yelp); ?>"  />
						</td>
					</tr>
					
					<tr>
						<th><label for="qc_pd_item_subtitle"><?php _e( 'Facebook Address', 'qc-pd' ); ?></label>
						</th>

						<td>
							<input type="text" name="item_facebook" class="field-long pd_text_width" value="<?php echo esc_html($row->facebook); ?>"  />
						</td>
					</tr>
					
					<tr>
						<th><label for="qc_pd_jobsize"><?php _e( 'Item Image', 'qc-pd' ); ?></label>
						</th>

						<td>
							<input type="hidden" name="pd_pf_image_url" id="pd_pf_image_url" class="regular-text" value="<?php echo esc_attr($row->image_url); ?>">
							<input type="button" name="upload-btn" id="pd-upload-btn" class="button-secondary" value="Upload Image">
							
							<div style="clear:both"></div>
								<div id="pd_preview_img">
									<?php if($row->image_url!=''): ?>
										<span class="pd_remove_bg_image">X</span>
										<img  src="<?php echo $row->image_url ?>" alt="">
									<?php endif; ?>
								</div>
						</td>
					</tr>
					
					<tr>
						<th><label><?php echo __('Category', 'qc-pd') ?> <span class="pd_required">*</span></label></th>
						<td>
						<?php 
						$taxonomy = 'pd_cat';
						$terms = get_terms($taxonomy); //
						if ( $terms && !is_wp_error( $terms ) ) :
						?>
							<select id="qc_pd_category" class="pd_text_width" name="qc_pd_category" >
								<option value="" ><?php echo __('All List', 'qc-pd') ?></option>
								<?php foreach ( $terms as $term ) { ?>
									<?php if($term->name==$row->category): ?>
										<option value="<?php echo $term->name; ?>"selected="selected"><?php echo esc_attr($term->name); ?></option>
									<?php else: ?>
										<option value="<?php echo $term->name; ?>"><?php echo esc_attr($term->name); ?></option>
									<?php endif; ?>
									
								<?php } ?>
							</select>
						<?php
						endif;
						?>
						</td>
					</tr>
					
					<tr>
						<th><label><?php echo __('Select List', 'qc-pd') ?> <span class="pd_required">*</span></label></th>
						<td><select id="qc_pd_list" class="pd_text_width" name="qc_pd_list" required>
							<?php
								
								


								if(!empty($row->category) ){
									
									$pd = new WP_Query( array( 
										'post_type' => 'pd',
										'tax_query' => array(
											array (
												'taxonomy' => 'pd_cat',
												'field' => 'name',
												'terms' => $row->category,
											)
										),
										'posts_per_page' => -1,
										'order' => 'ASC',
										'orderby' => 'menu_order'
										) 
									);
									
								}else{
									$pd = new WP_Query( array( 
										'post_type' => 'pd',				
										'posts_per_page' => -1,
										'order' => 'ASC',
										'orderby' => 'menu_order'
										) 
									);
								}
								while( $pd->have_posts() ) : $pd->the_post();
								
								?>
									<?php if(get_the_ID()==$row->pd_list): ?>
										<option value="<?php echo get_the_ID(); ?>" selected="selected"><?php the_title(); ?></option>
									<?php else: ?>
										<option value="<?php echo get_the_ID(); ?>"><?php the_title(); ?></option>
									<?php endif; ?>
								<?php
								endwhile;
							?>
						</select>
						</td>
					</tr>
					
                    <tr>
                        <th><label for="qc_pd_item_subtitle"><?php _e( 'No Follow', 'pd' ); ?></label>
                        </th>

                        <td>
                            <input type="checkbox" value="1" <?php echo ($row->nofollow==1?'checked="checked"':''); ?> name="item_no_follow" />
                        </td>
                    </tr>

					<tr>
						<th><label for="qc_pd_item_subtitle"><?php _e( 'Approve', 'pd' ); ?></label>
						</th>

						<td>
							<input type="checkbox" value="1" checked="checked" name="approve" />
						</td>
					</tr>
					


				</table>
				<p class="submit">
					<input type="hidden" name="uid" value="<?php echo $recid; ?>" />
					<input name="submit" id="submit" class="button button-primary" value="Update Item" type="submit">
				</p>
			</form>
			<?php
}

	}

	
	/**
	 * Returns the data for table header.
	 *
	 * @return string
	 */
	public function pd_table_header(){
		global $wpdb;
		
		$getid = "select id from {$wpdb->prefix}pd_user_entry";
		$ids = $wpdb->get_results($getid);
		
		
		$total = $wpdb->get_var( "SELECT count(*) FROM {$wpdb->prefix}pd_user_entry where 1" );
		
		$pending = $wpdb->get_var( "SELECT count(*) FROM {$wpdb->prefix}pd_user_entry where 1 and (approval=0 or approval=3)" );
		$deny = $wpdb->get_var( "SELECT count(*) FROM {$wpdb->prefix}pd_user_entry where 1 and approval=2 " );
		$approved = $wpdb->get_var( "SELECT count(*) FROM {$wpdb->prefix}pd_user_entry where 1 and approval=1 " );
		
		$edited = $wpdb->get_var( "SELECT count(*) FROM {$wpdb->prefix}pd_user_entry where 1 and approval=3 " );

		$paiditem = $wpdb->get_var( "SELECT count(*) FROM {$wpdb->prefix}pd_user_entry where 1 and package_id!=0 " );
		$freeitem = $wpdb->get_var( "SELECT count(*) FROM {$wpdb->prefix}pd_user_entry where 1 and package_id=0 " );

		echo '<p>
			<a href="'.(sprintf( '?post_type=pd&page=%s', esc_attr( $_REQUEST['page'] ) )).'">All ('.($total==''||$total==0?0:$total).')</a> || 
			
			<a href="'.(sprintf( '?post_type=pd&page=%s&stat=pending', esc_attr( $_REQUEST['page'] ) )).'">'.__('Pending', 'qc-pd').' ('.($pending==''||$pending==0?0:$pending).') </a>|| 
			<a href="'.(sprintf( '?post_type=pd&page=%s&stat=approved', esc_attr( $_REQUEST['page'] ) )).'">'.__('Approved', 'qc-pd').' ('.($approved==''||$approved==0?0:$approved).')</a> ||
			<a href="'.(sprintf( '?post_type=pd&page=%s&stat=denied', esc_attr( $_REQUEST['page'] ) )).'">'.__('Denied', 'qc-pd').'  ('.($deny==''||$deny==0?0:$deny).')</a> ||
			<a href="'.(sprintf( '?post_type=pd&page=%s&stat=paid', esc_attr( $_REQUEST['page'] ) )).'">'.__('Paid', 'qc-pd').'  ('.($paiditem==''||$paiditem==0?0:$paiditem).')</a> ||
			<a href="'.(sprintf( '?post_type=pd&page=%s&stat=free', esc_attr( $_REQUEST['page'] ) )).'">'.__('Free', 'qc-pd').'  ('.($freeitem==''||$freeitem==0?0:$freeitem).')</a>
			
			
		</p>';
		
	}
	/**
	 * Returns the count of records in the database.
	 *
	 * @return null|string
	 */
	public static function record_count() {
	  global $wpdb;
		
		$getid = "select id from {$wpdb->prefix}pd_user_entry";
		$ids = $wpdb->get_results($getid);

		$sql = "SELECT COUNT(*) FROM {$wpdb->prefix}pd_user_entry where 1";
		
	  return $wpdb->get_var( $sql );
	}
	
	/**
	 * Returns the Status format.
	 *
	 * @return string
	 */
	public function getStatus($args){
		if($args==0){
			return '<span style="color:#f4b042;font-weight:bold;">'.__('Pending', 'qc-pd').'</span>';
		}elseif($args==1){
			return '<span style="color:green;font-weight:bold;">'.__('Approved', 'qc-pd').'</span>';
		}elseif($args==2){
			return '<span style="color:red;font-weight:bold;">'.__('Deny', 'qc-pd').'</span>';
		}else{
			return '<span style="color:#f4b042;font-weight:bold;">'.__('Edited', 'qc-pd').'</span>';
		}
	}	
	
	/**
	 * Method for name column
	 *
	 * @param array $item an array of DB data
	 *
	 * @return string
	 */
	 
	function column_item_title( $item ) {

		$title = '<strong>' . $item['item_title'] . '</strong>';
		$actions = array(
		
			'edit'      => sprintf('<a href="edit.php?post_type=pd&page=%s&action=%s&book=%s">Edit</a>',$_REQUEST['page'],'edit',$item['id']),
			
			'delete'    => sprintf('<a href="edit.php?post_type=pd&page=%s&action=%s&book=%s">Delete</a>',$_REQUEST['page'],'delete',$item['id']),

			'view'    => sprintf('<a href="edit.php?post_type=pd&page=%s&action=%s&book=%s">Approve</a>',$_REQUEST['page'],'approve',$item['id']),

			'trash'    => sprintf('<a href="edit.php?post_type=pd&page=%s&action=%s&book=%s">Deny</a>',$_REQUEST['page'],'deny',$item['id']),
			
		);

		return sprintf('%1$s %2$s', $title, $this->row_actions($actions) );
	 
	}
	
	
	/**
	 * Method for Image column
	 *
	 * @param array $item an array of DB data
	 *
	 * @return string
	 */
	function column_image_url( $item ) {
	  if($item['image_url']!=''){
		  $image = '<img width="80" src="'.$item['image_url'].'" alt="'.$item['item_title'].'" />';
	  }else{
		  $image ='<img src="'.QCSBD_IMG_URL.'/noimage.png'.'" width="50"/>';
	  }
	  
	  return $image;
	}
	
	/**
	 * Method for pd_list column
	 *
	 * @param array $item an array of DB data
	 *
	 * @return string
	 */
	function column_pd_list( $item ) {
		$profession = get_the_title( $item['pd_list'] );
		return ''.$profession.'';
	}
	
	function column_category( $item ) {
		$profession = $item['category'];
		return ''.$profession.'';
	}

	/**
	 * Method for Business Hour column
	 *
	 * @param array $item an array of DB data
	 *
	 * @return string
	 */
	
	/**
	 * Method for item_link column
	 *
	 * @param array $item an array of DB data
	 *
	 * @return string
	 */
	function column_item_link( $item ) {
		
		return ''.$item['item_link'].'';
	}

	/**
	 * Method for Job Size column
	 *
	 * @param array $item an array of DB data
	 *
	 * @return string
	 */
	
	
	/**
	 * Method for item_subtitle column
	 *
	 * @param array $item an array of DB data
	 *
	 * @return string
	 */
	function column_item_subtitle( $item ) {
		
		return ''.$item['item_subtitle'].'';
	}
	
	/**
	 * Method for Date column
	 *
	 * @param array $item an array of DB data
	 *
	 * @return string
	 */
	function column_time( $item ) {
		
		return ''.$item['time'].'';
	}
	
	
	
	
	/**
	 * Method for User column
	 *
	 * @param array $item an array of DB data
	 *
	 * @return string
	 */
	function column_user_id( $item ) {
		$user = get_userdata($item['user_id']);
		if( $user && !is_wp_error($user) ){
			return ''.$user->user_login.'';
		}else{
			return '';
		}
	}
	
	/**
	 * Method for Status column
	 *
	 * @param array $item an array of DB data
	 *
	 * @return string
	 */
	function column_approval( $item ) {
		
		return $this->getStatus($item['approval']);
	}

	/**
	 * Method for Item Type column
	 * @return string
	 */
	function column_package_id( $item ) {

	    if($item['package_id']==0){
            return '<span style="color:#810049;font-weight:bold;">Free</span>';
        }else{
            return '<span style="color:#0B286C;font-weight:bold;">Paid</span>';
        }

	}
	
	/**
	 * Render a column when no column specific method exists.
	 *
	 * @param array $item
	 * @param string $column_name
	 *
	 * @return mixed
	 */
	public function column_default( $item, $column_name ) {
	  switch ( $column_name ) {
		case 'item_title':
			return $item[ $column_name ];
		case 'item_link':
		  return $item[ $column_name ];
		default:
		  //return print_r( $item, true ); //Show the whole array for troubleshooting purposes
	  }
	}
	
	/**
	 * Render the bulk edit checkbox
	 *
	 * @param array $item
	 *
	 * @return string
	 */
	function column_cb( $item ) {
	  return sprintf(
		'<input type="checkbox" name="bulk-action[]" value="%s" />', $item['id']
	  );
	}

	/**
	 *  Associative array of columns
	 *
	 * @return array
	 */
	function get_columns() {
	  $columns = array(
		'cb'      => '<input type="checkbox" />',
		
		'image_url'    => __( 'Image', 'pd' ),
		'item_title'    => __( 'Item Title', 'pd' ),
		'item_link'    => __( 'Link', 'pd' ),
		'item_subtitle'    => __( 'Subtitle', 'pd' ),
		'category'    => __( 'Category', 'pd' ),
		'pd_list'    => __( 'List Title', 'pd' ),

		'user_id' => __( 'User', 'pd' ),
		'package_id' => __( 'Item Type', 'pd' ),
		'approval' => __( 'Status', 'pd' ),
		'time' => __( 'Date', 'pd' )
      );

	  return $columns;
	}
	
	
	/**
	 * Columns to make sortable.
	 *
	 * @return array
	 */
	public function get_sortable_columns() {
	  $sortable_columns = array(
		
		'item_title' => array( 'item_title', true ),
		'time' => array( 'time', false ),
		'user_id' => array( 'user_id', false ),
	  );

	  return $sortable_columns;
	}
	
	/**
	 * Returns an associative array containing the bulk action
	 *
	 * @return array
	 */
	public function get_bulk_actions() {
	  $actions = array(
		'bulk-approve' => 'Approve',
		'bulk-deny' => 'Deny',
		'bulk-delete' => 'Delete'
      );

	  return $actions;
	}
	
	/**
	 * Handles item actions.
	 */
	public function prepare_item_actions(){
		
	  /** Process bulk action */
	  $this->process_bulk_action();
	  $this->process_bulk_approve();
	  $this->process_bulk_deny();
	  
	  //single action
	  $this->process_delete_action();
	  $this->process_approve_action();
	  $this->process_deny_action();
	  $this->process_edit_action();
	  $this->process_view_action();
	}
	
	/**
	 * Handles data query and filter, sorting, and pagination.
	 */
	public function prepare_items() {

	  $this->_column_headers = $this->get_column_info();


	  $per_page     = $this->get_items_per_page( 'entry_per_page', 5 );
	  $current_page = $this->get_pagenum();
	  $total_items  = self::record_count();

	  $this->set_pagination_args( array(
		'total_items' => $total_items, //WE have to calculate the total number of items
		'per_page'    => $per_page //WE have to determine how many items to show on a page
      ) );


	  $this->items = self::get_subscriber_profiles( $per_page, $current_page );
	}

	/**
	 * Bulk Approve action
	 *
	 * @return null
	 */
	public function process_bulk_approve() {

		global $wpdb;
	  // If the delete bulk action is triggered
	  if ( ( isset( $_POST['action'] ) && $_POST['action'] == 'bulk-approve' )
		   || ( isset( $_POST['action2'] ) && $_POST['action2'] == 'bulk-approve' )
	  ) {
			
		$ids = esc_sql( $_POST['bulk-action'] );
		
		// loop over the array of record IDs and Approve them
		foreach ( $ids as $id ) {
			self::approve_subscriber_profile( $id );
		}
		echo '<div style="color: green;border: 1px solid green;margin: 2px;padding: 2px;text-align: center;margin-bottom: 8px;font-size: 18px;margin-top: 10px;">Bulk link approve Successfully!</div>';

		//wp_redirect( esc_url( add_query_arg() ) );
		//exit;
	  }
	}

	/**
	 * Bulk Deny action
	 *
	 * @return null
	 */
	public function process_bulk_deny() {

		global $wpdb;
	  // If the delete bulk action is triggered
	  if ( ( isset( $_POST['action'] ) && $_POST['action'] == 'bulk-deny' )
		   || ( isset( $_POST['action2'] ) && $_POST['action2'] == 'bulk-deny' )
	  ) {
			
		$ids = esc_sql( $_POST['bulk-action'] );
		
		// loop over the array of record IDs and deny them
		foreach ( $ids as $id ) {
			self::deny_subscriber_profile( $id );
		}
		echo '<div style="color: green;border: 1px solid green;margin: 2px;padding: 2px;text-align: center;margin-bottom: 8px;font-size: 18px;margin-top: 10px;">Bulk link deny Successfully!</div>';

		//wp_redirect( esc_url( add_query_arg() ) );
		//exit;
	  }
	}

	/**
	 * Bulk Delete action
	 *
	 * @return null
	 */
	public function process_bulk_action() {

	global $wpdb;
	  // If the delete bulk action is triggered
	  if ( ( isset( $_POST['action'] ) && $_POST['action'] == 'bulk-delete' )
		   || ( isset( $_POST['action2'] ) && $_POST['action2'] == 'bulk-delete' )
	  ) {
			
		$delete_ids = esc_sql( $_POST['bulk-action'] );
		
		
		// loop over the array of record IDs and delete them
		foreach ( $delete_ids as $id ) {			
			self::delete_subscriber_profile( $id );
		}
		echo '<div style="color: green;border: 1px solid green;margin: 2px;padding: 2px;text-align: center;margin-bottom: 8px;font-size: 18px;margin-top: 10px;">Bulk link has been delete Successfully!</div>';
		//wp_redirect( esc_url( add_query_arg() ) );
		//exit;
	  }
	}

	/**
	 * Delete action
	 *
	 * @return null
	 */
	public function process_delete_action() {

	global $wpdb;
	  if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'delete' )) {
			
		$id = esc_sql( $_GET['book'] );
		self::delete_subscriber_profile( $id );
		echo '<div style="color: green;border: 1px solid green;margin: 2px;padding: 2px;text-align: center;margin-bottom: 8px;font-size: 18px;margin-top: 10px;">Link has been deleted Successfully!</div>';
	  }
	}

	/**
	 * Approve action
	 *
	 * @return null
	 */
	public function process_approve_action() {

		global $wpdb;

	  if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'approve' )) {
		
		$id = esc_sql( $_GET['book'] );
		
		self::approve_subscriber_profile( $id );

		echo '<div style="color: green;border: 1px solid green;margin: 2px;padding: 2px;text-align: center;margin-bottom: 8px;font-size: 18px;margin-top: 10px;">Link has been approved Successfully!</div>';
		//wp_redirect( esc_url( add_query_arg() ) );
		//exit;
	  }
	}

	/**
	 * Deny action
	 *
	 * @return null
	 */
	public function process_deny_action() {

	global $wpdb;

	  if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'deny' )) {
		
		$id = esc_sql( $_GET['book'] );
		self::deny_subscriber_profile( $id );

		echo '<div style="color: green;border: 1px solid green;margin: 2px;padding: 2px;text-align: center;margin-bottom: 8px;font-size: 18px;margin-top: 10px;">Link has been denied successfully!</div>';
		//wp_redirect( esc_url( add_query_arg() ) );
		//exit;
	  }
	}

	/**
	 * Edit action
	 *
	 * @return null
	 */
	public function process_edit_action() {

	global $wpdb;

	  if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'edit' )) {
		
		$id = esc_sql( $_GET['book'] );
		self::edit_subscriber_profile( $id );

		//wp_redirect( esc_url( add_query_arg() ) );
		//exit;
	  }
	}
	
	
}