<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class Sbd_claim_order_list
{
	// class instance
	static $instance;

	public static function get_instance() {
		if ( ! isset( self::$instance ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	// class constructor
	public function __construct() {
		add_filter( 'set-screen-option', array( __CLASS__, 'set_screen' ), 10, 3 );
		add_action( 'admin_menu', array( $this, 'sld_custom_plugin_admin_menu' ) );

	}

	public static function set_screen( $status, $option, $value ) {
		return $value;
	}

	
	public function sld_custom_plugin_admin_menu() {

		$hook = add_submenu_page(
			'edit.php?post_type=pd',
			esc_html('Claimed Listing'),
			esc_html('Claimed Listing'),
			'manage_options',
			'qcsbd_claim_order_list',
			array(
				$this,
				'qc_sld_plugin_order_list_page'
			)
		);

	}
	
	/**
     * Approve Subscriber profile.
     *
     * @return null
     */

    public 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();
        $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,
				

            );

            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!=''){
                $this->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,

            );

            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')
            );
        }

    }
	    /**
     * Deny User Entry.
     *
     * @return null
     */

    public function deny_subscriber_profile($id){
        global $wpdb;

        $sql = "SELECT * FROM {$wpdb->prefix}pd_user_entry where 1 and id = ".$id;
        $identifier = time();
        $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 function sld_notification_approval( $user_id, $item ) {
		
		$user = new WP_User($user_id);
		$user_login = stripslashes($user->user_login);
		$user_email = stripslashes($user->user_email);
		$headers[] = 'Content-Type: text/html; charset=UTF-8';

        

		$sbd_lan_email_hi = pd_ot_get_option('sbd_lan_email_hi') != '' ? pd_ot_get_option('sbd_lan_email_hi') : __('Hi,', 'qc-pd');
		$sbd_lan_email_welcome_to = pd_ot_get_option('sbd_lan_email_welcome_to') != '' ? pd_ot_get_option('sbd_lan_email_welcome_to') : __('Welcome to', 'qc-pd');
		$sbd_lan_email_claim_listing_item = pd_ot_get_option('sbd_lan_email_claim_listing_item') != '' ? pd_ot_get_option('sbd_lan_email_claim_listing_item') : __('Your claim listing item ', 'qc-pd');
		$sbd_lan_email_has_been_approved = pd_ot_get_option('sbd_lan_email_has_been_approved') != '' ? pd_ot_get_option('sbd_lan_email_has_been_approved') : __('has been approved. ', 'qc-pd');


		$message  = __($sbd_lan_email_hi) . "\r\n\r\n";
		$message .= sprintf(__("%s %s! %s %s %s",'qc-pd'), $sbd_lan_email_welcome_to, get_option('blogname'),$sbd_lan_email_claim_listing_item,  $item, $sbd_lan_email_has_been_approved) . "\r\n\r\n";

		$sbd_lan_email_find_the_item_in = pd_ot_get_option('sbd_lan_email_find_the_item_in') != '' ? pd_ot_get_option('sbd_lan_email_find_the_item_in') : __('You can find the item in', 'qc-pd');
		$sbd_lan_email_dashboard_your_links = pd_ot_get_option('sbd_lan_email_dashboard_your_links') != '' ? pd_ot_get_option('sbd_lan_email_dashboard_your_links') : __('dashboard > your links', 'qc-pd');
		$sbd_lan_email_dashboard_tab = pd_ot_get_option('sbd_lan_email_dashboard_tab') != '' ? pd_ot_get_option('sbd_lan_email_dashboard_tab') : __('tab.', 'qc-pd');
		
		$message .= sprintf(__("%s <a href='%s'> %s </a> %s",'qc-pd'), $sbd_lan_email_find_the_item_in, qc_sbd_login_page()->pdcustom_login_get_translated_option_page( 'sld_dashboard_url',''), $sbd_lan_email_dashboard_your_links, $sbd_lan_email_dashboard_tab ) . "\r\n";

		$sbd_lan_list_has_been_approved = pd_ot_get_option('sbd_lan_list_has_been_approved') != '' ? pd_ot_get_option('sbd_lan_list_has_been_approved') : __('Your claim listing item has been approved!', 'qc-pd');

		wp_mail($user_email, sprintf(__('[%s] %s','qc-pd'), get_option('blogname'), $sbd_lan_list_has_been_approved ), $message, $headers);

	}
	public function top_action(){
		global $wpdb;
		$table             = $wpdb->prefix.'sbd_claim_purchase';
		
		if(isset($_GET['act']) and $_GET['act']=='delete' ){
			$id = $_GET['id'];
			$pdata = $wpdb->get_row("Select * from $table where 1 and `id`='$id'");
			$userid = $pdata->user_id;
			
			$wpdb->delete(
				$table,
				array( 'id' => $id ),
				array( '%d' )
			);
			
			echo '<div id="message" class="updated notice notice-success is-dismissible"><p>'.__('Claim Deleted','qc-pd').' </p><button type="button" class="notice-dismiss"><span class="screen-reader-text">'.__('Dismiss this notice.','qc-pd').'</span></button></div>';
		}
		
		if(isset($_GET['act']) and $_GET['act']=='approve'){
			
			
			
			$id = $_GET['id'];
			$pdata = $wpdb->get_row("Select * from $table where 1 and `id`='$id'");
			$userid = $pdata->user_id;
			
			$listId = $pdata->listid;
			if($pdata->status=='pending'){
				$lists = get_post_meta( $listId, 'qcpd_list_item01' );
				
				$userentry = $wpdb->prefix.'pd_user_entry';
				
				$category = get_the_terms($listId,'pd_cat');
				if(!empty($category)){
					$catslug = $category[0]->slug;
				}else{
					$catslug = '';
				}
				
				
				
				$datetime = date('Y-m-d H:i:s');
				$lastid = '';
				foreach($lists as $item){
					if($item['qcpd_item_title']==$pdata->item){

						if( isset($item['qcpd_item_img_link']) && $item['qcpd_item_img_link']!='' ){
							$inserted_image_url = $item['qcpd_item_img_link'];
						}else{
							if( isset($item['qcpd_item_img']) && $item['qcpd_item_img'] != '' ){
								$inserted_image_url = $item['qcpd_item_img'];
							}else{
								$inserted_image_url = '';
							}
						}

						$item['qcpd_item_nofollow'] = isset($item['qcpd_item_nofollow']) ? $item['qcpd_item_nofollow'] : 0;
						
						$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'  => $listId,
								'user_id'=>  $userid,
								'image_url'=> $inserted_image_url,
								'time'=> $datetime,
								'nofollow'=> $item['qcpd_item_nofollow'],
								'custom'=>$item['qcpd_timelaps'],
								'approval'=>3,
								'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'],
								'verified'=>'1',
								
							)
						);
						$lastid = $wpdb->insert_id;
						
						break;
						
						
					}
				}
				
				
				
				$wpdb->update(
					$table,
					array(
						'status'  => 'approved'
					),
					array( 'id' => $id),
					array(
						'%s',
					),
					array( '%d')
				);
				
				if($lastid!=''){
					$this->approve_subscriber_profile($lastid);
				}
				
				$this->sld_notification_approval($userid, $pdata->item);
				echo '<div id="message" class="updated notice notice-success is-dismissible"><p>'.__('Claim has been Approved successfully.','qc-pd').' </p><button type="button" class="notice-dismiss"><span class="screen-reader-text">'.__('Dismiss this notice.','qc-pd').'</span></button></div>';
			}else{
				echo '<div id="message" class="updated notice notice-success is-dismissible"><p>'.__('Claim has been Approved already.','qc-pd').' </p><button type="button" class="notice-dismiss"><span class="screen-reader-text">'.__('Dismiss this notice.','qc-pd').'</span></button></div>';
			}
		}
		
	}
	
	public function qc_sld_plugin_order_list_page(){
		
		global $wpdb;
		
		$ctable = $wpdb->prefix.'sbd_claim_purchase';
		$cptable = $wpdb->prefix.'sbd_claim_configuration';
		
		$current_user = wp_get_current_user();
		$this->top_action();
		$claimconfiguration     = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $cptable WHERE %d", 1 ) );

	?>
		<div class="qchero_sliders_list_wrapper">
			<div class="sld_menu_title">
				<h2 style="font-size: 26px;text-align:center"><?php echo __('Claimed Listing', 'qc-pd') ?></h2>

			</div>
			<div class="qchero_slider_table_area">
				<div class="pd_payment_table">
					<div class="pd_payment_row header">
						<div class="pd_payment_cell">
							<?php _e( 'Date', 'qc-pd' ) ?>
						</div>
						
						<div class="pd_payment_cell">
							<?php _e( 'List Name', 'qc-pd' ) ?>
						</div>
						<div class="pd_payment_cell">
							<?php _e( 'List Item Name', 'qc-pd' ) ?>
						</div>

						<div class="pd_payment_cell">
							<?php _e( 'Buyer Name', 'qc-pd' ) ?>
						</div>
						<div class="pd_payment_cell">
							<?php _e( 'User Name', 'qc-pd' ); ?>
						</div>
						<div class="pd_payment_cell">
							<?php _e( 'Payable Amount', 'qc-pd' ); ?>
						</div>
						<div class="pd_payment_cell">
							<?php _e( 'Paid Amount', 'qc-pd' ); ?>
						</div>
						<div class="pd_payment_cell">
							<?php _e( 'Payment Status', 'qc-pd' ); ?>
						</div>
						
						<div class="pd_payment_cell">
							<?php _e( 'Approval', 'qc-pd' ); ?>
						</div>
						
						<div class="pd_payment_cell">
							<?php _e( 'Action', 'qc-pd' ); ?>
						</div>
					</div>

			<?php
			$rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $ctable WHERE %d order by `date` DESC ", 1 ) );
			foreach($rows as $row){
			?>
				<div class="pd_payment_row">
					<div class="pd_payment_cell">
						<div class="pd_responsive_head"><?php echo __('Date', 'qc-pd') ?></div>
						<?php echo date('m/d/Y', strtotime($row->date)); ?>
					</div>
					
					<div class="pd_payment_cell">
						<div class="pd_responsive_head"><?php echo __('List Name', 'qc-pd') ?></div>
						<?php echo get_the_title($row->listid); ?>
					</div>
					<div class="pd_payment_cell">
						<div class="pd_responsive_head"><?php echo __('List Item Name', 'qc-pd') ?></div>
						<?php echo ($row->item); ?>
					</div>

					<div class="pd_payment_cell">
						<div class="pd_responsive_head"><?php echo __('Buyer Name', 'qc-pd') ?></div>
						<?php echo $row->payer_name; ?>
					</div>
					<div class="pd_payment_cell">
						<div class="pd_responsive_head"><?php echo __('User Name', 'qc-pd') ?></div>
						<?php
							$userinfo = get_user_by( 'ID', $row->user_id );
							if( $userinfo && !is_wp_error($userinfo) ){
								echo $userinfo->user_login;
							}
						?>
					</div>
					<div class="pd_payment_cell">
						<div class="pd_responsive_head"><?php echo __('Payable Amount', 'qc-pd') ?></div>
						<?php echo $row->paid_amount ?>
					</div>
					<div class="pd_payment_cell">
						<div class="pd_responsive_head"><?php echo __('Paid Amount', 'qc-pd') ?></div>
						<?php echo $row->paid_amount ?>
					</div>
					
					<div class="pd_payment_cell">
						<div class="pd_responsive_head"><?php echo __('Payment Status', 'qc-pd') ?></div>
						<?php 
							if($claimconfiguration->enable==1){
								if($row->paid_amount==0){
									echo '<span style="color:red">Not Paid</span>';
								}else{
									echo '<span style="color:green">Paid</span>';
								}
							}else{
								echo '<span style="color:green">Free</span>';
							}
						?>
					</div>
					<div class="pd_payment_cell">
						<div class="pd_responsive_head"><?php echo __('Approval', 'qc-pd') ?></div>
						<?php echo ucfirst($row->status); ?>
					</div>
					
					<div class="pd_payment_cell">
						<div class="pd_responsive_head"><?php echo __('Action', 'qc-pd') ?></div>
						
						<?php if($row->status!='approved'): ?>
						<a href="<?php echo wp_nonce_url( admin_url( 'edit.php?post_type=pd&page=qcsbd_claim_order_list&act=approve&id=' . $row->id ), 'pd' ) ?>">
							<button class="button button-primary"><?php echo __('Approve', 'qc-pd') ?></button>
							
						</a>
						<?php endif; ?>
						
						<?php if($row->status=='approved'):
						
							$userentry = $wpdb->prefix.'pd_user_entry';
							$get_user_item = $wpdb->get_row("Select * from $userentry where 1 and `pd_list` = '".$row->listid."' and `user_id` = '".$row->user_id."' order by id desc limit 1");
						?>
						<a href="<?php echo admin_url( 'edit.php?post_type=pd&page=qcpd_user_entry_list&action=edit&book='.$get_user_item->id ); ?>">
							<button class="button button-primary"><?php echo __('Edit Item', 'qc-pd') ?></button>
						</a>
						<?php endif; ?>
						
						<a href="<?php echo wp_nonce_url( admin_url( 'edit.php?post_type=pd&page=qcsbd_claim_order_list&act=delete&id=' . $row->id ), 'pd' ) ?>">
							<button class="button button-danger"><?php echo __('Delete', 'qc-pd') ?></button>
							
						</a>
					</div>
				</div>
			<?php
			}
			?>

			</div>

		</div>
		</div>
	<?php
	}
}
function Sbd_claim_order_list(){
	return Sbd_claim_order_list::get_instance();
}
Sbd_claim_order_list();