<?php  
if(!is_admin() && $GLOBALS['pagenow'] !== 'post.php'){	
	add_shortcode('DAPMemberContent', 'DAPMyContentShortcode');
	add_shortcode('DAPPayPerPostContent', 'DAPMemberContentPayPerPost');
}	


function DAPMyContentShortcode($atts, $content = null) {
 	if(isset($_REQUEST['tve']) && $_REQUEST['tve'] == true){return;}		
	extract(shortcode_atts(array(
	'id' => '',
	), $atts));
	
	
	//check if enqueue is working on the site
	 if(wp_style_is('wp_enqueue_test_css')) {  
		$includeCSSByEnqueue = true;
	}else{
		$includeCSSByEnqueue = false;
	}

	if(wp_script_is('wp_enqueue_test_js')) {
		$includeJSByEnqueue = true;
	}else{
		$includeJSByEnqueue = false;
	}
	//check if enqueue is working on the site
	
	$session = Dap_Session::getSession();
    $user = $session->getUser();
   
	//default variables
	$temp_type ="singlecol";
	$dm_img_type = "img_slider" ;
	$productid="ALL";
	$hideproductid="NONE";
	$showunavailableproducts = "N"; 	
	$dm_wid ="700";
	$dm_wid_outer ="850";
	$availabledata="";
	$availablecontent ="";
	$upcomingcontent ="";
	$upcomingdata ="";
	$orderlinks =""; 
	$numberoflinks ="10";
	$linktopopup =  "#"; 
	$box_wid = '300';	
	$dm_img_wid1 = 150; 
	$modulebg = '#d9edf7';
	/*******All messages from the settings page************/

	$orderoflinks = "NEWESTFIRST";
	$sorttype = "purchasedate";
	$pleaselogintext ="Click here to log in";
	$clicktologintext ="Sorry, you must log in before you can view this content";
	$currentlyhaveaccesstext="You currently have access to %%USERPRODUCTSCOUNT%% product(s).";
	$nocontent = "No Content Available";
	$dateformat = "YYYY-MM-DD";
	$showproductcount = "Y";
	$howmanylinks = "9999";
	$howmanyupcominglinks = "5";
	$howmanylinksperpage = "10";
	$available_up_data ="";
	
	$orderoflinks =  dapMemberGetMessageByKeyAndAction('mycontent','orderoflinks'); 
	$sorttype =   dapMemberGetMessageByKeyAndAction('mycontent','sorttype');
	$pleaselogintext =   dapMemberGetMessageByKeyAndAction('mycontent','pleaselogintext');
	$clicktologintext =   dapMemberGetMessageByKeyAndAction('mycontent','clicktologintext');
	$currentlyhaveaccesstext =   dapMemberGetMessageByKeyAndAction('mycontent','currentlyhaveaccesstext');
	$nocontent =   dapMemberGetMessageByKeyAndAction('mycontent','nocontent');
	$dateformat =   dapMemberGetMessageByKeyAndAction('mycontent','dateformat');
	$showproductcount =   dapMemberGetMessageByKeyAndAction('mycontent','showproductcount');
	$howmanylinks =   dapMemberGetMessageByKeyAndAction('mycontent','howmanylinks');
	$howmanyupcominglinks =   dapMemberGetMessageByKeyAndAction('mycontent','howmanyupcominglinks');
	$howmanylinksperpage =   dapMemberGetMessageByKeyAndAction('mycontent','howmanylinksperpage');
    
    if(!isset($howmanylinksperpage) || $howmanylinksperpage ==""){
		$howmanylinksperpage = "10";
	}     
    if(!isset($howmanyupcominglinks) || $howmanyupcominglinks ==""){
		$howmanyupcominglinks = "5";
	}     
    if(!isset($howmanylinks) || $howmanylinks ==""){
		$howmanylinks = "9999";
	}     
  /*
	if($orderoflinks == "NEWESTFIRST"){
		$orderlinks ="asc";
	}else{
		$orderlinks ="desc";
	}*/
	$orderlinks ="desc";
	$style_attr =" <style> #notloggedin_outer  a {font-weight: 600;color: #333;font-size: 15px;} #notloggedin_outer .not_logged { color: #2239b9;font-weight: 600; text-decoration: underline; }</style>";
	  
    if( !Dap_Session::isLoggedIn() || !isset($user) ) {
        $errorHTML = mb_convert_encoding($pleaselogintext, "UTF-8", "auto") . " <a class='not_logged' href=\"" . Dap_Config::get("LOGIN_URL") . "\">". mb_convert_encoding($clicktologintext, "UTF-8", "auto") . "</a>";
        return "<div id='notloggedin_outer'>".$errorHTML.$style_attr."</div>";
    }
    $random = rand(10,100);
    
     //load data by id
	 $mp_obj = DAP_MemberPages::loadById($id);
	//echo "<pre>";print_r($mp_obj); die;
	
	if($mp_obj){		
		$action_id = $mp_obj->getId();	 
		
		$gettemp =  $mp_obj->getTemplate();
		$gettemp = explode("||",$gettemp);
		$template_selected_name =  $gettemp[0];
		$template =  $gettemp[1];
		$temp_type =  $gettemp[2];

		$template_html =  $mp_obj->getTemplateHtml();
		$template_html =  str_replace('contenteditable="true"','contenteditable="false"',$template_html);
		$template_html =  str_replace('%%IMAGESPATH%%','',$template_html); 
		 
		$template_html = explode("|:|",$template_html);			
		$template_customized_html = $template_html[0];			
		$clicktostart = $template_html[1];			
		$upcoming_days = $template_html[2];		
		$availabledata = $template_html[3];		
		$upcomingdata = $template_html[4];		
		$available_up_data = $template_html[5];		
		
		$styling_options = $mp_obj->getStylingOptions();
		$styling_options = explode("|||",$styling_options);
		
		//echo "<pre>"; print_r($styling_options);
		//customize template variable  
		if(isset($styling_options[0])){			
			$dm_content_temp = explode("||",$styling_options[0]);			
			$dm_wid =  $dm_content_temp[0];
			$prod_per_row =  $dm_content_temp[13];			
			$dm_wid_outer =  $dm_content_temp[14];			
			$dm_temp_align =  $dm_content_temp[15];			
			$box_wid =  $dm_content_temp[16];
			$modulebg=  $dm_content_temp[18];			
		}
		 //customize  img variable 
		if(isset($styling_options[1])){			
			$dm_content_temp_img = explode("||",$styling_options[1]);			
			$show_img =  $dm_content_temp_img[0];
			$dm_img_type =  $dm_content_temp_img[1];
			$dm_img_res =  $dm_content_temp_img[2];
			$dm_img_wid =  $dm_content_temp_img[3];
			$dm_img_height =  $dm_content_temp_img[4];	
			$dm_img_wid1 =  $dm_content_temp_img[5];		 
		}
		
		//get the name-value pair
		$mpv_obj = DAP_MemberPagesValues::loadByActionId($action_id);		
		if($mpv_obj){
			$showunavailableproducts = DAP_MemberPagesValues::loadByActionIdAndName($action_id, 'showunavailableproducts');			 
			if(isset($showunavailableproducts)){
				$showunavailableproducts = $showunavailableproducts->getValue();				  				 					 
			}  
			 
			$productid_obj = DAP_MemberPagesValues::loadByActionIdAndName($action_id, 'productid');			 
			if(isset($productid_obj)){	
				$productid = $productid_obj->getValue();					 	 				 
			}  
		  
			$hideproductid_obj = DAP_MemberPagesValues::loadByActionIdAndName($action_id, 'hideproductid');			 
			if(isset($hideproductid_obj)){	
				$hideproductid	= $hideproductid_obj->getValue();			 	 				 
			}  
			if($temp_type =="contentlinks"){ 
				$select_prod_obj = DAP_MemberPagesValues::loadByActionIdAndName($action_id, 'select_prod');			 
				if(isset($select_prod_obj)){	
					$select_prod	= $select_prod_obj->getValue();			 	 				 
				}   
			}   
		}
		
		
		$productList = Dap_Product::loadProducts("","A");
		$displayoption = $template_selected_name;
		$csspath = dap_member_path."includes/templates/mycontent/".$temp_type. "/".$template_selected_name. "/template1.css?".rand(10,1000);	
		$scriptstyle  = '<link href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&display=swap" rel="stylesheet">		
		<link rel="stylesheet" id="font-awesome.min"  href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css?ver=1.0.0" type="text/css" media="all" /> 
		'; 
		
		
		// if template type is productlist
		if($temp_type =="productlist"){			
			$scriptstyle .= '<link href="'.$csspath.'" rel="stylesheet"> <link href="'. plugin_dir_url(__FILE__). 'includes/css/dap_mycontent_fe.css" rel="stylesheet">';
			
			$style ="<style> #dap_member_content_frontend_shortcode_".$random."  .dap_frontend_wrapper .porduct_list_heading {color: #333; font-family: 'Open Sans', sans-serif;font-weight: 600; font-size: 22px;line-height: 1;}</style> ";
			$template_customized_html_new ="";
			$prod_list_html ="";
			
			$productList = sortDisplayProducts($user, $productList, $sorttype, $showunavailableproducts,$productid, $hideproductid );
			 
			foreach($productList as $prod){
				$post_login_url = $prod->getlogged_in_url(); 
				if($post_login_url == ""){  
					$page_link =  "#";  
				}				 
				$prod_list  ='<li><a href="'.$post_login_url.'">'.$availabledata.'</a></li>';				
				$prod_list_html .=  str_replace( 'Test Product A', $prod->getName(), $prod_list);	 			 	
			}
			
	 		$template_customized_html_new  =  str_replace( '%%PRODUCTLISTS%%', $prod_list_html, $template_customized_html);	
			$html   = "<div id='dap_member_content_frontend_shortcode_".$random."' class='dap_member_frontend_shortcode ".$temp_type."_cls dap_member_content_frontend_shortcode_".$mp_obj->getId()."'> ".$template_customized_html_new." </div>";
			return $scriptstyle.$html.$style  ;		 	
		}
		 
		
		// if template type is contentlinks
		if($temp_type =="contentlinks"){	
			
			 
			$scriptstyle  .= '<link href="'.$csspath.'" rel="stylesheet"><link href="'. plugin_dir_url(__FILE__). 'includes/css/dap_mycontent_fe.css" rel="stylesheet">	'; 
			$template_customized_html_new ="";			
			$productId = $select_prod;
			  
			$content_list_html = DapMemberContentlinksTemplate($template_customized_html , $user, $productId, $orderlinks, $numberoflinks, $nocontent,$availabledata);			 
			$template_customized_html = DapMemberContentlinksTemplateMergeTags($template_customized_html , $user, $productId, $orderlinks, $numberoflinks, $nocontent);	
	 		$template_customized_html_new  =  str_replace( '%%PRODUCTLISTS%%', $content_list_html, $template_customized_html);	
	 		
	 		$scriptstyle .='
		<script type="text/javascript"> 
		var $jq = jQuery.noConflict();		 
		$jq(document).ready(function(){			 
			if($jq(".dap_product_links_list tbody tr").length < 1 ) {
				$jq(".dap_product_links_list tbody").addClass("dataTables_empty_outer");
				$jq(".dap_product_links_list tbody ").html("<tr><td>'.$nocontent.'</td></tr>");
			}		 	
		});
		</script>'; 
		 
	 		
			$html   = "<div id='dap_member_content_frontend_shortcode_".$random."' class='dap_member_frontend_shortcode ".$temp_type."_cls dap_member_content_frontend_shortcode_".$mp_obj->getId()."'> ".$template_customized_html_new." </div>";
			return $scriptstyle .$html ;		 	
		}
	 
		
		// if template type is onecol and multicol		
 
		 $dm_img_array = array(
				'1'=>'150*150',
				'2'=>'200*200',
				'3'=>'250*250',
				'4'=>'300*300',
				'5'=>'350*350',
				'6'=>'400*400',
				'7'=>'200*150',
				'8'=>'250*200',
				'9'=>'300*250',
				'10'=>'350*300',
				'11'=>'400*350',
				'12'=>'200*100',
				'13'=>'250*150',
				'14'=>'300*250',
				'15'=>'350*300',
				'16'=>'400*300',
				'17'=>'250*100',
				'18'=>'300*150',
				'19'=>'350*200',
				'20'=>'400*250',
				'21'=>'450*300',
				'22'=>'500*350',													
				'23'=>'300*100',													
				'24'=>'350*150',													
				'25'=>'400*200',													
				'26'=>'450*250',													
				'27'=>'500*300',													
				); 
				 
			$random = rand(10,100);				 
			if($temp_type == 'multicol'){
				$product_img_style = "<style>#dap_member_content_frontend_shortcode_".$random." .product_img { width: 100% !important; max-height:".$dm_img_wid."px; height:".$dm_img_wid."px;} #dap_member_content_frontend_shortcode_".$random." .product_img img { max-height:100% !important; height:100%!important;}</style>"; 
			}else{						 
				$product_img_style = "<style>#dap_member_content_frontend_shortcode_".$random." .product_img { width:".$dm_img_wid."px;max-height:".$dm_img_wid."px; height:".$dm_img_wid."px;} #dap_member_content_frontend_shortcode_".$random." .product_img img{ height:".$dm_img_wid."px; }</style>";
			}	
				
				
			$img_data =   $product_img_style ;
			
			
			$productList = sortDisplayProducts($user, $productList, $sorttype, $showunavailableproducts,$productid, $hideproductid );		
			 
			
			$accessuserProducts = Dap_UsersProducts::loadProducts($user->getId());
			foreach ($accessuserProducts as $userProduct1) {
				$userProduct_ids[] =  $userProduct1->getProduct_id();
			}
			$userprodcount = count($userProduct_ids);
			
			$clicktostarttext = '<div class="dap_member_tiny_editor click_to_start_btn click_to_start">'.$clicktostart.'</div>';
			$upcoming_daystext = '<div class="upcoming_days">'.$upcoming_days.'</div>';
			
			if($temp_type == "singlecol"){ 
				if($currentlyhaveaccesstext == ""){
					$userhasaccestoproductstext= "<div class='currentlyaccess_text' style='width:".$dm_wid."px; float:".$dm_temp_align."; margin:auto; display:none'>".$currentlyhaveaccesstext."</div>";
				}else{				
					$userhasaccestoproductstext= "<div class='currentlyaccess_text' style='width:".$dm_wid."px; float:".$dm_temp_align."; margin:auto'>".$currentlyhaveaccesstext."</div>";
				}
			}else{
				if($currentlyhaveaccesstext == ""){
					$userhasaccestoproductstext= '<div class="currentlyaccess_text" style="display:none">'.$currentlyhaveaccesstext.'</div>';
				}else{
					$userhasaccestoproductstext= '<div class="currentlyaccess_text">'.$currentlyhaveaccesstext.'</div>';
				}
				
			}
		
  
		$productscounttext =  str_replace( '%%USERPRODUCTSCOUNT%%',$userprodcount, $userhasaccestoproductstext); 
		
		$userId= $user->getId();
		$i =0;	
		$template_customized_html_new= '';	
		foreach($productList as $prod){			
			$productId = $prod->getId();
			 
			//hide the products
			if(isset($hideproductid)){			
				if($hideproductid != "NONE") {					 
					$hideProductIdArray = explode(",",$hideproductid);
					if( in_array($prod->getId(), $hideProductIdArray) ) {
						continue;
					}
				}
			}

			//show the products
			if(isset($productid)){	
				  
				if($productid != "ALL" ) {					 
					if(strstr($productid,",")!=false) {
					  $productIdArray = explode(",",$productid);
					  if( !in_array($prod->getId(), $productIdArray) ) {
						  continue;
					  }
					}
					else {
						$prodid=$productid;
						if( $prod->getId() != $prodid ) {
						   continue;
						}
					}
				}			   
			}		 
	
			//for multicolumn to display			
			if($temp_type == "multicol"){ 				
				 				 
				 if( in_array($prod->getId(), $userProduct_ids) ) {		
					$template_customized_html_new .= "<div class='dap_member_frontend_shortcode_inn matchheight  ".$prod_per_row."' >";
					$template_customized_html_new .= DapMemberContentReplaceMergeTags($user, $template_customized_html, $clicktostarttext, $upcoming_daystext,  $productId, $userId, $displayoption, $userProduct_ids , $availabledata , $temp_type, $upcomingdata, $available_up_data, $orderoflinks,"","", $nocontent, $howmanyupcominglinks, $howmanylinks); 
					$template_customized_html_new .= "</div>";					
				}
				if( !in_array($prod->getId(), $userProduct_ids) ) {		
					$template_customized_html_new .= "<div class='dap_member_frontend_shortcode_inn matchheight product_container_grey ".$prod_per_row."' >";
					$template_customized_html_new .= DapMemberContentReplaceMergeTags($user, $template_customized_html, $clicktostarttext, $upcoming_daystext, $productId,$userId,$displayoption , $userProduct_ids , $availabledata , $temp_type, $upcomingdata, $available_up_data,$orderoflinks,"", "", $nocontent, $howmanyupcominglinks, $howmanylinks); 
					$template_customized_html_new .= "</div>";
				}
				
				$template_customized_html_new .= '<style>#dap_member_content_frontend_shortcode_'.$random.' .dap_multi_column_outer {width:'.$box_wid.'px}</style>'  ;
				
				
			}else{
				
				/******Added for postmeta temp starts******/
				if($template_selected_name == "postmetadata"){ 
					
					$image_url =  plugins_url()."/DAP-WP-LiveLinks/includes/templates/mycontent/singlecol/postmetadata/noimg2.jpg";	
					 if( in_array($prod->getId(), $userProduct_ids) ) {		
						$template_customized_html_new .= "<div class='dap_member_frontend_shortcode_inn matchheight  ".$prod_per_row."' >";
						$template_customized_html_new .= DapMemberContentReplaceMergeTags($user, $template_customized_html, $clicktostarttext, $upcoming_daystext,  $productId, $userId, $displayoption, $userProduct_ids , $availabledata , $temp_type, $upcomingdata, $available_up_data, $orderoflinks,"postmeta" , $image_url, $nocontent, $howmanyupcominglinks, $howmanylinks); 
						$template_customized_html_new .= "</div>";					
					}
					if( !in_array($prod->getId(), $userProduct_ids) ) {		
						$template_customized_html_new .= "<div class='dap_member_frontend_shortcode_inn matchheight product_container_grey ".$prod_per_row."' >";
						$template_customized_html_new .= DapMemberContentReplaceMergeTags($user, $template_customized_html, $clicktostarttext, $upcoming_daystext, $productId,$userId,$displayoption , $userProduct_ids , $availabledata , $temp_type, $upcomingdata, $available_up_data,$orderoflinks,"postmeta" , $image_url, $nocontent, $howmanyupcominglinks, $howmanylinks); 
						$template_customized_html_new .= "</div>"; 
					}
					
						$template_customized_html_new .='<style>.lessons-content-block{    
						max-width: calc(100% - '.$dm_img_wid1.'px);
						max-width: -moz-calc(100% - '.$dm_img_wid1.'px);
						max-width: -webkit-calc(100% - '.$dm_img_wid1.'px);
						max-width: -ms-calc(100% - '.$dm_img_wid1.'px);}
						.dap_member_frontend_shortcode .single_col_newdata .module_lesson thead , .dap_member_frontend_shortcode .single_col_newdata .module_lesson thead tr {   background: '.$modulebg.'!important;  background-color: '.$modulebg.'!important;}  .dap_member_frontend_shortcode .single_col_newdata .module_lesson thead th{   background: '.$modulebg.'!important;  background-color: '.$modulebg.'!important;}</style>'  ;
				
					$template_customized_html_new .= '<style>#dap_member_content_frontend_shortcode_'.$random.' .dap_multi_column_outer {width:'.$box_wid.'px}</style>'  ;
					
				/******Added for postmeta temp ends******/	
				}else{
				
					//for onecolumn to display
					 if( in_array($prod->getId(), $userProduct_ids) ) {
						 $template_customized_html_new .= "<div class='dap_member_frontend_shortcode_inn matchheightonecol' id='dap_member_frontend_shortcode_inn_id'>";
						 $template_customized_html_new .= DapMemberContentReplaceMergeTags($user, $template_customized_html, $clicktostarttext, $upcoming_daystext,  $productId, $userId, $displayoption, $userProduct_ids, $availabledata , $temp_type, $upcomingdata, $available_up_data,$orderoflinks,"","", $nocontent, $howmanyupcominglinks, $howmanylinks); 
						 $template_customized_html_new .= "</div>";
						 $i++;
					}	
					if( !in_array($prod->getId(), $userProduct_ids) ) {		
						$template_customized_html_new .= "<div class='dap_member_frontend_shortcode_inn product_container_grey matchheightonecol' id='dap_member_frontend_shortcode_inn_id'>";
						$template_customized_html_new .= DapMemberContentReplaceMergeTags($user, $template_customized_html, $clicktostarttext, $upcoming_daystext, $productId,$userId, $displayoption , $userProduct_ids , $availabledata , $temp_type, $upcomingdata, $available_up_data,$orderoflinks,"","", $nocontent, $howmanyupcominglinks, $howmanylinks); 
						$template_customized_html_new .= "</div>";				
					}
				}
			}
		 }
		 
		
		if($temp_type == "singlecol" && $template_selected_name == "coursestyle"){ 
			 $scriptstyle  = "";
		}else{
			 $scriptstyle  = '<link href="'. plugin_dir_url(__FILE__). 'includes/css/bootstrap.min.css" rel="stylesheet">';
		 }
		 $tddata="<tr><td class='innertd' style='padding:5px 8px'>".$nocontent."</td></tr>";
		
		if(!wp_script_is('jquery')) {
			$scriptstyle .=' <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>	';	
		}
		
		$scriptstyle .='
		<script type="text/javascript"> 
		var $jq = jQuery.noConflict();
		
		
		function dap_member_show_loader(){
			$jq(".dap_member_loading_wrapper").show();
			$jq(".dap_member_frontend_shortcode ").hide();
		}

		function dap_member_hide_loader(){			
			$jq(".dap_member_loading_wrapper").hide();	
			$jq(".dap_member_frontend_shortcode ").show();
		}
		
		 $jq(function(){
				var $jq = jQuery.noConflict(); 
				$jq(".matchheight").matchHeight(); $jq(".matchheight1").matchHeight();
				$jq(".matchheightonecol").matchHeight({
					byRow: true,
					property: "height",
					target: null,
					remove: false
				});
 
				
			
			}); 
			$jq(window).load(function(){
				//dap_member_show_loader();
				var mycontent_temp_type = $jq(".mycontent_temp_type").val();					
				if(mycontent_temp_type == "multicol"){
					var mycontent_temp_wid = $jq(".dap_member_frontend_shortcode").width();				 
					var mycontent_wid_outer = $jq(".mycontent_wid_outer").val();
					var mycontent_box_wid = $jq(".mycontent_box_wid").val();
					var boxwid = mycontent_box_wid+"px"; 
					if(mycontent_temp_wid < mycontent_wid_outer){  
						 $jq("#dap_member_content_frontend_inn .dap_member_frontend_shortcode_inn").css("width",boxwid);  
					}
				}
				//dap_member_hide_loader();
			});
		
		$jq(document).ready(function(){
			
			var $jq = jQuery.noConflict(); 
			$jq.fn.dataTable.ext.errMode = "none";
			$jq(".report_Table, .report_table").on("error.dt", function ( e, settings, techNote, message ) {
			console.log( "An error has been reported by DataTables: ", message );
			}).DataTable({"bProcessing": true,
			"bSort": false, pageLength: '.$howmanylinksperpage.', 
			  fnDrawCallback : function() {
					if ($jq(this).find(".dataTables_empty").length == 1) {
					  
					   $jq(this).closest("#dap_customize_template_content_upcoming").hide();
					}
				},
		"oLanguage": {
				"sEmptyTable": "'.$nocontent.'"
			}});
			
			
			  $jq(".fancybox").each(function(){
					var popup_url = jQuery(this).attr("data-href");
					$jq(this).fancybox({
						 "autoScale" : false,
						 "href" : popup_url,
						 "closeClick"  : false,
						 "width":700,
						 "height":"auto",
						 "autoSize":false,
					});
				});
			
			   /*$jq(".dap_btn_container").click(function(){					 
					var href_url = jQuery(this).closest("a.linktopage").attr("href");
					if(href_url =="" || typeof href_url =="undefined" || typeof href_url ==undefined){
					}else{
						window.open(href_url, "_blank");
					}
					 
				});*/
		  				
			   $jq(".dap_member_frontend_shortcode  table tr.frontend_visibility td").each(function(){
					var row_data= $jq(this).text();	
					if(row_data ==""){
						$jq(this).text("'.$nocontent.'");	
						$jq(this).css("padding", "5px 8px");	
					}
			  });				 
			  $jq(".dap_member_frontend_shortcode  table tr.frontend_visibility td tbody").each(function(){
					var row_data= $jq(this).text();	
					if(row_data ==""){
					 
						 $jq(this).html("'.$tddata.'");		
					}
			  });				 
			
			$jq(".dap_member_loading_wrapper").hide();	
			$jq("#dap_member_content_frontend_shortcode_'.$random.'").show();
			 
		});
		 </script>'; 
		 
		  $scriptstyle .= ' 	 <link href="'.$csspath.'" rel="stylesheet">';
		  
		 // Added for where jquery is already included
		 if(wp_script_is('jquery')) {
			

			    //THie check is only for Hello Elementor theme
				$theme = wp_get_theme(); // gets the current theme		 
				if ( 'Hello Elementor' == $theme->name || 'Hello Elementor' == $theme->parent_theme ) {
					$scriptstyle .= '<link href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&display=swap" rel="stylesheet">	    
				   <script src="'. plugin_dir_url(__FILE__). 'includes/js/jquery.matchHeight-min.js"></script>	   
					<script src="'. plugin_dir_url(__FILE__). 'includes/js/jquery.fancybox.js"></script>
					<script src="'. plugin_dir_url(__FILE__). 'includes/js/jquery.dataTables.min.js"></script>	
					<link href="'. plugin_dir_url(__FILE__). 'includes/css/jquery.fancybox.css" rel="stylesheet">	
					<link href="'. plugin_dir_url(__FILE__). 'includes/css/dap_member_frontend_common.css" rel="stylesheet">	
					<link href="'.$csspath.'" rel="stylesheet">
					<link href="'. plugin_dir_url(__FILE__). 'includes/css/dap_mycontent_fe.css" rel="stylesheet"> ';
				}else{
					
					 // check for plugin using plugin name
					if(in_array('elementor/elementor.php', apply_filters('active_plugins', get_option('active_plugins')))){ 
						//plugin is activated
						 $scriptstyle .= '<link href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&display=swap" rel="stylesheet">	    
					   <script src="'. plugin_dir_url(__FILE__). 'includes/js/jquery.matchHeight-min.js"></script>	   
						<script src="'. plugin_dir_url(__FILE__). 'includes/js/jquery.fancybox.js"></script>
						<script src="'. plugin_dir_url(__FILE__). 'includes/js/jquery.dataTables.min.js"></script>	
						<link href="'. plugin_dir_url(__FILE__). 'includes/css/jquery.fancybox.css" rel="stylesheet">	
						<link href="'. plugin_dir_url(__FILE__). 'includes/css/dap_member_frontend_common.css" rel="stylesheet">	
						<link href="'.$csspath.'" rel="stylesheet">
						<link href="'. plugin_dir_url(__FILE__). 'includes/css/dap_mycontent_fe.css" rel="stylesheet"> '; 
					}else{
					
						//include css and js
						//add_action( 'wp_footer', 'dap_mycontent_scripts' );
						if($includeCSSByEnqueue){
							wp_enqueue_style( 'dap_fancybox1', dap_member_path.'includes/css/jquery.fancybox.css?'.round(10,1000));  
							wp_enqueue_style( 'dap_member_frontend_common', dap_member_path.'includes/css/dap_member_frontend_common.css?'.round(10,1000));  
							wp_enqueue_style( 'dap_mycontent_fe', dap_member_path.'includes/css/dap_mycontent_fe.css?'.round(10,1000) );
						}else{
							$scriptstyle .= '<link href="'. plugin_dir_url(__FILE__). 'includes/css/jquery.fancybox.css" rel="stylesheet">	
						<link href="'. plugin_dir_url(__FILE__). 'includes/css/dap_member_frontend_common.css" rel="stylesheet">	
						<link href="'.$csspath.'" rel="stylesheet">
						<link href="'. plugin_dir_url(__FILE__). 'includes/css/dap_mycontent_fe.css" rel="stylesheet"> '; 
						}

						if($includeJSByEnqueue){
							wp_enqueue_script(jQuery);
							wp_enqueue_script('jquery.min',  '//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js' , array('jquery'));
						    wp_enqueue_script('jquery.matchHeight-min1', dap_member_path. 'includes/js/jquery.matchHeight-min.js?'.round(10,1000), array('jquery'));
						    wp_enqueue_script('jquery.fancybox-latest1', dap_member_path. 'includes/js/jquery.fancybox.js?'.round(10,1000), array('jquery'));  
						    wp_enqueue_script('jquery.dataTables.min1', dap_member_path. 'includes/js/jquery.dataTables.min.js?'.round(10,1000), array('jquery')); 
						}else{
							$scriptstyle .= '<script src="'. plugin_dir_url(__FILE__). 'includes/js/jquery.matchHeight-min.js"></script>	   
							<script src="'. plugin_dir_url(__FILE__). 'includes/js/jquery.fancybox.js"></script>
							<script src="'. plugin_dir_url(__FILE__). 'includes/js/jquery.dataTables.min.js"></script>';	
						}
					}
				}
		 }else{			 
		 
			$scriptstyle .= '<link href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&display=swap" rel="stylesheet">	    
			   <script src="'. plugin_dir_url(__FILE__). 'includes/js/jquery.matchHeight-min.js"></script>	   
				<script src="'. plugin_dir_url(__FILE__). 'includes/js/jquery.fancybox.js"></script>
				<script src="'. plugin_dir_url(__FILE__). 'includes/js/jquery.dataTables.min.js"></script>	
				<link href="'. plugin_dir_url(__FILE__). 'includes/css/jquery.fancybox.css" rel="stylesheet">	
				<link href="'. plugin_dir_url(__FILE__). 'includes/css/dap_member_frontend_common.css" rel="stylesheet">	
				<link href="'.$csspath.'" rel="stylesheet">
				<link href="'. plugin_dir_url(__FILE__). 'includes/css/dap_mycontent_fe.css" rel="stylesheet"> ';
		}
		
		$hidden_field= '<input type="hidden" class="mycontent_wid_outer" value="'.$dm_wid_outer.'"/><input type="hidden" class="mycontent_temp_type" value="'.$temp_type.'"/><input type="hidden" class="mycontent_box_wid" value="'.$box_wid.'"/>';		 
		
		if($temp_type == "multicol"){ 
			//mutlicol template
			$html   = "<div id='dap_member_content_frontend_shortcode_".$random."' class='dap_member_frontend_shortcode live-links-outer dap_member_content_frontend_shortcode_".$mp_obj->getId()."'
			  style='width:".$dm_wid_outer."px; float:".$dm_temp_align."; margin:auto;display:none;'>
			<div class='dap_member_frontend_shortcode_inn col-sm-12' id='dap_member_content_frontend_inn'>".$productscounttext.			
			$template_customized_html_new.$hidden_field."</div></div>";
	 
		}else{
			//onecol template				
			if($template_selected_name == "postmetadata"){ 
				$html   = "<div id='dap_member_content_frontend_shortcode_".$random."' style= 'display:none;' class='dap_member_frontend_shortcode dap_member_content_frontend_shortcode_".$mp_obj->getId()."'><div class='dap_member_fe_inn col-sm-12' id='dap_member_content_fe_inn'>".$productscounttext.$template_customized_html_new.$hidden_field."</div></div>";
			}else{	
				$html   = "<div id='dap_member_content_frontend_shortcode_".$random."' style= 'display:none;' class='dap_member_frontend_shortcode dap_member_content_frontend_shortcode_".$mp_obj->getId()."'>".$productscounttext.$template_customized_html_new.$hidden_field."</div>";
			}
		}	 
	 
	 
	   $loader = DapMemberShowLoaderFe();
	   return $loader.$scriptstyle.$html.$img_data ;	
		
	}
	
	
}
 
 
/*
* Replace merge tags with products info
*/ 
function DapMemberContentReplaceMergeTags($user, $html = '', $clicktostarttext, $upcoming_text, $productId, $userId, $displayoption ,$userProduct_ids,$availabledata , $temp_type, $upcomingdata, $available_up_data,$orderoflinks, $postmeta='', $image_url='', $nocontent, $howmanyupcominglinks, $howmanylinks){
	 
	 
	 //load products
	$product = Dap_Product::loadProduct($productId);
	$product_id = $product->getId();
	$product_name = $product->getName();
	$product_desc = $product->getDescription();
	$prod_image = $product->getProduct_image_url();
	$sss = $product->getSelf_service_allowed();
	$sales_page_url = $product->getsales_page_url();   
	$logged_in_url =  $product->getlogged_in_url(); 
	$post_cancel_access = Dap_Config::get("POST_CANCEL_ACCESS");   
	$prod_image_link = "";
	$availablecontent ="";
	$upcomingcontent ="";
	$orderlinks =""; 
	$orderBy =""; 
	$numberoflinks ="10";
	$nocontentnew ="No Content Available";
	 $linktopopup =  "#";           
	 if($howmanyupcominglinks < 9999 ){
		$howmanyupcominglinks = $howmanyupcominglinks +1;
	}  
	/*if($orderoflinks == "NEWESTFIRST"){
		$orderlinks ="asc";
	}else{
		$orderlinks ="desc";
	}*/
	$orderlinks ="desc";
	if(defined("ORDER_OF_LINKS") && ORDER_OF_LINKS=="Y") {
		$orderlinks ="asc";
	}
	$mycontent_read_more =  dapMemberGetMessageByKeyAndAction('mycontent','mycontent_read_more');
	$mycontent_read_more_length =  dapMemberGetMessageByKeyAndAction('mycontent','mycontent_read_more_length');

	if($mycontent_read_more ==""){
		$mycontent_read_more = "Read More";
	}else{
		$mycontent_read_more = stripslashes($mycontent_read_more);
	}
	if($mycontent_read_more_length ==""){
		$mycontent_read_more_length = "130";
	}
	 
	
	//load userproducts
    $userProduct = Dap_UsersProducts::load($userId,  $productId);
     
    if(isset($userProduct)) {	 
		$product_acd = $userProduct->getAccess_start_date();
		$product_aed = $userProduct->getAccess_end_date() ;
		
		//Code for available/upcoming content 		
		
		if ($product->getSelf_service_allowed() == "N") { 
			// check if product type is course or not
			if ($product->getProductType() == "y" && $product->getProductStructure() == "module_lesson") {	
					$moduledata = DAP_CourseModule::loadByCourseId($product_id) ;	
					  $course_progress = $product->getCourseProgress();	
					  
					 								
					if(isset($moduledata)) {
						
						
						$unit_id_list = array();		
						// module loop					
						foreach($moduledata as $mod){				  						  
							 $lessonurls  =  Dap_Product::displayFileResourcesWithModuleIdCourseId($product_id, $mod->getId());					 		
							 if(isset($lessonurls)) {							 
								 foreach($lessonurls as $lessonurl){
									$unit_id_list[]  = $lessonurl['id'];							 					 
								 }							  
							 }									 
						 }			 				
					 
					 $lessondatas = DAP_UserCourseProgress::lessonDetailsByCourseIduserId($product_id , $userId );
					  
					 $key_of_last_module = 1;
					 if(count($lessondatas)){
						$key_of_last_module = array_search (end($lessondatas), $unit_id_list);
						$key_of_last_module = $key_of_last_module+1;
						
					 } 
					$availablecontent = "<div class='module_lesson_table_outer'>";
					$upcomingcontent = "<div class='module_lesson_table_outer'>";
						// module loop		
						$i = 0;			
						$upcomingcontent_data_empty_count = 0;	
						$upcomingcontent_data_empty_count1 = 0;	
						foreach($moduledata as $mod){
							 $mod_id = $mod->getId();
							 $mod_name = $mod->getModuleName();
							 $i++;
							if($i == $key_of_last_module){
								
								$add_lessclass = true;
							}else{
								$add_lessclass = false;
							}
													
							if( $postmeta =="postmeta"){								
								
								$availablecontent .= '<table class="dap_product_links_list module_lesson postmetatable report_table table course_structure" id="reportTable'.$product_id.'_mo'.$mod_id.'"> <thead><th>'.$mod_name .'</th></thead><tbody>';
								$availablecontent .=  $userProduct->getActiveResourcesNewContentForCourse("N", $orderlinks,$howmanylinks , "HTML", $nocontentnew, $clicktostarttext, $numberoflinks,$availabledata, $mod_id, $mod_name, $course_progress,$add_lessclass, $postmeta,$image_url, $mycontent_read_more, $mycontent_read_more_length);
								$availablecontent .= "</tbody></table> ";
								
								$upcomingcontent_data =   $userProduct->getFutureResourcesNewForCourse("N",  "asc",$howmanyupcominglinks, $makeLinksClickable="Y", "HTML", $nocontentnew, $numberoflinks, $upcoming_text, $upcomingdata, $mod_id, $postmeta, $image_url);					
								if($upcomingcontent_data == ''){
									$upcomingcontent_data_empty_count = $upcomingcontent_data_empty_count +1; 									 
								}
								
								$upcomingcontent .= '<table class="dap_product_links_list module_lesson postmetatable report_table table course_structure '.$table_empty_class.' " id="reportTableUpcoming'.$product_id.'_mo'.$mod_id.'"> <thead><th>'.$mod_name .'</th></thead><tbody>';
								$upcomingcontent .= $upcomingcontent_data;
								$upcomingcontent .= "</tbody></table> ";
								
							}else{
								$availablecontent .= '<table class="dap_product_links_list module_lesson report_table table course_structure" id="reportTable'.$product_id.'_mo'.$mod_id.'"> <thead><th>'.$mod_name .'</th></thead><tbody>';
								$availablecontent .=  $userProduct->getActiveResourcesNewContentForCourse("N", $orderlinks,$howmanylinks , "HTML", $nocontentnew, $clicktostarttext, $numberoflinks,$availabledata, $mod_id, $mod_name, $course_progress,$add_lessclass, $postmeta,$image_url, "", "");
								$availablecontent .= "</tbody></table> ";
								
								$upcomingcontent_data =  $userProduct->getFutureResourcesNewForCourse("N",  "asc",$howmanyupcominglinks, $makeLinksClickable="Y", "HTML", $nocontentnew, $numberoflinks, $upcoming_text, $upcomingdata, $module_id, $postmeta, $image_url);				
								if($upcomingcontent_data == ''){
									$upcomingcontent_data_empty_count1 = $upcomingcontent_data_empty_count1 +1; 									 
								}
								
								$upcomingcontent .= '<table class="dap_product_links_list module_lesson report_table table course_structure" id="reportTableUpcoming'.$product_id.'_mo'.$mod_id.'"> <thead><th>'.$mod_name .'</th></thead><tbody>';
								$upcomingcontent .=   $userProduct->getFutureResourcesNewForCourse("N", "asc", $howmanyupcominglinks, $makeLinksClickable="Y", "HTML", $nocontentnew, $numberoflinks, $upcoming_text, $upcomingdata, $module_id, $postmeta, $image_url);
								$upcomingcontent .= "</tbody></table> ";
							}
						 }// close foreach
						 if( $postmeta =="postmeta" && (count($moduledata) == $upcomingcontent_data_empty_count)){
							 $upcomingcontent = '<table class="dap_product_links_list module_lesson postmetatable  table course_structure table_empty " > <thead style="display:none !important"><tr><th></th></tr></thead><tbody><tr><td class="innertd" style=" padding: 0 20px !important;">'.$nocontent.'</td></tr></tbody></table>';
						 }else  if( $postmeta =="" && (count($moduledata) == $upcomingcontent_data_empty_count1)){
							 $upcomingcontent = '<table class="dap_product_links_list module_lesson report_table table course_structure table_empty " > <thead style="display:none !important"><tr><th></th></tr></thead><tbody><tr><td class="innertd" >'.$nocontent.'</td></tr></tbody></table>';
						 }
						 
						 
						$upcomingcontent .= "</div> ";	 	
						$availablecontent .= "</div> ";	 	
					}
					//$upcomingcontent =   $userProduct->getFutureResourcesNew("N", $orderlinks,"10000", $makeLinksClickable="Y", "HTML", $nocontentnew, $numberoflinks, $upcoming_text, $upcomingdata);		
				 
				
			} else{
				 
				$availablecontent =  $userProduct->getActiveResourcesNewContent("N", $orderlinks,$howmanylinks , "HTML", $nocontentnew, $clicktostarttext, $numberoflinks,$availabledata, $postmeta, $image_url, $mycontent_read_more, $mycontent_read_more_length);
				$upcomingcontent =   $userProduct->getFutureResourcesNew("N",  "asc",$howmanyupcominglinks, $makeLinksClickable="Y", "HTML", $nocontentnew, $numberoflinks, $upcoming_text, $upcomingdata, $postmeta, $image_url);
			}
			
		}
		else {				 
			$availablecontent =   $userProduct->getActiveResourcesNewContent("N", $orderlinks,$howmanylinks , "HTML", $nocontentnew, $clicktostarttext, $numberoflinks,$availabledata, $postmeta, $image_url, $mycontent_read_more, $mycontent_read_more_length);
			$upcomingcontent =   $userProduct->getFutureResourcesNew("N",  "asc",$howmanyupcominglinks, $makeLinksClickable="Y", "HTML", $nocontentnew, $numberoflinks, $upcoming_text, 
			$upcomingdata, $postmeta, $image_url);
		} 
		
			 
	}	 


	
	if( !Dap_Session::isLoggedIn() || !isset($user) ) {
        
            if($sales_page_url == ""){
                  $page_link =  "#";               
                    
            }else{  
                  $page_link = $sales_page_url;                  
                    
            }       
    }else{
            if(in_array($product_id, $userProduct_ids)){
                
                if($logged_in_url == ""){  
                      
                        if($displayoption == "redirect"){ 
                           $page_link =  "#";              
                        }elseif($displayoption == "popup"){ 
                            $page_link =  "#"; 
                              $linktopopup =  "#maindiv".$product_id;                   
                        }else{
							$page_link =  "#";  
							     
                        }                       
                         
                }else{      
                     
                    if($displayoption == "redirect"){                        
                            $page_link =  $logged_in_url; 
                                 
                        }elseif($displayoption == "popup"){	 
							 $page_link =  "#"; 
							   $linktopopup =  "#maindiv".$product_id;                       
                        }else{             
                           $page_link =  "#";  
                                  
                        }
                }
            
            }else{
                    if($sales_page_url == ""){                        
                        if($displayoption == "redirect"){                            
                          $page_link =  "#"; 
                            
                        }elseif($displayoption == "popup"){ 
                           $page_link =  "#";                               
                                              
                        }else{                            
                          $page_link =  "#";                         
                        }                           
                    }else{                        
                        if($displayoption == "redirect"){                            
                              $page_link = $sales_page_url;  
                             
                        }elseif($displayoption == "popup"){                            
                               $page_link = $sales_page_url;  
								 
                        }else{                            
                             $page_link = $sales_page_url;  
                            
                        }
                        
                    }                   
            }
       }
         
    $productpage = $page_link;   
	if($sales_page_url == ""){ 
		$sales_page_url = "#";
	}
	if($prod_image ==""){
		$prod_image =   dap_member_path."includes/images/no-image.jpg"; 
	}
	
	
	//echo $available_up_data;	 
	if($temp_type == "multicol"){ 
		$availabledata_html ='<div class="multicol_div" id="maindiv'.$productId.'" style="display:none">'.$available_up_data .'</div>';
	}
	$html = $html.$availabledata_html;
	
	//echo '<img src="' . $prod_image . '"  />';
	//$prod_image1 = getImageXY( $prod_image, $imgDimsMax=140 );
	/*$image = explode("||", $prod_image1);
	$prod_image1 =	$image[0];
	$imgWidth =	$image[1];
	$imgHeight = $image[2];
	$top =	$image[3];
	$left =	$image[4];
	
	if($imgWidth ==""){
		$imgWidth ="300";
	}
	
	if($imgHeight ==""){
		$imgHeight ="300";
	}
	*/
	//$html = str_replace( '%%HEIGHT%%',$imgHeight, $html); 
	//$html = str_replace( '%%WIDTH%%',$imgWidth, $html); 
	//$html = str_replace( '%%FRONTPROIMG%%','position:relative;display:inline;top:'.$top.'px;left:'.$left.'px;', $html); 
	$html = str_replace( '%%FRONTPROIMG%%','', $html); 
	 
	$html = str_replace( '%%PRODUCT_NAME%%',$product_name, $html);	
	$html = str_replace( 'Product Name',$product_name, $html);	
	$html = str_replace( '%%ASD%%',$product_acd, $html); 
	$html = str_replace( '%%AED%%',$product_aed, $html); 
	$html = str_replace( '%%PRODUCT_DESC%%',$product_desc, $html); 
	$html = str_replace( '%%PRODUCT_IMAGE%%',$prod_image, $html); 
	$html = str_replace( '%%PRODUCTIMAGEURLINKEDTO%%',"#", $html); 
	$html = str_replace( '%%INDIVIDUALITEMS%%',$availablecontent, $html);   
	$html = str_replace( '%%INDIVIDUALITEMSAVAIBLE%%',$availablecontent, $html); 
	$html = str_replace( '%%INDIVIDUALITEMSUPCOMING%%',$upcomingcontent, $html); 
	$html = str_replace( '%%productpage%%',$productpage, $html);
	$html = str_replace( '%%PRODUCTPAGE%%',$productpage, $html);
	$html = str_replace( '%%PRODUCTIMAGEURLINKEDTO%%',$sales_page_url, $html);
	$html = str_replace( '%%SALESURL%%',$sales_page_url, $html);
	$html = str_replace( '%%LINKTOPOPUP%%',$linktopopup, $html);
	$html = str_replace( '%%PRODUCTID%%',$productId, $html);
	//$html = str_replace( '%%INDIVIDUALITEMS%%',$prod_image, $html); 
	return $html;
}    
 
 
function getImageXY( $image, $imgDimsMax=300 ) {
    $top = 0;
    $left = 0;
    $aspectRatio= 1;    // deafult aspect ratio...keep the image as is.

    // set the default dimensions.
    $imgWidth   = $imgDimsMax;
    $imgHeight  = $imgDimsMax;

    //list( $width, $height, $type, $attr ) = getimagesize( $image );

    if( $width == $height ) {
        // if the image is less than ( $imgDimsMax x $imgDimsMax ), use it as is..
        if( $width < $imgDimsMax ) {
            $imgWidth   = $width;
            $imgHeight  = $height;
            $top = $imgDimsMax - $imgWidth;
            $left = $imgDimsMax - $imgWidth;
        }
    } else {
        if( $width > $height ) {
            // set $imgWidth to $imgDimsMax and resize $imgHeight proportionately
            $aspectRatio    = $imgWidth / $width;
            $imgHeight      = floor ( $height * $aspectRatio );
            $top = ( $imgDimsMax - $imgHeight ) / 2;
        } else if( $width < $height ) {
            // set $imgHeight to $imgDimsMax and resize $imgWidth proportionately
            $aspectRatio    = $imgHeight / $height;
            $imgWidth       = floor ( $width * $aspectRatio );
            $left = ( $imgDimsMax - $imgWidth ) / 2;
        }
    }
	return $image."||".$imgWidth."||".$imgHeight."||".$top."||".$left;
    // return '<img src="' . $image . '" width="' . $imgWidth . '" height="' . $imgHeight . '" style="position:relative;display:inline;top:'.$top.'px;left:'.$left.'px;" />';
}


// display products , sort for logged in and for not loggedin users
  
function sortDisplayProducts($user, $productList, $sorttype, $showunavailableproducts, $productid,$hideproductid ){
	   
	if( !Dap_Session::isLoggedIn() || !isset($user) ) { 
            if($sorttype == "name") {
                foreach($productList as $prod){
                    $product = Dap_Product::loadProduct($prod->getId());
                        $product_sort[$product->name] = $prod;  
                }   
                ksort($product_sort);
                $productList = $product_sort;
            }else{
                foreach($productList as $prod){
                    $product = Dap_Product::loadProduct($prod->getId());
                        $product_sort[$product->id] = $prod;
                    }   
                ksort($product_sort);
                $productList = $product_sort;
            }
    }else{
		 // if user is loggedin  , get the user products		 
		$userProducts = Dap_UsersProducts::loadProducts($user->getId());
		$accessuserProducts = Dap_UsersProducts::loadProducts($user->getId());
		foreach ($accessuserProducts as $userProduct1) {
			$userProduct_ids[] =  $userProduct1->getProduct_id();
		}
		foreach ($accessuserProducts as $userProduct_date) {
			$userProduct_alldate[$userProduct_date->getProduct_id()] =  array(
			'access_start_date'=>$userProduct_date->getAccess_start_date(),
			'access_end_date'=>$userProduct_date->getAccess_end_date());
		}
		
		//  if showunavailableproducts is set to no
        if($showunavailableproducts == "N"){
            if($sorttype == "name") {
                foreach($productList as $prod){
                    $product = Dap_Product::loadProduct($prod->getId());
                    if(in_array($prod->getId(), $userProduct_ids)){
                        $product_sort[$product->name] = $prod;  
                    }   
                }   
                ksort($product_sort);
                $productList = $product_sort;
                
            }elseif($sorttype == "id"){
                foreach($productList as $prod){
                    $product = Dap_Product::loadProduct($prod->getId());
                    if(in_array($prod->getId(), $userProduct_ids)){
                        $product_sort[$product->id] = $prod;
                    }   
                }   
                ksort($product_sort);
                $productList = $product_sort;
                            
            }else{  
                $access_prod = array();
                $date_array =array();
                $now = time(); 
                foreach($productList as $key=>$prod){
                    $product = Dap_Product::loadProduct($prod->getId());
                    $access_start_date_new = $userProduct_alldate[$prod->getId()]['access_start_date'];
                    $your_date = strtotime($access_start_date_new);
                    $datediff = $now - $your_date;
                    if(in_array($prod->getId(), $userProduct_ids)){
                        $date_array[$key] = floor($datediff/(60*60*24));
                    }
                    if(in_array($prod->getId(), $userProduct_ids)){
                        $access_prod[] = $prod;
                    }
                } 
                $date_array_new = asort($date_array);                   
                $array_prods= array();
                foreach($date_array as $key=>$value){
                    $array_prods[] =$productList[$key];
                }
                $productList = $array_prods;        
            
            }
            
        }else{
            
            // if user is loggedin and showunavailableproducts is set to yes
            if($sorttype == "name") {
                $access_prod = array();
                foreach($productList as $prod){
                    $product = Dap_Product::loadProduct($prod->getId());
                    if(in_array($prod->getId(), $userProduct_ids)){
                        $access_prod[$product->name] = $prod;
                    }
                }
                ksort($access_prod);    
                $non_access_prod = array();
                foreach($productList as $prod){
                    $product = Dap_Product::loadProduct($prod->getId());
                    if(!in_array($prod->getId(), $userProduct_ids)){
                        $non_access_prod[$product->name] = $prod;
                    }
                }   
                ksort($non_access_prod);
                $productList = array_merge($access_prod, $non_access_prod);             
                            
            }elseif($sorttype == "id"){
                $access_prod = array();
                foreach($productList as $prod){
                    $product = Dap_Product::loadProduct($prod->getId());
                    if(in_array($prod->getId(), $userProduct_ids)){
                        $access_prod[$product->id] = $prod;
                    }
                }
                ksort($access_prod);    
                $non_access_prod = array();
                foreach($productList as $prod){
                    $product = Dap_Product::loadProduct($prod->getId());
                    if(!in_array($prod->getId(), $userProduct_ids)){
                        $non_access_prod[$product->id] = $prod;
                    }
                }   
                ksort($non_access_prod);
                $productList = array_merge($access_prod, $non_access_prod);     
                
            }else{ //($sorttype == "purchasedate")
                $access_prod = array();
                $date_array =array();
                $now = time(); 
                
                foreach($productList as $key=>$prod){
                    $product = Dap_Product::loadProduct($prod->getId());
                    $access_start_date_new = $userProduct_alldate[$prod->getId()]['access_start_date'];
                    $your_date = strtotime($access_start_date_new);
                    $datediff = $now - $your_date;
                    $date_array[$key] = floor($datediff/(60*60*24));
                    
                    if(in_array($prod->getId(), $userProduct_ids)){
                        $access_prod[] = $prod;
                    }
                } 
                $date_array_new = asort($date_array);                   
                $array_prods= array();
                foreach($date_array as $key=>$value){
                    $array_prods[] =$productList[$key];
                }
                $productList = $array_prods;
                
            }

        }
    }
    
	

    return  $productList;
}    
// if template type is contentlinks
  
function DapMemberContentlinksTemplateMergeTags($template_customized_html='' , $user , $productId, $orderlinks, $numberoflinks , $nocontentnew){
		$prod_list_html ="";  
		$clicktostarttext="";
		$userProduct = Dap_UsersProducts::load($user->getId(), $productId);

		if( isset($userProduct) && ($userProduct != null) ) {
			$product = Dap_Product::loadProduct($productId);
			 
			$product_name = $product->getName();
			$product_desc = $product->getDescription();
			$product_acd = $userProduct->getAccess_start_date();
			$product_aed = $userProduct->getAccess_end_date() ;
			$template_customized_html = str_replace( '%%PRODUCT_NAME%%',$product_name, $template_customized_html); 
			$template_customized_html = str_replace( '%%ASD%%',$product_acd, $template_customized_html); 
			$template_customized_html = str_replace( '%%AED%%',$product_aed, $template_customized_html); 
			$template_customized_html = str_replace( '%%PRODUCT_DESC%%',$product_desc, $template_customized_html); 			
			return $template_customized_html;
		}else{
			return "";
		}
	
} 
   
function DapMemberContentlinksTemplate($template_customized_html='' , $user , $productId, $orderlinks, $numberoflinks , $nocontentnew,$contentdata){
		$prod_list_html ="";  
		$clicktostarttext="";
		$userProduct = Dap_UsersProducts::load($user->getId(), $productId);

		if( isset($userProduct) && ($userProduct != null) ) {			 
			$prod_list_html  =  $userProduct->getActiveResourcesNewContent("N", $orderlinks,"10000", "HTML", $nocontentnew, "", $numberoflinks,$contentdata);
		}
	return $prod_list_html;
}    

   

function dap_mycontent_scripts(){	 
	wp_enqueue_script(jQuery);
	wp_enqueue_script('jquery.min',  '//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js' , array('jquery'));
    wp_enqueue_script('jquery.matchHeight-min1', dap_member_path. 'includes/js/jquery.matchHeight-min.js?'.round(10,1000), array('jquery'));
    wp_enqueue_script('jquery.fancybox-latest1', dap_member_path. 'includes/js/jquery.fancybox.js?'.round(10,1000), array('jquery'));  
    wp_enqueue_script('jquery.dataTables.min1', dap_member_path. 'includes/js/jquery.dataTables.min.js?'.round(10,1000), array('jquery'));   
	wp_enqueue_style( 'dap_fancybox1', dap_member_path.'includes/css/jquery.fancybox.css?'.round(10,1000));  
	wp_enqueue_style( 'dap_member_frontend_common', dap_member_path.'includes/css/dap_member_frontend_common.css?'.round(10,1000));  
	wp_enqueue_style( 'dap_mycontent_fe', dap_member_path.'includes/css/dap_mycontent_fe.css?'.round(10,1000) ); 
}

 function DapMemberShowLoaderFe(){
	$html = '
			<div class="dap_member_loading_wrapper" >
			<div id="dap_member_loadingoverlay"></div>
			<div id="dap_member_loader_icon">
				<div class="lds-css ng-scope"><div style="width:100%;height:100%" class="lds-dual-ring"><div></div></div></div>
			</div>
			</div>';
	return $html;
}

 
function DAPMemberContentPayPerPost($atts, $content = null) {
 
	extract(shortcode_atts(array(
	'id' => '',
	), $atts));
	
	$session = Dap_Session::getSession();
    $user = $session->getUser();
    
    $orderoflinks = "NEWESTFIRST";
	$sorttype = "purchasedate";
	$pleaselogintext ="Click here to log in";
	$clicktologintext ="Sorry, you must log in before you can view this content";
	$currentlyhaveaccesstext="You currently have access to %%USERPRODUCTSCOUNT%% product(s).";
	$nocontent = "No Content Available";
	$dateformat = "YYYY-MM-DD";
	$showproductcount = "Y";
	$howmanylinks = "9999";
	$howmanyupcominglinks = "5";
	$howmanylinksperpage = "10";
	$available_up_data ="";
	
	$orderoflinks =  dapMemberGetMessageByKeyAndAction('mycontent','orderoflinks'); 
	$sorttype =   dapMemberGetMessageByKeyAndAction('mycontent','sorttype');
	$pleaselogintext =   dapMemberGetMessageByKeyAndAction('mycontent','pleaselogintext');
	$clicktologintext =   dapMemberGetMessageByKeyAndAction('mycontent','clicktologintext');
	$currentlyhaveaccesstext =   dapMemberGetMessageByKeyAndAction('mycontent','currentlyhaveaccesstext');
	$nocontent =   dapMemberGetMessageByKeyAndAction('mycontent','nocontent');
	$dateformat =   dapMemberGetMessageByKeyAndAction('mycontent','dateformat');
	$showproductcount =   dapMemberGetMessageByKeyAndAction('mycontent','showproductcount');
	$howmanylinks =   dapMemberGetMessageByKeyAndAction('mycontent','howmanylinks');
	$howmanyupcominglinks =   dapMemberGetMessageByKeyAndAction('mycontent','howmanyupcominglinks');
	$howmanylinksperpage =   dapMemberGetMessageByKeyAndAction('mycontent','howmanylinksperpage');
    
    if(!isset($howmanylinksperpage) || $howmanylinksperpage ==""){
		$howmanylinksperpage = "10";
	}     
    if(!isset($howmanylinks) || $howmanylinks ==""){
		$howmanylinks = "9999";
	}     
    if(!isset($howmanyupcominglinks) || $howmanyupcominglinks ==""){
		$howmanyupcominglinks = "5";
	}     
  
	$orderlinks ="desc";
	
	$style_attr =" <style> #notloggedin_outer  a {font-weight: 600;color: #333;font-size: 15px;} #notloggedin_outer .not_logged { color: #2239b9;font-weight: 600; text-decoration: underline; }</style>";
	  
	if( !Dap_Session::isLoggedIn() || !isset($user) ) {
        $errorHTML = mb_convert_encoding($pleaselogintext, "UTF-8", "auto") . " <a class='not_logged' href=\"" . Dap_Config::get("LOGIN_URL") . "\">". mb_convert_encoding($clicktologintext, "UTF-8", "auto") . "</a>";
        return "<div id='notloggedin_outer'>".$errorHTML.$style_attr."</div>";
    }
    $random = rand(10,100);
    
     //load data by id
	 $mp_obj = DAP_MemberPages::loadById($id);
	  
	  if($mp_obj){		
		$action_id = $mp_obj->getId();		
		$gettemp =  $mp_obj->getTemplate();
		$gettemp = explode("||",$gettemp);
		$template_selected_name =  $gettemp[0];
		$template =  $gettemp[1];
		$temp_type =  $gettemp[2];
		$template_html =  $mp_obj->getTemplateHtml();
		$template_html =  str_replace('contenteditable="true"','contenteditable="false"',$template_html);
		$template_html =  str_replace('%%IMAGESPATH%%','',$template_html); 		 
		$template_html = explode("|:|",$template_html);			
		$template_customized_html = $template_html[0];			
		$availabledata = $template_html[1];		
		
		$styling_options = $mp_obj->getStylingOptions();
		$styling_options = explode("|||",$styling_options);
		

		//customize template variable  
		if(isset($styling_options[0])){			
			$dm_content_temp = explode("||",$styling_options[0]);			
			$dm_wid =  $dm_content_temp[0];
			$prod_per_row =  $dm_content_temp[13];			
			$dm_wid_outer =  $dm_content_temp[14];			
			$dm_temp_align =  $dm_content_temp[15];			
			$box_wid =  $dm_content_temp[16];			
		}
		 
		$userId = $user->getId();
		$payperpostdata1 = DAP_UserPayPerPost::loadDataByUserId($userId, "new");
		$payperpostdata2 = DAP_UserPayPerPost::loadDataByUserId($userId, "expire");
		$payperpostdata = array_merge($payperpostdata1, $payperpostdata2); 
		// 	echo "<pre>"; print_r($payperpostdata);
		$prod_list_html = '<table class="report_Table table">
			<thead style="display:none">
				<tr><th></th></tr>
			</thead>
			<tbody>';
		$date = new DateTime();				 	
		$today_date = $date->format("Y-m-d");	 	 
		foreach($payperpostdata as $payperpost){
			$postid = $payperpost->getResourceId();		
			$post_title = get_the_title( $postid ); 	
			$post_url = $payperpost->getPostURL();
			$access_end = $payperpost->getAccessEnd();
			$classnew ="";		 
				
			if($postid != ""){	
				if($post_url == ""){	
					$post_url = get_permalink( $postid ); 
				}
				if($access_end >= $today_date){
				$classnew = "active_class";
				}else{
				$classnew = "expire_class";
				}
				$prod_list  ='<tr class="'.$classnew.'"> <td><a href="'.$post_url.'">'.$availabledata.'</a></td></tr>';				
				$prod_list_html .=  str_replace( 'Test Content A', $post_title, $prod_list);	
			} 			 	
		}
		
		 $prod_list_html .= ' 
			</tbody>	
		</table>';
			
		 
		$csspath = dap_member_path."includes/templates/mycontent/payperpost/inpage/template1.css?".rand(10,1000);		 	
		$scriptstyle = '<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
	 	<link href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&display=swap" rel="stylesheet">	 
	 	<link href="'. plugin_dir_url(__FILE__). 'includes/css/bootstrap.min.css" rel="stylesheet">
		<script src="'. plugin_dir_url(__FILE__). 'includes/js/jquery.dataTables.min.js"></script>
		<link href="'.$csspath.'" rel="stylesheet"><link href="'. plugin_dir_url(__FILE__). 'includes/css/dap_mycontent_fe.css" rel="stylesheet"> ';	
		$scriptstyle .='
		
		<script type="text/javascript"> 
		 
		var $jq = jQuery.noConflict(); 
		 		 
		$jq(document).ready(function(){		
			$jq.fn.dataTable.ext.errMode = "none";
			$jq(".report_Table , .report_table").on("error.dt", function ( e, settings, techNote, message ) {
			console.log( "An error has been reported by DataTables: ", message );
			}).DataTable( {"bProcessing": true,
			"bSort": false, pageLength: '.$howmanylinksperpage.', 
			  fnDrawCallback : function() {
					if ($jq(this).find(".dataTables_empty").length == 1) {					  
					   $jq(this).closest("#dap_customize_template_content_upcoming").hide();
					}
				},
		"oLanguage": {
				"sEmptyTable": "'.$nocontent.'"
			}});	 
			if($jq(".dap_product_links_list tbody tr").length < 1 ) {
				$jq(".dap_product_links_list tbody").addClass("dataTables_empty_outer");
				$jq(".dap_product_links_list tbody ").html("<tr><td>'.$nocontent.'</td></tr>");
			}		 	
		});
		</script>'; 
		
		
		
		$template_customized_html_new  =  str_replace( '%%PAYPERPOSTPURCHASEDLIST%%', $prod_list_html, $template_customized_html);	
		$html   = "<div id='dap_member_content_frontend_shortcode_".$random."' class='live-links-outer dap_member_frontend_shortcode ".$temp_type."_cls dap_member_content_frontend_shortcode_".$mp_obj->getId()."'> ".$template_customized_html_new." </div>";
		return $scriptstyle.$html ;			 	
	
	}
	  
    
}
