<?php

add_action('wp_head', 'qcpd_ajax_ajaxurl');
add_action('admin_head', 'qcpd_ajax_ajaxurl');

function qcpd_ajax_ajaxurl()
{

    echo '<script type="text/javascript">
           	var ajaxurl = "' . admin_url( 'admin-ajax.php', is_ssl() ? 'https' : 'http' ) . '";
            var qc_sbd_get_ajax_nonce = "'.wp_create_nonce( 'qc-pd').'";
         </script>';
}

//Doing ajax action stuff

function sbd_upvote_ajax_action_stuff(){

	check_ajax_referer( 'qc-pd', 'security');

    //Get posted items
    $action = trim($_POST['action']);
    $post_id = trim($_POST['post_id']);
    $meta_title = trim($_POST['meta_title']);
    $meta_link = trim($_POST['meta_link']);
    $li_id = trim($_POST['li_id']);

    //Check wpdb directly, for all matching meta items
    global $wpdb;

    $results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE post_id = $post_id AND meta_key = 'qcpd_list_item01'");

    //Defaults
    $votes = 0;

    $data['votes'] = 0;
    $data['vote_status'] = 'failed';

    $exists = in_array("$li_id", $_COOKIE['voted_li']);

    //If li-id not exists in the cookie, then prceed to vote
    if (!$exists) {

    	if(!empty($results)){
	        //Iterate through items
	        foreach ($results as $key => $value) {

	            $item = $value;

	            $meta_id = $value->meta_id;

	            $unserialized = unserialize($value->meta_value);

	            //If meta title and link matches with unserialized data
	            if (trim($unserialized['qcpd_item_title']) == wp_unslash(trim($meta_title)) && trim($unserialized['qcpd_item_link']) == trim($meta_link)) {

	                $metaId = $meta_id;

	                //Defaults for current iteration
	                $upvote_count = 0;
	                $new_array = array();
	                $flag = 0;

	                //Check if there already a set value (previous)
	                if (array_key_exists('qcpd_upvote_count', $unserialized)) {
	                    $upvote_count = (int)$unserialized['qcpd_upvote_count'];
	                    $flag = 1;
	                }

	                foreach ($unserialized as $key => $value) {
	                    if ($flag) {
	                        if ($key == 'qcpd_upvote_count') {
	                            $new_array[$key] = $upvote_count + 1;
	                        } else {
	                            $new_array[$key] = $value;
	                        }
	                    } else {
	                        $new_array[$key] = $value;
	                    }
	                }

	                if (!$flag) {
	                    $new_array['qcpd_upvote_count'] = $upvote_count + 1;
	                }

	                $votes = (int)$new_array['qcpd_upvote_count'];

	                $updated_value = serialize($new_array);

	                $wpdb->update(
	                    $wpdb->postmeta,
	                    array(
	                        'meta_value' => $updated_value,
	                    ),
	                    array('meta_id' => $metaId)
	                );

	                $voted_li = array("$li_id");

	                $total = 0;
	                $total = count($_COOKIE['voted_li']);
	                $total = $total + 1;

	                setcookie("voted_li[$total]", $li_id, time() + (86400 * 30), "/");

	                $data['vote_status'] = 'success';
	                $data['votes'] = $votes;
	            }

	        }

        }
    }

    $data['cookies'] = $_COOKIE['voted_li'];

    echo json_encode($data);


    die(); // stop executing script
}

//Implementing the ajax action for frontend users
add_action('wp_ajax_qcpd_upvote_action', 'sbd_upvote_ajax_action_stuff'); // ajax for logged in users
add_action('wp_ajax_nopriv_qcpd_upvote_action', 'sbd_upvote_ajax_action_stuff'); // ajax for not logged in users

//captcha image change script
function qcld_pd_change_captcha(){
	session_start();
	if(isset($_SESSION['sbd_captcha'])){
		unset($_SESSION['sbd_captcha']);
	}
	$_SESSION['sbd_captcha'] = pd_simple_php_captcha();
	echo $_SESSION['sbd_captcha']['image_src'];
	die();
}

add_action('wp_ajax_qcld_pd_change_captcha', 'qcld_pd_change_captcha'); // ajax for logged in users
add_action('wp_ajax_nopriv_qcld_pd_change_captcha', 'qcld_pd_change_captcha'); // ajax for not logged in users

//captcha image change script
function qcld_pd_change_captcha1(){
	session_start();
	if(isset($_SESSION['sbd_captcha'])){
		unset($_SESSION['sbd_captcha']);
	}
	$_SESSION['sbd_captcha'] = pd_simple_php_captcha();
	$data['url'] = $_SESSION['sbd_captcha']['image_src'];
	$data['code'] = (strtolower($_SESSION['sbd_captcha']['sbd_code']));
	echo json_encode($data);
	die();
}

add_action('wp_ajax_qcld_pd_change_captcha1', 'qcld_pd_change_captcha1'); // ajax for logged in users
add_action('wp_ajax_nopriv_qcld_pd_change_captcha1', 'qcld_pd_change_captcha1'); // ajax for not logged in users


function qcld_pd_loadmore_function(){

 if(pd_ot_get_option('pd_use_global_thumbs_up')!=''){
     $pd_thumbs_up = pd_ot_get_option('pd_use_global_thumbs_up');
 }else{
     $pd_thumbs_up = 'fa-thumbs-up';
 }

	
	
	$paged = $_POST['page'];
	$column = $_POST['column'];
	$upvote = $_POST['upvote'];
	$itemperpage = $_POST['itemperpage'];
	$item_count = $_POST['itemcount'];
	

	$list_args = array(
		'post_type' => 'pd',
		'posts_per_page' => $itemperpage,
		'paged'	=> $paged
		
	);
	
	$list_query = new WP_Query( $list_args );
	
	
	$listId = 1;

	while ( $list_query->have_posts() )
	{
		$list_query->the_post();

		$lists = get_post_meta( get_the_ID(), 'qcpd_list_item01' );

		$conf = get_post_meta( get_the_ID(), 'qcpd_list_conf', true );

		$addvertise = get_post_meta( get_the_ID(), 'pd_add_block', true );

		$addvertiseContent = isset($addvertise['add_block_text']) ? $addvertise['add_block_text'] : '';

		//adding extra variable in config
		$conf['item_title_font_size'] = $title_font_size;
		$conf['item_subtitle_font_size'] = $subtitle_font_size;
		$conf['item_title_line_height'] = $title_line_height;
		$conf['item_subtitle_line_height'] = $subtitle_line_height;

		?>

		

		<!-- Override Set Style Elements -->
		<style>
			#list-item-<?php echo $listId .'-'. get_the_ID(); ?>.simple ul{
				border-top-color: <?php echo $conf['list_border_color']; ?>;
			}

			#list-item-<?php echo $listId .'-'. get_the_ID(); ?>.simple ul li a{
				background-color: <?php echo $conf['list_bg_color']; ?>;
				color: <?php echo $conf['list_txt_color']; ?>;

				<?php if($conf['item_title_font_size']!=''): ?>
				font-size:<?php echo $conf['item_title_font_size']; ?>;
				<?php endif; ?>

				<?php if($conf['item_title_line_height']!=''): ?>
				line-height:<?php echo $conf['item_title_line_height']; ?>;
				<?php endif; ?>

				<?php if( $conf['item_bdr_color'] != "" ) : ?>
				border-bottom-color: <?php echo $conf['item_bdr_color']; ?> !important;
				<?php endif; ?>
			}

			#list-item-<?php echo $listId .'-'. get_the_ID(); ?>.simple ul li a:hover{
				background-color: <?php echo $conf['list_bg_color_hov']; ?>;
				color: <?php echo $conf['list_txt_color_hov']; ?>;

				<?php if( $conf['item_bdr_color_hov'] != "" ) : ?>
				border-bottom-color: <?php echo $conf['item_bdr_color_hov']; ?> !important;
				<?php endif; ?>
			}

			#list-item-<?php echo $listId .'-'. get_the_ID(); ?>.simple .upvote-section .sbd-upvote-btn, #list-item-<?php echo $listId .'-'. get_the_ID(); ?>.simple .upvote-section .upvote-count {
				color: <?php echo $conf['list_txt_color']; ?>;
			}

			#list-item-<?php echo $listId .'-'. get_the_ID(); ?>.simple .upvote-section .sbd-upvote-btn:hover, #list-item-<?php echo $listId .'-'. get_the_ID(); ?>.simple li:hover .sbd-upvote-btn, #list-item-<?php echo $listId .'-'. get_the_ID(); ?>.simple li:hover .upvote-count{
				color: <?php echo $conf['list_txt_color_hov']; ?>;
			}

			#item-<?php echo $listId .'-'. get_the_ID(); ?>-add-block .advertise-block.tpl-default{
				border-top: 5px solid #f86960;
				border-top-color: <?php echo $conf['list_border_color']; ?>;
				box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.2);
			}

			#item-<?php echo $listId .'-'. get_the_ID(); ?>-add-block .advertise-block.tpl-default ul{
				border: none;
				box-shadow: none !important;
				margin-bottom: 0 !important;
			}

		</style>


		<!-- Individual List Item -->
		<div id="list-item-<?php echo $listId .'-'. get_the_ID(); ?>" class="qc-grid-item qcpd-list-column opd-column-<?php echo $column; echo " simple";?> <?php echo "opd-list-id-" . get_the_ID(); ?>">
			<div class="qcpd-single-list-pd">
				<?php
					$item_count_disp = "";

					if( $item_count == "on" ){
						$item_count_disp = count(get_post_meta( get_the_ID(), 'qcpd_list_item01' ));
					}
				?>
				<h2 <?php echo (isset($conf['list_title_color'])&&$conf['list_title_color']!=''?'style="color:'.$conf['list_title_color'].';"':''); ?>>
					<?php echo get_the_title(); ?>
					<?php
						if($item_count == 'on'){
							echo '<span class="opd-item-count">('.$item_count_disp.')</span>';
						}
					?>
				</h2>

				<ul id="jp-list-<?php echo get_the_ID(); ?>">
					<?php

						if( $item_orderby == 'upvotes' )
						{
    						$lists = sbd_filter_by_upvote($lists);
						}

						if( $item_orderby == 'title' )
						{
    						usort($lists, "pd_custom_sort_by_tpl_title");
						}

						if( $item_orderby == 'timestamp' )
						{
							usort($lists, "pd_custom_sort_by_tpl_timestamp");
						}

						if( $item_orderby == 'random' )
						{
							shuffle( $lists );
						}

						$count = 1;

						foreach( $lists as $list ) :

						$tooltip_content = '';

						if( $tooltip === 'true' ){
							$tooltip_content = ' data-tooltip="'.$list['qcpd_item_subtitle'].'" data-tooltip-stickto="top" data-tooltip-color="#000" data-tooltip-animate-function="scalein"';
						}
					?>
					<li id="item-<?php echo get_the_ID() ."-". $count; ?>" <?php echo $tooltip_content; ?>>

						<?php
							$item_url = $list['qcpd_item_link'];
							$masked_url = $list['qcpd_item_link'];

							$mask_url = isset($mask_url) ? $mask_url : 'off';

							if( $mask_url == 'on' ){
								$masked_url = 'http://' . qcpd_get_domain($list['qcpd_item_link']);
							}
						?>
						<!-- List Anchor -->
						<a <?php if( $mask_url == 'on') { echo 'onclick="document.location.href = \''.$item_url.'\'; return false;"'; } ?> <?php echo (isset($list['qcpd_item_nofollow']) && $list['qcpd_item_nofollow'] == 1) ? 'rel="nofollow"' : ''; ?> <?php echo (isset($main_click_action)&&$main_click_action==3?'':'href="'.$masked_url.'"'); ?>"
							<?php echo (isset($list['qcpd_item_newtab']) && $list['qcpd_item_newtab'] == 1) ? 'target="_blank"' : ''; ?>  >

							<?php
								$iconClass = (isset($list['qcpd_fa_icon']) && trim($list['qcpd_fa_icon']) != "") ? $list['qcpd_fa_icon'] : "";

								$showFavicon = (isset($list['qcpd_use_favicon']) && trim($list['qcpd_use_favicon']) != "") ? $list['qcpd_use_favicon'] : "";

								$faviconImgUrl = "";
								$faviconFetchable = false;
								$filteredUrl = "";

								$directImgLink = (isset($list['qcpd_item_img_link']) && trim($list['qcpd_item_img_link']) != "") ? $list['qcpd_item_img_link'] : "";

								if( $showFavicon == 1 )
								{
									$filteredUrl = qcpd_remove_http( $item_url );

									if( $item_url != '' )
									{

										$faviconImgUrl = 'https://www.google.com/s2/favicons?domain=' . $filteredUrl;
									}

									if( $directImgLink != '' )
									{

										$faviconImgUrl = trim($directImgLink);
									}

									$faviconFetchable = true;

									if( $item_url == '' && $directImgLink == '' ){
										$faviconFetchable = false;
									}
								}

							?>

							<!-- Image, If Present -->
							<?php if( ($list_img == "true") && isset($list['qcpd_item_img'])  && $list['qcpd_item_img'] != "" ) : ?>
								<span class="list-img">
									<?php
										$img = wp_get_attachment_image_src($list['qcpd_item_img']);
									?>
									<img src="<?php echo $img[0]; ?>" alt="<?php echo $list['qcpd_item_title']; ?>">
								</span>
							<?php elseif( $iconClass != "" ) : ?>
								<span class="list-img">
									<i class="fa <?php echo $iconClass; ?>"></i>
								</span>
							<?php elseif( $showFavicon == 1 && $faviconFetchable == true ) : ?>
								<span class="list-img favicon-loaded">
									<img src="<?php echo $faviconImgUrl; ?>" alt="<?php echo $list['qcpd_item_title']; ?>">
								</span>
							<?php else : ?>
								<span class="list-img">
									<img src="<?php echo QCSBD_IMG_URL; ?>/list-image-placeholder.png" alt="<?php echo $list['qcpd_item_title']; ?>">
								</span>
							<?php endif; ?>

							<!-- Link Text -->
							<?php
								echo $list['qcpd_item_title'];
							?>

						</a>

						<?php if( $upvote == 'on' ) : ?>

							<!-- upvote section -->
							<div class="upvote-section">
								<span data-post-id="<?php echo get_the_ID(); ?>" data-item-title="<?php echo trim($list['qcpd_item_title']); ?>" data-item-link="<?php echo $list['qcpd_item_link']; ?>" class="sbd-upvote-btn upvote-on">
									<i class="fa <?php echo $pd_thumbs_up; ?>"></i>
								</span>
								<span class="upvote-count">
									<?php
									  if( isset($list['qcpd_upvote_count']) && (int)$list['qcpd_upvote_count'] > 0 ){
									  	echo (int)$list['qcpd_upvote_count'];
									  }
									?>
								</span>
							</div>
							<!-- /upvote section -->

						<?php endif; ?>
						
						<?php if(pd_ot_get_option('pd_enable_bookmark')=='on'): ?>
							<!-- upvote section -->
							<div class="bookmark-section">
							
								<?php 
								$bookmark = 0;
								if(isset($list['qcpd_is_bookmarked']) and $list['qcpd_is_bookmarked']!=''){
									$unv = explode(',',$list['qcpd_is_bookmarked']);
									if(in_array(get_current_user_id(),$unv)){
										$bookmark = 1;
									}
								}
								?>
							
							
								<span data-post-id="<?php echo get_the_ID(); ?>" data-item-code="<?php echo trim($list['qcpd_timelaps']); ?>" data-is-bookmarked="<?php echo ($bookmark); ?>" class="bookmark-btn bookmark-on">
									
									<i class="fa <?php echo ($bookmark==1?'fa-star':'fa-star-o'); ?>" aria-hidden="true"></i>
								</span>
								
							</div>
							<?php endif; ?>
						
						<?php 
								if(isset($list['qcpd_new']) and $list['qcpd_new']==1):
							?>
							<!-- new icon section -->
							<div class="new-icon-section">
								<span>new</span>
							</div>
							<!-- /new icon section -->
							<?php endif; ?>
							
							
							<?php 
								if(isset($list['qcpd_featured']) and $list['qcpd_featured']==1):
							?>
							<!-- featured section -->
							<div class="featured-section">
								
							</div>
							<!-- /featured section -->
							<?php endif; ?>

					</li>

					<?php $count++; endforeach; ?>

				</ul>

				

			</div>

		</div>
		<!-- /Individual List Item -->


		<?php

		$listId++;
	}

	
	
	die();
}


add_action('wp_ajax_qcld_pd_loadmore', 'qcld_pd_loadmore_function'); // ajax for logged in users
add_action('wp_ajax_nopriv_qcld_pd_loadmore', 'qcld_pd_loadmore_function'); // ajax for not logged in users

function qcld_pd_loadmore_filter_function(){
	
	$paged 			= $_POST['page'];
	$column 		= $_POST['column'];
	$item_count 	= $_POST['itemcount'];
	$itemperpage 	= $_POST['itemperpage'];
	

	$list_args = array(
		'post_type' 		=> 'pd',
		'posts_per_page' 	=> $itemperpage,
		'paged'				=> $paged
		
	);
	
	$listItems = get_posts( $list_args );
	
	
	foreach ($listItems as $item) :
		$config = get_post_meta( $item->ID, 'qcpd_list_conf' );
		$filter_background_color = '';
		$filter_text_color = '';
		if(isset($config[0]['filter_background_color']) and $config[0]['filter_background_color']!=''){
			$filter_background_color = $config[0]['filter_background_color'];
		}
		if(isset($config[0]['filter_text_color']) and $config[0]['filter_text_color']!=''){
			$filter_text_color = $config[0]['filter_text_color'];
		}
		?>

		<?php
		$item_count_disp = "";

		if( $item_count == "on" ){
			$item_count_disp = count(get_post_meta( $item->ID, 'qcpd_list_item01' ));
		}
		?>

		<a href="#" class="filter-btn" data-filter="opd-list-id-<?php echo $item->ID; ?>" style="background:<?php echo $filter_background_color ?>;color:<?php echo $filter_text_color ?>">
			<?php echo $item->post_title; ?>
			<?php
			if($item_count == 'on'){
				echo '<span class="opd-item-count-fil">('.$item_count_disp.')</span>';
			}
			?>
		</a>

	<?php endforeach;
	die();
}


add_action('wp_ajax_qcld_pd_loadmore_filter', 'qcld_pd_loadmore_filter_function'); // ajax for logged in users
add_action('wp_ajax_nopriv_qcld_pd_loadmore_filter', 'qcld_pd_loadmore_filter_function'); // ajax for not logged in users

function qcpd_search_pd_page_function(){
	if(trim($_POST['shortcode'])!=''){
		$shortcode = trim($_POST['shortcode']);
		$list_args = array(
			'post_type' => 'page',
			'posts_per_page' => -1,
			'post_status' => array('publish') 
			
		);
		$listItems = get_posts( $list_args );
		$data = '';
		foreach($listItems as $item){
			
			if(strpos($item->post_content, $shortcode ) !== false ){
				if($shortcode=='sbd_login'){
					$data = 'Login page found!<br><a href="'.get_permalink($item->ID).'">'.get_permalink($item->ID).'</a>';
				}
				if($shortcode=='sbd_registration'){
					$data = 'Registration page found!<br><a href="'.get_permalink($item->ID).'">'.get_permalink($item->ID).'</a>';
				}
				if($shortcode=='sbd_dashboard'){
					$data = 'Dashboard page found!<br><a href="'.get_permalink($item->ID).'">'.get_permalink($item->ID).'</a>';
				}
				if($shortcode=='sbd_restore'){
					$data = 'Password Restore page found!<br><a href="'.get_permalink($item->ID).'">'.get_permalink($item->ID).'</a>';
				}
				break;
			}
		}
		if($data!=''){
			echo $data;
		}else{
			
				if($shortcode=='sbd_login'){
					echo 'Login page not found!';
				}
				if($shortcode=='sbd_registration'){
					echo 'Registration page not found!';
				}
				if($shortcode=='sbd_dashboard'){
					echo 'Dashboard page not found!';
				}
				if($shortcode=='sbd_restore'){
					echo 'Password restore Page not found!';
				}
			
		}
	}
	die();
}



add_action('wp_ajax_qcpd_search_pd_page', 'qcpd_search_pd_page_function'); // ajax for logged in users
add_action('wp_ajax_nopriv_qcpd_search_pd_page', 'qcpd_search_pd_page_function'); // ajax for not logged in users

/* URL Filtering Logic, to remove http:// or https:// */
function qcsbd_remove_http($url) {
   $disallowed = array('http://', 'https://');
   foreach($disallowed as $d) {
      if(strpos($url, $d) === 0) {
         return str_replace($d, '', $url);
      }
   }
   return trim($url);
}

function qcpd_load_long_description_function(){
	
	$post_id = trim($_POST['post_id']);
    $meta_title = wp_unslash(trim($_POST['meta_title']));
    $meta_link = trim($_POST['meta_link']);
	$popup_map = $_POST['popup_map'];
	$upvote = $_POST['upvote'];
	$mailto = $_POST['mailto'];
	global $wpdb;
    $results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE post_id = $post_id AND meta_key = 'qcpd_list_item01'");
	
	foreach ($results as $key => $value) {
		$list = unserialize($value->meta_value);
		if (trim($list['qcpd_item_title']) == trim($meta_title) && trim($list['qcpd_item_link']) == trim($meta_link)) {
			echo '<div class="pd_main_container"><div class="pd_single_content" '.($popup_map=="false"?'style="width:100%"':'').'>';
?>
		<div class="pd_top_area">
			<div class="feature-image">
			<?php
				$iconClass = (isset($list['qcpd_fa_icon']) && trim($list['qcpd_fa_icon']) != "") ? $list['qcpd_fa_icon'] : "";

				$showFavicon = (isset($list['qcpd_use_favicon']) && trim($list['qcpd_use_favicon']) != "") ? $list['qcpd_use_favicon'] : "";

				$faviconImgUrl = "";
				$faviconFetchable = false;
				$filteredUrl = "";

				$directImgLink = (isset($list['qcpd_item_img_link']) && trim($list['qcpd_item_img_link']) != "") ? $list['qcpd_item_img_link'] : "";

				if( $showFavicon == 1 )
				{
					$filteredUrl = qcsbd_remove_http( $item_url );

					if( $item_url != '' )
					{

						$faviconImgUrl = 'https://www.google.com/s2/favicons?domain=' . $filteredUrl;
					}

					if( $directImgLink != '' )
					{

						$faviconImgUrl = trim($directImgLink);
					}

					$faviconFetchable = true;

					if( $item_url == '' && $directImgLink == '' ){
						$faviconFetchable = false;
					}
				}
				?>
			<!-- Image, If Present -->
				<?php if( isset($list['qcpd_item_img'])  && $list['qcpd_item_img'] != "" ) : ?>


					<?php
						
						if (strpos($list['qcpd_item_img'], 'http') === FALSE){
							$img = wp_get_attachment_image_src($list['qcpd_item_img'], 'medium');
						?>
							<img src="<?php echo $img[0]; ?>" alt="<?php echo $list['qcpd_item_title']; ?>">
						<?php
						}else{
							
							$img = $list['qcpd_item_img'];
						?>
							<img src="<?php echo $img; ?>" alt="<?php echo $list['qcpd_item_title']; ?>">
						<?php
						}
						
					?>
					


				<?php elseif( $iconClass != "" ) : ?>

					<span class="icon fa-icon">
						<i class="fa <?php echo $iconClass; ?>"></i>
					</span>

				<?php elseif( $showFavicon == 1 && $faviconFetchable == true ) : ?>

					<img src="<?php echo $faviconImgUrl; ?>" alt="<?php echo $list['qcpd_item_title']; ?>">

				<?php else : ?>

					<img src="<?php echo QCSBD_IMG_URL; ?>/list-image-placeholder.png" alt="<?php echo $list['qcpd_item_title']; ?>">

				<?php endif; ?>
			</div>
			<div class="pd_bottom_desc">

				<?php if(isset($list['qcpd_item_business_hour']) and $list['qcpd_item_business_hour']!=''): 
				if(pd_ot_get_option('sbd_lan_business_hour')!=''){
					$businesstext = pd_ot_get_option('sbd_lan_business_hour');
				}else{
					$businesstext = __('Business Hour','qc-pd');
				}
				?>
					<div class="pd_business_hour">
						<p><span><i class="fa fa-clock-o fa-clock" aria-hidden="true"></i> <?php echo $businesstext; ?>:</span> <?php echo (isset($list['qcpd_item_business_hour']) && $list['qcpd_item_business_hour']!=''?trim($list['qcpd_item_business_hour']):''); ?></p>
					</div>
				<?php endif; ?>
				<?php
					if(isset($list['qcpd_item_phone']) and $list['qcpd_item_phone']!=''):
						if(pd_ot_get_option('sbd_lan_phone')!=''){
							$phone_text = pd_ot_get_option('sbd_lan_phone');
						}else{
							$phone_text = __('Phone','qc-pd');
						}
				?>
				<div class="pd_business_hour">
					<p class="sbd_popup_phone_content"><span><i class="fa fa-phone" aria-hidden="true"></i> <span class="sbd_popup_phone_text"><?php echo $phone_text; ?>:</span></span> <a href="tel:<?php echo preg_replace("/[^0-9]/", "",$list['qcpd_item_phone']); ?>"><?php echo $list['qcpd_item_phone']; ?></a></p>
				</div>
				<?php endif; ?>
				
				<?php
				if(isset($list['qcpd_item_email']) and $list['qcpd_item_email']!=''):
					if(pd_ot_get_option('sbd_lan_email')!=''){
						$email_text = pd_ot_get_option('sbd_lan_email');
					}else{
						$email_text = __('Email','qc-pd');
					}
				?>
				<div class="pd_business_hour">
					<?php if( $mailto == 'true' ){ ?>
						<p class="sbd_popup_email_content"><span><i class="fa fa-envelope-o fa-envelope" aria-hidden="true"></i> <span class="sbd_popup_email_text"><?php echo $email_text; ?>:</span></span> <a href="mailto:<?php echo antispambot($list['qcpd_item_email'], 1); ?>" data-email="<?php echo (isset($list['qcpd_item_email']) && $list['qcpd_item_email']!=''?trim($list['qcpd_item_email']):'#'); ?>" ><?php echo (pd_ot_get_option('sbd_lan_email_send_click')!=''?pd_ot_get_option('sbd_lan_email_send_click'):__('Click to Send Email', 'qc-pd')); ?></a></p>
					<?php }else{ ?>
						<p class="sbd_popup_email_content"><span><i class="fa fa-envelope-o fa-envelope" aria-hidden="true"></i> <span class="sbd_popup_email_text"><?php echo $email_text; ?>:</span></span> <a href="#" data-email="<?php echo (isset($list['qcpd_item_email']) && $list['qcpd_item_email']!=''?trim($list['qcpd_item_email']):'#'); ?>" class="sbd_email_form"><?php echo (pd_ot_get_option('sbd_lan_email_send_click')!=''?pd_ot_get_option('sbd_lan_email_send_click'):__('Click to Send Email', 'qc-pd')); ?></a></p>
					<?php } ?>
				</div>
				<?php endif; ?>
				
				<?php
				if(isset($list['qcpd_item_full_address']) and $list['qcpd_item_full_address']!=''):
					if(pd_ot_get_option('sbd_lan_adress')!=''){
						$address_text = pd_ot_get_option('sbd_lan_adress');
					}else{
						$address_text = __('Address','qc-pd');
					}
				?>
				<div class="pd_business_hour">
					<p class="sbd_popup_address_content"><span><i class="fa fa-map-marker fa-map-marker-alt" aria-hidden="true"></i> <span class="sbd_popup_address_text"><?php echo $address_text; ?>:</span></span> <?php echo $list['qcpd_item_full_address']; ?></p>
				</div>
				<?php endif; ?>
				
				<div class="pd-bottom-area" style="text-align:left">
				<?php if($list['qcpd_item_facebook']!='' || $list['qcpd_item_yelp']!='' || $list['qcpd_item_linkedin']!='' || $list['qcpd_item_twitter']!=''): ?>
				<p style="font-weight:bold"><i class="fa fa-users" aria-hidden="true"></i> <span class="sbd_popup_social_text"><?php echo (pd_ot_get_option('sbd_lan_social')!=''?pd_ot_get_option('sbd_lan_social'):__('Social', 'qc-pd')); ?>:</span></p>
				<?php if(isset($list['qcpd_item_facebook']) and $list['qcpd_item_facebook']!=''): ?>
				<p><a target="_blank" href="<?php echo (isset($list['qcpd_item_facebook']) && $list['qcpd_item_facebook']!=''?trim($list['qcpd_item_facebook']):'#'); ?>"><i class="fa fa-facebook"></i></a></p>
				<?php endif; ?>
				<?php if(isset($list['qcpd_item_yelp']) and $list['qcpd_item_yelp']!=''): ?>
				<p><a target="_blank" href="<?php echo (isset($list['qcpd_item_yelp']) && $list['qcpd_item_yelp']!=''?trim($list['qcpd_item_yelp']):'#'); ?>"><i class="fa fa-yelp"></i></a></p>
				<?php endif; ?>
				<?php if(isset($list['qcpd_item_linkedin']) and $list['qcpd_item_linkedin']!=''): ?>
				<p><a target="_blank" href="<?php echo (isset($list['qcpd_item_linkedin']) && $list['qcpd_item_linkedin']!=''?trim($list['qcpd_item_linkedin']):'#'); ?>"><i class="fa <?php echo (sbd_is_linkedin($list['qcpd_item_linkedin'])?'fa-linkedin-square fa-linkedin':'fa-instagram'); ?>"></i></a></p>
				<?php endif; ?>
				
				<?php if(isset($list['qcpd_item_twitter']) and $list['qcpd_item_twitter']!=''): ?>
				<p><a target="_blank" href="<?php echo (isset($list['qcpd_item_twitter']) && $list['qcpd_item_twitter']!=''?trim($list['qcpd_item_twitter']):'#'); ?>"><i class="fa fa-twitter-square"></i></a></p>
				<?php endif; ?>
				<?php endif; ?>
				<?php
					include(QCSBD_DIR_MOD.'/template-common/qc_custom_icon_content.php');
				?>
			</div>

				<?php
					if( function_exists('qcpdr_show_rating_with_numbered_icon') && function_exists('qcpdr_ot_get_option')  && qcpdr_ot_get_option('qcpdr_enable_reviews') != 'off' ){
						echo '<div  class="qcpdr-long-desc-popup-review">';
						echo '<i class="fa fa-star"></i><span style="font-weight: 700;">'.esc_html__('Reviews: ', 'qcpd-review').'</span> <div title="add your own review" class="sbd-long-desc-popup-average-review-field">';
						qcpdr_show_rating_with_numbered_icon( $post_id , $list);
						echo '</div></div>';
					}
				?>
				
			</div>			
		</div>
		<div style="clear:both"></div>
		<div class="pd_content_text">
<?php
			$categories = get_the_terms( $post_id, 'pd_cat' );
			if(!empty($categories)){
				$categorytxt = '';
				foreach($categories as $category){
					$categorytxt .= $category->name.', ';
				}
				$categorytxt = rtrim($categorytxt, ', ');
				
				echo '<p class="qcpd_popup_breadcumb">'.esc_html($categorytxt).' > '.esc_html(get_the_title($post_id)).'</p>';
			}			
			echo '<h2>'.esc_html($list['qcpd_item_title']);
?>
			<?php if($upvote=='on'): ?>
			<div class="upvote-section upvote-section-style-single">
				<span data-post-id="<?php echo $post_id; ?>" data-unique="<?php echo $post_id.'_'.$list['qcpd_timelaps']; ?>" data-item-title="<?php echo trim($list['qcpd_item_title']); ?>" data-item-link="<?php echo $list['qcpd_item_link']; ?>" class="pd-sbd-upvote-btn-single upvote-on">
					<i class="fa fa-thumbs-up"></i>
				</span>
				<span class="upvote-count count">
					<?php
					  if( isset($list['qcpd_upvote_count']) && (int)$list['qcpd_upvote_count'] > 0 ){
						echo (int)$list['qcpd_upvote_count'];
					  }
					?>
				</span>
			</div>
			<?php endif; ?>
<?php		
			echo '</h2>';	
			
			echo apply_filters( 'the_content', $list['qcpd_description'] );

			
			?>
<?php
	include(QCSBD_DIR_MOD.'/template-common/qc_custom_body_content.php');
?>
		
			<?php
			if(pd_ot_get_option('sbd_lan_visit_link')!=''){
				$visitlink = pd_ot_get_option('sbd_lan_visit_link');
			}else{
				$visitlink = __('Visit This Link','qc-pd');
			}
			if($list['qcpd_item_link']!=''){
				echo '<div style="clear:both"></br></div><a href="'.$list['qcpd_item_link'].'" target="_blank" class="pd_single_button">'.$visitlink.'</a><br><br>';
			}
			echo '</div>';
			//do_action('qcpdr_ajax_single_item_review', );
			if( class_exists('QCPD\FrontEnd\Review\Reviews') ){
				$sbd_review = new \QCPD\FrontEnd\Review\Reviews();
				$sbd_review->display_ajax_review_fields( $list['qcpd_timelaps'], $post_id );
			}
			echo '</div>';
?>
<?php if($popup_map=="true"): ?>
<div class="pd_content_right">
	<div id="pd_popup_map_container"></div>
</div>
<?php endif; ?>

<?php
			echo '</div>';
?>
<style type="text/css">
.mfp-content{padding:0px !important;}
</style>

<?php			
		}
	}
	die();
}



add_action('wp_ajax_qcpd_load_long_description', 'qcpd_load_long_description_function'); // ajax for logged in users
add_action('wp_ajax_nopriv_qcpd_load_long_description', 'qcpd_load_long_description_function'); // ajax for not logged in users

//load list items
function qcld_sbd_show_list_item_fnc(){
	global $wpdb;
	$listId = $_POST['listid'];
	$lists = get_post_meta( $listId, 'qcpd_list_item01' );
	
	foreach( $lists as $list ) :
		echo '<option value="'.$list['qcpd_item_title'].'">'.$list['qcpd_item_title'].'</option>';
	endforeach;
	
	die();
}


add_action('wp_ajax_qcld_sbd_show_list_item', 'qcld_sbd_show_list_item_fnc'); // ajax for logged in users
add_action('wp_ajax_nopriv_qcld_sbd_show_list_item', 'qcld_sbd_show_list_item_fnc'); // ajax for not logged in users

function qcpd_tag_pd_page_fnc(){
	
	global $wpdb;
	
?>
<div class="fa-field-modal-wrap">
<div class="fa-field-modal" id="fa-field-modal-tag" style="display:block">
  <div class="fa-field-modal-close">&times;</div>
  <h1 class="fa-field-modal-title"><?php _e( 'Add Tags', 'qc-pdb' ); ?></h1>
  <p style="margin-top: 28px;margin-bottom: 0;">Press (enter) to add a tag & (Backspace) to remove tag.</p>

	<div class="sld-form-control tags" id="pd-tags" style="margin-top: 40px;">
      	<input type="text" class="labelinput">
        <input id="pdtagvalue" type="hidden" value="" name="result">
     </div>
  <input type="submit" id="pd_tag_select" name="submit" value="Add Tags" />
</div>
</div>

<?php
	
	die();
	
}

add_action('wp_ajax_qcpd_tag_pd_page', 'qcpd_tag_pd_page_fnc'); // ajax for logged in users
add_action('wp_ajax_nopriv_qcpd_tag_pd_page', 'qcpd_tag_pd_page_fnc'); // ajax for not logged in users

function qcpd_search_pd_tags_fnc(){
	
	global $wpdb;

	$results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE 1 AND meta_key = 'qcpd_list_item01'");
	$lists = array();
	if(!empty($results)){
		foreach($results as $result){
			$unserialize = unserialize($result->meta_value);			
			if(isset($unserialize['qcpd_tags']) && $unserialize['qcpd_tags']!=''){				
				foreach(explode(',',$unserialize['qcpd_tags']) as $itm){
					if(!in_array($itm, $lists)){
						array_push($lists, $itm);
					}
				}				
			}			
		}
	}
	echo implode(',',$lists);
	
	die();
	
}

add_action('wp_ajax_qcpd_search_pd_tags', 'qcpd_search_pd_tags_fnc'); // ajax for logged in users
add_action('wp_ajax_nopriv_qcpd_search_pd_tags', 'qcpd_search_pd_tags_fnc'); // ajax for not 

function qcpd_img_download_fnc(){
	
	global $wpdb;
	$url = $_POST['url'];
	$attach_id = '';
	$blueprint = array(
		'attachmentid'=>'',
		'imgurl'=>''
	);
						
		$image = sld_get_web_page("https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=".$url."&screenshot=true");
		$image = json_decode($image, true);
		// $image = $image['screenshot']['data'];
		$image = $image['lighthouseResult']['audits']['final-screenshot']['details']['data'];
		$upload_dir       = wp_upload_dir();
		$upload_path      = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
		$image = str_replace(array('_', '-'), array('/', '+'), $image);
		$imgBase64 = str_replace('data:image/jpeg;base64,', '', $image);
		$imgBase64 = str_replace(' ', '+', $imgBase64);
		$decoded = base64_decode($imgBase64);
		$filename         = 'sldwebsite.jpg';
		$hashed_filename  = md5( $filename . microtime() ) . '_' . $filename;
		$image_upload     = file_put_contents( $upload_path . $hashed_filename, $decoded );
		if( !function_exists( 'wp_handle_sideload' ) ) {
		  require_once( ABSPATH . 'wp-admin/includes/file.php' );
		}
		if( !function_exists( 'wp_get_current_user' ) ) {
		  require_once( ABSPATH . 'wp-includes/pluggable.php' );
		}
		$file             = array();
		$file['error']    = '';
		$file['tmp_name'] = $upload_path . $hashed_filename;
		$file['name']     = $hashed_filename;
		$file['type']     = 'image/jpeg';
		$file['size']     = filesize( $upload_path . $hashed_filename );
		$file_return      = wp_handle_sideload( $file, array( 'test_form' => false ) );
		$filename = $file_return['file'];
		$attachment = array(
		 'post_mime_type' => $file_return['type'],
		 'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
		 'post_content' => '',
		 'post_status' => 'inherit',
		 'guid' => $upload_dir['url'] . '/' . basename($filename)
		 );
		$attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
		require_once(ABSPATH . 'wp-admin/includes/image.php');
		$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
		wp_update_attachment_metadata( $attach_id, $attach_data );					
		
		$thumb = @wp_get_attachment_image_src($attach_id,'thumbnail');
		$blueprint['attachmentid'] = $attach_id;
		$blueprint['imgurl'] = (!empty($thumb)?$thumb[0]:'');
		echo json_encode($blueprint);
	
	die();
	
}

add_action('wp_ajax_qcpd_img_download', 'qcpd_img_download_fnc'); // ajax for logged in users
add_action('wp_ajax_nopriv_qcpd_img_download', 'qcpd_img_download_fnc'); // ajax for not logged in users


//add_action('init', 'test_fnc_init');
function test_fnc_init(){
	global $wpdb;
	$results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE 1 AND meta_key = 'qcpd_list_item01'");
	$lists = array();
	if(!empty($results)){
		foreach($results as $result){
			$unserialize = unserialize($result->meta_value);			
			if(isset($unserialize['qcpd_tags']) && $unserialize['qcpd_tags']!=''){				
				foreach(explode(',',$unserialize['qcpd_tags']) as $itm){
					if(!in_array($itm, $lists)){
						array_push($lists, $itm);
					}
				}				
			}			
		}
	}
	echo implode(',',$lists);
	exit;	
}

function qcpd_generate_text_fnc(){
	
	global $wpdb;
	$url = $_POST['url'];
	$schema = array(
		'title'=>'',
		'description'=>'',
	);
	if($url!=''){
		
		$html = sld_get_web_page($url);

		$html_dom = new DOMDocument();
		@$html_dom->loadHTML($html);
		$xpath = new DOMXPath($html_dom);
		
		if($xpath->query('/html/head/meta[@name="description"]/@content')->item(0)->textContent!=''){
			$schema['description'] = iconv("UTF-8", "ISO-8859-1", $xpath->query('/html/head/meta[@name="description"]/@content')->item(0)->textContent);
			if( !$schema['description'] ){
				$schema['description'] = $xpath->query('/html/head/meta[@name="description"]/@content')->item(0)->textContent;
			}
		}
		if($xpath->query('//title')->item(0)->textContent!=''){
			$schema['title'] = iconv("UTF-8", "ISO-8859-1", $xpath->query('//title')->item(0)->textContent);
			if( !$schema['title'] ){
				$schema['title'] = $xpath->query('//title')->item(0)->textContent;
			}
		}
		echo json_encode($schema);
		
	}
	
	die();
	
}

add_action('wp_ajax_qcpd_generate_text', 'qcpd_generate_text_fnc'); // ajax for logged in users
add_action('wp_ajax_nopriv_qcpd_generate_text', 'qcpd_generate_text_fnc'); // ajax for not logged in users

function qcld_pd_send_visitors_email_fnc(){
	
	$response = array();
	$response['status'] = false;

	if(isset($_POST['data'])){
		$name 				= isset( $_POST['data']['name'] ) 				? sanitize_text_field($_POST['data']['name']) : '';
		$subject 			= isset( $_POST['data']['subject'] ) 			? sanitize_text_field($_POST['data']['subject']) : '';
		$message 			= isset( $_POST['data']['message'] ) 			? sanitize_text_field($_POST['data']['message']) : '';
		$email 				= isset( $_POST['data']['email'] ) 				? sanitize_email($_POST['data']['email']) : '';
		$to 				= isset( $_POST['data']['to'] ) 				? sanitize_email($_POST['data']['to']) : '';
		$sbd_email_title 	= isset( $_POST['data']['sbd_email_title'] ) 	? sanitize_text_field($_POST['data']['sbd_email_title']) : '';
		$sbd_email_subtitle = isset( $_POST['data']['sbd_email_subtitle'] ) ? sanitize_text_field($_POST['data']['sbd_email_subtitle']) : '';

		if( pd_ot_get_option( 'pd_enable_recaptcha') !='on' ){
			$code 	= isset( $_POST['data']['captcha'] ) 	? sanitize_text_field((strtolower($_POST['data']['captcha']))) : '';
			$ccode 	= isset( $_POST['data']['ccaptcha'] ) 	? sanitize_text_field($_POST['data']['ccaptcha']) : '';
		}
		check_ajax_referer( '2q3c5sbd-email1-ajax2-noncea', 'security' );
		
		if( pd_ot_get_option( 'pd_enable_recaptcha') !='on' ){
			if(strtolower($code) != strtolower($ccode)){
				$response['status'] = false;
				$response['message'] = __('Invalid Captcha!', 'qc-pd');
				echo json_encode($response);
				die();
			}
		}

		if( pd_ot_get_option( 'pd_enable_recaptcha') =='on' ){
			$recaptcha=$_POST['data']['recaptcha'];
			if(!empty($recaptcha)){
				$google_url = "https://www.google.com/recaptcha/api/siteverify";
				$secret = pd_ot_get_option( 'pd_recaptcha_secret_key');

				$response = wp_remote_get( add_query_arg( array(
                                              'secret'   => $secret,
                                              'response' => $recaptcha,
                                          ), $google_url ) );

				if( is_wp_error( $response ) || empty($response['body']) || ! ($json = json_decode( $response['body'] )) || ! $json->success ){
					
					$response['status'] = false;
					$response['message'] = __('Invalid reCaptcha!', 'qc-pd');
					echo json_encode($response);
					die();
				}
			} else {
				$response['status'] = false;
				$response['message'] = __('Invalid reCaptcha!', 'qc-pd');
				echo json_encode($response);
				die();
			}
		}
		
		
		
		$admin_email = (pd_ot_get_option('pd_admin_email')!=''?pd_ot_get_option('pd_admin_email'):get_option( 'admin_email' ));
		
		$email_not_send = (pd_ot_get_option('sbd_lan_email_notsent')!=''?pd_ot_get_option('sbd_lan_email_notsent'):__('Unable to send email. Please contact your server administrator.', 'qc-pd'));
		
		if(pd_ot_get_option('pd_enable_admin_email_also')=='on'){
			$headers[] = 'Cc: '.$admin_email;
		}
		
		$name_text 		= pd_ot_get_option('sbd_lan_name') != '' ? pd_ot_get_option('sbd_lan_name') : 'Name';
		$mail_text 		= pd_ot_get_option('sbd_lan_email') != '' ? pd_ot_get_option('sbd_lan_email') : 'Email';
		$subject_text 	= pd_ot_get_option('sbd_lan_subject') != '' ? pd_ot_get_option('sbd_lan_subject') : 'Subject';
		$message_text 	= pd_ot_get_option('sbd_lan_message') != '' ? pd_ot_get_option('sbd_lan_message') : 'Message';
		$message_title 	= pd_ot_get_option('sbd_lan_title_mail') != '' ? pd_ot_get_option('sbd_lan_title_mail') : 'List Item Title';
		$message_subtitle 	= pd_ot_get_option('sbd_lan_subtitle_mail') != '' ? pd_ot_get_option('sbd_lan_subtitle_mail') : 'List Item Subtitle';

		$message_content  = sprintf(__('%1$s: %2$s','qc-pd'), $name_text, $name) . "\r\n\r\n";
		$message_content  .= sprintf(__('%1$s: %2$s','qc-pd'), $mail_text, $email) . "\r\n\r\n";
		$message_content  .= sprintf(__('%1$s: %2$s','qc-pd'), $subject_text, $subject) . "\r\n\r\n";
		$message_content .= sprintf(__('%1$s: %2$s','qc-pd'), $message_text, $message) . "\r\n\r\n";
		if(!empty($sbd_email_title)){
			$message_content .= "---------------------------\r\n\r\n";
			$message_content .= sprintf(__('%1$s: %2$s','qc-pd'), $message_title, $sbd_email_title) . "\r\n\r\n";
		}
		if(!empty($sbd_email_subtitle)){
		$message_content .= sprintf(__('%1$s: %2$s','qc-pd'), $message_subtitle, $sbd_email_subtitle) . "\r\n\r\n";
		}
		
		$headers[]   = 'Reply-To: '.$name.' <'.$email.'>';

		$message_content = apply_filters('sbd_style_email_body', $message_content, $to, $subject, $headers, $name, $email, $message);

		$success = wp_mail( $to, $subject, $message_content, $headers );
		if($success){
			$response['status'] = true;
			$response['msg'] = $sbd_email_title;
			echo json_encode($response);
		}else{
			$response['status'] = false;
			$response['message'] = $email_not_send;
			echo json_encode($response);			
		}
		
	}
	die();
	
}

add_action('wp_ajax_qcld_pd_send_visitors_email', 'qcld_pd_send_visitors_email_fnc'); // ajax for logged in users
add_action('wp_ajax_nopriv_qcld_pd_send_visitors_email', 'qcld_pd_send_visitors_email_fnc'); // ajax for not logged in users

function qcpd_flash_rewrite_rules_fnc(){
	flush_rewrite_rules();
	die();
}


add_action('wp_ajax_qcpd_flash_rewrite_rules', 'qcpd_flash_rewrite_rules_fnc'); // ajax for logged in users
add_action('wp_ajax_nopriv_qcpd_flash_rewrite_rules', 'qcpd_flash_rewrite_rules_fnc'); // ajax for not logged in users




function qcpd_ajax_live_search_functions(){
	
	global $wpdb;

	if(isset($_POST['search'])){
        $search = sanitize_text_field($_POST['search']);

    	$results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key = 'qcpd_list_item01' and meta_value like '%$search%' group by post_id");

        //Iterate through items
        $response = array();
        if(!empty($results)){
	        foreach($results as $key => $value){

	        	$post_id = $value->post_id;

	        	$lists = get_post_meta( $post_id, 'qcpd_list_item01' );

				foreach($lists as $list ){

					if (stripos($list['qcpd_item_title'], $search) !== false) {
					    $response[] = array("value"=>$post_id,"label"=>$list['qcpd_item_title']);
					}
				}
	        }

	    }

        echo json_encode($response);
    }
	
    exit();
	
}

add_action('wp_ajax_qcpd_ajax_live_search_functions', 'qcpd_ajax_live_search_functions'); // ajax for logged in users
add_action('wp_ajax_nopriv_qcpd_ajax_live_search_functions', 'qcpd_ajax_live_search_functions'); // ajax for not 