<?php

 function dap_mycontentshortcode($atts, $content=null){ 
  
	global $wpdb;
    extract(shortcode_atts(array(
        'showproductimage' => 'Y',
        'showproductname' => 'Y',
        'showaccessstartdate' => 'Y',
        'showaccessenddate' => 'Y',
        'showdescription' => 'Y',
        'showlinks' => 'Y',
        'orderoflinks' => 'NEWESTFIRST',
        'howmanylinks' => '10000',      
        'errmsgtemplate' => 'SHORT',
        'showunavailableproducts' => 'N',
        'sidebarorfullwidth' => 'sidebar',
        'productid' => 'ALL',
        'boxwidth' => '700',
        'imagewidth' => '250',
        'imageheight' => '300',
        'width_sidebar' => '250',
        'availablebutton' => '#16b123',
        'unavailablebutton' => '#545454',
        'paginationbutton' => '#545454',
        'sorttype' => 'purchasedate',
        'dateformat' => 'MM-DD-YYYY',
        'showproductcount' => 'Y',
        'showrenewalhtml' => 'Y',
        'hideproductid' => 'NONE',
        'mycontentheadertext' => 'My Content',
        'availcontentheadertext' => 'Available Content',
        'upcomingcontentheadertext' => 'Upcoming Content',
        'showavailablecontent' => 'Y',
        'showupcomingcontent' => 'N',
        'howmanyupcominglinks' => '10000',
        'comingsoonheadertext' => 'Coming Soon (In Days)',
        'clickheretext' => 'Click Here to Access',
        'clickheretextunavilable' => 'Click Here to Get Access',
        'showlinkscollapsed' => 'Y',
        'nocontenttext' => 'No Content Available Currently',
        'template' => 'template1',
        'selecttemplate' => 'template1',
        'displayoption' => 'showPopup',
        'yourproductstext' => 'Your Products',
        'singleproductid' => '',
        'displayradiobuttonoption' => '',
        'headfonts' => '',
        'datafonts' => '',
        'csprodbgcolor' => '#2784d8',
        'csstartbtnbgcolor' => '#18cba3',
        'cslinksactivehovercolor' => '#edfcf9',
        'csprodtextcolor' => '#ffffff',
        'csstarttextcolor' => '#ffffff',
        'cslinkscolor' => '#f1f1f1',
        'cslinkstextcolor' => '#333333',
        'nocontentnew' => 'No Content Available',
        'showproddescription' => 'N',
        'clicktostarttext' => 'Click to Start',
        'lessontext' => 'Lessons',
        'bordercol' => '#f1f1f1',
        'showborforcontent' => 'Y',
        'numberoflinks' => '10',
        'currentlyhaveaccesstext' => 'You currently have access to ',
        'userlinksproducttext' => 'product(s)',
        'accessstartdatetext' => 'Access Start Date:',
        'accessenddatetext' => 'Access End Date:',
        'productnametext' => 'Product Name',
        'productdesctext' => 'Product Description',
        'linkstext' => 'Links',
        'nolinksfoundtext' => 'Sorry, no content found. This could be because no content has been made available to you yet, or because your access to this product has expired.',
		'howmanylinksperpage' => '10',
 
    ), $atts)); 
    
 
    $lldocroot = defined('SITEROOT') ? SITEROOT : $_SERVER['DOCUMENT_ROOT'];

    $mycontentheadertext=urldecode($mycontentheadertext);
    $availcontentheadertext=urldecode($availcontentheadertext);
    $upcomingcontentheadertext=urldecode($upcomingcontentheadertext);
    $comingsoonheadertext=urldecode($comingsoonheadertext);
    $clickheretext=urldecode($clickheretext);
    $clickheretextunavilable=urldecode($clickheretextunavilable);
    $nocontenttext=urldecode($nocontenttext);
    
 
    if($currentlyhaveaccesstext == ""){	
		$currentlyhaveaccesstext = USER_LINKS_YOUCURRENTLYHAVEACCESSTO_TEXT;
	}else{
		$currentlyhaveaccesstext = $currentlyhaveaccesstext;
	}
		 
	if($userlinksproducttext == ""){	
		$userlinksproducttext = USER_LINKS_PRODUCTS_TEXT;
	}else{
		$userlinksproducttext = $userlinksproducttext;
	}
	
 
	if($accessstartdatetext == ""){	
		$accessstartdatetext = ACCESS_START_DATE_TEXT;
	}else{
		$accessstartdatetext = $accessstartdatetext;
	}
	 
	if($accessenddatetext == ""){	
		$accessenddatetext = ACCESS_END_DATE_TEXT;
	}else{
		$accessenddatetext = $accessenddatetext;
	}
		 
	if($productnametext == ""){	
		$productnametext = PRODUCT_NAME_TEXT;
	}else{
		$productnametext = $productnametext;
	}
	if($productdesctext == ""){	
		$productdesctext = PRODUCT_DESCRIPTION_TEXT;
	}else{
		$productdesctext = $productdesctext;
	}
	
	if($linkstext == ""){	
		$linkstext = USER_LINKS_LINKS_TEXT;
	}else{
		$linkstext = $linkstext;
	} 
	if($nolinksfoundtext == ""){	
		$nolinksfoundtext = USER_LINKS_NOLINKSFOUND_TEXT;
	}else{
		$nolinksfoundtext = $nolinksfoundtext;
	}
	 
	add_action( 'wp_footer', 'mydap_content_js' );
	$includejscss ="";
	$scriptstylesvar = '<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"  >
    <link href="'. plugin_dir_url(__FILE__). 'includes/css/dataTables.bootstrap.min.css" >
     <link href ="'. plugin_dir_url(__FILE__). 'includes/css/dap-mycontent-frontend.css?v=3">';  
    $session = Dap_Session::getSession();
    $user = $session->getUser();
    
    //logToFile("mycontentheadertext=".$mycontentheadertext);
    
    if( !Dap_Session::isLoggedIn() || !isset($user) ) {
        //logToFile("Not logged in, returning errmsgtemplate");
        $errorHTML = mb_convert_encoding(MSG_PLS_LOGIN, "UTF-8", "auto") . " <a href=\"" . Dap_Config::get("LOGIN_URL") . "\">". mb_convert_encoding(MSG_CLICK_HERE_TO_LOGIN, "UTF-8", "auto") . "</a>";
        return $errorHTML;
    }

    $userProducts = null;
    $productList = null;

    if( !Dap_Session::isLoggedIn() || !isset($user) ) {
        $errorHTML = mb_convert_encoding(MSG_PLS_LOGIN, "UTF-8", "auto") . " <a href=\"" . Dap_Config::get("LOGIN_URL") . "\">". mb_convert_encoding(MSG_CLICK_HERE_TO_LOGIN, "UTF-8", "auto") . "</a>";
        if($showunavailableproducts == "N"){
        }else{
            $productList = Dap_Product::loadProducts("","A");
        }
    }else{
        if($user){
            $userId = $user->getId();   
        }
        if( isset($user) ) {
            $userProducts = Dap_UsersProducts::loadProducts($user->getId());
            $productList = Dap_Product::loadProducts("","A");
        }
        $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());
        }
    }

    //$template="template1";
    $template=urldecode($selecttemplate);


    $headfonts = explode("||", $headfonts);
    $datafonts = explode("||", $datafonts);
    $length = 6;
    $uniguefonts_id = substr(str_shuffle(md5(time())),0,$length);

    /* If the template is template3 then show the  Products links only*/
    if( $template == "template3"){

        if($displayradiobuttonoption == "showbulletedlist"){
            $class_radiobutton ="showbulletedlist";
        }elseif($displayradiobuttonoption == "showstyledlist"){
            $class_radiobutton ="showstyledlist";
        }else{
            $class_radiobutton ="nostyle";
        }
 
            if( isset($userProducts) && ($userProducts != null) && ( sizeof($userProducts) > 0 ) ) {
               if($sorttype == "name") {
               
                  $prod_name = array();
                  foreach($productList as $prod){
                      $product = Dap_Product::loadProduct($prod->getId());
                      if(in_array($prod->getId(), $userProduct_ids)){
                          $prod_name[$product->name] = $prod;
                      }
                  }
                  ksort($prod_name);        
                  $product_list = $prod_name;     

                }elseif($sorttype == "id") {
                   $product_sort=array();  
                   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);
                $product_list = $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];
                    }
                    $product_list = $array_prods;  

                  }

                $output = '<div class="yourprod_container" id="cont_'.$uniguefonts_id.'">';
            
                $output .=  '<h3 class="yourprod_heading">'.$yourproductstext.'</h3>';
                $output .=  '<ul id="prod_container_in">';  
                foreach ($product_list as $userProduct) { 
                  $output .= '<li class="'.$class_radiobutton.'"><a href="'.$userProduct->getLogged_in_url().'">'. $userProduct->getName() . '</a></li>';
                }
                
                $output .= '<style>#cont_'.$uniguefonts_id.' li a, #cont_'.$uniguefonts_id.' a:visited, #cont_'.$uniguefonts_id.' a:visited{   color:'.$datafonts[2].' !important; font-size: '.$datafonts[0].'px !important; font-weight: '.$datafonts[3].'!important; font-family: '.$datafonts[1].'!important;}</style></ul></div>';

            }

            return $output.$scriptstylesvar;
        }
        
        
  /* If the template is template4 then show the  Products Details Based on ProductID*/
    if($template == "template4"){

         if($displayradiobuttonoption == "showbulletedlist"){
            $class_radiobutton1 ="showbulletedlist1";
        }elseif($displayradiobuttonoption == "showstyledlist"){
            $class_radiobutton1 ="showstyledlist1";
        }else{
            $class_radiobutton1 ="nostyle1";
        }
        if($orderoflinks == "NEWESTFIRST"){
			$orderlinks ="asc";
		}else{
			$orderlinks ="desc";
		}

        $productId = $singleproductid;
        $userProduct = Dap_UsersProducts::load($user->getId(), $productId);

        if( isset($userProduct) && ($userProduct != null) ) {
          $product = Dap_Product::loadProduct($productId);
          $output .=   ' <table id="dap_single_product_links_table" class="cont_'.$uniguefonts_id.'">';

          if(strtolower($showproductname)=="y") { 
          $output .=   ' <tr> 
                <td><strong>'.$productnametext.'</strong> ' . $product->getName() . '</span></td> 
              </tr> ';
          }

          if(strtolower($showdescription)=="y") { 
          $output .=   ' <tr> 
                <td><strong>'.$productdesctext.'</strong> ' . $product->getDescription() . '</span></td> 
              </tr> ';
          }

          if(strtolower($showaccessstartdate)=="y") { 
          $output .=   ' <tr> 
                <td><strong>'.$accessstartdatetext.'</strong> ' . $userProduct->getAccess_start_date() . '</td> 
              </tr> ';
          }

          if(strtolower($showaccessenddate)=="y") { 
          $output .=   ' <tr> 
                <td><strong>'.$accessenddatetext.'</strong> ' . $userProduct->getAccess_end_date() . '</td> 
              </tr>';
          }
          if(strtolower($showlinks) == "y") { 
          $output .=   '<tr  class="'.$class_radiobutton1.'"> 
                <td><strong>'.$linkstext.'</strong> ' . $userProduct->getActiveResourcesNew("N", $orderlinks,"10000", "HTML", $nolinksfoundtext, "" , "", $displayoption ) . '</td> 
              </tr> ';
          }


          $output .=   ' <style>.cont_'.$uniguefonts_id.' li a, .cont_'.$uniguefonts_id.' a:visited, .cont_'.$uniguefonts_id.' a:visited, .cont_'.$uniguefonts_id.' td{   color:'.$datafonts[2].' !important; font-size: '.$datafonts[0].'px !important; font-weight: '.$datafonts[3].'!important; font-family: '.$datafonts[1].'!important;}.cont_'.$uniguefonts_id.' td strong{   color:'.$headfonts[2].' !important; font-size: '.$headfonts[0].'px !important; font-weight: '.$headfonts[3].'!important; font-family: '.$headfonts[1].'!important;}</style></table><br/><br/>';
        }
        return $output.$scriptstylesvar;

    } 

	/* If the template is course style */
    if( $template == "template1"){  
 
            if($displayoption == "showCourseStyle"){
               if( isset($userProducts) && ($userProducts != null) && ( sizeof($userProducts) > 0 ) ) {
				   if($sorttype == "name") {
				   
					  $prod_name = array();
					  foreach($productList as $prod){
						  $product = Dap_Product::loadProduct($prod->getId());
						  if(in_array($prod->getId(), $userProduct_ids)){
							  $prod_name[$product->name] = $prod;
						  }
					  }
					  ksort($prod_name);        
					  $product_list = $prod_name;     

					}elseif($sorttype == "id") {
					   $product_sort=array();  
					   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);
					$product_list = $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];
						}
						$product_list = $array_prods;  

					  }
                  
					if($orderoflinks == "NEWESTFIRST"){
						//$orderlinks ="asc";
						$orderlinks ="desc";
					}else{
						//$orderlinks ="desc";
						$orderlinks ="asc";
					}
				    
					  $output = '<div class="yourprod_container" id="coursestyle_div" style="width:'.$boxwidth.'px;max-width:100%;style:display:none">';             
					
					  $output .=  '<ul id="prod_container_iner">'; 
					 
						foreach ($product_list as $userProduct) { 
							$userProduct1 = Dap_UsersProducts::load($user->getId(),  $userProduct->id);
							if($showproddescription == "Y"){
								$proddes = '<div class="prod_desc1"><p>'.$userProduct->description.'</p></div>';
							}else{
								$proddes = '';
							}
							if($lessontext != ""){
								$lessontextdata = '<h6>'.$lessontext.'</h6>';
							}else{
								$lessontextdata = '<h6 style="display:none">'.$lessontext.'</h6>';
							}
							if($showborforcontent == "Y"){
								$contentdata = '<div class="contentcontiner" style="border:1px solid '.$bordercol.'">'.$proddes.$lessontextdata. 
								$userProduct1->getActiveResourcesNew("N", $orderlinks,"10000", "HTML", $nocontentnew, $clicktostarttext, $numberoflinks, $displayoption) . '</div>';
							}else{
								$contentdata = '<div class="contentcontiner" style="border:0px solid '.$bordercol.'">'.$proddes.$lessontextdata.
								 $userProduct1->getActiveResourcesNew("N", $orderlinks,"10000", "HTML", $nocontentnew, $clicktostarttext, $numberoflinks, $displayoption) . '</div>';
							}
							
							
							
							
							$output .= '<li class=""> <h4 class=" ">'. $userProduct->getName() . '</h4>'.$contentdata.'</li>';
						}

						$output .=   '<style>#prod_container_iner li { list-style: none;}#prod_container_iner li h4{background:'.$csprodbgcolor.'!important;color:'.$csprodtextcolor.'!important}
						 #prod_container_iner .dap_product_links_list tr {background:'.$cslinkscolor.'!important;color:'.$cslinkstextcolor.'!important}
						  #prod_container_iner .dap_product_links_list tr label{color:'.$cslinkstextcolor.'!important}
						 #prod_container_iner .dap_product_links_list tr:hover, #prod_container_iner .dap_product_links_list tr:first-child {background:'.$cslinksactivehovercolor.'!important}
						  #prod_container_iner .list-group-item a{background:'.$csstartbtnbgcolor.'!important;color:'.$csstarttextcolor.'!important}
						 .check_icon i{color:'.$csstartbtnbgcolor.'!important}  </style></ul></div>'; 
        

			 }
		 $content  = ' <script type="text/javascript">

						var $jq = jQuery.noConflict(); 

						$jq(document).ready(function(){

							$jq(".report_table").DataTable({"bProcessing": true,
"bSort": false, pageLength: '.$numberoflinks.', "oLanguage": {
        "sEmptyTable": "'.$nocontentnew.'"
    }});
							});</script>';
			return $output.$content.$scriptstylesvar;
			}
        }
	/* If the template is course style ends*/

    $regulardrip_template_path=ABSPATH . "/wp-content/plugins/DAP-WP-LiveLinks/includes/mycontenttemplates/".$template;
    $regulardrip_template_path1=ABSPATH . "/wp-content/plugins/DAP-WP-LiveLinks/includes/mycontenttemplates/";

    //REGULAR DRIP HEADER TEMPLATE CONTENT
    $regularDripHeaderTemplateName="/DAPMyContentHeaderTemplate.html";
    $customRegularDripHeaderTemplateName="/customDAPMyContentHeaderTemplate.html";     
      if($showproductcount == 'Y') {
        //$content = $currentlyhaveaccesstext . count($userProducts). $userlinksproducttext . "<br/><br/>";
        if($template == "template1"){
			   $regulardrip_head_temp_content='<div class="product_div"><p style="padding: 20px 20px 10px 0; float: left; width: 100%;font-size: 18px; color: #000; line-height: normal; margin: 5px 0px 25px 0px;">'.$currentlyhaveaccesstext . count($userProducts). $userlinksproducttext . '</p><br/><br/>'.getDripTemplateContent($regulardrip_template_path, $regularDripHeaderTemplateName, $customRegularDripHeaderTemplateName).'</div>';
         }else{
            $regulardrip_head_temp_content='<div class="product_div"><p style="padding: 20px 20px 10px 0; float: left; width: 100%;font-size: 18px; color: #000; line-height: normal; margin: 5px 0px 25px 10px;">'.$currentlyhaveaccesstext . count($userProducts). $userlinksproducttext . '</p><br/><br/>'.getDripTemplateContent($regulardrip_template_path, $regularDripHeaderTemplateName, $customRegularDripHeaderTemplateName).'</div>';
        }
    }  else{
        $regulardrip_head_temp_content='<div class="product_div">'.getDripTemplateContent($regulardrip_template_path, $regularDripHeaderTemplateName, $customRegularDripHeaderTemplateName).'</div>';
    }   
    
    
    $cssurl= plugin_dir_url(__FILE__). "includes/mycontenttemplates/".$template."/css"; 
    $fancyboxurl= plugin_dir_url(__FILE__). "includes/css/jquery.fancybox.css"; 
    $datatableurl= plugin_dir_url(__FILE__). "includes/css/dataTables.bootstrap.min.css";   
    //$sidebarcsspath= DAPMYCONTENT_URL."/includes/mycontenttemplates/sidebar/css/mycontentsidebar.css";    
    $csspath= plugin_dir_url(__FILE__). "includes/mycontenttemplates/".$template."/css";       

    if( file_exists($csspath . "/custommycontent.css") ) 
        $cssurl = $cssurl . "/custommycontent.css";
    else 
        $cssurl = $cssurl . "/mycontent.css";
    
      $regulardrip_head_temp_content = str_replace( '[CSSURL]',$cssurl.$includejscss, $regulardrip_head_temp_content);    
    
    //REGULAR DRIP  INDIVIDUAL PRODUCT TEMPLATE
    //$regularProductTemplateName="/DAPMyContentIndividualProductTemplate.html";
    $regularProductTemplateName="/DAPMyContentIndividualProductTemplate.html";
    
    
    
    if( !Dap_Session::isLoggedIn() || !isset($user) ) {
        $errorHTML = mb_convert_encoding(MSG_PLS_LOGIN, "UTF-8", "auto") . " <a href=\"" . Dap_Config::get("LOGIN_URL") . "\">". mb_convert_encoding(MSG_CLICK_HERE_TO_LOGIN, "UTF-8", "auto") . "</a>";
        
        if($showunavailableproducts == "N"){
            return $errorHTML;
        }else{
            echo $errorHTML;
            $productList = Dap_Product::loadProducts("","A");
        }
    }
    if( !Dap_Session::isLoggedIn() || !isset($user) ) {
        $regularProductTemplateName="/DAPMyContentIndividualProductTemplate.html";
        $regularProductNoImageTemplateName="/DAPMyContentIndividualProductNoImageTemplate.html";
        $customRegularProductTemplateName="/customDAPMyContentIndividualProductTemplate.html";
        $customRegularProductNoImageTemplateName="/customDAPMyContentIndividualProductNoImageTemplate";
        
    }else{  
        if($displayoption == "showProductPage"){
            $regularProductTemplateName="/DAPMyContentIndividualProductTemplate.html";
            $regularProductNoImageTemplateName="/DAPMyContentIndividualProductNoImageTemplate.html";
            $customRegularProductTemplateName="/customDAPMyContentIndividualProductTemplate.html";
            $customRegularProductNoImageTemplateName="/customDAPMyContentIndividualProductNoImageTemplate";
        }elseif($displayoption == "showPopup"){
            $regularProductTemplateName="/popup/DAPMyContentIndividualProductTemplate.html";
            $regularProductNoImageTemplateName="/popup/DAPMyContentIndividualProductNoImageTemplate.html";
            $customRegularProductTemplateName="/popup/customDAPMyContentIndividualProductTemplate.html";
            $customRegularProductNoImageTemplateName="/popup/customDAPMyContentIndividualProductNoImageTemplate";
        }else{
            $regularProductTemplateName="/inpage/DAPMyContentIndividualProductTemplate.html";
            $regularProductNoImageTemplateName="/inpage/DAPMyContentIndividualProductNoImageTemplate.html";
            $customRegularProductTemplateName="/inpage/customDAPMyContentIndividualProductTemplate.html";
            $customRegularProductNoImageTemplateName="/inpage/customDAPMyContentIndividualProductNoImageTemplate";
        }
    }   
      
    
    $regulardrip_prod_temp_content=getDripTemplateContent($regulardrip_template_path, $regularProductTemplateName, $customRegularProductTemplateName);

    $regulardrip_prod_noimage_temp_content=getDripTemplateContent($regulardrip_template_path, $regularProductNoImageTemplateName, $customRegularProductNoImageTemplateName);
    
    $regularDripTemplateName="/DAPMyContentAvailableContentTemplate.html";
    $customRegularDripTemplateName="/customDAPMyContentAvailableContentTemplate.html";
    $regulardrip_temp_content=getDripTemplateContent($regulardrip_template_path, $regularDripTemplateName, $customRegularDripTemplateName);
    
    //REGULAR DRIP INDIVIDUAL CONTENT TEMPLATE
    $upcomingRegularDripTemplateName="/DAPMyContentUpcomingContentTemplate.html";
    $customUpcomingRegularDripTemplateName="/customDAPMyContentUpcomingContentTemplate.html";
    $upcoming_regulardrip_temp_content=getDripTemplateContent($regulardrip_template_path, $upcomingRegularDripTemplateName, $customUpcomingRegularDripTemplateName);
    
    //Sidebar   
    //$regularMyContentSidebarTemplate = "/sidebar/DAPMyContentSidebarTemplate.html";
    //$customRegularMyContentSidebarTemplate = "/sidebar/customDAPMyContentSidebarTemplate.html";
    //$regulardrip_prod_sidebar_temp = getDripTemplateContent($regulardrip_template_path1, $regularMyContentSidebarTemplate, $customRegularMyContentSidebarTemplate);
    
    $ind_prod_content="";
    //loop over each product from the list
    logToFile("DAP-ShortCodes-Transactions: Iterate through each user->product",LOG_INFO_DAP);
    
    if(file_exists($lldocroot."/dap/dap-mycontent.php")) 
        include_once ($lldocroot."/dap/dap-mycontent.php"); 
    else {
        $errorHTML = "Missing Required File (/dap/dap-mycontent.php)";
        return $errorHTML;  
    }
    
    /*************** Condition for sorting  products******************/
    
    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($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($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;
                
            }

        }
    }
    //echo "<pre>"; print_r($productList);echo "</pre>";die;
    
    /*************** Product loop starts ******************/


    $i=0;   
        
    foreach ($productList as $prod) {   
        if($hideproductid != "NONE") {
            $hideProductIdArray = explode(",",$hideproductid);
            if( in_array($prod->getId(), $hideProductIdArray) ) {
                continue;
            }
        }
        
        if($productid != "ALL") {
            if(strstr($productid,",")!=false) {
              $productIdArray = explode(",",$productid);
              if( !in_array($prod->getId(), $productIdArray) ) {
                  continue;
              }
            }
            else {
                $prodid=$productid;
                if( $prod->getId() != $prodid ) {
                  //logToFile("DAP-ShortCodes-MemberLinks: prodid=" . $prodid . "  prodid=".$userProduct->getProduct_id());
                  continue;
                }
            }
          //  logToFile("DAP-ShortCodes-MemberLinks: prodid=".$prod->getId());
        }
        
        $product = Dap_Product::loadProduct($prod->getId());
    //  echo "<pre>"; print_r($product);    echo "</pre>";die;  

        if(!isset($product)) {
            logToFile("DAP-ShortCodes-MemberLinks: no product found");
            return $content;
        }
        
       // logToFile("DAP-ShortCodes-MemberLinks: product found");
        
        //$dripType=$product->getDrip_type();
          
        $dripType=1;
        
        if($dripType==2)  {
            logToFile("DAP-ShortCodes-MemberLinks: can't process conditional drip products");
            continue;
        }
        
        $productId=$product->getId();
  //      logToFile("DAP-ShortCodes-MemberLinks:  product(id=$productId) found");
 //       logToFile("DAP-ShortCodes-MemberLinks:  user(id=$userId) found");
        
        $expired = false;
        if( !Dap_Session::isLoggedIn() || !isset($user) ) {
        }else{
            if($user->hasAccessTo($product->getId()) === false) {
                $expired = true;
            }
        }
        //access start date
        $oldDate = $userProduct_alldate[$prod->getId()]['access_start_date'];

        //$middle = strtotime($oldDate);
        $middle = new DateTime($oldDate);
        $stringFormat = "";
        if($dateformat == "MM-DD-YYYY") {
            $stringFormat = "m-d-Y";
        } else if($dateformat == "DD-MM-YYYY") {
            $stringFormat = "d-m-Y";
        }  else if($dateformat == "YYYY-MM-DD") {
            $stringFormat = "Y-m-d";
        }
        //$newDate = date($stringFormat, $middle);
        $newStartDate = $middle->format($stringFormat);

        //access start date
        $oldDate = $userProduct_alldate[$prod->getId()]['access_end_date'];
        
        //$middle = strtotime($oldDate);
        $middle = new DateTime($oldDate);
        $stringFormat = "";
        if($dateformat == "MM-DD-YYYY") {
            $stringFormat = "m-d-Y";
        } else if($dateformat == "DD-MM-YYYY") {
            $stringFormat = "d-m-Y";
        }  else if($dateformat == "YYYY-MM-DD") {
            $stringFormat = "Y-m-d";
        }
        //$newDate = date($stringFormat, $middle);
        $newEndDate = $middle->format($stringFormat);

 
        $highlightCode = "";
        if($expired) {
          $highlightCode = ' class="dap_highlight_bg" ';
        }
        
        $post_cancel_access = Dap_Config::get("POST_CANCEL_ACCESS");
        if(isset($post_cancel_access)) {
            $post_cancel_access = strtolower($post_cancel_access);
        }       
            
    //   logToFile("DAP-ShortCodes-MemberLinks: user's access has expired to $productId.. check... renewal html");
        
        if($dripType==2) {
            continue;
        }
        else if(strtolower($showproductimage)=="y") {
            $ind_prod_content = $regulardrip_prod_temp_content;
            
        }
        else {
            $ind_prod_content = $regulardrip_prod_noimage_temp_content;
                
        }  
        
        if( $expired && ($showrenewalhtml == "Y") ) {
            //If user's access to product has expired, then show renewal HTML
            //$content .= '<div>'.$product->getRenewal_html().'</div>';
            $ind_prod_content = str_replace( '[RENEWAL_HTML]',$product->getRenewal_html(), $ind_prod_content);
            $ind_prod_content = str_replace( '[RENEWALHTMLVISIBILITY]',"block", $ind_prod_content); 
            
            logToFile("DAP-ShortCodes-MemberLinks: user's access has expired.. show renewal html");
            
        }
        else {
            $ind_prod_content = str_replace( '[RENEWAL_HTML]',"", $ind_prod_content); 
            $ind_prod_content = str_replace( '[RENEWALHTMLVISIBILITY]',"none", $ind_prod_content); 
        }
        
        
    //    logToFile("DAP-ShortCodes-MemberLinks: before showlinks: ".strtolower($showlinks));
        //$dripType=$product->getDrip_type();
        
        
        if(strtolower($showproductimage)=="y") {
            
            $prod_image = $product->getProduct_image_url();
                        
            if($prod_image==""){
                //$prod_image="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRCI53HWVRvF_uRmJxVDLfgKuOLjksNq3xXbRMv8IfbJ7t56Uf8";
                $prod_image=  plugin_dir_url(__FILE__)."includes/images/no-image.jpg";
                
            }   
            $ind_prod_content = str_replace( '[PRODUCT_IMAGE]',$prod_image, $ind_prod_content); 
            $ind_prod_content = str_replace( '[PRODUCTIMGVISIBILITY]',"block", $ind_prod_content);  
        }
        else {
            $ind_prod_content = str_replace( '[PRODUCTIMGVISIBILITY]',"none", $ind_prod_content); 
            $ind_prod_content = str_replace( '[PRODUCT_IMAGE]',"", $ind_prod_content); 
        }
        
        if(strtolower($showproductname)=="y") {
            $ind_prod_content = str_replace( '[PRODUCT_NAME]',$product->getName(), $ind_prod_content); 
            $ind_prod_content = str_replace( '[PRODUCTNAMEVISIBILITY]',"block", $ind_prod_content); 
        }
        else {
            $ind_prod_content = str_replace( '[PRODUCTNAMEVISIBILITY]',"none", $ind_prod_content); 
            $ind_prod_content = str_replace( '[PRODUCT_NAME]',"", $ind_prod_content); 
        }

        if(strtolower($showdescription)=="y") {
            $ind_prod_content = str_replace( '[PRODUCT_DESCRIPTION]',$product->getDescription(), $ind_prod_content); 
            $ind_prod_content = str_replace( '[PRODUCTDESCRIPTIONVISIBILITY]',"block", $ind_prod_content);  
        }
        else {
            $ind_prod_content = str_replace( '[PRODUCTDESCRIPTIONVISIBILITY]',"none", $ind_prod_content); 
            $ind_prod_content = str_replace( '[PRODUCT_DESCRIPTION]',"", $ind_prod_content); 
            
        }
        if(strtolower($showaccessstartdate)=="y") {
            $access_start_date_label=$accessstartdatetext;
             
            $ind_prod_content = str_replace( '[ACCESS_START_DATE]',$access_start_date_label, $ind_prod_content); 
            $ind_prod_content = str_replace( '[ASD]',$newStartDate, $ind_prod_content); 
            $ind_prod_content = str_replace( '[ACCESSSTARTVISIBILITY]',"block", $ind_prod_content); 
            $ind_prod_content = str_replace( '[ASDLABEL]',$accessstartdatetext, $ind_prod_content); 
        }
        else {
           $access_start_date_label=$accessstartdatetext;
            $ind_prod_content = str_replace( '[ACCESS_START_DATE]',$access_start_date_label, $ind_prod_content); 
            $ind_prod_content = str_replace( '[ASD]',"", $ind_prod_content); 
            $ind_prod_content = str_replace( '[ACCESSSTARTVISIBILITY]',"none", $ind_prod_content); 
            $ind_prod_content = str_replace( '[ASDLABEL]',"", $ind_prod_content);
        }
        
        if(strtolower($showaccessenddate)=="y") {
			
            $access_end_date_label= $accessenddatetext;             
            $ind_prod_content = str_replace( '[AEDLABEL]',$access_end_date_label, $ind_prod_content); 
            $ind_prod_content = str_replace( '[ACCESS_END_DATE]',$access_end_date_label, $ind_prod_content); 
            $ind_prod_content = str_replace( '[AED]',$newEndDate, $ind_prod_content); 
            $ind_prod_content = str_replace( '[ACCESSENDVISIBILITY]',"block", $ind_prod_content); 
        }
        else {
            $access_end_date_label= $accessenddatetext;
            $ind_prod_content = str_replace( '[ACCESS_END_DATE]',$access_start_date_label, $ind_prod_content); 
            $ind_prod_content = str_replace( '[AED]',$newEndDate, $ind_prod_content); 
            $ind_prod_content = str_replace( '[ACCESSENDVISIBILITY]',"none", $ind_prod_content); 
            $ind_prod_content = str_replace( '[AEDLABEL]',"", $ind_prod_content); 
        }
    
        $ind_prod_content = str_replace( '[PRODUCTID]',$product->getId(), $ind_prod_content); 
                
        //echo $logged_in_url = $userProduct->getlogged_in_url();
        //echo $sales_page_url = $userProduct->getSales_page_url();
        
        
    /*************** Condition for display options starts ******************/   
        if( !Dap_Session::isLoggedIn() || !isset($user) ) {
        
            if($product->getsales_page_url() == ""){
                    $ind_prod_content = str_replace( '[LINK_SALES_POST_LINK]',"#", $ind_prod_content);
                    $ind_prod_content = str_replace( '[PRODUCT_CLASS]',"product_container_grey", $ind_prod_content);
                    $ind_prod_content = str_replace( '[TARGET]','', $ind_prod_content);
                    $ind_prod_content = str_replace(  '[LINK_CLASS]','click_button', $ind_prod_content);
                    //$ind_prod_content = str_replace( '[HREFCONTENT]','#', $ind_prod_content);
                    
            }else{  
                    $ind_prod_content = str_replace( '[LINK_SALES_POST_LINK]',$product->getsales_page_url(), $ind_prod_content);
                    $ind_prod_content = str_replace( '[PRODUCT_CLASS]',"product_container_grey", $ind_prod_content);
                    $ind_prod_content = str_replace( '[TARGET]','target="_blank"', $ind_prod_content);
                    $ind_prod_content = str_replace(  '[LINK_CLASS]','click_button', $ind_prod_content);
                    //$ind_prod_content = str_replace( '[HREFCONTENT]',"javascript:showHideContentDIV([PRODUCTID],'block');", $ind_prod_content);
                    
            }       
        }else{
            if(in_array($prod->getId(), $userProduct_ids)){
                
                if($product->getlogged_in_url() == ""){
                    
                        $ind_prod_content = str_replace( '[PRODUCT_CLASS]',"product_container_white", $ind_prod_content);
                        $ind_prod_content = str_replace( '[PRODUCTID]', $prod->getId(), $ind_prod_content);
                       
                        if($displayoption == "showProductPage"){
                            $ind_prod_content = str_replace(  '[LINK_CLASS]','click_button', $ind_prod_content);
                            $ind_prod_content = str_replace( '[LINK_SALES_POST_LINK]',"#", $ind_prod_content);
                             $ind_prod_content = str_replace( '[TARGET]','', $ind_prod_content);
                        }elseif($displayoption == "showPopup"){
                            $ind_prod_content = str_replace(  '[LINK_CLASS]','fancybox fancybox_box click_button', $ind_prod_content);
                            $ind_prod_content = str_replace( '[LINK_SALES_POST_LINK]',"#", $ind_prod_content);
                            $ind_prod_content = str_replace( '[TARGET]','data-href="#mainswitch_'.$prod->getId().'"', $ind_prod_content);
                        }else{
                            $ind_prod_content = str_replace(  '[LINK_CLASS]','click_button',$ind_prod_content);
                            $ind_prod_content = str_replace( '[LINK_SALES_POST_LINK]',"javascript:showHideContentDIV(".$prod->getId().",'block');", $ind_prod_content);
                             $ind_prod_content = str_replace( '[TARGET]','', $ind_prod_content);
                        }
                        
                         
                }else{      
 
                    $ind_prod_content = str_replace( '[PRODUCT_CLASS]',"product_container_white", $ind_prod_content);
                     $ind_prod_content = str_replace( '[PRODUCTID]', $prod->getId(), $ind_prod_content);
                    if($displayoption == "showProductPage"){
                            $ind_prod_content = str_replace(  '[LINK_CLASS]','click_button', $ind_prod_content);
                            $ind_prod_content = str_replace( '[LINK_SALES_POST_LINK]',$product->getlogged_in_url(), $ind_prod_content);
                            $ind_prod_content = str_replace( '[TARGET]','target="_blank"', $ind_prod_content);
                        }elseif($displayoption == "showPopup"){
                            $ind_prod_content = str_replace(  '[LINK_CLASS]','fancybox  fancybox_box click_button 111', $ind_prod_content);
                            $ind_prod_content = str_replace( '[LINK_SALES_POST_LINK]',"#", $ind_prod_content);
                            $ind_prod_content = str_replace( '[TARGET]','data-href="#mainswitch_'.$prod->getId().'"', $ind_prod_content);
                        }else{
                            $ind_prod_content = str_replace(  '[LINK_CLASS]','click_button',$ind_prod_content);
                            $ind_prod_content = str_replace( '[LINK_SALES_POST_LINK]',"javascript:showHideContentDIV(".$prod->getId().",'block');", $ind_prod_content);
                            $ind_prod_content = str_replace( '[TARGET]','', $ind_prod_content);
                        }
                }
            
            }else{
                    if($product->getsales_page_url() == ""){
                        
                        $ind_prod_content = str_replace( '[PRODUCT_CLASS]',"product_container_grey", $ind_prod_content);
                       $ind_prod_content = str_replace( '[LINK_CLASS]','click_button', $ind_prod_content);
                        if($displayoption == "showProductPage"){
                            $ind_prod_content = str_replace(  '[LINK_CLASS]','click_button', $ind_prod_content);
                            $ind_prod_content = str_replace( '[LINK_SALES_POST_LINK]',"#", $ind_prod_content);
                             $ind_prod_content = str_replace( '[TARGET]','', $ind_prod_content);
                        }elseif($displayoption == "showPopup"){
                            $ind_prod_content = str_replace(  '[LINK_CLASS]','click_button', $ind_prod_content);
                            $ind_prod_content = str_replace( '[LINK_SALES_POST_LINK]',"#", $ind_prod_content);
                            $ind_prod_content = str_replace( '[TARGET]','data-href="#mainswitch_'.$prod->getId().'"', $ind_prod_content);
                        }else{
                            $ind_prod_content = str_replace(  '[LINK_CLASS]','click_button',$ind_prod_content);
                            $ind_prod_content = str_replace( '[LINK_SALES_POST_LINK]',"#", $ind_prod_content);
                            $ind_prod_content = str_replace( '[TARGET]','', $ind_prod_content);
                        }   
                    }else{  
                        
                        $ind_prod_content = str_replace( '[PRODUCT_CLASS]',"product_container_grey", $ind_prod_content);
                        $ind_prod_content = str_replace( '[TARGET]','target="_blank"', $ind_prod_content);
                        if($displayoption == "showProductPage"){
                            $ind_prod_content = str_replace(  '[LINK_CLASS]','click_button', $ind_prod_content);
                            $ind_prod_content = str_replace( '[LINK_SALES_POST_LINK]',$product->getsales_page_url(), $ind_prod_content);
                        }elseif($displayoption == "showPopup"){
                            $ind_prod_content = str_replace(  '[LINK_CLASS]','click_button', $ind_prod_content);
                            $ind_prod_content = str_replace( '[LINK_SALES_POST_LINK]',$product->getsales_page_url(), $ind_prod_content);
                        }else{
                            $ind_prod_content = str_replace(  '[LINK_CLASS]','click_button',$ind_prod_content);
                            $ind_prod_content = str_replace( '[LINK_SALES_POST_LINK]',$product->getsales_page_url(), $ind_prod_content);
                        }
                        
                    }                   
            }
        }
            
        
        /*************** Condition for display options ends ******************/ 
        
        $course_content="";

        if(strtolower($showlinks) == "y") {
            
            if( !Dap_Session::isLoggedIn() || !isset($user) ) {
                if( (strtolower($showavailablecontent) == "n") && (strtolower($showupcomingcontent) == "n")) {
                    $ind_prod_content = str_replace( '[PRODUCTLINKSVISIBILITY]',"none", $ind_prod_content);     
                    $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',$clickheretextunavilable, $ind_prod_content); 
                    //$ind_prod_content = str_replace( '[LINKSTEXTVISIBILITY]',"none", $ind_prod_content);  
                }
                //if($displayoption == "showInpage"){
                    if(strtolower($showlinkscollapsed) == "y") {
                        $ind_prod_content = str_replace( '[PRODUCTLINKSVISIBILITY]',"none", $ind_prod_content);     
                        $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',$clickheretextunavilable, $ind_prod_content); 
                        //$ind_prod_content = str_replace( '[LINKSTEXTVISIBILITY]',"block", $ind_prod_content); 
                        logToFile("DAP-ShortCodes-MemberLinks: showlinkscollapsed: ".strtolower($showlinkscollapsed));
                    }
                    else{
                        
                        //$ind_prod_content = str_replace( '[LINKSTEXTVISIBILITY]',"none", $ind_prod_content); 
                        $ind_prod_content = str_replace( '[PRODUCTLINKSVISIBILITY]',"none", $ind_prod_content);     
                        $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',$clickheretextunavilable, $ind_prod_content); 
                    }
                //}

            }else{  
            
                if(in_array($prod->getId(), $userProduct_ids)){
                    if( (strtolower($showavailablecontent) == "n") && (strtolower($showupcomingcontent) == "n")) {
                        $ind_prod_content = str_replace( '[PRODUCTLINKSVISIBILITY]',"none", $ind_prod_content);     
                        $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',$clickheretext, $ind_prod_content); 
                        //$ind_prod_content = str_replace( '[LINKSTEXTVISIBILITY]',"none", $ind_prod_content);  
                    }
                    if($displayoption == "showInpage"){
                        if(strtolower($showlinkscollapsed) == "y") {
                            $ind_prod_content = str_replace( '[PRODUCTLINKSVISIBILITY]',"none", $ind_prod_content);     
                            $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',$clickheretext, $ind_prod_content); 
                            $ind_prod_content = str_replace( '[LINKSTEXTVISIBILITY]',"block", $ind_prod_content); 
                  //         logToFile("DAP-ShortCodes-MemberLinks: showlinkscollapsed: ".strtolower($showlinkscollapsed));
                        }
                        else{
                            $ind_prod_content = str_replace( '[LINKSTEXTVISIBILITY]',"none", $ind_prod_content); 
                            $ind_prod_content = str_replace( '[PRODUCTLINKSVISIBILITY]',"block", $ind_prod_content);    
                            $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',$clickheretext, $ind_prod_content); 
                        }
                    }else{
                        if(strtolower($showlinkscollapsed) == "y") {
                            $ind_prod_content = str_replace( '[PRODUCTLINKSVISIBILITY]',"block", $ind_prod_content);    
                            $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',$clickheretext, $ind_prod_content); 
                            //$ind_prod_content = str_replace( '[LINKSTEXTVISIBILITY]',"block", $ind_prod_content); 
                  //          logToFile("DAP-ShortCodes-MemberLinks: showlinkscollapsed: ".strtolower($showlinkscollapsed));
                        }
                        else{
                            
                            //$ind_prod_content = str_replace( '[LINKSTEXTVISIBILITY]',"block", $ind_prod_content); 
                            $ind_prod_content = str_replace( '[PRODUCTLINKSVISIBILITY]',"block", $ind_prod_content);    
                            $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',$clickheretext, $ind_prod_content); 
                        }
                    }

                }else{

                        if( (strtolower($showavailablecontent) == "n") && (strtolower($showupcomingcontent) == "n")) {
                                $ind_prod_content = str_replace( '[PRODUCTLINKSVISIBILITY]',"none", $ind_prod_content);     
                                $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',$clickheretextunavilable, $ind_prod_content); 
                                //$ind_prod_content = str_replace( '[LINKSTEXTVISIBILITY]',"none", $ind_prod_content);  
                            }
                            if(strtolower($showlinkscollapsed) == "y") {
                                $ind_prod_content = str_replace( '[PRODUCTLINKSVISIBILITY]',"none", $ind_prod_content);     
                                $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',$clickheretextunavilable, $ind_prod_content);  
                                //$ind_prod_content = str_replace( '[LINKSTEXTVISIBILITY]',"block", $ind_prod_content); 
                      //          logToFile("DAP-ShortCodes-MemberLinks: showlinkscollapsed: ".strtolower($showlinkscollapsed));
                            }
                            else{
                                
                                //$ind_prod_content = str_replace( '[LINKSTEXTVISIBILITY]',"none", $ind_prod_content); 
                                $ind_prod_content = str_replace( '[PRODUCTLINKSVISIBILITY]',"block", $ind_prod_content);    
                                $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',$clickheretextunavilable, $ind_prod_content); 
                            }

                }
            }           
        
        }
        else {
                            
            if( !Dap_Session::isLoggedIn() || !isset($user) ) {
                
                    $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',$clickheretextunavilable, $ind_prod_content); 

            }else{  
                
                if(in_array($prod->getId(), $userProduct_ids)){
                    $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',$clickheretext, $ind_prod_content); 
                }else{
                    $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',$clickheretextunavilable, $ind_prod_content); 
                }
                
            }           
            $ind_prod_content = str_replace( '[UPCOMINGCONTENTVISIBILITY]',"none", $ind_prod_content);  
            $ind_prod_content = str_replace( '[AVAILABLECONTENTVISIBILITY]',"none", $ind_prod_content);
            $ind_prod_content = str_replace( '[PRODUCTLINKSVISIBILITY]',"none", $ind_prod_content);     
            $ind_prod_content = str_replace( '[LINKSTEXTVISIBILITY]',"none", $ind_prod_content);

            $ind_prod_content = str_replace( '[UPCOMING_CONTENT]',"", $ind_prod_content); 
            $ind_prod_content = str_replace( '[UPCOMING_CONTENT_HEADER]',"", $ind_prod_content); 
            $ind_prod_content = str_replace( '[UPCOMING_IN_DAYS_HEADER]',"", $ind_prod_content);
                
            $ind_prod_content = str_replace( '[AVAILABLE_CONTENT]',"", $ind_prod_content);  
            $ind_prod_content = str_replace( '[AVAILABLE_CONTENT_HEADER]',"", $ind_prod_content);   
                
        }
        
        
        //echo $ind_prod_content;
        if(strtolower($showlinks) == "y") {
            $orderBy = "desc";
            
            if(strtolower($orderoflinks) == "oldestfirst") {
              $orderBy = "asc";
            }
            $sss = $product->getSelf_service_allowed();
            
            //get currently available content
            
                        
            if( (strtolower($showavailablecontent) == "y") || (strtolower($showupcomingcontent) == "y")) {
                $ind_prod_content = str_replace( '[PRODUCTLINKSVISIBILITY]',"none", $ind_prod_content); 
                $ind_prod_content = str_replace( '[PRODUCT_LINKS_HREF]',"", $ind_prod_content); 
            
                $ind_prod_content = str_replace( '[LINKS]',$mycontentheadertext, $ind_prod_content); 
                $ind_prod_content = str_replace( '[STATUS]',$statusheader, $ind_prod_content); 
            
                if(strtolower($showavailablecontent) == "y") {
                    $ind_prod_content = str_replace( '[AVAILABLE_CONTENT_HEADER]',$availcontentheadertext, $ind_prod_content); 
                    $ind_prod_content = str_replace( '[AVAILABLECONTENTVISIBILITY]',"block", $ind_prod_content); 
                    $course_content="";
                    
                    //$ind_prod_content = str_replace( '[UPCOMINGCONTENTVISIBILITY]',"none", $ind_prod_content);    
                    if ($product->getSelf_service_allowed() == "N") { 
                    //  $resources=$userProduct->getActiveResources($product->getSelf_service_allowed(),$orderBy,$howmanylinks,"ARRAY");
                        $resources=getActiveRes($userId,$productId,$product->getSelf_service_allowed(),$orderBy,$howmanylinks,"ARRAY");
                    }
                    else {
                        // $resources=$userProduct->getActiveResources("Y",$orderBy,$howmanylinks,"ARRAY");
                        $resources=getActiveRes($userId,$productId,"Y",$orderBy,$howmanylinks,"ARRAY");
                    }
                         
                    $contentFound=false;
                    if(isset($resources)) {
                        $drip_content="";
                        foreach ($resources as $resource) {
                            //logToFile("DAP-ShortCodes-MemberLinks: course_content: ".$course_content);
                            $drip_content .=  getRegularDripAndSSSResources($resource,$userId,$productId,$sss,$post_cancel_access,$regulardrip_temp_content); 
                            if($drip_content!="")
                                $contentFound=true;
                        }
                    }
                    if($contentFound==false) {
                        logToFile("DAP-ShortCodes-MemberLinks: nocontenttext: ".$nocontenttext);
                        $drip_content="<tr><td>$nocontenttext</td></tr>";
                    }
                    $ind_prod_content = str_replace( '[AVAILABLE_CONTENT]',$drip_content, $ind_prod_content);   
                    
                } //showavailablecontent==Y
                else {
                    $ind_prod_content = str_replace( '[AVAILABLECONTENTVISIBILITY]',"none", $ind_prod_content); 
                }
                
                if( strtolower($showupcomingcontent) == "y") {
                    $ind_prod_content = str_replace( '[UPCOMINGCONTENTVISIBILITY]',"block", $ind_prod_content); 
                    $ind_prod_content = str_replace( '[UPCOMING_CONTENT_HEADER]',$upcomingcontentheadertext, $ind_prod_content); 
                    $ind_prod_content = str_replace( '[UPCOMING_IN_DAYS_HEADER]',$comingsoonheadertext, $ind_prod_content);
                    
                    $upcomingLaterResources=getFutureRes($userId,$productId,"N",$orderBy,$howmanyupcominglinks,"Y","ARRAY");
                    $upcoming_regular_drip_content="";
                    $contentFound=false;
                    if(isset($upcomingLaterResources)) {
                        foreach ($upcomingLaterResources as $resource) {
                       //     logToFile("DAP-ShortCodes-MemberLinks: get upcoming regular drip resources: ". $upcoming_regulardrip_temp_content);
                            $upcoming_regular_drip_content .= getRegularDripAndSSSFutureResources($resource,$userId,$productId,$sss,$post_cancel_access,$upcoming_regulardrip_temp_content); 
                            if($upcoming_regular_drip_content!="")
                                $contentFound=true;
                        }
                    }
                    if($contentFound==false) {
                        logToFile("DAP-ShortCodes-MemberLinks: upcoming nocontenttext: ".$nocontenttext);
                        $upcoming_regular_drip_content="<tr><td>$nocontenttext</td></tr>";
                    }
                    
                    $ind_prod_content = str_replace( '[UPCOMING_CONTENT]',$upcoming_regular_drip_content, $ind_prod_content); 
                    
                    
                }
                else {
                    $ind_prod_content = str_replace( '[UPCOMINGCONTENTVISIBILITY]',"none", $ind_prod_content);  
                    
                }
            } //if( (strtolower($showavailablecontent) == "y") || (strtolower($showupcomingcontent) == "y")) {
            else {
            //hidelinks
              $ind_prod_content = str_replace( '[LINKS]',"", $ind_prod_content); 
              $ind_prod_content = str_replace( '[STATUS]',"", $ind_prod_content); 
              $ind_prod_content = str_replace( '[UPCOMINGCONTENTVISIBILITY]',"none", $ind_prod_content);    
              $ind_prod_content = str_replace( '[AVAILABLECONTENTVISIBILITY]',"none", $ind_prod_content);
              $ind_prod_content = str_replace( '[PRODUCTLINKSVISIBILITY]',"none", $ind_prod_content); 
              $ind_prod_content = str_replace( '[PRODUCT_LINKS_HREF]',"", $ind_prod_content); 
              $ind_prod_content = str_replace( '[LINKSTEXTVISIBILITY]',"none", $ind_prod_content); 
              $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',"", $ind_prod_content); 
            }
        } //showlinks
        else {

            //hidelinks
            $ind_prod_content = str_replace( '[LINKS]',"", $ind_prod_content); 
            $ind_prod_content = str_replace( '[STATUS]',"", $ind_prod_content); 
            $ind_prod_content = str_replace( '[UPCOMINGCONTENTVISIBILITY]',"none", $ind_prod_content);  
            $ind_prod_content = str_replace( '[AVAILABLECONTENTVISIBILITY]',"none", $ind_prod_content);
            $ind_prod_content = str_replace( '[PRODUCTLINKSVISIBILITY]',"none", $ind_prod_content); 
            $ind_prod_content = str_replace( '[PRODUCT_LINKS_HREF]',"", $ind_prod_content); 
            $ind_prod_content = str_replace( '[LINKSTEXTVISIBILITY]',"none", $ind_prod_content); 
            $ind_prod_content = str_replace( '[PRODUCT_LINKS_TEXT]',"", $ind_prod_content); 
        }

        
        $i++;
        $productAll.=$ind_prod_content;
               
    } //end foreach  

    $content .= '<link rel="stylesheet" href="'. $cssurl  . '"/>';
    
    $content .= ' <script type="text/javascript">

    var $jq = jQuery.noConflict();

    $jq(function(){

        $jq(".matchheight").matchHeight();$jq(".matchheight1").matchHeight();$jq(".matchheight2").matchHeight();

    }); 

    $jq(document).ready(function(){


        $jq.fn.dataTable.ext.errMode = "none"; 

        $jq(".report_Table").on("error.dt", function ( e, settings, techNote, message ) {

        console.log( "An error has been reported by DataTables: ", message );

        }).DataTable();

    
		$jq(".report_table").DataTable({"bProcessing": true,
"bSort": false, pageLength: '.$howmanylinksperpage.', "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(document).ready(function(){

        var prod_parent_width = $jq(".product_outer").parent().innerWidth();

        var prod_width_child = $jq(".product_div .product-box-item").innerWidth();;

        var number_of_box = parseInt(prod_parent_width / prod_width_child);

        var box_outer_width = parseInt(prod_width_child * number_of_box);

    /*  var getmargin_right = $jq(".product-box-item").css("margin-right");
        var getmargin_left = $jq(".product-box-item").css("margin-left");
        var res_margin_right = getmargin_right.split("px");
        var res_margin_left = getmargin_left.split("px");
        var marginright = parseInt(res_margin_right[0]);
        var marginleft = parseInt(res_margin_left[0]);
        var finalres_margin = parseInt(marginright + marginleft);*/
        

        var  border_width = parseInt(2 * number_of_box);

        var new_number_of_box = parseInt(number_of_box); 

        var getmargin = parseInt(20 * new_number_of_box);

        var getmargin_final = parseInt(getmargin + border_width);

        var oneboxwidth = parseInt(box_outer_width + getmargin_final);

        

        $jq("#productoutercontainter .product_div").css("width", oneboxwidth);



    });

</script>'; 

    $desired_width = '300';
    $desired_height = '300';
    $desired_boxwidth = '700';
    if($imagewidth > 300){
        $imagewidth = $desired_width;
    }
    if($imageheight > 300){
        $imageheight = $desired_height;
    }
    /**** template condtion*******/     
    if($template == "template1"){
        /****imagewidth*******/
        if(strtolower($showproductimage)=="y") {
            if($imagewidth == 0 || $imagewidth == "undefined" || $imagewidth == '' ){
                $content .= '<style>.product-image{width :'.$desired_width.'px !important}</style>'; 
                $content .= '<style>.product-item-details {width: -moz-calc(100% - '.$desired_width.'px);width: -webkit-calc(100% - '.$desired_width.'px);width: -o-calc(100% - '.$desired_width.'px);width: calc(100% - '.$desired_width.'px);}</style>';
            }elseif($imagewidth > $boxwidth ){  
            
                $content .= '<style>.product-image{width :'.$boxwidth.'px !important}</style>'; 
                $content .= '<style>.product-item-details {width: -moz-calc(100% - '.$boxwidth.'px);width: -webkit-calc(100% - '.$boxwidth.'px);width: -o-calc(100% - '.$boxwidth.'px);width: calc(100% - '.$boxwidth.'px);}</style>';
                
            }else{
                $content .= '<style>.product-image {width :'.$imagewidth.'px !important}</style>'; 
                $content .= '<style>.product-item-details {width: -moz-calc(100% - '.$imagewidth.'px);width: -webkit-calc(100% - '.$imagewidth.'px);width: -o-calc(100% - '.$imagewidth.'px);width: calc(100% - '.$imagewidth.'px);}</style>';              
            }
            /****imageheight*******/
            if($imageheight == 0 || $imageheight == "undefined" || $imageheight == '' ){
                $content .= '<style>.product-image {height :'.$desired_height.'px !important}</style>';     
            
            }else{
                $content .= '<style>.product-image {height :'.$imagewidth.'px !important}</style>';             
            }
            /****boxwidth*******/ 
            if($boxwidth == 0 || $boxwidth == "undefined" || $boxwidth == ''){
                $content .= '<style>.product-box-item{width :700px !important}</style>';             
            }elseif($boxwidth < 605 && $boxwidth > 310){

                 $content .= '<style>.product-box-item{width :'.$boxwidth.'px !important}</style>';  
                 $content .= '<style>.product-box-item .product-item-details{width :100% !important;}.product-box-item {margin-right: 15px;}.product-item-details{padding: 5px !important;}.product-box-item .product-image-outer {width: 100%;}.product-box-item .click_button {bottom: 10px;left: 10px;margin: 0;position: absolute;right: 10px;float:left;width:100%;}.product-box-item .product-item-details {position: static !important;}.product-box-item {position: relative;}.product-item-details {text-align: center;}.product-image {display: inline-block;margin: 0 auto;}.product-box-item .product-image-outer {float: left;text-align: center;width: 100%;}.product-box-item .product-item-details .click_button {left: 15px;margin: 0 auto;max-width: 220px;right: 15px;width: auto;} .product-box-item  .click_button{ margin-bottom: 10px !important;}</style>'; 
   
             }elseif($boxwidth < $imagewidth || $boxwidth <= 310){
                $content .= '<style>.product-image{max-width: 100% !important;}</style>'; 
                $content .= '<style>.product-box-item{width :'.$boxwidth.'px !important}</style>';  
                $content .= '<style>.product-box-item .product-item-details{width :100% !important;}.product-box-item {margin-right: 15px;}.product-item-details{padding: 5px !important;}.product-box-item .product-image-outer {width: 100%;}.product-box-item .product-item-details {position: static !important;}.product-box-item {position: relative;}.product-item-details {text-align: center;}.product-image {display: inline-block;margin: 0 auto;}.product-box-item .product-image-outer {float: left;text-align: center;width: 100%;}.product-box-item .product-item-details .click_button {left: 15px;margin: 0 auto;max-width: 220px;right: 15px;width: auto;} .product-box-item  .click_button{ margin-bottom: 10px !important;}</style>'; 
                $content .= '<style>.product-image {height: auto !important;}.product-box-item .product-image img {position: static;}</style>';     
            }else{
                   $content .= '<style>.product-box-item{width :'.$boxwidth.'px !important}</style>';                                                
            }
            
        }else{
            
            if($imagewidth == 0 || $imagewidth == "undefined" || $imagewidth == '' ){
                $content .= '<style>.product-image{width :'.$desired_width.'px !important}</style>'; 
                $content .= '<style>.product-item-details {width: -moz-calc(100%);width: -webkit-calc(100%);width: -o-calc(100%);width: calc(100%);}</style>';
            }elseif($imagewidth > $boxwidth ){  
            
                $content .= '<style>.product-image{width :'.$boxwidth.'px !important}</style>'; 
                $content .= '<style>.product-item-details {width: -moz-calc(100%);width: -webkit-calc(100%);width: -o-calc(100%);width: calc(100% );}</style>';
                
            }else{
                $content .= '<style>.product-image {width :'.$imagewidth.'px !important}</style>'; 
                $content .= '<style>.product-item-details {width: -moz-calc(100%);width: -webkit-calc(100%);width: -o-calc(100%);width: calc(100%);}</style>';              
            }
            /****imageheight*******/
            if($imageheight == 0 || $imageheight == "undefined" || $imageheight == '' ){
                $content .= '<style>.product-image {height :'.$desired_height.'px !important}</style>';     
            
            }else{
                $content .= '<style>.product-image {height :'.$imagewidth.'px !important}</style>';             
            }
            /****boxwidth*******/ 
            if($boxwidth == 0 || $boxwidth == "undefined" || $boxwidth == ''){
                $content .= '<style>.product-box-item{width :700px !important}</style>';             
            }elseif($boxwidth < 605 && $boxwidth > 310){

                 $content .= '<style>.product-box-item{width :'.$boxwidth.'px !important}</style>';  
                 $content .= '<style>.product-box-item .product-item-details{width :100% !important;}.product-box-item {margin-right: 15px;}.product-item-details{padding: 5px !important;}.product-box-item .product-image-outer {width: 100%;}.product-box-item .click_button {bottom: 10px;left: 10px;margin: 0;position: absolute;right: 10px;float:left;width:100%;}.product-box-item .product-item-details {position: static !important;}.product-box-item {position: relative;}.product-item-details {text-align: center;}.product-image {display: inline-block;margin: 0 auto;}.product-box-item .product-image-outer {float: left;text-align: center;width: 100%;}.product-box-item .product-item-details .click_button {left: 15px;margin: 0 auto;max-width: 220px;right: 15px;width: auto;} .product-box-item  .click_button{ margin-bottom: 10px !important;}</style>'; 
   
             }elseif($boxwidth < $imagewidth || $boxwidth <= 310){
                $content .= '<style>.product-image{max-width: 100% !important;}</style>'; 
                $content .= '<style>.product-box-item{width :'.$boxwidth.'px !important}</style>';  
                $content .= '<style>.product-box-item .product-item-details{width :100% !important;}.product-box-item {margin-right: 15px;}.product-item-details{padding: 5px !important;}.product-box-item .product-image-outer {width: 100%;}.product-box-item .product-item-details {position: static !important;}.product-box-item {position: relative;}.product-item-details {text-align: center;}.product-image {display: inline-block;margin: 0 auto;}.product-box-item .product-image-outer {float: left;text-align: center;width: 100%;}.product-box-item .product-item-details .click_button {left: 15px;margin: 0 auto;max-width: 220px;right: 15px;width: auto;} .product-box-item  .click_button{ margin-bottom: 10px !important;} </style>'; 
                $content .= '<style>.product-image {height: auto !important;}.product-box-item .product-image img {position: static;}</style>';     
            }else{
                   $content .= '<style>.product-box-item{width :'.$boxwidth.'px !important}</style>';                                                
            }
            
        }
    }elseif($template == "template2"){
        /****imagewidth*******/
        if($imagewidth == 0 || $imagewidth == "undefined" || $imagewidth == '' ){
            $content .= '<style>.product-image{width :'.$desired_width.'px !important}</style>'; 
        }else{
            $content .= '<style>.product-image {width :'.$imagewidth.'px !important}</style>';          
        }
        /****imageheight*******/
        if($imageheight == 0 || $imageheight == "undefined" || $imageheight == '' ){
            $content .= '<style>.product-image {height :'.$desired_height.'px !important}</style>';     
        
        }else{
            $content .= '<style>.product-image {height :'.$imagewidth.'px !important}</style>';             
        }
        /****boxwidth*******/
        $boxwidth = $imagewidth;
        if($boxwidth == 0 || $boxwidth == "undefined" || $boxwidth == ''){
            $content .= '<style>.product-box-item{width :'.$desired_width.'px !important}</style>';
        }else{
             $content .= '<style>.product-box-item{width :'.$boxwidth.'px !important}</style>';  
        }       
    }

     $content .= '<style>.product_container_white .click_button {background :'.$availablebutton.' !important}</style>';
     $content .= '<style>.product_container_grey .click_button {background :'.$unavailablebutton.' !important}</style>';        
     $content .= '<style>.paginate_button.previous, .paginate_button.next, .paginate_button{background :'.$paginationbutton.' !important}</style>';


        if($sidebarorfullwidth == "sidebar"){
            $content .=  '<style>.product_div .product-box-item{ float: left; text-align: left;} .product_div {margin: 0 auto;  float: left;  max-width: 100%; width:100% !important } .thrv_wrapper.thrv-tabbed-content div.tve_scT .tve_scTC{float:left} </style>';
        }
        else{ 
            $content .=  '<style>.product_div .product-box-item{ float: left;}.product_div {margin: 0 auto;  float: none;  max-width: 100%; width:100% !important} .thrv_wrapper.thrv-tabbed-content div.tve_scT .tve_scTC{float:left} </style>';
        }
        
     
    $content .=  '<div class="product_outer" id="productoutercontainter" style="float:left; width:100%;">';
    $regulardrip_head_temp_content = str_replace( '[PRODUCTS]', $productAll, $regulardrip_head_temp_content);   
    $content .= $regulardrip_head_temp_content; 
    $content .=  '</div>';
    
    return $content.$includejscss.$scriptstylesvar;
    
}
 /******* include js and css ********/
function mydap_content_js(){
    
    wp_enqueue_script(jQuery);
    wp_enqueue_script('jquery.matchHeight-min', plugin_dir_url(__FILE__). 'includes/js/jquery.matchHeight-min.js', array('jquery'));
    wp_enqueue_script('jquery.fancybox-latest', plugin_dir_url(__FILE__). 'includes/js/jquery.fancybox.js', array('jquery'));  
    wp_enqueue_script('jquery.dataTables.min', plugin_dir_url(__FILE__). 'includes/js/jquery.dataTables.min.js', array('jquery'));
    
    wp_enqueue_style('jquery.fancybox.min', plugin_dir_url(__FILE__). 'includes/css/jquery.fancybox.css');
    wp_enqueue_style('jquery.dataTables.min', plugin_dir_url(__FILE__). 'includes/css/dataTables.bootstrap.min.css');
    wp_enqueue_style('jquery.mycontent.css', plugin_dir_url(__FILE__). 'includes/css/dap-mycontent-frontend.css?v=3');
    
}
 /******* get template  ********/    
function getDripTemplateContent($template_path, $courseTemplateName, $customCourseTemplateName)
{
    if(file_exists($template_path.$customCourseTemplateName)) {
      $course_temp_content = file_get_contents($template_path.$customCourseTemplateName);
    }
    
    if($course_temp_content == "") {
        if(file_exists($template_path.$courseTemplateName)) {
            $course_temp_content = file_get_contents($template_path.$courseTemplateName);
        }
        else{
            $course_temp_content = "";
        }
      
        logToFile("DAP-ShortCodes-Transactions: no custom template found=".$template_path.$courseTemplateName,LOG_INFO_DAP);
    } else {
        logToFile("DAP-ShortCodes-Transactions: custom template found=".$template_path.$customCourseTemplateName,LOG_INFO_DAP);  
    }   
    
    return $course_temp_content;
    
}


function dap_myprofileshortcode($atts, $content=null){ 
	global $wpdb;
		
	  extract(shortcode_atts(array(
		'showaccountsection' => '',
		'showbillingsection' => '',
		'showadditionalsection' => '',
		'showfirstname' => 'Y',
		'showlastname' => 'Y',
		'showusername' => 'Y',
		'showemail' => 'Y',
		'showpassword' => 'Y',
		'showaddress1' => 'Y',
		'showaddress2' => 'Y',
		'showcity' => 'Y',
		'showstate' => 'Y',
		'showzip' => 'Y',
		'showcountry' => 'Y',
		'showphone' => 'Y',
		'showfax' => 'Y',
		'showcompany' => 'Y',
		'showtitle' => 'Y',
		'showpaypalemail' => 'Y',
		'showoptedout' => 'Y',
		'showcustomfields' => 'Y',
		'customfieldvalues' => 'all',
		'formalign'=>'Y',
		'showuserprofileheading' => 'Y',
		'account_info_heading'=>'Account Info',
		'billing_info_heading'=>'Billing Info',
		'additional_info_heading'=>'Additional Info',
		'redirect' => '',
		'template' => 'template1',
		'allowgdpr' => '',
		'gdprouter' => '',
		'gdpr_label' => '',
		'gdpr_confirmation' => '',
	  ), $atts));
  
/*******GDPR*********/

 
  $content =  do_shortcode(dap_clean_shortcode_content($content));	
  $requestURI = explode("?",$_SERVER['REQUEST_URI']);
  $redirectTo = ($redirect == "") ? $requestURI[0] : $redirect;
  
  $session = Dap_Session::getSession();
  $user = $session->getUser();

  if( !Dap_Session::isLoggedIn() || !isset($user) ) {
    //logToFile("Not logged in, returning errmsgtemplate");
    $errorHTML = mb_convert_encoding(MSG_PLS_LOGIN, "UTF-8", "auto") . " <a href=\"" . Dap_Config::get("LOGIN_URL") . "\">". mb_convert_encoding(MSG_CLICK_HERE_TO_LOGIN, "UTF-8", "auto") . "</a>";
    return $errorHTML;
  }

  $userId = $user->getId();

  $user = Dap_User::loadUserById($userId);
  
	$scriptvar ="";
     $scriptvar .= '<script src="//code.jquery.com/jquery-2.2.4.min.js"></script>';
  $jqueryForResponsive='<script language="javascript">window.onload=function(){
    var maxwidth=jQuery("#dapprofile-container").width();
    window.onresize=function(){
    jQuery("#dapprofile-container").removeClass("resizedform");
    var windowsize = jQuery("html").width()-5;
    
    var containerw=Number(document.getElementById("dapprofile-container").offsetWidth); 
    if(containerw>windowsize){
      jQuery("#dapprofile-container").css("width",(windowsize-4)+"px");
    }else{
      var containerWidth=jQuery("#dapprofile-container").addClass("resizedform").width;
      if(maxwidth>containerWidth) {
        jQuery("#dapprofile-container").addClass("resizedform");
      }
      else {
        jQuery("#dapprofile-container").removeClass("resizedform");
      }
    }
    
    } 
  };
   
    </script>';
   
  $myprofile_content = '<script language="javascript" type="text/javascript" src="/dap/javascript/jsstrings.php"></script>'; 
  
  //$template="template1";
//  $myprofile_template_path=ABSPATH . "/wp-content/plugins/DAP-WP-LiveLinks/includes/myprofiletemplates/".$template;
  $myprofile_template_path=WP_PLUGIN_DIR . "/DAP-WP-LiveLinks/includes/myprofiletemplates/".$template;
  
  //REGULAR DRIP HEADER TEMPLATE CONTENT
  $myProfileTemplateName="/".$template.".html";
  $customMyProfileTemplateName="/custom".$template.".html";
  $myprofile_content.=getMyProfileTemplateContent($myprofile_template_path, $myProfileTemplateName, $customMyProfileTemplateName);
  
  
  
  //$cssurl=get_option('siteurl')."/wp-content/plugins/DAP-WP-LiveLinks/includes/myprofiletemplates/".$template."/css"; 
  $cssurl= plugin_dir_url(__FILE__)."includes/myprofiletemplates/".$template."/css";  
  $csspath= WP_PLUGIN_DIR."/DAP-WP-LiveLinks/includes/myprofiletemplates/".$template."/css";  
  
  if( file_exists($csspath . "/custommyprofile.css") ) 
    $cssurl = $cssurl . "/custommyprofile.css";
  else 
    $cssurl = $cssurl . "/myprofile.css";
  
  $myprofile_content = str_replace( '[CSSURL]',$cssurl, $myprofile_content);  
  
  if( isset($_GET['msg']) && ($_GET['msg'] != "") ) {
    if( defined($_GET['msg']) ) {
      $_GET['msg'] = constant($_GET['msg']);
    } else {
      $_GET['msg'] = str_replace("_"," ",$_GET['msg']);
    }
    $myprofile_content = str_replace( '[SUCCESSMSG]',$_GET['msg'], $myprofile_content);
        
   /* add_action( 'wp_footer', 'DAP_my_profile_display_msg' );
    
    function DAP_my_profile_display_msg(){
       $scriptvar .=  "<script>
      jQuery(document).ready(function(){
      jQuery('.confirmationMessage1').removeAttr('style');
      });
      </script>";
    } */
    
      $scriptvar .=  "<script>
      jQuery(document).ready(function(){
      jQuery('.confirmationMessage1').removeAttr('style');
      });
      </script>";
      
  } 
  
  $myprofile_content = str_replace( '[ACCOUNT_DETAILS_HEADING_LABEL]',$account_info_heading, $myprofile_content);
  $myprofile_content = str_replace( '[BILLING_DETAILS_HEADING_LABEL]',$billing_info_heading, $myprofile_content);
  $myprofile_content = str_replace( '[ADDITIONAL_DETAILS_HEADING_LABEL]',$additional_info_heading, $myprofile_content);
  
     $scriptvar .= "<script> var ShownElements = [];</script>";  
   
   if($showaccountsection == "Y"){
       $scriptvar .= "<script>ShownElements.push('#acc_info');</script>"; 
   }
   if($showbillingsection == "Y"){
       $scriptvar .= "<script>ShownElements.push('#bill_info');</script>";  
   }
   if($showadditionalsection == "Y"){
       $scriptvar .= "<script>ShownElements.push('#add_info');</script>"; 
   }
   
  //Start creating form fields
  if($showfirstname == "Y") {
    $myprofile_content = str_replace( '[USER_PROFILE_FIRST_NAME_LABEL]',USER_PROFILE_FIRST_NAME_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_FIRST_NAME]',$user->getFirst_name(), $myprofile_content);
         $scriptvar .= "<script>ShownElements.push('#fname');</script>";    
  }
    else {
    $myprofile_content = str_replace( '[USER_PROFILE_FIRST_NAME]',$user->getFirst_name(), $myprofile_content); 
  }  
    if($showlastname == "Y") {
    $myprofile_content = str_replace( '[USER_PROFILE_LAST_NAME_LABEL]',USER_PROFILE_LAST_NAME_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_LAST_NAME]',$user->getLast_name(), $myprofile_content); 
     $scriptvar .= "<script>ShownElements.push('#lname');</script>";
  }
    else {
    $myprofile_content = str_replace( '[USER_PROFILE_LAST_NAME]',$user->getLast_name(), $myprofile_content); 
  }
  
    if($showusername == "Y") {
    $myprofile_content = str_replace( '[USER_PROFILE_USER_NAME_LABEL]',USER_PROFILE_USER_NAME_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_USER_NAME]',$user->getUser_name(), $myprofile_content); 

    $readonly = "";
    $style = "";
    if($user->getUser_name() != "") {
      $readonly = ' readonly="" ';
      $style='style="background-color: #CCCCCC;"';
    }
    
    $myprofile_content = str_replace( '[READONLY]',$readonly , $myprofile_content); 
    $myprofile_content = str_replace( '[STYLE_USERNAME]',$style, $myprofile_content); 
      $scriptvar .= "<script>ShownElements.push('#uname');</script>";
  } else {
    $myprofile_content = str_replace( '[USER_PROFILE_USER_NAME]',$user->getUser_name(), $myprofile_content); 
  }  
  
  $myprofile_content = str_replace( '[USER_PROFILE_EMAIL_LABEL]',USER_PROFILE_EMAIL_LABEL, $myprofile_content);   
  $myprofile_content = str_replace( '[USER_PROFILE_EMAIL]',$user->getEmail(), $myprofile_content); 
  if($showemail == "Y") {
     $scriptvar .= "<script>ShownElements.push('#email');</script>";
  }
  else {
    $myprofile_content = str_replace( '[USER_PROFILE_EMAIL]',$user->getEmail(), $myprofile_content);  
  }

  if($showpassword == "Y") {
    $myprofile_content = str_replace( '[USER_PROFILE_NEW_PASSWORD_LABEL_DAPUSERPROFILE]',USER_PROFILE_NEW_PASSWORD_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_REPEAT_PASSWORD_LABEL]',USER_PROFILE_REPEAT_PASSWORD_LABEL, $myprofile_content); 
     $scriptvar .= "<script>ShownElements.push('#pass');</script>";
     $scriptvar .= "<script>ShownElements.push('#cpass');</script>";
  }else{
		 $scriptvar .= '<script>
    jQuery(document).ready(function(){
      jQuery("#u_password").attr("disabled",true);
      jQuery("#password_repeat").attr("disabled",true);
    });
    
    </script>';
	}
  

  if($showaddress1 == "Y") {
    $myprofile_content = str_replace( '[USER_PROFILE_ADDRESS1_LABEL]',USER_PROFILE_ADDRESS1_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_ADDRESS1]',$user->getAddress1(), $myprofile_content); 
     $scriptvar .= "<script>ShownElements.push('#add1');</script>";
  }
  else {
    $myprofile_content = str_replace( '[USER_PROFILE_ADDRESS1]',$user->getAddress1(), $myprofile_content);  
  }


  if($showaddress2 == "Y") {
    $myprofile_content = str_replace( '[USER_PROFILE_ADDRESS2_LABEL]',USER_PROFILE_ADDRESS2_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_ADDRESS2]',$user->getAddress2(), $myprofile_content);  
     $scriptvar .= "<script>ShownElements.push('#add2');</script>";
  }
  else {
    $myprofile_content = str_replace( '[USER_PROFILE_ADDRESS2]',$user->getAddress2(), $myprofile_content);  
  }
  
  if($showcity == "Y") {
    $myprofile_content = str_replace( '[USER_PROFILE_CITY_LABEL]',USER_PROFILE_CITY_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_CITY]',$user->getCity(), $myprofile_content);  
     $scriptvar .= "<script>ShownElements.push('#city');</script>";
  }
  else {
    $myprofile_content = str_replace( '[USER_PROFILE_CITY]',$user->getCity(), $myprofile_content);  
  }
  
  if($showstate == "Y") {
    $myprofile_content = str_replace( '[USER_PROFILE_STATE_LABEL]',USER_PROFILE_STATE_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_STATE]',$user->getState(), $myprofile_content); 
     $scriptvar .= "<script>ShownElements.push('#state');</script>";    
  }
  else {
    $myprofile_content = str_replace( '[USER_PROFILE_STATE]',$user->getState(), $myprofile_content);  
  }
  
  
  if($showzip == "Y") {
    $myprofile_content = str_replace( '[USER_PROFILE_ZIP_LABEL]',USER_PROFILE_ZIP_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_ZIP]',$user->getZip(), $myprofile_content);  
     $scriptvar .= "<script>ShownElements.push('#zip');</script>";
  }else {
    $myprofile_content = str_replace( '[USER_PROFILE_ZIP]',$user->getZip(), $myprofile_content);  
  }
  
  if($showcountry == "Y") {
    $myprofile_content = str_replace( '[USER_PROFILE_COUNTRY_LABEL]',USER_PROFILE_COUNTRY_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_COUNTRY]',$user->getCountry(), $myprofile_content);  
     $scriptvar .= "<script>ShownElements.push('#country');</script>";
  }
  else {
    $myprofile_content = str_replace( '[USER_PROFILE_COUNTRY]',$user->getCountry(), $myprofile_content);  
  }
  
  if($showphone == "Y") {
    $myprofile_content = str_replace( '[USER_PROFILE_PHONE_LABEL]',USER_PROFILE_PHONE_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_PHONE]',$user->getPhone(), $myprofile_content); 
     $scriptvar .= "<script>ShownElements.push('#phone');</script>";
  }
  else {
    $myprofile_content = str_replace( '[USER_PROFILE_PHONE]',$user->getPhone(), $myprofile_content);  
  }
  
  if($showfax == "Y") {
    $myprofile_content = str_replace( '[USER_PROFILE_FAX_LABEL]',USER_PROFILE_FAX_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_FAX]',$user->getFax(), $myprofile_content); 
     $scriptvar .= "<script>ShownElements.push('#fax');</script>";
  }
  else {
    $myprofile_content = str_replace( '[USER_PROFILE_FAX]',$user->getFax(), $myprofile_content);  
  }
  
  if($showcompany == "Y") {
    $myprofile_content = str_replace( '[USER_PROFILE_COMPANY_LABEL]',USER_PROFILE_COMPANY_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_COMPANY]',$user->getCompany(), $myprofile_content); 
     $scriptvar .= "<script>ShownElements.push('#company');</script>";
  }
  else {
    $myprofile_content = str_replace( '[USER_PROFILE_COMPANY]',$user->getCompany(), $myprofile_content);  
  }
  
  if($showtitle == "Y") {
    $myprofile_content = str_replace( '[USER_PROFILE_TITLE_LABEL]',USER_PROFILE_TITLE_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_TITLE]',$user->getTitle(), $myprofile_content);
     $scriptvar .= "<script>ShownElements.push('#title');</script>";
  }else {
    $myprofile_content = str_replace( '[USER_PROFILE_TITLE]',$user->getTitle(), $myprofile_content);  
  }
  
  
  //if( (Dap_Config::get('DISPLAY_AFFILIATE') == "Y") && ($showpaypalemail == "Y") ) {
  if($showpaypalemail == "Y")  {
    $myprofile_content = str_replace( '[USER_PROFILE_PAYPAL_EMAIL_LABEL]',USER_PROFILE_PAYPAL_EMAIL_LABEL, $myprofile_content); 
    $myprofile_content = str_replace( '[USER_PROFILE_PAYPAL_EMAIL_EXTRA_LABEL]',USER_PROFILE_PAYPAL_EMAIL_EXTRA_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_PAYPAL_EMAIL]',$user->getPaypal_email(), $myprofile_content); 
     $scriptvar .= "<script>ShownElements.push('#pay_email');</script>";
  }
    else {
    $myprofile_content = str_replace( '[USER_PROFILE_PAYPAL_EMAIL]',$user->getPaypal_email(), $myprofile_content); 
  }
  
  if($showoptedout == "Y") {
    $isChecked = ($user->getOpted_out() == "N") ? " checked='.$isChecked.' " : "";
    logToFile("isChecked: $isChecked , user->getOpted_out(): " . $user->getOpted_out());
    $myprofile_content = str_replace( '[USER_PROFILE_UNSUBSCRIBE_LABEL]',USER_PROFILE_UNSUBSCRIBE_LABEL, $myprofile_content);   
    $myprofile_content = str_replace( '[USER_PROFILE_IS_CHECKED]',$isChecked, $myprofile_content); 
     $scriptvar .= "<script>ShownElements.push('#sub_checkbox');</script>";
  }
  
  if($formalign != "")
  {   
     $scriptvar .= '<script>
    jQuery(document).ready(function(){
      jQuery("#dapprofile-container1").css("float","'.$formalign.'");
    });
    
    </script>';
  }
  
  if( ($showcustomfields == "Y") || ($showcustomfields != "") ) {
    $customFieldsArray = null;
    if($showcustomfields != "Y") {
      $customFieldsArray = explode(",",$showcustomfields);
    }
    

    $customFields = Dap_CustomFields::loadUserFacingCustomFields();
    if($customfieldvalues != "all"){
      $customArray = explode(',',$customfieldvalues);
    }else{
      $customArray = array();
      //$customFields = array_merge($customFields,$customArray);
    }
  
    foreach ($customFields as $custom) {
      if(empty($customArray) || in_array($custom['id'],$customArray)){
     /* $mycustom_tmp_fields_profile_content=$mycustom_fields_profile_content;*/
     
	  logToFile("userprofile.inc.php: loadCustomFields(): id =" . $custom['id']);
      logToFile("userprofile.inc.php: loadCustomFields(): userId =" . $userId);
      $required = " ";
      $requiredStar = "";
 
      if ($custom['showonlytoadmin'] == "Y") {
        continue;
      }
      
      //logToFile("custom[name]: " . $custom['name']); 
      if ( !is_null($customFieldsArray) && !in_array($custom['name'],$customFieldsArray) ){
        continue;
      }
      
      if($custom['required'] == "Y") {
        $required = "required";
        $requiredStar = "*";
      }
      
      $user_custom_value = Dap_UserCustomFields::loadUserCustomFieldsByCustomFieldId($custom['id'], $userId);
      $value = "";
      
      if ($user_custom_value) {
        foreach ($user_custom_value as $val) {
          //logToFile("val=" . $val['custom_value']);
          $value = $val['custom_value'];
        }
      }
       
      
      if($custom['field_type'] == "textarea"){
		  $mycustom_tmp_fields_profile_content = '<li>
				<label class="form_text">[CUSTOM_FIELD_LABEL][REQUIREDSTAR]</label>
				<textarea class="form_setting" realname="[CUSTOM_FIELD_LABEL]" [REQUIRED] name="custom_[CUSTOM_FIELD_NAME]" id="custom_[CUSTOM_FIELD_NAME]"  cols="20" rows="6" >[CUSTOM_FIELD_VALUE]</textarea>
		</li>';
	  }else{
		$mycustom_tmp_fields_profile_content = '<li>
				<label class="form_text">[CUSTOM_FIELD_LABEL][REQUIREDSTAR]</label>
				<input class="form_setting" realname="[CUSTOM_FIELD_LABEL]" [REQUIRED] name="custom_[CUSTOM_FIELD_NAME]" type="text" id="custom_[CUSTOM_FIELD_NAME]" size="20" value="[CUSTOM_FIELD_VALUE]">
		</li>';
	  }
      $mycustom_tmp_fields_profile_content = str_replace( '[REQUIREDSTAR]', $requiredStar, $mycustom_tmp_fields_profile_content);
      $mycustom_tmp_fields_profile_content = str_replace( '[CUSTOM_FIELD_LABEL]', $custom['label'], $mycustom_tmp_fields_profile_content);  
      $mycustom_tmp_fields_profile_content = str_replace( '[CUSTOM_FIELD_NAME]', $custom["name"], $mycustom_tmp_fields_profile_content); 
      $mycustom_tmp_fields_profile_content = str_replace( '[CUSTOM_FIELD_VALUE]', $value, $mycustom_tmp_fields_profile_content); 
      $mycustom_tmp_fields_profile_content = str_replace( '[REQUIRED]', $required, $mycustom_tmp_fields_profile_content); 
      
      
      
      $custom_fields_content.=$mycustom_tmp_fields_profile_content;
      } // end if in_array
    } //end foreach 
  }
  $myprofile_content = str_replace( '[CUSTOM_FIELDS]',$custom_fields_content, $myprofile_content); 

/******GDPR DATA starts*********/
$ip = $_SERVER['REMOTE_ADDR'];
$user_consent = $user->getGDPRConsent();
$gdpr_compliance_date = $user->getGDPRCompliance_date();
$current_date = date('Y-m-d h:i:s'); 
$gdprcountry = dapGetGDPRStatus($ip);

$okbuttontext="OK";
if( defined('ALERT_MESSAGE_FOR_OK_BUTTON') ) 
	$okbuttontext = ALERT_MESSAGE_FOR_OK_BUTTON;

$cancelbuttontext="CANCEL";
if( defined('ALERT_MESSAGE_FOR_CANCEL_BUTTON') )
	$cancelbuttontext = ALERT_MESSAGE_FOR_CANCEL_BUTTON;

if($allowgdpr == "Y"){
	  logToFile("DAP-ShortCodes-MyProfile:allowgdpr=" . $allowgdpr,LOG_INFO_DAP);
	  
  if($gdprcountry == 1){
	   logToFile("DAP-ShortCodes-MyProfile:gdprcountry=" . $gdprcountry,LOG_INFO_DAP);
	   
   $myjquerycodegdpr = "<script>
    jQuery(document).ready(function(){
      jQuery('#dapprofile-container').find('.editable_textarea').attr('contenteditable', false);
      jQuery('#dapprofile-container').find('.gdpr_checkbox').attr('disabled', false);
      jQuery('#dapprofile-container').find('.gdpr_checkbox').removeAttr('disabled');
      var form = document.MyProfileForm;

     var user_consent = '".$user_consent."';
      var current_date = '".$current_date."';
       var gdpr_compliance_date = '".$gdpr_compliance_date."';
      if(user_consent == 'GDPR_CONSENT_YES'){
        jQuery('#dapprofile-container').find('.gdpr_checkbox').attr('checked', true);
         jQuery('#gdpr_compliance_date').val(gdpr_compliance_date);
     }else{
        jQuery('#dapprofile-container').find('.gdpr_checkbox').attr('checked', false);
         jQuery('#gdpr_compliance_date').val(gdpr_compliance_date);
     }

    jQuery('.gdpr_checkbox').change(function() {
      if (this.checked == true) {
          jQuery('#gdpr_consent').val('GDPR_CONSENT_YES');
          jQuery('#gdpr_compliance_date').val(current_date);
      }else{
         jQuery('#gdpr_consent').val('GDPR_CONSENT_NO');
          jQuery('#gdpr_compliance_date').val(current_date);
      }
    });

     jQuery('#button_edit_user').on('click', function(){
         var gdpr_check = jQuery('.gdpr_checkbox').prop('checked');
          var gdprconfirmation = '".$gdpr_confirmation."';
          var okbuttontext = '".$okbuttontext."';
          var cancelbuttontext = '".$cancelbuttontext."';
           
         if (gdprconfirmation == '' || gdprconfirmation == 'undefined'  || gdprconfirmation == 'null') {
           jQuery('#gdpr_consent').val('GDPR_CONSENT_NO');
            jQuery('#gdpr_compliance_date').val(current_date);
            updateUser(form); 
          }else{
             if (gdpr_check != true) {
               swal({
                    title: '',
                    text: '".$gdpr_confirmation."',
                    confirmButtonText: okbuttontext,
                    showCancelButton: true,
                     cancelButtonText: cancelbuttontext,
                  },
                  function(isConfirm){

                     if (isConfirm) {
                          setTimeout(function() {
                             jQuery('#gdpr_consent').val('GDPR_CONSENT_NO');
                              jQuery('#gdpr_compliance_date').val(current_date);
                             updateUser(form); 
                          }, 'slow');
                    }else{
                       return false;
                    }
                  });
                  return false;
            }
          }


      }); 
    });
    </script>";
	
	logToFile("DAP-ShortCodes-MyProfile:GDPR_ALLOW",LOG_INFO_DAP);
	 
    $myprofile_content = str_replace( '[GDPR_ALLOW]',"display:block", $myprofile_content); 
    $myprofile_content = str_replace( '[GDPR_TERM_LABEL]',$gdpr_label, $myprofile_content); 
    $myprofile_content = str_replace( '[GDPR_TERM_DATA]',htmlspecialchars_decode($gdprouter), $myprofile_content); 

  }else{
    $myjquerycodegdpr = "<script>
    jQuery(document).ready(function(){
      jQuery('#button_edit_user').on('click', function(){
        jQuery('#gdpr_consent').val('NOT_GDPR_USER');
         jQuery('#gdpr_compliance_date').val('');
      }); 
    });
    </script>";

    $myprofile_content = str_replace( '[GDPR_ALLOW]',"display:none", $myprofile_content); 
  }
}else{
  $myprofile_content = str_replace( '[GDPR_ALLOW]',"display:none", $myprofile_content); 
}


/******GDPR DATA ends*********/
 add_action( 'wp_enqueue_scripts', 'addMyProfileJS' ); 
  $myprofile_content = str_replace( '[BUTTON_UPDATE_TEXT]',BUTTON_UPDATE, $myprofile_content); 
  $myprofile_content = str_replace( '[REDIRECT]',$redirectTo, $myprofile_content); 
  $myprofile_content .= MSG_REQUIRED_FIELD;
  $myjquerycode = "<script>
  jQuery(document).ready(function(){
    for(var i =0;i < (ShownElements.length);i++){
      jQuery(ShownElements[i]).removeAttr('style');
    }
    
  });
  </script>";
 /****Add JS/CSS*******/
	add_action( 'wp_enqueue_scripts', 'addMyProfileJS' ); 
	$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'] : "http://".$_SERVER['SERVER_NAME'];  		
		
	$scriptstylenew = 	"<script type='text/javascript' src='". $url."/dap/javascript/ajaxWrapper.js'></script>
		<script type='text/javascript' src='". $url."/dap/javascript/common.js'></script> 
		<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js'></script> 
		<link rel='stylesheet' href='". plugin_dir_url(__FILE__)."includes/css/sweetalert.min.css' type='text/css' media='all' />
		<script type='text/javascript' src='". $url."/dap/javascript/UserProfileShortcode.js'></script>";
	   
 
  return $scriptstylenew.$myprofile_content.$scriptvar.$jqueryForResponsive.$myjquerycode.$myjquerycodegdpr;
}

function getMyProfileTemplateContent($template_path, $profileTemplateName, $customProfileTemplateName)
{
  if(file_exists($template_path.$customProfileTemplateName)) {
    $myprofile_template_content = file_get_contents($template_path.$customProfileTemplateName);
  }
  
  if($myprofile_template_content == "") {
    if(file_exists($template_path.$profileTemplateName)) {
      $myprofile_template_content = file_get_contents($template_path.$profileTemplateName);
    }
    else{
      $myprofile_template_content = "";
    }
  
   // logToFile("DAP-ShortCodes-Transactions: no custom template found=".$template_path.$profileTemplateName,LOG_INFO_DAP);
  } else {
    //logToFile("DAP-ShortCodes-Transactions: custom template found=".$template_path.$customProfileTemplateName,LOG_INFO_DAP);  
  } 

  return $myprofile_template_content;
  
}



function addMyProfileJS() { 
		$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'] : "http://".$_SERVER['SERVER_NAME'];  
		wp_register_script('dap-ajaxWrapper', $url . '/dap/javascript/ajaxWrapper.js');
		wp_register_script('dap-common', $url . '/dap/javascript/common.js');
		wp_register_script('jquery-swal-min', '//cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js');   

		wp_register_style( 'googleapis.css', 'http://fonts.googleapis.com/css?family=Lato', false, '1.0.0' ); 

		wp_enqueue_script( 'ajaxWrapper' );
		wp_enqueue_script( 'dap-common' );
		wp_enqueue_script( 'dap-MyProfile' );
		wp_enqueue_script( 'jquery-swal-min' );
		wp_register_style( 'sweetalert.min.css', plugin_dir_url(__FILE__). 'includes/css/sweetalert.min.css', false, '1.0.0' ); 
		wp_enqueue_style( 'sweetalert.min.css' );

}



function dap_affiliate_detailsshortcode(){ 
	
	$lldocroot = defined('SITEROOT') ? SITEROOT : $_SERVER['DOCUMENT_ROOT'];
	if(file_exists($lldocroot . "/dap/dap-config.php")) include_once ($lldocroot . "/dap/dap-config.php"); // dap config call
	
	
	ob_start();
	if(!Dap_Session::isLoggedIn()) {
		$output = mb_convert_encoding(MSG_PLS_LOGIN, "UTF-8", "auto") . " <a href=\"" . Dap_Config::get("LOGIN_URL") . "\">". mb_convert_encoding(MSG_CLICK_HERE_TO_LOGIN, "UTF-8", "auto") . "</a>";
	}
	else {
 		eval("?>" . file_get_contents($lldocroot . "/dap/inc/content/affiliatedetails.inc.php"));
		$output = ob_get_contents();
		ob_end_clean();
		  
	}
  
    return $content.$output;
}


 

function dap_loginform_permalinkshortcode($atts, $content=null){ 
   
    global $wpdb, $post, $table_prefix;
    if ($post->ID) {
        $current_postid = $post->ID;
        $post_id = get_post($current_postid);
        $permalink = get_permalink($post_id);
        //logToFile("_dapshoppingcart.php: dapshoppingcart_shortcode post permalink=".$permalink);
    }
	return $permalink;
	
}

function dap_loginformshortcode($atts, $content=null){ 
	extract(shortcode_atts(array(
		'redirect' => '',
		'template' => 'template6',
		'forgotpasswordheading' => 'Forgot Your Password?',
		'forgotpasswordsubheading' => 'Enter your email address below and we will send you a link to reset your password.',
		'forgotpasswordemailplaceholder' => 'Email Address',
		'forgotpasswordbtntext' => 'Send reset link',
		'forgotpasswordbtnbg' => '#66b14c',
		'forgotpasswordmissingemail' => 'Sorry, no user found with the email address.',
		'forgotpasswordlinksent' => 'Please check your email shortly for a link to reset your password.',
		'resetpasswordheading' => 'Reset Your Password',
		'resetpasswordplaceholder' => 'Enter New Password',
		'reresetpasswordplaceholder' => 'Re-Enter Password',
		'resetpasswordbtntext' => 'Reset Password',
		'resetpasswordbtnbg' => '#66b14c',
		'resetpasswordsuccess' => 'Your Password has been reset.',
		'showcaptcha' => 'no',
		'gdprenabled' => '',
		'gdprredirecturl' => '',
		'forgotpasswordtext' => 'Forgot Password?',
	), $atts));

	if( defined('SITEROOT') ) 
		$lldocroot = SITEROOT;
	else 
		$lldocroot = $_SERVER['DOCUMENT_ROOT'];
	
	
	include_once ($lldocroot . "/dap/dap-config.php");	
	
	
	$content = do_shortcode(dap_clean_shortcode_content($content));	
	$permalink = do_shortcode(dap_loginform_permalinkshortcode($content));	

	unset($_SESSION['script_added']);
	$_SESSION['daploginform']="";
	unset($_SESSION['daploginform']);
	$_SESSION['gdprEnabled'] = $gdprenabled;
	$_SESSION['gdprRedirectURL'] = $gdprredirecturl;
	
//	logToFile("DAP-ShortCodes-LoginForm: session gdprenabled=".$_SESSION['gdprEnabled']);
//	logToFile("DAP-ShortCodes-LoginForm: session gdprRedirectURL=".$_SESSION['gdprRedirectURL']);
	$session = Dap_Session::getSession();
	$signup_page = Dap_Config::get("SITE_URL_DAP");
	if ( isset($_GET['request']) && ($_GET['request'] != "") ) {
		//request is available in query string
		//logToFile("There's a request URL: " . $_GET['request']); 
		$redirectURL = $_GET['request'];
	} 
	else {
		if($redirect!="")
			$redirectURL=urldecode($redirect);	
	}
	//logToFile("DAP-ShortCodes-LoginForm: redirectURL=" .$redirectURL); 
	
	if(!Dap_Session::isLoggedIn()) { //Not logged in
		//logToFile("not logged in",LOG_DEBUG_DAP);
		$output = "";
		
		$loginFormFilepath = WP_PLUGIN_DIR . "/DAP-WP-LiveLinks/includes/login/templates/" . $template;
		
		if( file_exists($loginFormFilepath . "/custom" . $template . ".html") ) 
			$loginFormFileName = $loginFormFilepath . "/custom" . $template . ".html";
		else 
			$loginFormFileName = $loginFormFilepath . "/" . $template . ".html";

		//logToFile("loginFormFileName=$loginFormFileName",LOG_DEBUG_DAP);
		
		if(file_exists($loginFormFileName)) 
			$tempContent = file_get_contents($loginFormFileName);
	 	else {
			$errorHTML = mb_convert_encoding("Login Template Not Found", "UTF-8", "auto");
			return $errorHTML;	
		}
		
		$tempContent = str_replace( '%%REQUEST%%',$redirectURL, $tempContent); 
		$cssurl=get_option('siteurl')."/wp-content/plugins/DAP-WP-LiveLinks/includes/login/templates/".$template;	
		$csspath=WP_PLUGIN_DIR."/DAP-WP-LiveLinks/includes/login/templates/".$template;	
		
		if( file_exists($csspath . "/customstyle.css") ) 
			$cssurl = $cssurl . "/customstyle.css";
		else 
			$cssurl = $cssurl . "/style.css";
		
		$tempContent = str_replace( '[CSSURL]',$cssurl, $tempContent); 
		
	
		if( isset($_GET['msg']) ) {
			$msg = mb_convert_encoding(stripslashes($_GET['msg']), "UTF-8", "auto");
			if( !empty($_GET['msg']) ) {
					$tempContent .= "<style>#errorText, #errorText label{display:block;}</style>"; 
			}
		}
 
		$tempContent = str_replace( '%%ERRORTEXT%%', $msg, $tempContent); 
	

		if(!empty($forgotpasswordheading)){
			$tempContent = str_replace( '%%FORGOTPASSWORDHEADING%%', $forgotpasswordheading, $tempContent); 
		}
		if(!empty($forgotpasswordsubheading)){
			$tempContent = str_replace( '%%FORGOTPASSWORDSUBHEADING%%', $forgotpasswordsubheading, $tempContent); 
		}
		if(!empty($forgotpasswordemailplaceholder)){
			$tempContent = str_replace( '%%EMAILADDRESS%%', $forgotpasswordemailplaceholder, $tempContent); 
		}
		if(!empty($forgotpasswordbtntext)){
			$tempContent = str_replace( '%%SENDRESETLINK%%', $forgotpasswordbtntext, $tempContent); 
		}
		if(!empty($forgotpasswordbtnbg)){
			$tempContent = str_replace( '%%SENDRESETBGCOLOR%%', $forgotpasswordbtnbg, $tempContent); 
		}
		if(!empty($forgotpasswordmissingemail)){
			$tempContent = str_replace( '%%MISSINGEMAIL%%', $forgotpasswordmissingemail, $tempContent); 
		}
		if(!empty($forgotpasswordlinksent)){
			$tempContent = str_replace( '%%PASSWORDSENDLINK%%', $forgotpasswordlinksent, $tempContent); 
		}
		if(!empty($resetpasswordheading)){
			$tempContent = str_replace( '%%RESETYOURPASSWORD%%', $resetpasswordheading, $tempContent); 
		}
		if(!empty($resetpasswordplaceholder)){
			$tempContent = str_replace( '%%NEWRESETPASSWORD%%', $resetpasswordplaceholder, $tempContent); 
		}
		if(!empty($reresetpasswordplaceholder)){
			$tempContent = str_replace( '%%REENTERRESETPASSWORD%%', $reresetpasswordplaceholder, $tempContent); 
		}
		if(!empty($resetpasswordbtntext)){
			$tempContent = str_replace( '%%RESETPASSWORDBTNTEXT%%', $resetpasswordbtntext, $tempContent); 
		}
		if(!empty($resetpasswordbtnbg)){
			$tempContent = str_replace( '%%RESETPASSWORDBTNBG%%', $resetpasswordbtnbg, $tempContent); 
		}
		if(!empty($resetpasswordsuccess)){
			$tempContent = str_replace( '%%PASSWORDRESETSUCCESS%%', $resetpasswordsuccess, $tempContent); 
		}
		if(!empty($forgotpasswordtext)){
			$tempContent = str_replace( '%%FORGOTPASSWORDTEXT%%', $forgotpasswordtext, $tempContent); 
		}
		$getemailifkeyexist = Dap_User::getkeyDetails($_GET['key']);
		//$getemailifkeyexist = Dap_User::getkeyDetails($_GET['key']);
		
		
		if( isset($_GET['key']) ) {
			$tempContent = str_replace( '%%SHOWHIDEMEMBERLOGIN%%', "none", $tempContent); 
		}else{
			$tempContent = str_replace( '%%SHOWHIDEMEMBERLOGIN%%', "block", $tempContent); 
		}
		
		if( isset($_GET['key']) ) {
			
			$getemailifkeyexist = Dap_User::getkeyDetails($_GET['key']);
			
			if(!empty($getemailifkeyexist)){
				$tempContent = str_replace( '%%SHOWHIDERESETPASS%%', "block", $tempContent); 
			}else{
				$tempContent = str_replace( '%%SHOWHIDERESETPASS%%', "none", $tempContent); 
			}

		}else{
			$tempContent = str_replace( '%%SHOWHIDERESETPASS%%', "none", $tempContent); 
		}
		/********Add common  scripts*********/
       // add_action('wp_footer','mylogin_jquery');

		/*** Added For captacha  starts**/
		$google_site_key=Dap_Config::get("GOOGLE_SITE_KEY");
		$flength = 5;
		$rand_lid =  substr(str_shuffle(md5(time())),0,$flength);
		$tempContent =  str_replace( '%%LOGINTEMPLATEID%%','loginformtempid'.$rand_lid, $tempContent);
		$tempContent =  str_replace( '%%LOGINFORMID%%','loginform'.$rand_lid, $tempContent);
		$includecss = '<link rel="stylesheet" type="text/css" href="' . WP_PLUGIN_URL.'/DAP-WP-LiveLinks/includes/css/dap-loginform.css?2" />';
		if($showcaptcha =="yes"){
			if(!empty($google_site_key)){

				/*add_action('wp_footer','mylogin_commonstyle');
				add_action('wp_footer','mylogin_stylescripts');*/
				
				if(defined('INCLUDE_LOGIN_JS')) {
					$includejs =  '';
				} else { 
					$includejs =  '<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>';
				}   
				
				$includecssandjs =  ' 
				<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
				<script type="text/javascript" src="'.WP_PLUGIN_URL.'/DAP-WP-LiveLinks/includes/js/loginform_captcha.js?21"></script>
				<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css" /> 
				';
				
				$tempContent =  str_replace( '%%SHOWHIDEFORGOOGLESITEKEY%%','', $tempContent);
				
				/*if($template == "sidebar1" || $template == "sidebar2"){
					$tempContent = str_replace( '%%VALIDATELOGINFORM%%','onSubmit="validateWWithCaptcha(document.loginFormW); return false;"', $tempContent);
					$tempContent = str_replace( '%%VALIDATELOGINFORMBUTTON%%','validateWWithCaptcha(this.form);return false;', $tempContent);
					$tempContent = str_replace( '%%GOOGLECAPTCHA%%','<div class="frontend_captcha_login" id="sidecap_'.$rand_lid.'" data-sitekey="'.$google_site_key.'" data-id="sidecaptt_'.$rand_lid.'"   style="display:block"></div>', $tempContent);
				}else{*/
					$tempContent = str_replace( '%%VALIDATELOGINFORM%%','validateDAPLoginFormWithCaptcha(document.loginFormLoginForm); return false;', $tempContent);
					$tempContent = str_replace( '%%VALIDATELOGINFORMBUTTON%%','validateDAPLoginFormWithCaptcha(this.form);return false;', $tempContent);
					$tempContent = str_replace( '%%GOOGLECAPTCHA%%','<div class="frontend_captcha_login" id="cap_'.$rand_lid.'" data-sitekey="'.$google_site_key.'" data-id="captt_'.$rand_lid.'"   style="display:block"></div>', $tempContent);
				/*}*/
				$tempContent = str_replace( '%%CAPTCHAVAL%%','yes', $tempContent);
				$tempContent = str_replace( '%%CAPTCHAMSG%%','<input type="hidden" name="captchamsg" class="captcha_msg" value="'.mb_convert_encoding(PLEASE_SELECT_CAPTCHA, "UTF-8", "auto").'">', $tempContent);
				   
				if(!isset($_SESSION['script_added'])){
					
   					?>
					<script src="https://www.google.com/recaptcha/api.js?onload=dapCallBack&render=explicit" async defer></script>
					<script>
				
						var dapCallBack = function() {							
							jQuery('.frontend_captcha_login').each(function(index, el) {
								if(jQuery(this).is(':empty')){
									var widgetId = grecaptcha.render(el, {'sitekey' : '<?php echo $google_site_key ;?>'});
									jQuery(this).attr('data-id', widgetId);
									grecaptcha.reset(widgetId);
								}
																
							}); 
						};
						dapCallBack();
					
					</script>
					<?php
					$_SESSION['script_added'] = 'Y';
				}
			}else{
				$tempContent =  str_replace( '%%SHOWHIDEFORGOOGLESITEKEY%%','<div class="error_empty_capcha">ERROR: Google Captcha Site key is Empty.</div>', $tempContent);
				$tempContent = str_replace( '%%CAPTCHAMSG%%','', $tempContent);
				$tempContent = str_replace( '%%GOOGLECAPTCHA%%','', $tempContent);
			}
		}else{
			$tempContent =  str_replace( '%%SHOWHIDEFORGOOGLESITEKEY%%','', $tempContent);
			
			/*if($template == "sidebar1" || $template == "sidebar2"){
				$tempContent = str_replace( '%%VALIDATELOGINFORM%%','onSubmit="validateW(document.loginFormW); return false;"', $tempContent);
				$tempContent = str_replace( '%%VALIDATELOGINFORMBUTTON%%','validateW(this.form);return false;', $tempContent);
			}else{*/
				$tempContent = str_replace( '%%VALIDATELOGINFORM%%','validateDAPLoginForm(document.loginFormLoginForm); return false;', $tempContent);
				$tempContent = str_replace( '%%VALIDATELOGINFORMBUTTON%%','validateDAPLoginForm(this.form);return false;', $tempContent);
			/*}*/
			
			$tempContent = str_replace( '%%GOOGLECAPTCHA%%','', $tempContent);
			$tempContent = str_replace( '%%CAPTCHAVAL%%','no', $tempContent);
			$tempContent = str_replace( '%%CAPTCHAMSG%%','', $tempContent);
		}
		/*** Added For captacha  ends**/
	 
		/*** Added For Client site issue with optimizepress menus are not clickable for not logged in **/
		$script_op = '<script>jQuery(".op-navbar li  a, .op-navbar a.navbar-brand").on("click", function(){
			var href_li = jQuery(this).attr("href");
			window.location.href = href_li;
			});
			jQuery("html, body").animate({ scrollTop: 0 }, "slow");	
</script>';

		//For CS login
		$_SESSION["daploginform"]="yes";		

		$tempContentAll  = $tempContent.$includejs.$includecssandjs.$includecss.$script_op ;
 
		return $tempContentAll; exit;
	} //End Not Logged In
	
	else if(Dap_Session::isLoggedIn()) {
		//Check if there is a request uri
		//logToFile("loggedIn",LOG_DEBUG_DAP);
		$msg = "";
		$session = DAP_Session::getSession();
		$user = $session->getUser();		
		//ob_end_clean();
		
		
		if(strstr($template,"sidebar")) {
			$logoutHTMLFilepath = "/DAP-WP-LiveLinks/includes/logout/logout.html";
			if( file_exists(WP_PLUGIN_DIR . "/DAP-WP-LiveLinks/includes/logout/customlogout.html") ) {
				$logoutHTMLFilepath = "/DAP-WP-LiveLinks/includes/logout/customlogout.html";
			}
			
			$output = file_get_contents(WP_PLUGIN_DIR . $logoutHTMLFilepath);
			return $output;	
		}
	
		if ( isset($_GET['request']) && ($_GET['request'] != "") ) {
		//request is available in query string
		//logToFile("There's a request URL: " . $_GET['request']); 
			$redirectURL = $_GET['request'];
		} 
		else if ($redirect!="") {
			$redirectURL=urldecode($redirect);	
		}
		else 
			$redirectURL = Dap_UsersProducts::getLoggedInURL();
		
		//@header("Location:".$redirectURL);
		
		$output = "[" . MSG_ALREADY_LOGGEDIN_1 . " <a href='" . $redirectURL . "'>" . MSG_ALREADY_LOGGEDIN_2 . "</a>]<br/><br/>";
		
		if( $session->isAdmin() ) {
			$output = $output . ">>> <a href='/dap/admin/'>You are logged in as DAP Admin. Proceed to DAP Admin Dashboard</a> <<< <br/><br/>";
		}
		else if($user->getAccount_type() == "C" && $user->getCustom_role_id() != ""){
			try{
				$role = Dap_UserRoles::loadRoleById($user->getCustom_role_id());
				if(isset($role) && $role != "")
					$output = $output . ">>> <a href='/dap/admin/'>You are logged in as ".$role['name'].". Click here to proceed</a> <<< <br/><br/>";
			}
			catch(Exception $e){
				logToFile('DAP-Shortcodes-LoginForm.php: Cant get the role details');
			}
			
		}
		
		//$output = mb_convert_encoding($output, "UTF-8", "auto");
		
		if( isset($_GET['msg']) ) {
			//$msg = mb_convert_encoding($msg, "UTF-8", "auto");
			$output = "<div class='confirmationMessage'>" . stripslashes($_GET['msg']) . "</div><br/><br/>" . $output;
		}
		
		if( isset($_GET['request']) && ($_GET['request'] != "") ) {
			$permalink = $_GET['request'];
			//logToFile("permalink: " . $permalink); 
			
			$salesPageURL = Dap_Config::get("SALES_PAGE_URL"); //global SPU
			if($salesPageURL == "") $salesPageURL = "/";


			$errorHTMLPath = $lldocroot . "/dap/inc/error-loggedin.php";
			//Check for custom error page
			if( file_exists($lldocroot . "/dap/inc/customerror-loggedin.php") ) {
				$errorHTMLPath = $lldocroot . "/dap/inc/customerror-loggedin.php";
			}
			
			//$productCount = $user->hasAccessToHowManyDistinctProducts();
			//$permalink = str_replace( $_SERVER['REQUEST_QUERY'], '', $_SERVER['REQUEST_URI'] );
			//logToFile("permalink: " . $permalink); 
			//logToFile($_SERVER['REQUEST_QUERY']); 
			//logToFile($_SERVER['REQUEST_URI']); 
			$productCount = Dap_Product::isPartOfHowManyDistinctProducts($permalink);
			//logToFile("productCount: $productCount");
			if( $productCount == 1 ) {
				$product = Dap_Product::getProductDetailsByResource($permalink);
				if(!is_null($product) && isset($product)) {
					if ($product->getSales_page_url() != "") {
						$salesPageURL = $product->getSales_page_url();
					}
					if ($product->getLogged_in_url() != "") {
						$loggedInURL = $product->getLogged_in_url();
					}
				}
			}
			$output2 = replaceFillers($errorHTMLPath,"%%LOGIN_URL%%",Dap_Config::get("LOGIN_URL"));
			$output2 = str_replace("%%SALES_PAGE_URL%%",$salesPageURL,$output2);
			//logToFile("About to return");
			
			$output = $output2 . "<br/><br/>" . $output;
		}
		
		return $output;  
		exit;
	}
	
	

}


/******* get template  ********/    
function getDripTemplateDAPLoginFormContent($template_path, $courseTemplateName, $customCourseTemplateName)
{
	
	if(file_exists($template_path.$customCourseTemplateName)) {
	  $course_temp_content = file_get_contents($template_path.$customCourseTemplateName);
	}
	
	if($course_temp_content == "") {
		if(file_exists($template_path.$courseTemplateName)) {
			$course_temp_content = file_get_contents($template_path.$courseTemplateName);
		}
		else{
			$course_temp_content = "";
		}
	  
		logToFile("DAP-Loginform: no custom template found=".$template_path.$courseTemplateName,LOG_INFO_DAP);
	} else {
		logToFile("DAP-Loginform: custom template found=".$template_path.$customCourseTemplateName,LOG_INFO_DAP);  
	}	
	
	return $course_temp_content; 
	
}
 /******* include js and css ********/
 function mylogin_jquery(){  
    	wp_enqueue_script('dap-jquery-min', '//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
} 	
function mylogin_stylescripts(){
	wp_enqueue_style('validateform-sweet', '//cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css');
	wp_enqueue_script('validateform-min-sweet', '//cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js');
	wp_enqueue_script('login-form-js',  WP_PLUGIN_URL.'/DAP-WP-LiveLinks/includes/js/loginform_captcha.js?21');
}

function mylogin_commonstyle(){
	wp_enqueue_style('commom-login-form-css',  WP_PLUGIN_URL.'/DAP-WP-LiveLinks/includes/css/dap-loginform.css?1');
}

function dap_displaytransactionsshortcode($atts, $content=null){ 
  extract(shortcode_atts(array(
	  'template' =>'template1',
	  'invoicetemplate'=>'template1',
	  'adminemail'=>'',
	  'companyname'=>'',
	  'companyurl'=>'',
	  'logo'=>'',		
	  'notranmsg'=>'Sorry, no transactions found',
	  'showinvoice' =>'Y'
  ), $atts));
  
  $content = do_shortcode(dap_clean_shortcode_content($content));		
  
  $session = Dap_Session::getSession();
  $user = $session->getUser();
  if($adminemail=='')
  {
 	 $adminemail = Dap_Config::get("ADMIN_EMAIL");
  }
  if($companyname=='')
  {
  	$companyname = Dap_Config::get("SITE_URL_DAP"); 
  }
  $frontendCommoncss =  $blogpath . "/wp-content/plugins/DAP-WP-LiveLinks/includes/css/dap_member_frontend_common.css";
	  echo '<link rel="stylesheet" type="text/css" href="' . $frontendCommoncss . '" />';
  if( !Dap_Session::isLoggedIn() || !isset($user) ) {
	  //logToFile("Not logged in, returning errmsgtemplate");
	  $errorHTML = mb_convert_encoding(MSG_PLS_LOGIN, "UTF-8", "auto") . " <a class='dap_not_loggedin_link' href=\"" . Dap_Config::get("LOGIN_URL") . "\">". mb_convert_encoding(MSG_CLICK_HERE_TO_LOGIN, "UTF-8", "auto") . "</a>";
	  return $errorHTML;
  }

  $userId = $user->getId();
  $blogpath=get_option("siteurl");
  
  $fullcustomcss =  WP_PLUGIN_DIR . "/DAP-WP-LiveLinks/includes/transactions/".$template."/css/customtransactiontemplate.css";   
  $bootstrapmin4css =  $blogpath . "/wp-content/plugins/DAP-WP-LiveLinks/includes/css/bootstrap4.min.css"; 
  $customcss=get_option('siteurl')."/wp-content/plugins/DAP-WP-LiveLinks/includes/transactions/".$template."/css/customtransactiontemplate.css";
  $fcss = parse_url($customcss);
  $customcss=$fcss["path"];
   
  $formcss=get_option('siteurl')."/wp-content/plugins/DAP-WP-LiveLinks/includes/transactions/".$template."/css/transactiontemplate.css";
  $fcss = parse_url($formcss);
  $formcss=$fcss["path"];
 // logToFile("DAP-ShortCodes-Transactions: formcss= ". $formcss); 
  
  if($logo == "") 
  	$logo=get_option('siteurl')."/wp-content/plugins/DAP-WP-LiveLinks/includes/transactions/invoices/" . $template . "/images/invoice_logo.jpg";
	
  if(file_exists($fullcustomcss)) {
	 $formcss=$customcss;
//	 logToFile("DAP-ShortCodes-Transactions: custom css: ". $customcss);
  }
  
  $content .= '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  <script>
  function invoicepdf( formname, prodId,invoicetemplate,adminemail,companyname,currency,status,email,fname,lname,address1,city,state,zip,country, amount,  paymentProcessor,recurringId,transactionId,logo,tdate,blogpath) {

	var submiturl="'.get_option("siteurl").'/wp-content/plugins/DAP-WP-LiveLinks/includes/tcpdf/data/converter.php";
	var url = "'.get_option("siteurl").'/wp-content/plugins/DAP-WP-LiveLinks/includes/tcpdf/data/converter.php?productId="+prodId+"&invoicetemplate="+invoicetemplate+"&currency="+currency+"&amount="+amount+"&ptype="+paymentProcessor+"&transactionId="+transactionId+"&tdate="+tdate+"&logo="+logo+"&email="+email+"&fname="+fname+"&lname="+lname+"&address1="+address1+"&city="+city+"&state="+state+"&zip="+zip+"&country="+country+"&companyname="+companyname;

   
	jQuery("body").append("<form action='.''.get_option("siteurl").'/wp-content/plugins/DAP-WP-LiveLinks/includes/tcpdf/data/converter.php'.' method='.'post'.' name='.'mform'.' target='.'_blank'.'>");
  
    jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'productId'.' value='.'"+prodId+"'.'>");
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'invoicetemplate'.' value='.'"+invoicetemplate+"'.'>");
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'currency'.' value='.'"+currency+"'.'>");
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'amount'.' value='.'"+amount+"'.'>");
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'ptype'.' value='.'"+paymentProcessor+"'.'>");
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'tdate'.' value='.'"+tdate+"'.'>");
    jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'transactionId'.' value='.'"+transactionId+"'.'>");
    jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'logo'.' value='.'"+logo+"'.'>");
    jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'email'.' value='.'"+email+"'.'>");  
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'fname'.' value='.'"+fname+"'.'>");  
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'lname'.' value='.'"+lname+"'.'>");  		
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'address1'.' value='.'"+address1+"'.'>"); 	
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'city'.' value='.'"+city+"'.'>");  
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'state'.' value='.'"+state+"'.'>"); 	
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'zip'.' value='.'"+zip+"'.'>");  	
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'country'.' value='.'"+country+"'.'>");   
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'companyname'.' value='.'"+companyname+"'.'>");  
	jQuery("form[name='.'mform'.']").submit();
	
	jQuery("form[name='.'mform'.']").remove();
	return false;
	window.open(url);		 
	return;
  }
  </script>';
   $cssvar ="";
  $cssvar .= "<style>
	@media (max-width:479px){
		.table-responsive{ overflow:auto; width:100%}
	}
		.op3-element[data-op3-element-type=treemenu] .op3-treemenu-content>[data-op3-children],
.op3-element[data-op3-element-type=column]>.op3-column-content{
    
    height:auto !important;
}
</style>";

  $content .= '<link rel="stylesheet" type="text/css" href="' . $formcss . '?v=7" />';
  $content .= '<link rel="stylesheet" type="text/css" href="' . $bootstrapmin4css . '" />';
  $content .= '<div class="table-responsive live-links-bootstrap_outer"><div id="wrapper1">';
  $content .= '<form name="formshowtrans" id="formshowtrans">';
  
  $lldocroot = defined('SITEROOT') ? SITEROOT : $_SERVER['DOCUMENT_ROOT'];
  $template_headerpath= ABSPATH ."/wp-content/plugins/DAP-WP-LiveLinks/includes/transactions/".$template."/customtransactionHeaderTemplate.html";
  
  if(file_exists($template_headerpath)) {
  	$temp_headercontent = file_get_contents($template_headerpath);
  }
  
  if($temp_headercontent == "") {
  	$template_headerpath=ABSPATH . "/wp-content/plugins/DAP-WP-LiveLinks/includes/transactions/".$template."/transactionHeaderTemplate.html";
	 //logToFile("DAP-ShortCodes-Transactions: template_headerpath= ". $template_headerpath); 
	 
	if(file_exists($template_headerpath)) {
	  $temp_headercontent = file_get_contents($template_headerpath);
	  $content .= $temp_headercontent;   
	  if($showinvoice=='Y')
	  {
		// $content .= '<div class="cell-header-invoice">Invoice</div>';
	  } 
	 // $content .=  '</div>';
	}
	else{
		$temp_headercontent ='<div class="cell-header">Sorry template is not found</div>';
		$content .= $temp_headercontent;
	}
  	
	//logToFile("DAP-ShortCodes-Transactions: no custom header template found=".$template_headerpath,LOG_DEBUG_DAP);
  } else {
	//logToFile("DAP-ShortCodes-Transactions: custom headertemplate found=".$template_headerpath,LOG_DEBUG_DAP);  
  }
  
  $template_path=$ABSPATH . "/wp-content/plugins/DAP-WP-LiveLinks/includes/transactions/".$template."/customtransactionTemplate.html";
  if(file_exists($template_path)) {
	  $temp_content = file_get_contents($template_path);
  }
  
  if($temp_content == "") {
  	$template_path=ABSPATH . "/wp-content/plugins/DAP-WP-LiveLinks/includes/transactions/".$template."/transactionTemplate.html";
	if(file_exists($template_headerpath)) {
		$temp_content = file_get_contents($template_path);
	}
	else{
		$temp_content = "";
  	}
  	
//	logToFile("DAP-ShortCodes-Transactions: no custom template found=".$template_path,LOG_DEBUG_DAP);
  } else {
	//logToFile("DAP-ShortCodes-Transactions: custom template found=".$template_path,LOG_DEBUG_DAP);  
  }
  
  $emailFilter = $user->getEmail();
 
  logToFile("DAP-ShortCodes-Transactions: emailFilter=".$emailFilter,LOG_DEBUG_DAP);
 		
  $TransactionsList = Dap_Transactions::loadTransactions($transNumFilter, $emailFilter, $productIdFilter, $statusFilter);
  $recurring_id ="";
  $found=false;
  foreach ($TransactionsList as $transaction) {
	//logToFile("DAP-ShortCodes-Transactions: found transaction for emailFilter=".$emailFilter,LOG_DEBUG_DAP);
	parse_str($transaction->getTrans_blob(), $list);	  
	if($transaction->getTrans_type() == "subscr_signup") {
		continue;
	}
	$recurring_id="";
	if(array_key_exists('recurring_payment_id',$list)) {
		$recurring_id = $list["recurring_payment_id"];
	}
	else if(array_key_exists('subscr_id',$list)) {
		$recurring_id = $list["subscr_id"];
	}
	else if(array_key_exists('sub_id',$list)) {
		$recurring_id = $list["sub_id"];
	}
	
	$payment_processor = $transaction->getPayment_processor();
	$transaction_id=$transaction->getTrans_num();
	
	$newtrans=explode(':',$transaction_id);
	if($recurring_id=="")
		$recurring_id=$newtrans[0];
		
	$amount= $transaction->getPayment_value();
	$productId=$transaction->getProduct_id();
	$transDate=$transaction->getDate();
	$status=$transaction->getPayment_status();
	$currency=$transaction->getPayment_currency();
	
//	logToFile("DAP-ShortCodes-Transactions: productId=".$productId,LOG_DEBUG_DAP);
	 
	if( $productId != "") {
	  $product = Dap_Product::loadProduct($productId);  
	  $pname=$product->getName();
//	  logToFile("DAP-ShortCodes-Transactions: product name=".$pname,LOG_DEBUG_DAP);
	  $prodId=$product->getId();
	  $email=$user->getEmail();
	  $fname=$user->getFirst_name();
	  $lname=$user->getLast_name();	  
	  $address1=urlencode($user->getAddress1());	  
	  $city=urlencode($user->getCity());	  
	  $state=urlencode($user->getState());	  
	  $zip=urlencode($user->getZip());	  
	  $country=urlencode($user->getCountry());
	  $desc=$product->getDescription();
	}
	
	$current_msg=$temp_content;
	
	$currencySymbols = LiveLinksGetCurrencySymbol();	
	
	if(isset($currencySymbols[$currency]) && $currencySymbols[$currency] != ''){
		$currency	 = $currencySymbols[$currency];
	}			
	
	if($currency == ''){
		$currency = trim(Dap_Config::get('CURRENCY_SYMBOL'));	
	}
		
	$current_msg = str_replace( '[FORMNAME]', "document.formshowtrans", $current_msg); 
	$current_msg = str_replace( '[AMOUNT]', $currency.$amount, $current_msg); 
	$current_msg = str_replace( '[ITEMNAME]', $product->getName(), $current_msg); 
	$current_msg = str_replace( '[DATE]', $transDate, $current_msg); 
	$current_msg = str_replace( '[CURRENCY]', $currency, $current_msg); 
	$current_msg = str_replace( '[PAYSTATUS]', $status, $current_msg); 
	$current_msg = str_replace( '[PAYMENTPROCESSOR]', $payment_processor, $current_msg); 
	$current_msg = str_replace( '[TRANSACTIONID]', $newtrans[0], $current_msg); 
	
	$_SESSION["invblogpath"]=ABSPATH;
	$_SESSION["invinvoicetemplate"]=$invoicetemplate;
	$_SESSION["templatepath"]= WP_PLUGIN_DIR;
	$_SESSION["invadminemail"]=$adminemail;
	$_SESSION["invcompanyname"]=$companyname;
	$_SESSION["invcompanyurl"]=$companyurl;
	$_SESSION["invemail"]=$email;
	$_SESSION["invfname"]=$fname;
	$_SESSION["invlname"]=$lname;
	$_SESSION["invaddress1"]=$address1;	
	$_SESSION["invcity"]=$city;	
	$_SESSION["invstate"]=$state;	
	$_SESSION["invzip"]=$zip;	
	$_SESSION["invcountry"]=$country;
	$_SESSION["invlogo"]=$logo;
	
	$_SESSION["invpid"]=$prodId;
	$_SESSION["invcurrency"]=$amount;
	$_SESSION["invamount"]=$currency;
	$_SESSION["incptype"]=$payment_processor;
	$_SESSION["invtid"]=$recurring_id;
	$_SESSION["invtdate"]=$transDate;
	
	if($showinvoice=='Y') {
	  $pdf = ' <td class="cell-left-center">';
	  $pdf .='<a href="" onclick="';
	  $pdf .="return invoicepdf(document.formshowtrans,'";
	    if($currency == '₹'){
			$currency = 'INR';
		} 
	 // $pdf .= urlencode(base64_encode($prodId))."','".urlencode(base64_encode($invoicetemplate))."','".urlencode(base64_encode($adminemail))."','".urlencode(base64_encode($companyname))."','".urlencode(base64_encode($currency))."','".urlencode(base64_encode($status))."','".urlencode(base64_encode($email))."','".urlencode(base64_encode($fname))."','".urlencode(base64_encode($lname))."','".urlencode(base64_encode($amount))."','".urlencode(base64_encode($payment_processor))."','".urlencode(base64_encode($recurring_id))."','".urlencode(base64_encode($newtrans[0]))."','".urlencode(base64_encode($logo))."','".urlencode(base64_encode($transDate))."','" . ABSPATH . "');";
	  $pdf .="$prodId','$invoicetemplate','$adminemail','$companyname','$currency','$status','$email','$fname','$lname','$address1','$city','$state','$zip','$country','$amount','$payment_processor','$recurring_id','$newtrans[0]','$logo','$transDate','" . ABSPATH . "');";
	  $pdf .='">View PDF</a>';
	  $pdf .='</td>';
	  $current_msg = str_replace( '[pdf]', $pdf, $current_msg); 
	}
	else
	{
		$pdf = '<td class="cell-left-center" style="display:none"></td>';
	  $current_msg = str_replace( '[pdf]', $pdf, $current_msg);
	}
		//$content .= $current_msg;	
	$found=true;
	$html .= $current_msg;
	
	//echo $tempcontent;die;
//	echo $content;die;
/*	$content .= $tempcontent;
/*$html .= $content;
	if($i++ == 4){
		break;
	}*/
  } //end foreach
  
	$html .=  DapMemberShowLoader(); 
  $content = str_replace( '[INVOICETABLEDATA]', $html, $content);
	if($showinvoice=='Y') {
		$content = str_replace( '[DISPLAYINVOICE]', 'display:table-cell' , $content);
	}else{
		$content = str_replace( '[DISPLAYINVOICE]', 'display:none' , $content);	
	}

  if(!$found) {
	// $content.=$notranmsg;
  }
 
  $content.='</form></div></div>';
  return $content.$cssvar;

}

function dap_displayInvoiceshortcode($atts, $content=null){ 
	  extract(shortcode_atts(array(
		  'id' =>'id',
	  ), $atts));
  
	$data = DAP_MemberPages::loadById($id);
	if(isset($data)){
		$invoicetemplate = $template = $data->getTemplate();	
	}	
	
  $adminemail = DAP_MemberPagesValues::loadByActionIdAndName($id,'admin_email');
	if(isset($adminemail)){
		$adminemail =  $adminemail->getValue();	
	}
  $page_template = DAP_MemberPagesValues::loadByActionIdAndName($id,'page_template');
	if(isset($page_template)){
		$page_template =  $page_template->getValue();	
	}
  $showinvoice = DAP_MemberPagesValues::loadByActionIdAndName($id,'view_invoice_link');
	if(isset($showinvoice)){
		$showinvoice =  $showinvoice->getValue();	
	}
  $companyname = DAP_MemberPagesValues::loadByActionIdAndName($id,'company_name');
	if(isset($companyname)){
		$companyname =  $companyname->getValue();	
	}
  $companyurl = DAP_MemberPagesValues::loadByActionIdAndName($id,'company_url');
	if(isset($companyurl)){
		$companyurl =  $companyurl->getValue();	
	}  
  $no_transaction_msg = DAP_MemberPagesValues::loadByActionIdAndName($id,'no_transaction_msg');
if(isset($no_transaction_msg)){
	$no_transaction_msg =  $no_transaction_msg->getValue();	
}   
  $logo = DAP_MemberPagesValues::loadByActionIdAndName($id,'logo');
if(isset($logo)){
	$logo =  $logo->getValue();	
}  
  $content = do_shortcode(dap_clean_shortcode_content($content));		
  
  $session = Dap_Session::getSession();
  $user = $session->getUser();
  if($adminemail=='')
  {
 	 $adminemail = Dap_Config::get("ADMIN_EMAIL");
  }
  if($companyname=='')
  {
  	$companyname = Dap_Config::get("SITE_URL_DAP"); 
  }
  $frontendCommoncss =  $blogpath . "/wp-content/plugins/DAP-WP-LiveLinks/includes/css/dap_member_frontend_common.css";
	  echo '<link rel="stylesheet" type="text/css" href="' . $frontendCommoncss . '" />';
  if( !Dap_Session::isLoggedIn() || !isset($user) ) {
	  //logToFile("Not logged in, returning errmsgtemplate");
	  $errorHTML = mb_convert_encoding(MSG_PLS_LOGIN, "UTF-8", "auto") . " <a class='dap_not_loggedin_link' href=\"" . Dap_Config::get("LOGIN_URL") . "\">". mb_convert_encoding(MSG_CLICK_HERE_TO_LOGIN, "UTF-8", "auto") . "</a>";
	  return $errorHTML;
  }

  $userId = $user->getId();
  $blogpath=get_option("siteurl");
  
  $fullcustomcss =  WP_PLUGIN_DIR . "/DAP-WP-LiveLinks/includes/transactions/".$template."/css/customtransactiontemplate.css";   
 // $frontendCommoncss =  $blogpath . "/wp-content/plugins/DAP-WP-LiveLinks/includes/css/dap_member_frontend_common.css";   
  $bootstrapmin4css =  $blogpath . "/wp-content/plugins/DAP-WP-LiveLinks/includes/css/bootstrap4.min.css";   
  $frontendCommonjs =  $blogpath . "/wp-content/plugins/DAP-WP-LiveLinks/includes/js/dap_member_frontend_common.js";   
  $customcss=get_option('siteurl')."/wp-content/plugins/DAP-WP-LiveLinks/includes/transactions/".$template."/css/customtransactiontemplate.css";
  $fcss = parse_url($customcss);
  $customcss=$fcss["path"];
   
  $formcss=get_option('siteurl')."/wp-content/plugins/DAP-WP-LiveLinks/includes/transactions/".$template."/css/transactiontemplate.css";
  $fcss = parse_url($formcss);
  $formcss=$fcss["path"];
 // logToFile("DAP-ShortCodes-Transactions: formcss= ". $formcss); 
  
  if($logo == "") 
  	$logo=get_option('siteurl')."/wp-content/plugins/DAP-WP-LiveLinks/includes/transactions/invoices/" . $template . "/images/invoice_logo.jpg";
	
  if(file_exists($fullcustomcss)) {
	 $formcss=$customcss;
//	 logToFile("DAP-ShortCodes-Transactions: custom css: ". $customcss);
  }
  
  if(!wp_script_is('jquery')) {
		$scriptstyle .=' <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>	';	
	}
  $content .= ' 
  <script src="'.$frontendCommonjs . '" type="text/javascript"></script>
  <script>
  function invoicepdf( formname, prodId,invoicetemplate,adminemail,companyname,currency,status,email,fname,lname,address1,city,state,zip,country, amount,  paymentProcessor,recurringId,transactionId,logo,tdate,blogpath) {

	var submiturl="'.get_option("siteurl").'/wp-content/plugins/DAP-WP-LiveLinks/includes/tcpdf/data/converter.php";
	var url = "'.get_option("siteurl").'/wp-content/plugins/DAP-WP-LiveLinks/includes/tcpdf/data/converter.php?productId="+prodId+"&invoicetemplate="+invoicetemplate+"&currency="+currency+"&amount="+amount+"&ptype="+paymentProcessor+"&transactionId="+transactionId+"&tdate="+tdate+"&logo="+logo+"&email="+email+"&fname="+fname+"&lname="+lname+"&address1="+address1+"&city="+city+"&state="+state+"&zip="+zip+"&country="+country+"&companyname="+companyname;

   
	jQuery("body").append("<form action='.''.get_option("siteurl").'/wp-content/plugins/DAP-WP-LiveLinks/includes/tcpdf/data/converter.php'.' method='.'post'.' name='.'mform'.' target='.'_blank'.'>");
  
    jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'productId'.' value='.'"+prodId+"'.'>");
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'invoicetemplate'.' value='.'"+invoicetemplate+"'.'>");
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'currency'.' value='.'"+currency+"'.'>");
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'amount'.' value='.'"+amount+"'.'>");
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'ptype'.' value='.'"+paymentProcessor+"'.'>");
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'tdate'.' value='.'"+tdate+"'.'>");
    jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'transactionId'.' value='.'"+transactionId+"'.'>");
    jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'logo'.' value='.'"+logo+"'.'>");
    jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'email'.' value='.'"+email+"'.'>");  
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'fname'.' value='.'"+fname+"'.'>");  
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'lname'.' value='.'"+lname+"'.'>");  		
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'address1'.' value='.'"+address1+"'.'>"); 	
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'city'.' value='.'"+city+"'.'>");  
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'state'.' value='.'"+state+"'.'>"); 	
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'zip'.' value='.'"+zip+"'.'>");  	
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'country'.' value='.'"+country+"'.'>");   
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'companyname'.' value='.'"+companyname+"'.'>");  
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'invoicetemplate'.' value='.'"+invoicetemplate+"'.'>");  
	jQuery("form[name='.'mform'.']").append("<input type='.'hidden'.' name='.'blogpath'.' value='.'"+blogpath+"'.'>");  
	jQuery("form[name='.'mform'.']").submit();
	
	jQuery("form[name='.'mform'.']").remove();
	return false;
	window.open(url);		 
	return;
  }
  </script>';
   $cssvar ="";
  $cssvar .= "<style>
			.op3-element[data-op3-element-type=treemenu] .op3-treemenu-content>[data-op3-children],
.op3-element[data-op3-element-type=column]>.op3-column-content{
    
    height:auto !important;
}
</style>";

  $content .= '<link rel="stylesheet" type="text/css" href="' . $formcss . '?v=2" />';
 // $content .= '<link rel="stylesheet" type="text/css" href="' . $frontendCommoncss . '" />';
  $content .= '<link rel="stylesheet" type="text/css" href="' . $bootstrapmin4css . '" />';
  $content .= '<div class="table-responsive live-links-bootstrap_outer"><div id="wrapper1">';
  $content .= '<form name="formshowtrans" id="formshowtrans">';
  
  $lldocroot = defined('SITEROOT') ? SITEROOT : $_SERVER['DOCUMENT_ROOT'];
  $template_headerpath= ABSPATH ."/wp-content/plugins/DAP-WP-LiveLinks/includes/transactions/".$template."/customtransactionHeaderTemplate.html";
  
  if(file_exists($template_headerpath)) {
  	$temp_headercontent = file_get_contents($template_headerpath);
  }
  
  if($temp_headercontent == "") {
  	$template_headerpath=ABSPATH . "/wp-content/plugins/DAP-WP-LiveLinks/includes/transactions/".$template."/transactionHeaderTemplate.html";
	 //logToFile("DAP-ShortCodes-Transactions: template_headerpath= ". $template_headerpath); 
	 
	if(file_exists($template_headerpath)) {
	  $temp_headercontent = file_get_contents($template_headerpath);
	  $content .= $temp_headercontent;   
	  if($showinvoice=='Y')
	  {
		// $content .= '<div class="cell-header-invoice">Invoice</div>';
	  } 
	  //$content .=  '</div>';
	}
	else{
		$temp_headercontent ='<div class="cell-header">Sorry template is not found</div>';
		$content .= $temp_headercontent;
	}
  	
	//logToFile("DAP-ShortCodes-Transactions: no custom header template found=".$template_headerpath,LOG_DEBUG_DAP);
  } else {
	//logToFile("DAP-ShortCodes-Transactions: custom headertemplate found=".$template_headerpath,LOG_DEBUG_DAP);  
  }
  
  $template_path=$ABSPATH . "/wp-content/plugins/DAP-WP-LiveLinks/includes/transactions/".$template."/customtransactionTemplate.html";
  if(file_exists($template_path)) {
	  $temp_content = file_get_contents($template_path);
  }
  
  if($temp_content == "") {
  	$template_path=ABSPATH . "/wp-content/plugins/DAP-WP-LiveLinks/includes/transactions/".$template."/transactionTemplate.html";
	if(file_exists($template_headerpath)) {
		$temp_content = file_get_contents($template_path);
	}
	else{
		$temp_content = "";
  	}
  	
//	logToFile("DAP-ShortCodes-Transactions: no custom template found=".$template_path,LOG_DEBUG_DAP);
  } else {
	//logToFile("DAP-ShortCodes-Transactions: custom template found=".$template_path,LOG_DEBUG_DAP);  
  }
  
  $emailFilter = $user->getEmail();
 
  logToFile("DAP-ShortCodes-Transactions: emailFilter=".$emailFilter,LOG_DEBUG_DAP);
 		
  $TransactionsList = Dap_Transactions::loadTransactions($transNumFilter, $emailFilter, $productIdFilter, $statusFilter);
  $recurring_id ="";
  $found=false;
  $html  = '';
  $i = 0;
  
  foreach ($TransactionsList as $transaction) {
	//logToFile("DAP-ShortCodes-Transactions: found transaction for emailFilter=".$emailFilter,LOG_DEBUG_DAP);
	parse_str($transaction->getTrans_blob(), $list);	  
	if($transaction->getTrans_type() == "subscr_signup") {
		continue;
	}
	$recurring_id="";
	if(array_key_exists('recurring_payment_id',$list)) {
		$recurring_id = $list["recurring_payment_id"];
	}
	else if(array_key_exists('subscr_id',$list)) {
		$recurring_id = $list["subscr_id"];
	}
	else if(array_key_exists('sub_id',$list)) {
		$recurring_id = $list["sub_id"];
	}
	
	$payment_processor = $transaction->getPayment_processor();
	$transaction_id=$transaction->getTrans_num();
	
	$newtrans=explode(':',$transaction_id);
	if($recurring_id=="")
		$recurring_id=$newtrans[0];
		
	$amount= $transaction->getPayment_value();
	$productId=$transaction->getProduct_id();
	$transDate=$transaction->getDate();
	$status=$transaction->getPayment_status();
	$currency=$transaction->getPayment_currency();
	
//	logToFile("DAP-ShortCodes-Transactions: productId=".$productId,LOG_DEBUG_DAP);
	 
	if( $productId != "") {
	  $product = Dap_Product::loadProduct($productId);  
	  $pname=$product->getName();
//	  logToFile("DAP-ShortCodes-Transactions: product name=".$pname,LOG_DEBUG_DAP);
	  $prodId=$product->getId();
	  $email=$user->getEmail();
	  $fname=$user->getFirst_name();
	  $lname=$user->getLast_name();	  
	  $address1=urlencode($user->getAddress1());	  
	  $city=urlencode($user->getCity());	  
	  $state=urlencode($user->getState());	  
	  $zip=urlencode($user->getZip());	  
	  $country=urlencode($user->getCountry());
	  $desc=$product->getDescription();
	}
	
	$current_msg=$temp_content;

	$currencySymbols = LiveLinksGetCurrencySymbol();	
	
	if(isset($currencySymbols[$currency]) && $currencySymbols[$currency] != ''){
		$currency	 = $currencySymbols[$currency];
	}			
	
	if($currency == ''){
		$currency = trim(Dap_Config::get('CURRENCY_SYMBOL'));	
	}
	
	$current_msg = str_replace( '[FORMNAME]', "document.formshowtrans", $current_msg); 
	$current_msg = str_replace( '[AMOUNT]', $currency.$amount, $current_msg); 
	$current_msg = str_replace( '[ITEMNAME]', $product->getName(), $current_msg); 
	$current_msg = str_replace( '[DATE]', $transDate, $current_msg); 
	$current_msg = str_replace( '[CURRENCY]', $currency, $current_msg); 
	$current_msg = str_replace( '[PAYSTATUS]', $status, $current_msg); 
	$current_msg = str_replace( '[PAYMENTPROCESSOR]', $payment_processor, $current_msg); 
	$current_msg = str_replace( '[TRANSACTIONID]', $newtrans[0], $current_msg); 
	
	$_SESSION["invblogpath"]=ABSPATH;
	$_SESSION["invinvoicetemplate"]=$invoicetemplate;
	$_SESSION["templatepath"]= WP_PLUGIN_DIR;
	$_SESSION["invadminemail"]=$adminemail;
	$_SESSION["invcompanyname"]=$companyname;
	$_SESSION["invcompanyurl"]=$companyurl;
	$_SESSION["invemail"]=$email;
	$_SESSION["invfname"]=$fname;
	$_SESSION["invlname"]=$lname;
	$_SESSION["invaddress1"]=$address1;	
	$_SESSION["invcity"]=$city;	
	$_SESSION["invstate"]=$state;	
	$_SESSION["invzip"]=$zip;	
	$_SESSION["invcountry"]=$country;
	$_SESSION["invlogo"]=$logo;
	
	$_SESSION["invpid"]=$prodId;
	$_SESSION["invcurrency"]=$amount;
	$_SESSION["invamount"]=$currency;
	$_SESSION["incptype"]=$payment_processor;
	$_SESSION["invtid"]=$recurring_id;
	$_SESSION["invtdate"]=$transDate;
	
	if($showinvoice=='Y') {
	  $pdf = ' <td class="cell-left-center">';
	  $pdf .='<a href="" onclick="';
	  $pdf .="return invoicepdf(document.formshowtrans,'";
	    if($currency == '₹'){
			$currency = 'INR';
		} 
	 // $pdf .= urlencode(base64_encode($prodId))."','".urlencode(base64_encode($invoicetemplate))."','".urlencode(base64_encode($adminemail))."','".urlencode(base64_encode($companyname))."','".urlencode(base64_encode($currency))."','".urlencode(base64_encode($status))."','".urlencode(base64_encode($email))."','".urlencode(base64_encode($fname))."','".urlencode(base64_encode($lname))."','".urlencode(base64_encode($amount))."','".urlencode(base64_encode($payment_processor))."','".urlencode(base64_encode($recurring_id))."','".urlencode(base64_encode($newtrans[0]))."','".urlencode(base64_encode($logo))."','".urlencode(base64_encode($transDate))."','" . ABSPATH . "');";
	  $pdf .="$prodId','$invoicetemplate','$adminemail','$companyname','$currency','$status','$email','$fname','$lname','$address1','$city','$state','$zip','$country','$amount','$payment_processor','$recurring_id','$newtrans[0]','$logo','$transDate','" . ABSPATH . "');";
	  $pdf .='">View PDF</a>';
	  $pdf .='</td>';
	  $current_msg = str_replace( '[pdf]', $pdf, $current_msg); 
	}
	else
	{
	$pdf = '<td class="cell-left-center invoiceDisplay" style="display:none"></td>';
	  $current_msg = str_replace( '[pdf]', $pdf, $current_msg);
	}
	//$content .= $current_msg;	
	$found=true;
	$html .= $current_msg;
	
	//echo $tempcontent;die;
//	echo $content;die;
/*	$content .= $tempcontent;
/*$html .= $content;
	if($i++ == 4){
		break;
	}*/
  } //end foreach
  
	$html .=  DapMemberShowLoader(); 
	
	if($showinvoice=='Y') {
		$content = str_replace( '[DISPLAYINVOICE]', 'display:table-cell' , $content);
	}else{
		$cssvar .= "<style>.invoiceDisplay{display:none !important}</style>";
		$content = str_replace( '[DISPLAYINVOICE]', 'display:none' , $content);	
	}
  $content = str_replace( '[INVOICETABLEDATA]', $html, $content);
 

  if(!$found) {
	// $content.=$notranmsg;
  }
 
  $content.='</form></div></div>';
  return $content.$cssvar;
}
 


function dap_membersubscriptionshortcode($atts, $content=null){ 
  extract(shortcode_atts(array(
	  'showcancel' => 'Y',
	  'showalltransactions' => 'N',
	  'productid' => 'ALL',
	  'template'  => 'template1',
	  'payment' => 'PAYPAL',		
	  'showrenewal' => 'Y',
	  'bgcolor'     => '#f9f9f9',
	  'templatetextcolor' => '#000',
	  'dateformat' => 'YYYY-MM-DD',
	  'cancelledtext' => 'CANCELLED',
	  'cancelsuccess' => 'Subscription Cancellation Completed Successfully!',
	  'cancelfailed' => 'Sorry, could not cancel the subscription.',
	  'confirmmsg' => 'Are you sure you want to cancel subscription?',
	  'cancelimage' => '',
	  'cancelcontact' => 'Contact Us',
	  'cancelcontacturl' => (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]",
	  'cancelbuttonstyle' => '',
	  'cancelbuttontext' => '',
	  'upgradelink' => '',
	  'upgradetext' => 'UPGRADE',
	  'upgradetextcolor'=> 'blue',
	  'canceltext' => 'CANCEL',
	  'canceltextcolor'=> 'blue',
	  'cancelledtextcolor' => 'red',
	  'notransfoundmsg'=> 'Sorry, no active transactions found',
	  'showpause'=> 'N',
	  'pausesuccess'=> 'Subscription paused successfully.',
	  'pausefail'=> 'Sorry,could not pause the subscription.',
	  'pauseconfirm'=> 'Are you sure you pause the subscription?',
	  'pauseurl' => '',
	  'pausebuttonstyle'=> '',
	  'pausebuttontext'=> '',
	  'resumesuccess' => 'Subscription resumed successfully.',
	  'resumefail' => 'Sorry,could not Resume the subscription.',
	  'resumeconfirm' => 'Are you sure you resume the subscription?',
	  'resumeurl' => '',
	  'resumebuttonstyle' => '',
	  'resumebuttontext' => ''
  ), $atts));
 
  $content = do_shortcode(dap_clean_shortcode_content($content));	
  
  $session = Dap_Session::getSession();
  $user = $session->getUser();
  
 	$frontendCommoncss =  $blogpath . "/wp-content/plugins/DAP-WP-LiveLinks/includes/css/dap_member_frontend_common.css";
	  echo '<link rel="stylesheet" type="text/css" href="' . $frontendCommoncss . '" />';
	
  if( !Dap_Session::isLoggedIn() || !isset($user) ) {
	  //logToFile("Not logged in, returning errmsgtemplate");
	  $errorHTML = mb_convert_encoding(MSG_PLS_LOGIN, "UTF-8", "auto") . " <a class='dap_not_loggedin_link' href=\"" . Dap_Config::get("LOGIN_URL") . "\">". mb_convert_encoding(MSG_CLICK_HERE_TO_LOGIN, "UTF-8", "auto") . "</a>";
	  return $errorHTML;
  }

  $userId = $user->getId();
  $userProducts = null;
  
  logToFile("cancelimage= ". $cancelimage);
  logToFile("cancelcontact= ". $cancelcontact);
  logToFile("cancelcontacturl= ". $cancelcontacturl);
  
  if($cancelimage == "") {
    //$cancelimage = get_option('siteurl'). "/wp-content/plugins/DAP-WP-LiveLinks/includes/images/CancelButtonUp.gif";
	if($template=='template2')
		$cancelimage ='';
  }
  	

  if( Dap_Session::isLoggedIn() && isset($user) ) { 
	  //get userid
	  $userProducts = Dap_UsersProducts::loadProducts($user->getId());
  }
  
  $blogpath=get_option("siteurl");
  
  $fullformcss=  WP_PLUGIN_DIR . "/DAP-WP-LiveLinks/includes/cancel/".$template."/css/autocanceltemplate.css";
  $fullcustomcss =  WP_PLUGIN_DIR . "/DAP-WP-LiveLinks/includes/cancel/".$template."/css/customautocanceltemplate.css";
  $jqueryMin = 'https://code.jquery.com/jquery-3.4.1.min.js';   
	$frontendCommonjs =  $blogpath . "/wp-content/plugins/DAP-WP-LiveLinks/includes/js/dap_member_frontend_common.js";   
  $customcss=get_option('siteurl')."/wp-content/plugins/DAP-WP-LiveLinks/includes/cancel/".$template."/css/customautocanceltemplate.css";
  $fcss = parse_url($customcss);
  $customcss=$fcss["path"];
  //logToFile("custom css: ". $customcss);	
   
  $formcss=get_option('siteurl')."/wp-content/plugins/DAP-WP-LiveLinks/includes/cancel/".$template."/css/autocanceltemplate.css";
  $fcss = parse_url($formcss);
  $formcss=$fcss["path"];
  //logToFile("formcss css: ". $formcss);	
  
  if(file_exists($fullcustomcss)) {
	 //logToFile("custom css: ". $customcss);	
	 $formcss=$customcss;
	 //logToFile("custom css: ". $customcss);
  }
	
  $content .= '<script src="'.$jqueryMin. '" type="text/javascript"></script><script src="'.$frontendCommonjs . '" type="text/javascript"></script>
  <script>
  function cancelSubscription(formname, productId, recurringId, paymentProcessor,transNum) {
	//alert("in cancel subscription " + formname + "," + productId + "," + recurringId);
	var r=confirm("'.$confirmmsg.'");
	if (r==true)
  	{
  		
    var submiturl="/dap/dap-userSubscriptionStatus.php";
	
	var cancelsuccess = "' . $cancelsuccess . '";
	var cancelfailed = "' . $cancelfailed . '";
	//alert("here");
	//alert(cancelsuccess);
	jQuery.ajax({
	  url: submiturl,
	  type: "POST",
	  async: false,
	  data: {"productId":productId,"recurringId":recurringId,"action":"Cancel","paymentProcessor":paymentProcessor,"transNum":transNum, "sucessmsg":cancelsuccess, "failedmsg":cancelfailed},
	  cache: false,
	  success: function (returnval) {
		alert(returnval);
		window.location.reload();
		//~ if(returnval==0) {
		 //~ alert("Completed cancellation successfully");  
		 //~ // alert(cancelsuccess);
		  //~ window.location.reload();
 		//~ }
		//~ else if(returnval==1) {
		  //~ alert(cancelfailed);
		//~ }
	  }
	}); //ajax
	return;
  	}
	else{
		return false;
	
	}
  }
  
	function pauseSubscription(formname, productId, recurringId, paymentProcessor,transNum){
		var r=confirm("'.$pauseconfirm.'");
		if (r==true)
		{
			var submiturl="/dap/dap-userPauseResume.php";
			
			var pauseconfirm = "' . $pauseconfirm . '";
			var pausefail = "' . $pausefail . '";
			jQuery.ajax({
			  url: submiturl,
			  type: "POST",
			  async: false,
			  data: {"productId":productId,"recurringId":recurringId,"action":"Pause","paymentProcessor":paymentProcessor,"transNum":transNum},
			  cache: false,
			  success: function (returnval) {
				if(returnval==0) {
				 alert("'.$pausesuccess.'");  
				 window.location.reload();
				}
				else if(returnval==1) {
				  alert(pausefail);
				}
			  }
			}); 
			return false;
		}
		else{
			return false;
		}
	}
	
	function resumeSubscription(formname, productId, recurringId, paymentProcessor,transNum){
		var r=confirm("'.$resumeconfirm.'");
		if (r==true)
		{
			var submiturl="/dap/dap-userPauseResume.php";
			
			var resumeconfirm = "' . $resumeconfirm . '";
			var resumefail = "' . $resumefail . '";
			jQuery.ajax({
			  url: submiturl,
			  type: "POST",
			  async: false,
			  data: {"productId":productId,"recurringId":recurringId,"action":"Resume","paymentProcessor":paymentProcessor,"transNum":transNum},
			  cache: false,
			  success: function (returnval) {
				if(returnval==0) {
					alert("'.$resumesuccess.'");  
					window.location.reload();
				}
				else if(returnval==1) {
				  alert(resumefail);
				}
			  }
			}); 
			return;
		}
		else{
			return false;
		}
	}
  </script>';
  
  $templatetextcolorstyle= "";
  $bgcolorstyle = "";
  $upgradetextcolorstyle= "";
  $content .= '<link rel="stylesheet" type="text/css" href="' . $formcss . '?v=2" />';
   //$content .= '<link rel="stylesheet" type="text/css" href="' . $frontendCommoncss . '" />';
//  $content .= '<div class="scroller"><div id="wrapper">';
  if($bgcolor){
	  $bgcolorstyle = "<style>#autoCancellationDark{background:$bgcolor;}</style>"; 
  }
	if($upgradetextcolor){
	   $bgcolorstyle =  "<style>.upgrade > a{color:$upgradetextcolor;}</style>";  
	}
  if($canceltextcolor){
	   $bgcolorstyle =  "<style>.cancel > a{color:$canceltextcolor;}</style>";  
	}
  $content .= '<form class="formautoaction live-links-bootstrap_outer" id="formautoaction">';
  if($template =='template2') {
	$content .= '<div id="autoCancellationDark">';
	if($templatetextcolor){
	   $templatetextcolorstyle = "<style>#autoCancellationDark{color:$templatetextcolor;}</style>";  
	}
  }
  
  $lldocroot = defined('SITEROOT') ? SITEROOT : $_SERVER['DOCUMENT_ROOT'];
  $fullcustomheaderhtml =  ABSPATH ."/wp-content/plugins/DAP-WP-LiveLinks/includes/cancel/".$template."/customautocancelheadertemplate.html";   
  if(file_exists($fullcustomheaderhtml)) 
    $template_headerpath=$fullcustomheaderhtml;
  else
    $template_headerpath=ABSPATH."/wp-content/plugins/DAP-WP-LiveLinks/includes/cancel/".$template."/autocancelheadertemplate.html";
   
   //logToFile("DAP USER CANCELLATION : template_headerpath =" . $template_headerpath,LOG_INFO_DAP);
   
  $temp_headercontent = file_get_contents($template_headerpath);
  $current_msg=$temp_headercontent;
  $current_msg = str_replace( '[USERNAME]', $user->getFirst_name().$user->getLast_name(), $current_msg); 
  $current_msg = str_replace( '[USEREMAIL]', $user->getEmail(), $current_msg);
  $content .= $current_msg;
  if($template=='template1') {
	if($upgradelink !='') 
	  $content .= '<div class="cell-head">Upgrade</div>';
	/*if($showcancel != "N") 
	//  $content .= '<div class="cell-head">Cancel</div>'; 
	if($showpause == "Y")
	 // $content .= '<div class="cell-head">Pause/Resume</div>'; 
	//$content .=  '</div>';*/
  }
  
  //logToFile("DAP USER CANCELLATION : cancel =" . $temp_headercontent,LOG_INFO_DAP);
  
  $fullcustomhtml =  dirname(__FILE__) ."/includes/cancel/".$template."/customautocanceltemplate.html";   
  if(file_exists($fullcustomhtml))
	$template_path=$fullcustomhtml;
  else
	$template_path= dirname(__FILE__)."/includes/cancel/".$template."/autocanceltemplate.html";
  //$template_path=$blogpath."/wp-content/plugins/DAP-WP-LiveLinks/includes/".$template."/autocanceltemplate.html";
  $temp_content = file_get_contents($template_path);
//echo "<pre>";
//print_r($userProducts); exit;
  //loop over each product from the list
  foreach ($userProducts as $userProduct) {
	//logToFile("DAP USER CANCELLATION : USERPRODUCTS ENTER",LOG_INFO_DAP);
	
	if($productid != "ALL") {
		$productIdArray = explode(",",$productid);
		if( !in_array($userProduct->getProduct_id(), $productIdArray) ) {
		  continue;
	    }
	}
		  
	$product = Dap_Product::loadProduct($userProduct->getProduct_id());
	$is_recur = $product->getIs_recurring();

	$expired = false;
	$productId=$product->getId();
	//logToFile("DAP USER CANCELLATION : check if users access to product=".$productId." has expired",LOG_INFO_DAP);
		
	if($user->hasAccessTo($product->getId()) === false) {
		//logToFile("Users access to product=".$productId." expired",LOG_INFO_DAP);
		$expired = true;
	}
		
	//$product->getName()
	
	$oldDate = $userProduct->getAccess_start_date();
	//logToFile("DAP USER CANCELLATION : oldDate newStartDate=".$oldDate,LOG_INFO_DAP);
	$middle = new DateTime($oldDate);
	
	//logToFile("DAP USER CANCELLATION : middle newStartDate=".$middle,LOG_INFO_DAP);
	
	$stringFormat = "";
	if($dateformat == "MM-DD-YYYY") {
		$stringFormat = "m-d-Y";
	} else if($dateformat == "DD-MM-YYYY") {
		$stringFormat = "d-m-Y";
	}  else if($dateformat == "YYYY-MM-DD") {
		$stringFormat = "Y-m-d";
	}
	
	$newStartDate = $middle->format($stringFormat);
	logToFile("DAP USER CANCELLATION : newStartDate=".$newStartDate,LOG_INFO_DAP);
	
	$oldDate = $userProduct->getAccess_end_date();
	$middle = new DateTime($oldDate);
	//logToFile("DAP USER CANCELLATION : middle newEndDate=".$middle,LOG_INFO_DAP);
	$stringFormat = "";
	if($dateformat == "MM-DD-YYYY") {
		$stringFormat = "m-d-Y";
	} else if($dateformat == "DD-MM-YYYY") {
		$stringFormat = "d-m-Y";
	}  else if($dateformat == "YYYY-MM-DD") {
		$stringFormat = "Y-m-d";
	}
	$newEndDate = $middle->format($stringFormat);
	//logToFile("DAP USER CANCELLATION : newEndDate=".$newEndDate,LOG_INFO_DAP);
	
	$highlightCode = "";
	if($expired) {
		$highlightCode = ' class="dap_highlight_bg" ';
	}
	
	if( $expired && ($showrenewal == "Y") ) {
		//If user's access to product has expired, then show renewal HTML
		//$content .= '<div>'.$product->getRenewal_html().'</div>';
	}
		
	$emailFilter = $user->getEmail();
	$productIdFilter = $userProduct->getProduct_id();
	
	$transIdFilter = $userProduct->getTransaction_id();
	$showTran="N";
	$foundTransaction=false;
	$authnet=false;
	$paypal=false;
	$stripe=false;
	$recurring_id="";
	$stripe_customer_id="";
	$showpause;
	
	$cancelled_subscription="";
	
	if($transIdFilter <= 0) {
		//logToFile("SKIP transNumFilter=".$transNumFilter . " less than 0, product=".$productIdFilter,LOG_INFO_DAP);
		continue;
	}
	
	$statusFilter = "";
	
	// TODO: only pick up subscription transaction
	logToFile("transIdFilter=".$transIdFilter,LOG_INFO_DAP);
	logToFile("transNumFilter=".$transNumFilter,LOG_INFO_DAP);
	logToFile("emailFilter=".$emailFilter,LOG_INFO_DAP);
	logToFile("productIdFilter=".$productIdFilter,LOG_INFO_DAP);
	logToFile("statusFilter=".$statusFilter,LOG_INFO_DAP);
	
	$TransactionsList = Dap_Transactions::loadTransactions($transNumFilter, $emailFilter, $productIdFilter, $statusFilter,"","",$transIdFilter);
	
	$status = '';
	foreach ($TransactionsList as $transaction) {
	  $authnet=false;
	  $paypal=false;
	  $stripe=false;
	  
	  parse_str($transaction->getTrans_blob(), $list);
	  logToFile("DAP-Auto-Cancellation: found transactions",LOG_INFO_DAP); 
	  
	  if (($list == NULL) || !isset($list))
		 //logToFile("DAP-Auto-Cancellation::LIST EMPTY"); 
		  
	  foreach ($list as $key => $value) {
		// logToFile("DAP-Auto-Cancellation::LIST DETAILS(): Key=".$key.", Value=".$value); 
	  }
	  
	  //logToFile("DAP-Auto-Cancellation::TRANSACTION TYPE  =  " . $transaction->getTrans_type()); 
	  
	  if($transaction->getTrans_type() == "subscr_signup") {
		  continue;
	  }
	  
	  if(array_key_exists('recurring_payment_id',$list)) {
		  $recurring_id = $list["recurring_payment_id"];
	  }
	  else if(array_key_exists('subscr_id',$list)) {
		  $recurring_id = $list["subscr_id"];
	  }
	  else if(array_key_exists('sub_id',$list)) {
		 if($list["sub_id"] != ":")
		  $recurring_id = $list["sub_id"];
	  } 
	  else if(array_key_exists('stripe_customer_id',$list)) {
		  $recurring_id = $list["stripe_customer_id"];
	  }
	  
	  if(array_key_exists('cancel',$list)) {
		  $cancelled_subscription = $list["cancel"];
		  //logToFile("DAP-Auto-Cancellation::check if cancelled_subscription".$cancelled_subscription); 
	  }
	  
	  //logToFile("DAP-Auto-Cancellation::recurring_id".$recurring_id); 
	  
	  //PaypalPDT
	  $payment_processor = $transaction->getPayment_processor();
	  if ($payment_processor == "MANUAL") {
		//  continue;
	  }
	  if ($payment_processor == "AUTHNET") {
		  $authnet=true;
	  }
	  if (stristr($payment_processor,"PAYPAL")) {
		  $paypal=true;
	  }
	  if (stristr($payment_processor,"STRIPE")) {
		  $stripe=true;
	  }
	  $status = $transaction->getPayment_status();
	  $transaction_id=$transaction->getTrans_num();
	  $newtrans=explode(':',$transaction_id);
	  $amount= $transaction->getPayment_value();
	  $foundTransaction=true;
	  logToFile("DAP USER CANCELLATION : foundTransaction=".$foundTransaction,LOG_INFO_DAP);
	  break; 
	} //foreach transaction
		
	//logToFile("DAP USER CANCELLATION : found recurring_id=".$recurring_id,LOG_INFO_DAP);
		
	if($foundTransaction) { //Start Found Trans
		$showTran="Y";
		logToFile("DAP USER CANCELLATION : showalltransactions=".$showalltransactions,LOG_INFO_DAP);
		if($showalltransactions=="N") {
			if($recurring_id != "") {
				$showTran="Y";
			}	
			else {
				$showTran="N";
				$showpause = "N";
			}
		}
		  
		  if($showTran=="Y") { // Show Trans Yes
			logToFile("DAP USER CANCELLATION : found TRANS".$paypal,LOG_INFO_DAP);
		$ubtn='<td class="upgrade">&nbsp;&nbsp;<a href="'.$upgradelink.'" target="_blank" id="[PAYPALPRODID]"' ;
			$ubtn .='>'.$upgradetext.'</a></td>';
			if($template=='template1') {
				$ubtn='<td class="cell-data-left"><a id="upgrade" target="_blank" href="'.$upgradelink.'" id="[PAYPALPRODID]"' ;
				$ubtn .='>'.$upgradetext.'</a></td>';
			}							
			if($upgradetextcolor)
				$upgradetextcolorstyle= "<style>#upgrade{color:$upgradetextcolor;}</style>";
				
			$current_msg=$temp_content;
		  
			$current_msg = str_replace( '[ORDERPRODID]', "order_".$product->getId(), $current_msg); 
			$current_msg = str_replace( '[FORMNAME]', "document.formautoaction", $current_msg); 
			$current_msg = str_replace( '[AMOUNT]', $amount, $current_msg); 
			$current_msg = str_replace( '[ITEMNAME]', $product->getName(), $current_msg); 
			$current_msg = str_replace( '[ACCESSSTART]', $newStartDate, $current_msg); 
			$current_msg = str_replace( '[ACCESSEND]', $newEndDate, $current_msg); 
			$current_msg = str_replace( '[RECURRINGID]', $newtrans[0], $current_msg); 
			
			
			if($showpause == "N"){
				$current_msg = str_replace( '[BTN_PAUSE]','<td class="cell-data-left" align="justify"></td>', $current_msg); 
				$current_msg = str_replace( '[BTN_RESUME]',"", $current_msg); 
			}

			$today = date("Y-m-d", strtotime('today'));
				
			if($showcancel=="Y") { //Show cancel yes
				if($cancelled_subscription) { //IF cancelled Subscription
				$current_msg = str_replace( '[BTN_CODE]', "<td class='cell-data-left' align='justify' style='text-align:center;color:".$cancelledtextcolor."'><strong>" . $cancelledtext . "</strong></td>", $current_msg);
				$current_msg = str_replace( '[BTN_CANCEL]', "<td style='color:red;font-size: 12px;text-align:center;'>&nbsp;&nbsp;" .  $cancelledtext . "</td>", $current_msg);
				$current_msg = str_replace( '[BTN_PAUSE]', '<td class="cell-data-left" align="justify"></td>', $current_msg);
				$current_msg = str_replace( '[BTN_RESUME]', "", $current_msg);

				} // END IF cancelled Subscription
				else { // If not cancelled subscription
				if($paypal) { //Paypal start
					if($recurring_id != "") {
						logToFile("DAP USER CANCELLATION : paypal recurring id found=".$product->getName(),LOG_INFO_DAP);
						if($cancelimage) {
							$pbtn='<td class="cell-data-left">';
							$pbtn .='<input class="imageclass" type="image" src="[CANCELIMAGESRC]"  name="[PAYPALPRODID]" id="[PAYPALPRODID]" onClick="';
							$pbtn .="return cancelSubscription(document.formautoaction,'";
							$pbtn .="[PRODID]', '[RECURRINGID]','PAYPAL','[TRANSACTION_ID]');";
							$pbtn .='" value="CANCEL">';
							$pbtn .='</td>';
						}
						else {
							/*$pbtn='<div class="cell-data-left">';
							$pbtn .='<span1 class="cancel">&nbsp;&nbsp;<a href="" id="[PAYPALPRODID]" onclick="';
							$pbtn .="return cancelSubscription(document.formautoaction,'";
							$pbtn .="[PRODID]', '[RECURRINGID]','PAYPAL','[TRANSACTION_ID]');";
							$pbtn .='">'.$canceltext.'</a></span1>';
							$pbtn .='</div>';*/
							
							$pbtn = '<td class="cell-data-left"><button style="'.$cancelbuttonstyle.'" onClick="';
							$pbtn .="return cancelSubscription(document.formautoaction,'";
							$pbtn .="[PRODID]', '[RECURRINGID]','PAYPAL','[TRANSACTION_ID]');";
							$pbtn .= '">';
							$pbtn .= $cancelbuttontext;
							$pbtn .= '</button></td>';
							
							
						}
						if($cancelimage) {
							$cbtn ='<input class="imageclass" type="image" src="[CANCELIMAGESRC]"  name="[PAYPALPRODID]" id="[PAYPALPRODID]" onClick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','PAYPAL','[TRANSACTION_ID]');";
							$cbtn .='" value="CANCEL">';
						}
						else {
							/*$cbtn='<span1 class="cancel">&nbsp;&nbsp;<a href="" id="[PAYPALPRODID]" onclick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','PAYPAL','[TRANSACTION_ID]');";
							$cbtn .='">'.$canceltext.'</a></span1>';*/
							
							$cbtn = '<td class="cell-data-left"><button style="'.$cancelbuttonstyle.'" onClick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','PAYPAL','[TRANSACTION_ID]');";
							$cbtn .= '">';
							$cbtn .= $cancelbuttontext;
							$cbtn .= '</button></td>';
							
						}
							$current_msg = str_replace( '[BTN_CODE]', $pbtn, $current_msg); 
							$current_msg = str_replace( '[BTN_CANCEL]', $cbtn, $current_msg);

							if($upgradelink !='')
							$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
							else
							$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);

							$current_msg = str_replace( '[PAYPALPRODID]', "paypalorder_".$product->getId(), $current_msg);
					}
					else {
						/*$nocanceldiv='<div class="cell-data-left" align="justify"></div>';
						$current_msg = str_replace( '[BTN_CODE]', $nocanceldiv, $current_msg);   
						$current_msg = str_replace( '[BTN_CANCEL]', " ", $current_msg);*/

						if( ($cancelcontact!="") && ($cancelcontacturl!="")) {
								$cancelcontactlink="<td class='cell-data-left'><a style='text-align:center;color:blue' href=\"".$cancelcontacturl."\" target=\"_blank\">".$cancelcontact."</a></td>";
							logToFile("DAP-User-Subscription(): cancelcontactlink:  cancelcontactlink = ". $cancelcontactlink,LOG_INFO_DAP);
							$current_msg = str_replace( '[BTN_CANCEL]', $cancelcontactlink, $current_msg);  
							$current_msg = str_replace( '[BTN_CODE]', $cancelcontactlink, $current_msg); 
						} else {
							$nocanceldiv='<td class="cell-data-left" align="justify"></td>';
							$current_msg = str_replace( '[BTN_CODE]', $nocanceldiv, $current_msg);
							$current_msg = str_replace( '[BTN_CANCEL]', "", $current_msg);  

							if($upgradelink !='')
							$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
							else
							$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);
						}
					}
				}//paypal end
				else if($authnet) {//Authnet start
					if ($recurring_id != "") {
						logToFile("DAP USER CANCELLATION : authnet recurring id found=".$product->getName(),LOG_INFO_DAP);
						if($cancelimage) {
							$abtn ='<td class="cell-data-left">';
							$abtn .='<input type="image" class="imageclass" src="[CANCELIMAGESRC]" name="[AUTHNETPRODID]" id="[AUTHNETPRODID]" onClick="';
							$abtn .="return cancelSubscription(document.formautoaction,'";
							$abtn .="[PRODID]', '[RECURRINGID]','AUTHNET','[TRANSACTION_ID]');";
							$abtn .='" value="CANCEL">';
							$abtn .='</td>';
						}
						else {
							/*$abtn ='<div class="cell-data-left">';
							$abtn .='<span1 class="cancel">&nbsp;&nbsp;<a href="" id="[PAYPALPRODID]" onclick="';
							$abtn .="return cancelSubscription(document.formautoaction,'";
							$abtn .="[PRODID]', '[RECURRINGID]','AUTHNET','[TRANSACTION_ID]');";
							$abtn .='">'.$canceltext.'</a></span1>';
							$abtn .='</div>';*/	
							
							$abtn = '<td class="cell-data-left"><button style="'.$cancelbuttonstyle.'" onClick="';
							$abtn .="return cancelSubscription(document.formautoaction,'";
							$abtn .="[PRODID]', '[RECURRINGID]','AUTHNET','[TRANSACTION_ID]');";
							$abtn .= '">';
							$abtn .= $cancelbuttontext;
							$abtn .= '</button></td>';
						}
						if($cancelimage) {
							$cbtn ='<input type="image" class="imageclass" src="[CANCELIMAGESRC]"  name="[AUTHNETPRODID]" id="[AUTHNETPRODID]" onClick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','AUTHNET','[TRANSACTION_ID]');";
							$cbtn .='" value="CANCEL">';
						}
						else {
							/*$cbtn='<span1 class="cancel">&nbsp;&nbsp;<a href="" id="[PAYPALPRODID]" onclick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','AUTHNET','[TRANSACTION_ID]');";
							$cbtn .='">'.$canceltext.'</a></span1>';*/
							
							$cbtn = '<td class="cell-data-left"><button style="'.$cancelbuttonstyle.'" onClick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','AUTHNET','[TRANSACTION_ID]');";
							$cbtn .= '">';
							$cbtn .= $cancelbuttontext;
							$cbtn .= '</button></td>';
							
						}
						$ubtn='<td class="upgrade">&nbsp;&nbsp;<a target="_blank" href="'.$upgradelink.'" id="[AUTHNETPRODID]"' ;
						$ubtn .='>'.$upgradetext.'</a></td>';
						if($template=='template1') {
							$ubtn='<td class="cell-data-left"><a target="_blank" href="'.$upgradelink.'" id="[AUTHNETPRODID]"' ;
							$ubtn .='>'.$upgradetext.'</a></td>';
						}

						$current_msg = str_replace( '[BTN_CODE]', $abtn, $current_msg); 
						$current_msg = str_replace( '[BTN_CANCEL]', $cbtn, $current_msg);
						if($upgradelink !='')
							$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
						else
							$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);

						$current_msg = str_replace( '[AUTHNETPRODID]', "authnetorder_".$product->getId(), $current_msg); 
					}
					else {
						if( ($cancelcontact!="") && ($cancelcontacturl!="")) {
							$cancelcontactlink="<span class='cell-data-left'><a style='text-align:center;color:blue' href=\"".$cancelcontacturl."\" target=\"_blank\">".$cancelcontact."</a></span>";
							logToFile("DAP-User-Subscription(): cancelcontactlink:  cancelcontactlink = ". $cancelcontactlink,LOG_INFO_DAP);
							$current_msg = str_replace( '[BTN_CANCEL]', $cancelcontactlink, $current_msg);  
							$current_msg = str_replace( '[BTN_CODE]', $cancelcontactlink, $current_msg); 
						} else {
							$nocanceldiv='<td class="cell-data-left" align="justify"></td>';
							$current_msg = str_replace( '[BTN_CODE]', $nocanceldiv, $current_msg);
							$current_msg = str_replace( '[BTN_CANCEL]', "", $current_msg);  

							if($upgradelink !='')
								$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
							else
								$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);
						}
					}
					$current_msg = str_replace( '[BTN_PAUSE]', '<td class="cell-data-left" align="justify"></td>', $current_msg);
					$current_msg = str_replace( '[BTN_RESUME]', "", $current_msg);
				} // Authnet end
				else if($stripe) {//Stripe start
				// if (strtoupper($is_recur) == "Y") {
					if ( ($recurring_id != "") && (strtoupper($is_recur) == "Y") )  {
						logToFile("DAP USER CANCELLATION : stripe recurring id found=".$product->getName(),LOG_INFO_DAP);
						logToFile("DAP USER CANCELLATION : scancelimage=".$cancelimage,LOG_INFO_DAP);

						if($cancelimage) {
							$abtn ='<td class="cell-data-left">';
							$abtn .='<input type="image" class="imageclass" src="[CANCELIMAGESRC]" name="[STRIPEPRODID]" id="[STRIPEPRODID]" onClick="';
							$abtn .="return cancelSubscription(document.formautoaction,'";
							$abtn .="[PRODID]', '[RECURRINGID]','STRIPE','[TRANSACTION_ID]');";
							$abtn .='" value="CANCEL">';
							$abtn .='</td>';
						}
						else {
							/*$abtn ='<div class="cell-data-left">';
							$abtn .='<span1 class="cancel">&nbsp;&nbsp;<a href="" id="[STRIPEPRODID]" onclick="';
							$abtn .="return cancelSubscription(document.formautoaction,'";
							$abtn .="[PRODID]', '[RECURRINGID]','STRIPE','[TRANSACTION_ID]');";
							$abtn .='">'.$canceltext.'</a></span1>';
							$abtn .='</div>';	*/
							
							$abtn = '<td class="cell-data-left"><button style="'.$cancelbuttonstyle.'" onClick="';
							$abtn .="return cancelSubscription(document.formautoaction,'";
							$abtn .="[PRODID]', '[RECURRINGID]','STRIPE','[TRANSACTION_ID]');";
							$abtn .= '">';
							$abtn .= $cancelbuttontext;
							$abtn .= '</button></td>';
						}
						if($cancelimage) {
							$cbtn ='<input type="image" class="imageclass" src="[CANCELIMAGESRC]"  name="[STRIPEPRODID]" id="[STRIPEPRODID]" onClick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','STRIPE','[TRANSACTION_ID]');";
							$cbtn .='" value="CANCEL">';
						}
						else {
						/*	$cbtn='<span1 class="cancel">&nbsp;&nbsp;<a href="" id="[STRIPEPRODID]" onclick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','STRIPE','[TRANSACTION_ID]');";
							$cbtn .='">'.$canceltext.'</a></span1>';*/
							
							$cbtn = '<td class="cell-data-left"><button style="'.$cancelbuttonstyle.'" onClick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','STRIPE','[TRANSACTION_ID]');";
							$cbtn .= '">';
							$cbtn .= $cancelbuttontext;
							$cbtn .= '</button></td>';
							
						}
					$ubtn='<td class="upgrade">&nbsp;&nbsp;<a target="_blank" href="'.$upgradelink.'" id="[STRIPEPRODID]"' ;
						$ubtn .='>'.$upgradetext.'</a></td>';
						if($template=='template1') {
						$ubtn='<td class="cell-data-left"><a target="_blank" href="'.$upgradelink.'" id="[STRIPEPRODID]"' ;
						$ubtn .='>'.$upgradetext.'</a></td>';
						}

						$current_msg = str_replace( '[BTN_CODE]', $abtn, $current_msg); 
						$current_msg = str_replace( '[BTN_CANCEL]', $cbtn, $current_msg);
						if($upgradelink !='')
							$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
						else
							$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);

						$current_msg = str_replace( '[STRIPEPRODID]', "stripeorder_".$product->getId(), $current_msg); 
					}
					else {

						if( ($cancelcontact!="") && ($cancelcontacturl!="")) {
							$cancelcontactlink="<td class='cell-data-left'><a style='text-align:center;color:blue' href=\"".$cancelcontacturl."\" target=\"_blank\">".$cancelcontact."</a></td>";
							logToFile("DAP-User-Subscription(): cancelcontactlink:  cancelcontactlink = ". $cancelcontactlink,LOG_INFO_DAP);
							$current_msg = str_replace( '[BTN_CANCEL]', $cancelcontactlink, $current_msg);  
							$current_msg = str_replace( '[BTN_CODE]', $cancelcontactlink, $current_msg); 
						} else {
							$nocanceldiv='<td class="cell-data-left" align="justify"></td>';
							$current_msg = str_replace( '[BTN_CODE]', $nocanceldiv, $current_msg);
							$current_msg = str_replace( '[BTN_CANCEL]', "", $current_msg);  

						if($upgradelink !='')
							$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
						else
							$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);
						}
					}
				} // Stripe end
				else  {  // if Infusion and others (not paypal, authnet)

				logToFile("DAP-User-Subscription(): dap_usersubscription:  Payment Processor = ". $payment_processor,LOG_INFO_DAP);



				if( ($cancelcontact!="") && ($cancelcontacturl!="")) {
				$cancelcontactlink="<span class='cell-data-left'><a style='text-align:center;color:blue' href=\"".$cancelcontacturl."\" target=\"_blank\">".$cancelcontact."</a></span>";
				logToFile("DAP-User-Subscription(): cancelcontactlink:  cancelcontactlink = ". $cancelcontactlink,LOG_INFO_DAP);
				$current_msg = str_replace( '[BTN_CANCEL]', $cancelcontactlink, $current_msg);  
				$current_msg = str_replace( '[BTN_CODE]', $cancelcontactlink, $current_msg); 
				} else {
				$nocanceldiv='<td class="cell-data-left" align="justify"></td>';
				$current_msg = str_replace( '[BTN_CODE]', $nocanceldiv, $current_msg);
				$current_msg = str_replace( '[BTN_CANCEL]', "", $current_msg);  

				if($upgradelink !='')
				$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
				else
				$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);
				}
				logToFile("DAP-User-Subscription(): dap_usersubscription:  Complete Payment Processor = ". $payment_processor,LOG_INFO_DAP);

				}//Others end

				}//If not cancelled subscription

				$current_msg = str_replace( '[CANCELIMAGESRC]', $cancelimage, $current_msg); 
			} // END showcancel=Y
			else { // Start showcancel=N
				$current_msg = str_replace( '[BTN_CODE]', "", $current_msg);
				$current_msg = str_replace( '[BTN_CANCEL]', "", $current_msg);
				
			}// End Show cancel=N
			
			
			/* code to show/hide pause/resume */
			if($showpause == "Y"){
				
				// we will show these buttons only for stripe and paypal not for authnet
				if($paypal || $stripe){

					if($paypal){
						$processor = "PAYPAL";
					}						
					else{
						$processor = "STRIPE";
					}
					
					// now we will check for recurring_id
					if($recurring_id != "" && $is_recur == "Y"){
						
						if(strtolower($status) == "paused"){
							$showPause = ";display:none;";
							$showResume = "";
						}
						else{
							$showPause = "";
							$showResume = ";display:none;";
						}
						
						// first lets make pause button
						if($pauseurl != ""){ // get pause img url
							$pbtn ='<td class="cell-data-left"><input type="image" class="imageclass" src="'.$pauseurl.'" onClick="';
							$pbtn .="return pauseSubscription(document.formautoaction,'";
							$pbtn .="[PRODID]', '[RECURRINGID]','".$processor."','[TRANSACTION_ID]');";
							$pbtn .='" value="PAUSE" style="'.$showPause.'">';
						}
						else{ // get pause button data
							$pbtn = '<td class="cell-data-left"><button style="'.$pausebuttonstyle.$showPause.'" onClick="';
							$pbtn .="return pauseSubscription(document.formautoaction,'";
							$pbtn .="[PRODID]', '[RECURRINGID]','".$processor."','[TRANSACTION_ID]');";
							$pbtn .= '">';
							$pbtn .= $pausebuttontext;
							$pbtn .= '</button>';
						}
						
						$current_msg = str_replace( '[BTN_PAUSE]', $pbtn, $current_msg);
						
						if($resumeurl != ""){ // get pause img url
							$pbtn ='<input type="image" class="imageclass" src="'.$resumeurl.'" onClick="';
							$pbtn .="return resumeSubscription(document.formautoaction,'";
							$pbtn .="[PRODID]', '[RECURRINGID]','".$processor."','[TRANSACTION_ID]');";
							$pbtn .='" value="PAUSE" style="'.$showResume.'"></td>';
						}
						else{ // get pause button data
							$pbtn = '<button style="'.$resumebuttonstyle.$showResume.'" onClick="';
							$pbtn .="return resumeSubscription(document.formautoaction,'";
							$pbtn .="[PRODID]', '[RECURRINGID]','".$processor."','[TRANSACTION_ID]');";
							$pbtn .= '">';
							$pbtn .= $resumebuttontext;
							$pbtn .= '</button></td>';
						}
						
						$current_msg = str_replace( '[BTN_RESUME]', $pbtn, $current_msg);
						
					}
					else{
						$current_msg = str_replace( '[BTN_RESUME]', '<td class="cell-data-left" align="justify"></td>', $current_msg);
						$current_msg = str_replace( '[BTN_PAUSE]', "", $current_msg);
						
						logToFile("DAP-User-Subscription(): showpause=Y , But can't show because recurring_id is missing",LOG_INFO_DAP);
					}
				}else {
				  $current_msg = str_replace( '[BTN_PAUSE]', '<td class="cell-data-left" align="justify"></td>', $current_msg); 	
				  $current_msg = str_replace( '[BTN_RESUME]', "", $current_msg); 	
             	}
			}else {
			  $current_msg = str_replace( '[BTN_PAUSE]', '<td class="cell-data-left" align="justify"></td>', $current_msg); 	
			  $current_msg = str_replace( '[BTN_RESUME]', "", $current_msg); 	
			}
			
				
				
			
			
			if($upgradelink !='')
				$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
			else
				$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);
				
			$current_msg = str_replace( '[TRANSACTION_ID]', $transaction_id, $current_msg); 
			$current_msg = str_replace( '[RECURRINGID]', $recurring_id, $current_msg); 
			$current_msg = str_replace( '[PRODID]', $product->getId(), $current_msg); 
			$current_msg = str_replace( '[PAYMENTPROCESSOR]', $payment_processor, $current_msg); 
				
				//$content .= $current_msg;	
		} //End showTran=Y
			  
	} //End found trans
	else {
	  $current_msg = str_replace( '[BTN_PAUSE]', '<td class="cell-data-left" align="justify"></td>', $current_msg); 	
	  $current_msg = str_replace( '[BTN_RESUME]', "", $current_msg); 	
	}
	
		
	if($current_msg != ''){
		$html .= $current_msg;
	}	
  } //end foreach

   logToFile("DAP-User-Subscription(): showTran=".$showTran,LOG_INFO_DAP);
  
  //$html .=  DapMemberShowLoader(); 
  $html .=  DapMemberShowLoader(); 
  $content = str_replace( '[CANCELLATIONTABLEDATA]', $html, $content);
  
  $content.='</form>';
  
   if($template =='template2')
   $content .=  '</div>';
  
  if($showTran!="Y") {
	//$content .= $notransfoundmsg;
	logToFile("DAP-User-Subscription(): no active transactions found",LOG_INFO_DAP);
  }
  $content .= $templatetextcolorstyle.$bgcolorstyle.$upgradetextcolorstyle;
  return $content;
}




function dap_memberCancellationShortcode($atts, $content=null){ 
  extract(shortcode_atts(array(
	  'id' =>'id',
  ), $atts));
 
   
   $showcancel = '';
   $showalltransactions = '';
   $productid = '';
   $template = '';
   $payment = '';
   $showrenewal = '';
   $bgcolor = '';
   $templatetextcolor = '';
   $dateformat = '';
   $cancelledtext = '';
   $cancelsuccess = '';
   $cancelfailed = '';
   $confirmmsg = '';
   $cancelimage = '';
   $cancelcontact = '';
   $cancelcontacturl = '';
   $cancelbuttonstyle = '';
   $cancelbuttontext = '';
   $upgradelink = '';
   $upgradetext = '';
   $upgradetextcolor = '';
   $canceltext = '';
   $canceltextcolor = '';
   $cancelledtextcolor = '';
   $notransfoundmsg = '';
   $showpause = '';
   $pausesuccess = '';
   $pausefail = '';
   $pauseconfirm = '';
   $pauseurl = '';
   $pausebuttonstyle = '';
   $pausebuttontext = '';
   $resumesuccess = '';
   $resumefail = '';
   $resumeconfirm = '';
   $resumeurl = '';
   $resumebuttonstyle = '';
   $resumebuttontext = '';
   $template = 'template1';
$showcancel = DAP_MemberPagesValues::loadByActionIdAndName($id,'show_cancel');
	
	if($showcancel != '' && $showcancel != false){
		$showcancel =  $showcancel->getValue();	
	}
	
	$showalltransactions = DAP_MemberPagesValues::loadByActionIdAndName($id,'show_all_transactions');
	if($showalltransactions != '' && $showalltransactions != false){
		$showalltransactions =  $showalltransactions->getValue();	
	}
	
	$productid = DAP_MemberPagesValues::loadByActionIdAndName($id,'product_type');
	if($productid != '' && $productid != false){
		$productid =  $productid->getValue();	
	}
	
	$notransfoundmsg = DAP_MemberPagesValues::loadByActionIdAndName($id,'notransfoundmsg');
	if($notransfoundmsg != '' && $notransfoundmsg != false){
		$notransfoundmsg =  $notransfoundmsg->getValue();	
	}
	
	$contact_us = DAP_MemberPagesValues::loadByActionIdAndName($id,'contact_us');
	if($contact_us != '' && $contact_us != false){
		$contact_us =  $contact_us->getValue();	
	}
   
	$contact_us_link = DAP_MemberPagesValues::loadByActionIdAndName($id,'contact_us_link');
	if($contact_us_link != '' && $contact_us_link != false){
		$contact_us_link =  $contact_us_link->getValue();	
	}
   
	$cancel_text = DAP_MemberPagesValues::loadByActionIdAndName($id,'cancel_text');
	if($cancel_text != '' && $cancel_text != false){
		$cancel_text =  $cancel_text->getValue();	
	}
   
	$success_cancel_msg = DAP_MemberPagesValues::loadByActionIdAndName($id,'success_cancel_msg');
	if($success_cancel_msg != '' && $success_cancel_msg != false){
		$cancelsuccess =  $success_cancel_msg->getValue();	
	}
   
	$failed_cancel_msg = DAP_MemberPagesValues::loadByActionIdAndName($id,'failed_cancel_msg');
	if($failed_cancel_msg != '' && $failed_cancel_msg != false){
		$failed_cancel_msg =  $failed_cancel_msg->getValue();	
	}
   
	$cancel_cancel_msg = DAP_MemberPagesValues::loadByActionIdAndName($id,'cancel_cancel_msg');
	if($cancel_cancel_msg != '' && $cancel_cancel_msg != false){
		$confirmmsg =  $cancel_cancel_msg->getValue();	
	}
   
	$pause_resume_select = DAP_MemberPagesValues::loadByActionIdAndName($id,'pause_resume_select');
	if($pause_resume_select != '' && $pause_resume_select != false){
		$pause_resume_select =  $pause_resume_select->getValue();	
	}
   
	$dateformat = DAP_MemberPagesValues::loadByActionIdAndName($id,'dateformat');
	if($dateformat != '' && $dateformat != false){
		$dateformat =  $dateformat->getValue();	
	}
   
	$bgcolor = DAP_MemberPagesValues::loadByActionIdAndName($id,'bgcolor');
	if($bgcolor != '' && $bgcolor != false){
		$bgcolor =  $bgcolor->getValue();	
	}
   
	$payment = DAP_MemberPagesValues::loadByActionIdAndName($id,'payment');
	if($payment != '' && $payment != false){
		$payment =  $payment->getValue();	
	}
   
	$showrenewal = DAP_MemberPagesValues::loadByActionIdAndName($id,'showrenewal');
	if($showrenewal != '' && $showrenewal != false){
		$showrenewal =  $showrenewal->getValue();	
	}
   
	$templatetextcolor = DAP_MemberPagesValues::loadByActionIdAndName($id,'templatetextcolor');
	if($templatetextcolor != '' && $templatetextcolor != false){
		$templatetextcolor =  $templatetextcolor->getValue();	
	}
   
	$cancelimage = DAP_MemberPagesValues::loadByActionIdAndName($id,'cancelimage');
	if($cancelimage != '' && $cancelimage != false){
		$cancelimage =  $cancelimage->getValue();	
	}
   
	$cancelcontact = DAP_MemberPagesValues::loadByActionIdAndName($id,'cancelcontact');
	if($cancelcontact != '' && $cancelcontact != false){
		$cancelcontact =  $cancelcontact->getValue();	
	}else{
		$cancelcontact = 'Contact Us';	
	}
   
	$cancelcontacturl = DAP_MemberPagesValues::loadByActionIdAndName($id,'cancelcontacturl');
	if($cancelcontacturl != '' && $cancelcontacturl != false){
		$cancelcontacturl =  $cancelcontacturl->getValue();	
	}else{
		$cancelcontacturl = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]";	
	}
   
	$cancelbuttonstyle = DAP_MemberPagesValues::loadByActionIdAndName($id,'cancelbuttonstyle');
	if($cancelbuttonstyle != '' && $cancelbuttonstyle != false){
		$cancelbuttonstyle =  $cancelbuttonstyle->getValue();	
	}
   
	$cancelbuttontext = DAP_MemberPagesValues::loadByActionIdAndName($id,'cancelbuttontext');
	if($cancelbuttontext != '' && $cancelbuttontext != false){
		$cancelbuttontext =  $cancelbuttontext->getValue();	
	}
   
	$upgradelink = DAP_MemberPagesValues::loadByActionIdAndName($id,'upgradelink');
	if($upgradelink != '' && $upgradelink != false){
		$upgradelink =  $upgradelink->getValue();	
	}
   
	$upgradetextcolor = DAP_MemberPagesValues::loadByActionIdAndName($id,'upgradetextcolor');
	if($upgradetextcolor != '' && $upgradetextcolor != false){
		$upgradetextcolor =  $upgradetextcolor->getValue();	
	}
   
	$canceltext = DAP_MemberPagesValues::loadByActionIdAndName($id,'canceltext');
	if($canceltext != '' && $canceltext != false){
		$cancelbuttontext =  $canceltext->getValue();	
	}
   
	$canceltextcolor = DAP_MemberPagesValues::loadByActionIdAndName($id,'canceltextcolor');
	if($canceltextcolor != '' && $canceltextcolor != false){
		$canceltextcolor =  $canceltextcolor->getValue();	
	}
   
	$cancelledtextcolor = DAP_MemberPagesValues::loadByActionIdAndName($id,'cancelledtextcolor');
	if($cancelledtextcolor != '' && $cancelledtextcolor != false){
		$cancelledtextcolor =  $cancelledtextcolor->getValue();	
	}
	
	$cancelledtext = DAP_MemberPagesValues::loadByActionIdAndName($id,'cancelled_text');
	if($cancelledtext != '' && $cancelledtext != false){
		$cancelledtext =  $cancelledtext->getValue();	
	}
	
	
   
	$notransfoundmsg = DAP_MemberPagesValues::loadByActionIdAndName($id,'notransfoundmsg');
	if($notransfoundmsg != '' && $notransfoundmsg != false){
		$notransfoundmsg =  $notransfoundmsg->getValue();	
	}
   
	$showpause = DAP_MemberPagesValues::loadByActionIdAndName($id,'showpause');
	if($showpause != '' && $showpause != false){
		$showpause =  $showpause->getValue();	
	}


   
	$pausesuccess = DAP_MemberPagesValues::loadByActionIdAndName($id,'pausesuccess');
	if($pausesuccess != '' && $pausesuccess != false){
		$pausesuccess =  $pausesuccess->getValue();	
	}
   
	$pausefail = DAP_MemberPagesValues::loadByActionIdAndName($id,'pausefail');
	if($pausefail != '' && $pausefail != false){
		$pausefail =  $pausefail->getValue();	
	}
   
	$pauseconfirm = DAP_MemberPagesValues::loadByActionIdAndName($id,'pauseconfirm');
	if($pauseconfirm != '' && $pauseconfirm != false){
		$pauseconfirm =  $pauseconfirm->getValue();	
	}
   
	$pauseurl = DAP_MemberPagesValues::loadByActionIdAndName($id,'pauseurl');
	if($pauseurl != '' && $pauseurl != false){
		$pauseurl =  $pauseurl->getValue();	
	}
   
	$pausebuttonstyle = DAP_MemberPagesValues::loadByActionIdAndName($id,'pausebuttonstyle');
	if($pausebuttonstyle != '' && $pausebuttonstyle != false){
		$pausebuttonstyle =  $pausebuttonstyle->getValue();	
	}
   
	$pausebuttontext = DAP_MemberPagesValues::loadByActionIdAndName($id,'pausebuttontext');
	if($pausebuttontext != '' && $pausebuttontext != false){
		$pausebuttontext =  $pausebuttontext->getValue();	
	}
   
	$resumesuccess = DAP_MemberPagesValues::loadByActionIdAndName($id,'resumesuccess');
	if($resumesuccess != '' && $resumesuccess != false){
		$resumesuccess =  $resumesuccess->getValue();	
	}
   
	$resumefail = DAP_MemberPagesValues::loadByActionIdAndName($id,'resumefail');
	if($resumefail != '' && $resumefail != false){
		$resumefail =  $resumefail->getValue();	
	}
   
	$resumeconfirm = DAP_MemberPagesValues::loadByActionIdAndName($id,'resumeconfirm');
	if($resumeconfirm != '' && $resumeconfirm != false){
		$resumeconfirm =  $resumeconfirm->getValue();	
	}
   
	$resumeurl = DAP_MemberPagesValues::loadByActionIdAndName($id,'resumeurl');
	if($resumeurl != '' && $resumeurl != false){
		$resumeurl =  $resumeurl->getValue();	
	}
   
	$resumebuttonstyle = DAP_MemberPagesValues::loadByActionIdAndName($id,'resumebuttonstyle');
	if($resumebuttonstyle != '' && $resumebuttonstyle != false){
		$resumebuttonstyle =  $resumebuttonstyle->getValue();	
	}
   
	$resumebuttontext = DAP_MemberPagesValues::loadByActionIdAndName($id,'resumebuttontext');
	if($resumebuttontext != '' && $resumebuttontext != false){
		$resumebuttontext =  $resumebuttontext->getValue();	
	}

	 /* 'showalltransactions' => 'N',
	  'productid' => 'ALL',
	  'template'  => 'template1',
	  'payment' => 'PAYPAL',		
	  'showrenewal' => 'Y',
	  'bgcolor'     => '#f9f9f9',
	  'templatetextcolor' => '#000',
	  'dateformat' => 'YYYY-MM-DD',
	  'cancelledtext' => 'CANCELLED',
	  'cancelsuccess' => 'Subscription Cancellation Completed Successfully!',
	  'cancelfailed' => 'Sorry, could not cancel the subscription.',
	  'confirmmsg' => 'Are you sure you want to cancel subscription?',
	  'cancelimage' => '',
	  'cancelcontact' => '',
	  'cancelcontacturl' => '',
	  'cancelbuttonstyle' => '',
	  'cancelbuttontext' => '',
	  'upgradelink' => '',
	  'upgradetext' => 'UPGRADE',
	  'upgradetextcolor'=> 'blue',
	  'canceltext' => 'CANCEL',
	  'canceltextcolor'=> 'blue',
	  'cancelledtextcolor' => 'red',
	  'notransfoundmsg'=> 'Sorry, no active transactions found',
	  'showpause'=> 'N',
	  'pausesuccess'=> 'Subscription paused successfully.',
	  'pausefail'=> 'Sorry,could not pause the subscription.',
	  'pauseconfirm'=> 'Are you sure you pause the subscription?',
	  'pauseurl' => '',
	  'pausebuttonstyle'=> '',
	  'pausebuttontext'=> '',
	  'resumesuccess' => 'Subscription resumed successfully.',
	  'resumefail' => 'Sorry,could not Resume the subscription.',
	  'resumeconfirm' => 'Are you sure you resume the subscription?',
	  'resumeurl' => '',
	  'resumebuttonstyle' => '',
	  'resumebuttontext' => ''*/
 
  $content = do_shortcode(dap_clean_shortcode_content($content));	
  
  $session = Dap_Session::getSession();
  $user = $session->getUser();
	$frontendCommoncss =  $blogpath . "/wp-content/plugins/DAP-WP-LiveLinks/includes/css/dap_member_frontend_common.css";
	  echo '<link rel="stylesheet" type="text/css" href="' . $frontendCommoncss . '" />';
	
  if( !Dap_Session::isLoggedIn() || !isset($user) ) {
	  //logToFile("Not logged in, returning errmsgtemplate");
	  $errorHTML = mb_convert_encoding(MSG_PLS_LOGIN, "UTF-8", "auto") . " <a class='dap_not_loggedin_link' href=\"" . Dap_Config::get("LOGIN_URL") . "\">". mb_convert_encoding(MSG_CLICK_HERE_TO_LOGIN, "UTF-8", "auto") . "</a>";
	  return $errorHTML;
  }

  $userId = $user->getId();
  $userProducts = null;
  
  logToFile("cancelimage= ". $cancelimage);
  logToFile("cancelcontact= ". $cancelcontact);
  logToFile("cancelcontacturl= ". $cancelcontacturl);
  
  if($cancelimage == "") {
    //$cancelimage = get_option('siteurl'). "/wp-content/plugins/DAP-WP-LiveLinks/includes/images/CancelButtonUp.gif";
	if($template=='template2')
		$cancelimage ='';
  }
  	

  if( Dap_Session::isLoggedIn() && isset($user) ) { 
	  //get userid
	  $userProducts = Dap_UsersProducts::loadProducts($user->getId());
  }
  
  $blogpath=get_option("siteurl");
  
  $fullformcss=  WP_PLUGIN_DIR . "/DAP-WP-LiveLinks/includes/cancel/".$template."/css/autocanceltemplate.css";
  $fullcustomcss =  WP_PLUGIN_DIR . "/DAP-WP-LiveLinks/includes/cancel/".$template."/css/customautocanceltemplate.css";   
    $jqueryMin = 'https://code.jquery.com/jquery-3.4.1.min.js';   
	$bootstrapcss =  $blogpath . "/wp-content/plugins/DAP-WP-LiveLinks/includes/css/bootstrap4.min.css";   
	$frontendCommonjs =  $blogpath . "/wp-content/plugins/DAP-WP-LiveLinks/includes/js/dap_member_frontend_common.js";   
  
  $customcss=get_option('siteurl')."/wp-content/plugins/DAP-WP-LiveLinks/includes/cancel/".$template."/css/customautocanceltemplate.css";
  $fcss = parse_url($customcss);
  $customcss=$fcss["path"];
  //logToFile("custom css: ". $customcss);	
   
  $formcss=get_option('siteurl')."/wp-content/plugins/DAP-WP-LiveLinks/includes/cancel/".$template."/css/autocanceltemplate.css";
  $fcss = parse_url($formcss);
  $formcss=$fcss["path"];
  //logToFile("formcss css: ". $formcss);	
  
  if(file_exists($fullcustomcss)) {
	 //logToFile("custom css: ". $customcss);	
	 $formcss=$customcss;
	 //logToFile("custom css: ". $customcss);
  }
     if(!wp_script_is('jquery')) {
			$content .=' <script src="'.$jqueryMin. '" type="text/javascript"></script>';	
			}
	
  $content .= '<script src="'.$frontendCommonjs . '" type="text/javascript"></script>';
  $content .= '<script>
  function cancelSubscription(formname, productId, recurringId, paymentProcessor,transNum) {
	//alert("in cancel subscription " + formname + "," + productId + "," + recurringId);
	var r=confirm("'.$confirmmsg.'");
	if (r==true)
  	{
  		
    var submiturl="/dap/dap-userSubscriptionStatus.php";
	
	var cancelsuccess = "' . $cancelsuccess . '";
	var cancelfailed = "' . $cancelfailed . '";
	//alert("here");
	//alert(cancelsuccess);
	jQuery.ajax({
	  url: submiturl,
	  type: "POST",
	  async: false,
	  data: {"productId":productId,"recurringId":recurringId,"action":"Cancel","paymentProcessor":paymentProcessor,"transNum":transNum, "sucessmsg":cancelsuccess, "failedmsg":cancelfailed},
	  cache: false,
	  success: function (returnval) {
		alert(returnval);
		window.location.reload();
		//~ if(returnval==0) {
		 //~ alert("Completed cancellation successfully");  
		 //~ // alert(cancelsuccess);
		  //~ window.location.reload();
 		//~ }
		//~ else if(returnval==1) {
		  //~ alert(cancelfailed);
		//~ }
	  }
	}); //ajax
	return;
  	}
	else{
		return false;
	
	}
  }
  
	function pauseSubscription(formname, productId, recurringId, paymentProcessor,transNum){
		var r=confirm("'.$pauseconfirm.'");
		if (r==true)
		{
			var submiturl="/dap/dap-userPauseResume.php";
			
			var pauseconfirm = "' . $pauseconfirm . '";
			var pausefail = "' . $pausefail . '";
			jQuery.ajax({
			  url: submiturl,
			  type: "POST",
			  async: false,
			  data: {"productId":productId,"recurringId":recurringId,"action":"Pause","paymentProcessor":paymentProcessor,"transNum":transNum},
			  cache: false,
			  success: function (returnval) {
				if(returnval==0) {
				 alert("'.$pausesuccess.'");  
				 window.location.reload();
				}
				else if(returnval==1) {
				  alert(pausefail);
				}
			  }
			}); 
			return false;
		}
		else{
			return false;
		}
	}
	
	function resumeSubscription(formname, productId, recurringId, paymentProcessor,transNum){
		var r=confirm("'.$resumeconfirm.'");
		if (r==true)
		{
			var submiturl="/dap/dap-userPauseResume.php";
			
			var resumeconfirm = "' . $resumeconfirm . '";
			var resumefail = "' . $resumefail . '";
			jQuery.ajax({
			  url: submiturl,
			  type: "POST",
			  async: false,
			  data: {"productId":productId,"recurringId":recurringId,"action":"Resume","paymentProcessor":paymentProcessor,"transNum":transNum},
			  cache: false,
			  success: function (returnval) {
				if(returnval==0) {
					alert("'.$resumesuccess.'");  
					window.location.reload();
				}
				else if(returnval==1) {
				  alert(resumefail);
				}
			  }
			}); 
			return;
		}
		else{
			return false;
		}
	}
  </script>';
    
  $templatetextcolorstyle= "<style>#cancellation_table{ width: 100% !important;}</style>";
  $bgcolorstyle = "";
  $upgradetextcolorstyle= "";
  $content .= '<link rel="stylesheet" type="text/css" href="' . $formcss . '?v=3" />';
  $content .= '<link rel="stylesheet" type="text/css" href="' . $bootstrapcss . '" />';
  //$content .= '<div class="scroller"><div id="wrapper">';
  if($bgcolor){
	  $bgcolorstyle = "<style>#autoCancellationDark{background:$bgcolor;}</style>"; 
  }
	if($upgradetextcolor){
	   $bgcolorstyle =  "<style>.upgrade > a{color:$upgradetextcolor;}</style>";  
	}
  if($canceltextcolor){
	   $bgcolorstyle =  "<style>.cancel > a{color:$canceltextcolor;}</style>";  
	}
  $content .= '<form class="formautoaction live-links-bootstrap_outer" id="formautoaction">';
  if($template =='template2') {
	$content .= '<div id="autoCancellationDark">';
	if($templatetextcolor){
	   $templatetextcolorstyle = "<style>#autoCancellationDark{color:$templatetextcolor;}</style>";  
	}
  }
  
  $lldocroot = defined('SITEROOT') ? SITEROOT : $_SERVER['DOCUMENT_ROOT'];
  $fullcustomheaderhtml =  ABSPATH ."/wp-content/plugins/DAP-WP-LiveLinks/includes/cancel/".$template."/customautocancelheadertemplate.html";   
  if(file_exists($fullcustomheaderhtml)) 
    $template_headerpath=$fullcustomheaderhtml;
  else
    $template_headerpath=ABSPATH."/wp-content/plugins/DAP-WP-LiveLinks/includes/cancel/".$template."/autocancelheadertemplate.html";
   
   //logToFile("DAP USER CANCELLATION : template_headerpath =" . $template_headerpath,LOG_INFO_DAP);
   
  $temp_headercontent = file_get_contents($template_headerpath);
  $current_msg=$temp_headercontent;
  $current_msg = str_replace( '[USERNAME]', $user->getFirst_name().$user->getLast_name(), $current_msg); 
  $current_msg = str_replace( '[USEREMAIL]', $user->getEmail(), $current_msg);
  $content .= $current_msg;
  if($template=='template1') {
	if($upgradelink !='') 
	  $content .= '<div class="cell-head">Upgrade</div>';
	/*if($showcancel != "N") 
	 // $content .= '<div class="cell-head">Cancel</div>'; 
	if($showpause == "Y")
	 // $content .= '<div class="cell-head">Pause/Resume</div>'; 
	$content .=  '</div>';*/
  }
  
  //logToFile("DAP USER CANCELLATION : cancel =" . $temp_headercontent,LOG_INFO_DAP);
  
  $fullcustomhtml =  dirname(__FILE__) ."/includes/cancel/".$template."/customautocanceltemplate.html";   
  if(file_exists($fullcustomhtml))
	$template_path=$fullcustomhtml;
  else
	$template_path= dirname(__FILE__)."/includes/cancel/".$template."/autocanceltemplate.html";
  //$template_path=$blogpath."/wp-content/plugins/DAP-WP-LiveLinks/includes/".$template."/autocanceltemplate.html";
  $temp_content = file_get_contents($template_path);
//echo "<pre>";
//print_r($userProducts); exit;
  //loop over each product from the list
  $html = '';
  foreach ($userProducts as $userProduct) {
	//logToFile("DAP USER CANCELLATION : USERPRODUCTS ENTER",LOG_INFO_DAP);
	
	if($productid != "ALL") {
		$productIdArray = explode(",",$productid);
		if( !in_array($userProduct->getProduct_id(), $productIdArray) ) {
		  continue;
	    }
	}
		  
	$product = Dap_Product::loadProduct($userProduct->getProduct_id());
	$is_recur = $product->getIs_recurring();

	$expired = false;
	$productId=$product->getId();
	//logToFile("DAP USER CANCELLATION : check if users access to product=".$productId." has expired",LOG_INFO_DAP);
		
	if($user->hasAccessTo($product->getId()) === false) {
		//logToFile("Users access to product=".$productId." expired",LOG_INFO_DAP);
		$expired = true;
	}
		
	//$product->getName()
	
	$oldDate = $userProduct->getAccess_start_date();
	//logToFile("DAP USER CANCELLATION : oldDate newStartDate=".$oldDate,LOG_INFO_DAP);
	$middle = new DateTime($oldDate);
	
	//logToFile("DAP USER CANCELLATION : middle newStartDate=".$middle,LOG_INFO_DAP);
	
	$stringFormat = "";
	if($dateformat == "MM-DD-YYYY") {
		$stringFormat = "m-d-Y";
	} else if($dateformat == "DD-MM-YYYY") {
		$stringFormat = "d-m-Y";
	}  else if($dateformat == "YYYY-MM-DD") {
		$stringFormat = "Y-m-d";
	}
	
	$newStartDate = $middle->format($stringFormat);
	logToFile("DAP USER CANCELLATION : newStartDate=".$newStartDate,LOG_INFO_DAP);
	
	$oldDate = $userProduct->getAccess_end_date();
	$middle = new DateTime($oldDate);
	//logToFile("DAP USER CANCELLATION : middle newEndDate=".$middle,LOG_INFO_DAP);
	$stringFormat = "";
	if($dateformat == "MM-DD-YYYY") {
		$stringFormat = "m-d-Y";
	} else if($dateformat == "DD-MM-YYYY") {
		$stringFormat = "d-m-Y";
	}  else if($dateformat == "YYYY-MM-DD") {
		$stringFormat = "Y-m-d";
	}
	$newEndDate = $middle->format($stringFormat);
	//logToFile("DAP USER CANCELLATION : newEndDate=".$newEndDate,LOG_INFO_DAP);
	
	$highlightCode = "";
	if($expired) {
		$highlightCode = ' class="dap_highlight_bg" ';
	}
	
	if( $expired && ($showrenewal == "Y") ) {
		//If user's access to product has expired, then show renewal HTML
		//$content .= '<div>'.$product->getRenewal_html().'</div>';
	}
		
	$emailFilter = $user->getEmail();
	$productIdFilter = $userProduct->getProduct_id();
	
	$transIdFilter = $userProduct->getTransaction_id();
	$showTran="N";
	$foundTransaction=false;
	$authnet=false;
	$paypal=false;
	$stripe=false;
	$recurring_id="";
	$stripe_customer_id="";
	$showpause;
	
	$cancelled_subscription="";
	
	if($transIdFilter <= 0) {
		//logToFile("SKIP transNumFilter=".$transNumFilter . " less than 0, product=".$productIdFilter,LOG_INFO_DAP);
		continue;
	}
	
	$statusFilter = "";
	
	// TODO: only pick up subscription transaction
	logToFile("transIdFilter=".$transIdFilter,LOG_INFO_DAP);
	logToFile("transNumFilter=".$transNumFilter,LOG_INFO_DAP);
	logToFile("emailFilter=".$emailFilter,LOG_INFO_DAP);
	logToFile("productIdFilter=".$productIdFilter,LOG_INFO_DAP);
	logToFile("statusFilter=".$statusFilter,LOG_INFO_DAP);
	
	$TransactionsList = Dap_Transactions::loadTransactions($transNumFilter, $emailFilter, $productIdFilter, $statusFilter,"","",$transIdFilter);
	
	$status = '';
	
	
	foreach ($TransactionsList as $transaction) {
	  $authnet=false;
	  $paypal=false;
	  $stripe=false;
	  
	  parse_str($transaction->getTrans_blob(), $list);
	  logToFile("DAP-Auto-Cancellation: found transactions",LOG_INFO_DAP); 
	  
	  if (($list == NULL) || !isset($list))
		 //logToFile("DAP-Auto-Cancellation::LIST EMPTY"); 
		  
	  foreach ($list as $key => $value) {
		// logToFile("DAP-Auto-Cancellation::LIST DETAILS(): Key=".$key.", Value=".$value); 
	  }
	  
	  //logToFile("DAP-Auto-Cancellation::TRANSACTION TYPE  =  " . $transaction->getTrans_type()); 
	  
	  if($transaction->getTrans_type() == "subscr_signup") {
		  continue;
	  }
	  
	  if(array_key_exists('recurring_payment_id',$list)) {
		  $recurring_id = $list["recurring_payment_id"];
	  }
	  else if(array_key_exists('subscr_id',$list)) {
		  $recurring_id = $list["subscr_id"];
	  }
	  else if(array_key_exists('sub_id',$list)) {
		 if($list["sub_id"] != ":")
		  $recurring_id = $list["sub_id"];
	  } 
	  else if(array_key_exists('stripe_customer_id',$list)) {
		  $recurring_id = $list["stripe_customer_id"];
	  }
	  
	  if(array_key_exists('cancel',$list)) {
		  $cancelled_subscription = $list["cancel"];
		  logToFile("DAP-Auto-Cancellation::check if cancelled_subscription".$cancelled_subscription); 
	  }
	  
	  //logToFile("DAP-Auto-Cancellation::recurring_id".$recurring_id); 
	  
	  //PaypalPDT
	  $payment_processor = $transaction->getPayment_processor();
	  if ($payment_processor == "MANUAL") {
		//  continue;
	  }
	  if ($payment_processor == "AUTHNET") {
		  $authnet=true;
	  }
	  if (stristr($payment_processor,"PAYPAL")) {
		  $paypal=true;
	  }
	  if (stristr($payment_processor,"STRIPE")) {
		  $stripe=true;
	  }
	  $status = $transaction->getPayment_status();
	  $transaction_id=$transaction->getTrans_num();
	  $newtrans=explode(':',$transaction_id);
	  $amount= $transaction->getPayment_value();
	  $foundTransaction=true;
	  logToFile("DAP USER CANCELLATION : foundTransaction=".$foundTransaction,LOG_INFO_DAP);
	  break; 
	} //foreach transaction
		
	//logToFile("DAP USER CANCELLATION : found recurring_id=".$recurring_id,LOG_INFO_DAP);
	
	if($foundTransaction) { //Start Found Trans
		$showTran="Y";
		logToFile("DAP USER CANCELLATION : showalltransactions=".$showalltransactions,LOG_INFO_DAP);
		if($showalltransactions=="N") {
			if($recurring_id != "") {
				$showTran="Y";
			}	
			else {
				$showTran="Y";
				$showpause = "N";
			}
		}
		  
		  if($showTran=="Y") { // Show Trans Yes
			logToFile("DAP USER CANCELLATION : found TRANS".$paypal,LOG_INFO_DAP);
		$ubtn='<td class="upgrade">&nbsp;&nbsp;<a href="'.$upgradelink.'" target="_blank" id="[PAYPALPRODID]"' ;
			$ubtn .='>'.$upgradetext.'</a></td>';
			if($template=='template1') {
				$ubtn='<td class="cell-data-left"><a id="upgrade" target="_blank" href="'.$upgradelink.'" id="[PAYPALPRODID]"' ;
				$ubtn .='>'.$upgradetext.'</a></td>';
			}
			if($upgradetextcolor)
				$upgradetextcolorstyle= "<style>#upgrade{color:$upgradetextcolor;}</style>";
				
			$current_msg=$temp_content;
		  
			$current_msg = str_replace( '[ORDERPRODID]', "order_".$product->getId(), $current_msg); 
			$current_msg = str_replace( '[FORMNAME]', "document.formautoaction", $current_msg); 
			$current_msg = str_replace( '[AMOUNT]', $amount, $current_msg); 
			$current_msg = str_replace( '[ITEMNAME]', $product->getName(), $current_msg); 
			$current_msg = str_replace( '[ACCESSSTART]', $newStartDate, $current_msg); 
			$current_msg = str_replace( '[ACCESSEND]', $newEndDate, $current_msg); 
			$current_msg = str_replace( '[RECURRINGID]', $newtrans[0], $current_msg); 
			
			
			if($showpause == "N"){
				$current_msg = str_replace( '[BTN_PAUSE]',"<td class='cell-data-left' align='justify' style='display:none' ><strong></strong></td>", $current_msg); 
				$current_msg = str_replace( '[BTN_RESUME]',"", $current_msg); 
			}

			$today = date("Y-m-d", strtotime('today'));
				
			if($showcancel=="Y") { //Show cancel yes
				if($cancelled_subscription) { //IF cancelled Subscription
				logToFile("DAP USER CANCELLATION : cancelled_subscription".$cancelled_subscription,LOG_INFO_DAP);
				$current_msg = str_replace( '[BTN_CODE]', "<td class='cell-data-left' align='justify' style='text-align:center;color:".$cancelledtextcolor."'><strong>" . $cancelledtext . "</strong></td>", $current_msg);  
				$current_msg = str_replace( '[BTN_CANCEL]', "<td style='color:red;font-size: 12px;text-align:center;'>&nbsp;&nbsp;" .  $cancelledtext . "</td>", $current_msg);
				$current_msg = str_replace( '[BTN_PAUSE]', "<td class='cell-data-left' align='justify' ><strong></strong></td>", $current_msg);
				$current_msg = str_replace( '[BTN_RESUME]', "", $current_msg);

				} // END IF cancelled Subscription
				else { // If not cancelled subscription
				if($paypal) { //Paypal start
					if($recurring_id != "") {
						logToFile("DAP USER CANCELLATION : paypal recurring id found=".$product->getName(),LOG_INFO_DAP);
						if($cancelimage) {
							$pbtn='<td class="cell-data-left">';
							$pbtn .='<input class="imageclass" type="image" src="[CANCELIMAGESRC]"  name="[PAYPALPRODID]" id="[PAYPALPRODID]" onClick="';
							$pbtn .="return cancelSubscription(document.formautoaction,'";
							$pbtn .="[PRODID]', '[RECURRINGID]','PAYPAL','[TRANSACTION_ID]');";
							$pbtn .='" value="CANCEL">';
							$pbtn .='</td>';
						}
						else {
							/*$pbtn='<div class="cell-data-left">';
							$pbtn .='<span1 class="cancel">&nbsp;&nbsp;<a href="" id="[PAYPALPRODID]" onclick="';
							$pbtn .="return cancelSubscription(document.formautoaction,'";
							$pbtn .="[PRODID]', '[RECURRINGID]','PAYPAL','[TRANSACTION_ID]');";
							$pbtn .='">'.$canceltext.'</a></span1>';
							$pbtn .='</div>';*/
							
							$pbtn = '<td class="cell-data-left"><button style="'.$cancelbuttonstyle.'" onClick="';
							$pbtn .="return cancelSubscription(document.formautoaction,'";
							$pbtn .="[PRODID]', '[RECURRINGID]','PAYPAL','[TRANSACTION_ID]');";
							$pbtn .= '">';
							$pbtn .= $cancelbuttontext;
							$pbtn .= '</button></td>';
							
							
						}
						if($cancelimage) {
							$cbtn ='<input class="imageclass" type="image" src="[CANCELIMAGESRC]"  name="[PAYPALPRODID]" id="[PAYPALPRODID]" onClick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','PAYPAL','[TRANSACTION_ID]');";
							$cbtn .='" value="CANCEL">';
						}
						else {
							/*$cbtn='<span1 class="cancel">&nbsp;&nbsp;<a href="" id="[PAYPALPRODID]" onclick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','PAYPAL','[TRANSACTION_ID]');";
							$cbtn .='">'.$canceltext.'</a></span1>';*/
							$cbtn = '<td class="cell-data-left"><button style="'.$cancelbuttonstyle.'" onClick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','PAYPAL','[TRANSACTION_ID]');";
							$cbtn .= '">';
							$cbtn .= $cancelbuttontext;
							$cbtn .= '</button></td>';
							
						}
							$current_msg = str_replace( '[BTN_CODE]', $pbtn, $current_msg); 
							$current_msg = str_replace( '[BTN_CANCEL]', $cbtn, $current_msg);

							if($upgradelink !='')
							$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
							else
							$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);

							$current_msg = str_replace( '[PAYPALPRODID]', "paypalorder_".$product->getId(), $current_msg);
					}
					else {
						/*$nocanceldiv='<div class="cell-data-left" align="justify"></div>';
						$current_msg = str_replace( '[BTN_CODE]', $nocanceldiv, $current_msg);   
						$current_msg = str_replace( '[BTN_CANCEL]', " ", $current_msg);*/
						
						if( ($cancelcontact!="") && ($cancelcontacturl!="")) {
							$cancelcontactlink="<td class='cell-data-left'><a style='text-align:center;color:blue' href=\"".$cancelcontacturl."\" target=\"_blank\">".$cancelcontact."</a></td>";
							logToFile("DAP-User-Subscription(): cancelcontactlink:  cancelcontactlink = ". $cancelcontactlink,LOG_INFO_DAP);
							$current_msg = str_replace( '[BTN_CANCEL]', $cancelcontactlink, $current_msg);  
							$current_msg = str_replace( '[BTN_CODE]', $cancelcontactlink, $current_msg); 
							
						} else {
							$nocanceldiv='<td class="cell-data-left" align="justify"></td>';
							$current_msg = str_replace( '[BTN_CODE]', $nocanceldiv, $current_msg);
							$current_msg = str_replace( '[BTN_CANCEL]', "", $current_msg);  

							if($upgradelink !='')
							$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
							else
							$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);
						}
					}
				}//paypal end
				else if($authnet) {//Authnet start
					if ($recurring_id != "") {
						logToFile("DAP USER CANCELLATION : authnet recurring id found=".$product->getName(),LOG_INFO_DAP);
						if($cancelimage) {
							$abtn ='<td class="cell-data-left">';
							$abtn .='<input type="image" class="imageclass" src="[CANCELIMAGESRC]" name="[AUTHNETPRODID]" id="[AUTHNETPRODID]" onClick="';
							$abtn .="return cancelSubscription(document.formautoaction,'";
							$abtn .="[PRODID]', '[RECURRINGID]','AUTHNET','[TRANSACTION_ID]');";
							$abtn .='" value="CANCEL">';
							$abtn .='</td>';
						}
						else {
							/*$abtn ='<div class="cell-data-left">';
							$abtn .='<span1 class="cancel">&nbsp;&nbsp;<a href="" id="[PAYPALPRODID]" onclick="';
							$abtn .="return cancelSubscription(document.formautoaction,'";
							$abtn .="[PRODID]', '[RECURRINGID]','AUTHNET','[TRANSACTION_ID]');";
							$abtn .='">'.$canceltext.'</a></span1>';
							$abtn .='</div>';*/	
							
							$abtn = '<td class="cell-data-left"><button style="'.$cancelbuttonstyle.'" onClick="';
							$abtn .="return cancelSubscription(document.formautoaction,'";
							$abtn .="[PRODID]', '[RECURRINGID]','AUTHNET','[TRANSACTION_ID]');";
							$abtn .= '">';
							$abtn .= $cancelbuttontext;
							$abtn .= '</button></td>';
						}
						if($cancelimage) {
							$cbtn ='<input type="image" class="imageclass" src="[CANCELIMAGESRC]"  name="[AUTHNETPRODID]" id="[AUTHNETPRODID]" onClick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','AUTHNET','[TRANSACTION_ID]');";
							$cbtn .='" value="CANCEL">';
						}
						else {
							/*$cbtn='<span1 class="cancel">&nbsp;&nbsp;<a href="" id="[PAYPALPRODID]" onclick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','AUTHNET','[TRANSACTION_ID]');";
							$cbtn .='">'.$canceltext.'</a></span1>';*/
							
							$cbtn = '<td class="cell-data-left"><button style="'.$cancelbuttonstyle.'" onClick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','AUTHNET','[TRANSACTION_ID]');";
							$cbtn .= '">';
							$cbtn .= $cancelbuttontext;
							$cbtn .= '</button></td>';
							
						}
					$ubtn='<td class="upgrade">&nbsp;&nbsp;<a target="_blank" href="'.$upgradelink.'" id="[AUTHNETPRODID]"' ;
						$ubtn .='>'.$upgradetext.'</a></td>';
						if($template=='template1') {
							$ubtn='<td class="cell-data-left"><a target="_blank" href="'.$upgradelink.'" id="[AUTHNETPRODID]"' ;
							$ubtn .='>'.$upgradetext.'</a></td>';
						}

						$current_msg = str_replace( '[BTN_CODE]', $abtn, $current_msg); 
						$current_msg = str_replace( '[BTN_CANCEL]', $cbtn, $current_msg);
						if($upgradelink !='')
							$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
						else
							$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);

						$current_msg = str_replace( '[AUTHNETPRODID]', "authnetorder_".$product->getId(), $current_msg); 
					}
					else {
						if( ($cancelcontact!="") && ($cancelcontacturl!="")) {
							$cancelcontactlink="<td class='cell-data-left'><a style='text-align:center;color:blue' href=\"".$cancelcontacturl."\" target=\"_blank\">".$cancelcontact."</a></td>";
							logToFile("DAP-User-Subscription(): cancelcontactlink:  cancelcontactlink = ". $cancelcontactlink,LOG_INFO_DAP);
							$current_msg = str_replace( '[BTN_CANCEL]', $cancelcontactlink, $current_msg);  
							$current_msg = str_replace( '[BTN_CODE]', $cancelcontactlink, $current_msg); 
						} else {
							$nocanceldiv='<td class="cell-data-left" align="justify"></td>';
							$current_msg = str_replace( '[BTN_CODE]', $nocanceldiv, $current_msg);
							$current_msg = str_replace( '[BTN_CANCEL]', "", $current_msg);  

							if($upgradelink !='')
								$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
							else
								$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);
						}
					}
					$current_msg = str_replace( '[BTN_PAUSE]', "<td class='cell-data-left' align='justify' style='display:none' ><strong></strong></td>", $current_msg);
					$current_msg = str_replace( '[BTN_RESUME]', "", $current_msg);
				} // Authnet end
				else if($stripe) {//Stripe start
				// if (strtoupper($is_recur) == "Y") {
					if ( ($recurring_id != "") && (strtoupper($is_recur) == "Y") )  {
						logToFile("DAP USER CANCELLATION : stripe recurring id found=".$product->getName(),LOG_INFO_DAP);
						logToFile("DAP USER CANCELLATION : scancelimage=".$cancelimage,LOG_INFO_DAP);

						if($cancelimage) {
							$abtn ='<td class="cell-data-left">';
							$abtn .='<input type="image" class="imageclass" src="[CANCELIMAGESRC]" name="[STRIPEPRODID]" id="[STRIPEPRODID]" onClick="';
							$abtn .="return cancelSubscription(document.formautoaction,'";
							$abtn .="[PRODID]', '[RECURRINGID]','STRIPE','[TRANSACTION_ID]');";
							$abtn .='" value="CANCEL">';
							$abtn .='</td>';
						}
						else {
							/*$abtn ='<div class="cell-data-left">';
							$abtn .='<span1 class="cancel">&nbsp;&nbsp;<a href="" id="[STRIPEPRODID]" onclick="';
							$abtn .="return cancelSubscription(document.formautoaction,'";
							$abtn .="[PRODID]', '[RECURRINGID]','STRIPE','[TRANSACTION_ID]');";
							$abtn .='">'.$canceltext.'</a></span1>';
							$abtn .='</div>';	*/
							
							$abtn = '<td class="cell-data-left"><button style="'.$cancelbuttonstyle.'" onClick="';
							$abtn .="return cancelSubscription(document.formautoaction,'";
							$abtn .="[PRODID]', '[RECURRINGID]','STRIPE','[TRANSACTION_ID]');";
							$abtn .= '">';
							$abtn .= $cancelbuttontext;
							$abtn .= '</button></td>';
						}
						if($cancelimage) {
							$cbtn ='<input type="image" class="imageclass" src="[CANCELIMAGESRC]"  name="[STRIPEPRODID]" id="[STRIPEPRODID]" onClick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','STRIPE','[TRANSACTION_ID]');";
							$cbtn .='" value="CANCEL">';
						}
						else {
						/*	$cbtn='<span1 class="cancel">&nbsp;&nbsp;<a href="" id="[STRIPEPRODID]" onclick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','STRIPE','[TRANSACTION_ID]');";
							$cbtn .='">'.$canceltext.'</a></span1>';*/
							
							$cbtn = '<td class="cell-data-left"><button style="'.$cancelbuttonstyle.'" onClick="';
							$cbtn .="return cancelSubscription(document.formautoaction,'";
							$cbtn .="[PRODID]', '[RECURRINGID]','STRIPE','[TRANSACTION_ID]');";
							$cbtn .= '">';
							$cbtn .= $cancelbuttontext;
							$cbtn .= '</button></td>';
							
						}
					$ubtn='<td class="upgrade">&nbsp;&nbsp;<a target="_blank" href="'.$upgradelink.'" id="[STRIPEPRODID]"' ;
						$ubtn .='>'.$upgradetext.'</a></td>';
						if($template=='template1') {
						$ubtn='<td class="cell-data-left"><a target="_blank" href="'.$upgradelink.'" id="[STRIPEPRODID]"' ;
						$ubtn .='>'.$upgradetext.'</a></td>';
						}

						$current_msg = str_replace( '[BTN_CODE]', $abtn, $current_msg); 
						$current_msg = str_replace( '[BTN_CANCEL]', $cbtn, $current_msg);
						if($upgradelink !='')
							$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
						else
							$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);

						$current_msg = str_replace( '[STRIPEPRODID]', "stripeorder_".$product->getId(), $current_msg); 
					}
					else {

						if( ($cancelcontact!="") && ($cancelcontacturl!="")) {
							$cancelcontactlink="<td class='cell-data-left'><a style='text-align:center;color:blue' href=\"".$cancelcontacturl."\" target=\"_blank\">".$cancelcontact."</a></td>";
							logToFile("DAP-User-Subscription(): cancelcontactlink:  cancelcontactlink = ". $cancelcontactlink,LOG_INFO_DAP);
							$current_msg = str_replace( '[BTN_CANCEL]', $cancelcontactlink, $current_msg);  
							$current_msg = str_replace( '[BTN_CODE]', $cancelcontactlink, $current_msg); 
						} else {
							$nocanceldiv='<td class="cell-data-left" align="justify"></td>';
							$current_msg = str_replace( '[BTN_CODE]', $nocanceldiv, $current_msg);
							$current_msg = str_replace( '[BTN_CANCEL]', "", $current_msg);  

						if($upgradelink !='')
							$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
						else
							$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);
						}
					}
				} // Stripe end
				else  {  // if Infusion and others (not paypal, authnet)

				logToFile("DAP-User-Subscription(): dap_usersubscription:  Payment Processor = ". $payment_processor,LOG_INFO_DAP);



				if( ($cancelcontact!="") && ($cancelcontacturl!="")) {
				$cancelcontactlink="<td class='cell-data-left'><a style='text-align:center;color:blue' href=\"".$cancelcontacturl."\" target=\"_blank\">".$cancelcontact."</a></td>";
				logToFile("DAP-User-Subscription(): cancelcontactlink:  cancelcontactlink = ". $cancelcontactlink,LOG_INFO_DAP);
				$current_msg = str_replace( '[BTN_CANCEL]', $cancelcontactlink, $current_msg);  
				$current_msg = str_replace( '[BTN_CODE]', $cancelcontactlink, $current_msg); 
				} else {
				$nocanceldiv='<td class="cell-data-left" align="justify"></td>';
				$current_msg = str_replace( '[BTN_CODE]', $nocanceldiv, $current_msg);
				$current_msg = str_replace( '[BTN_CANCEL]', "", $current_msg);  

				if($upgradelink !='')
				$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
				else
				$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);
				}
				logToFile("DAP-User-Subscription(): dap_usersubscription:  Complete Payment Processor = ". $payment_processor,LOG_INFO_DAP);

				}//Others end

				}//If not cancelled subscription

				$current_msg = str_replace( '[CANCELIMAGESRC]', $cancelimage, $current_msg); 
			} // END showcancel=Y
			else { // Start showcancel=N
				$current_msg = str_replace( '[BTN_CODE]', "", $current_msg);
				$current_msg = str_replace( '[BTN_CANCEL]', "", $current_msg);
				
			}// End Show cancel=N
			
			
			/* code to show/hide pause/resume */
			if($showpause == "Y"){
				  
				// we will show these buttons only for stripe and paypal not for authnet
				if($paypal || $stripe){

					if($paypal){
						$processor = "PAYPAL";
					}						
					else{
						$processor = "STRIPE";
					}
					
					// now we will check for recurring_id
					if($recurring_id != "" && $is_recur == "Y"){
						
						if(strtolower($status) == "paused"){
							$showPause = ";display:none;";
							$showResume = "";
						}
						else{
							$showPause = "";
							$showResume = ";display:none;";
						}
						
						// first lets make pause button
						if($pauseurl != ""){ // get pause img url
							$pbtn ='<td class="cell-data-left"><input type="image" class="imageclass" src="'.$pauseurl.'" onClick="';
							$pbtn .="return pauseSubscription(document.formautoaction,'";
							$pbtn .="[PRODID]', '[RECURRINGID]','".$processor."','[TRANSACTION_ID]');";
							$pbtn .='" value="PAUSE" style="'.$showPause.'">';
						}
						else{ // get pause button data
							$pbtn = '<td class="cell-data-left"><button style="'.$pausebuttonstyle.$showPause.'" onClick="';
							$pbtn .="return pauseSubscription(document.formautoaction,'";
							$pbtn .="[PRODID]', '[RECURRINGID]','".$processor."','[TRANSACTION_ID]');";
							$pbtn .= '">';
							$pbtn .= $pausebuttontext;
							$pbtn .= '</button>';
						}
						
						$current_msg = str_replace( '[BTN_PAUSE]', $pbtn, $current_msg);
						
						if($resumeurl != ""){ // get pause img url
							$pbtn ='<input type="image" class="imageclass" src="'.$resumeurl.'" onClick="';
							$pbtn .="return resumeSubscription(document.formautoaction,'";
							$pbtn .="[PRODID]', '[RECURRINGID]','".$processor."','[TRANSACTION_ID]');";
							$pbtn .='" value="PAUSE" style="'.$showResume.'"></div>';
						}
						else{ // get pause button data
							$pbtn = '<button style="'.$resumebuttonstyle.$showResume.'" onClick="';
							$pbtn .="return resumeSubscription(document.formautoaction,'";
							$pbtn .="[PRODID]', '[RECURRINGID]','".$processor."','[TRANSACTION_ID]');";
							$pbtn .= '">';
							$pbtn .= $resumebuttontext;
							$pbtn .= '</button></div>';
						}
						
						$current_msg = str_replace( '[BTN_RESUME]', $pbtn, $current_msg);
						
					}
					else{
						$current_msg = str_replace( '[BTN_RESUME]', "", $current_msg);
						$current_msg = str_replace( '[BTN_PAUSE]', "<td class='cell-data-left' align='justify' style='display:none' ><strong></strong></td>", $current_msg);
						
						logToFile("DAP-User-Subscription(): showpause=Y , But can't show because recurring_id is missing",LOG_INFO_DAP);
					}
				}else {
				  $current_msg = str_replace( '[BTN_PAUSE]', "<td class='cell-data-left' align='justify' style='display:none' ><strong></strong></td>", $current_msg); 	
				  $current_msg = str_replace( '[BTN_RESUME]', "", $current_msg); 	
				}
			}else {

			  $current_msg = str_replace( '[BTN_PAUSE]', "<td class='cell-data-left' align='justify' style='display:none' ><strong></strong></td>", $current_msg); 	
			  $current_msg = str_replace( '[BTN_RESUME]', "", $current_msg); 
              
			}
			
				
				
			
			
			if($upgradelink !='')
				$current_msg = str_replace( '[BTN_UPGRADE]', $ubtn, $current_msg);
			else
				$current_msg = str_replace( '[BTN_UPGRADE]', "", $current_msg);
				
			$current_msg = str_replace( '[TRANSACTION_ID]', $transaction_id, $current_msg); 
			$current_msg = str_replace( '[RECURRINGID]', $recurring_id, $current_msg); 
			$current_msg = str_replace( '[PRODID]', $product->getId(), $current_msg); 
			$current_msg = str_replace( '[PAYMENTPROCESSOR]', $payment_processor, $current_msg); 
				
				//$content .= $current_msg;	
		} //End showTran=Y
			  
	} //End found trans
	else {
	  $current_msg = str_replace( '[BTN_PAUSE]', "<td class='cell-data-left' align='justify' style='display:none' ><strong></strong></td>", $current_msg); 	
	  $current_msg = str_replace( '[BTN_RESUME]', "", $current_msg); 
	}
	
	if($current_msg != ''){
		$html .= $current_msg;
	}

	
  } //end foreach
  
  //echo $content;die;
//	echo $content ;die;
//echo $html;die;
  logToFile("DAP-User-Subscription(): showTran=".$showTran,LOG_INFO_DAP);
  
  $html .=  DapMemberShowLoader(); 
  
	if($showpause == "Y"){
		$content = str_replace( '[DISPLAYPAUSERESUME]', 'display:table-cell', $content);
	}else{
		$content = str_replace( '[DISPLAYPAUSERESUME]', 'display:none!important', $content);	
	}

	
  $content = str_replace( '[CANCELLATIONTABLEDATA]', $html, $content);
  
  $content.='</form>';

   //echo $content;die;
  if($template =='template2')
   $content .=  '</div>';
 
 if($showTran!="Y") {
	//$content .= $notransfoundmsg;
	logToFile("DAP-User-Subscription(): no active transactions found",LOG_INFO_DAP);
  }
  $content .= $templatetextcolorstyle.$bgcolorstyle.$upgradetextcolorstyle;

  return $content;
}





function dap_shortcodeNew($atts, $content=null){ 
	

	extract(shortcode_atts(array(
		'isloggedin' => 'Y',
		'ispaiduser' => 'N',
		'hasaccessto' => 'ANY',
		'hasexpiredaccessto' => '',
		'hasaccesstoand' => '',
		'hasnoaccessto' => 'NONE',
		'neverhadaccessto' => '',
		'errmsgtemplate' => '',
		'userid' => '',
		'startday' => '',
		'endday' => '',
		'startdate' => '2008-10-10',
		'enddate' => '9999-12-31',
		'publicuntil' => '',
		'publicafter' => '',
		'gdprstatus' => ''
		
	), $atts));
	
	//$content = do_shortcode($content);
	$content = dap_clean_shortcode_content($content);	
 
	//First check - check publicUntil and publicAfter
//	logToFile("ENTER DAP-Shortcodes", LOG_DEBUG_DAP); 
	$now = strtotime(date("Y-m-d"));
	if($publicuntil != "") {
		$pubUntil = strtotime($publicuntil);
		$timeRemaining = intval($pubUntil) - intval($now);
		
		//logToFile("now: $now, pubUntil: $pubUntil, timeRemaining: $timeRemaining");
		if($timeRemaining >= 0) {
			//logToFile("There's still time for this to be public, so no protection. Return content as is"); 
			//There's still time for this to be public, so no protection. Return content as is.
			return do_shortcode($content);
		}
	}
	
	if($publicafter != "") {
		$pubAfter = strtotime($publicafter);
		$timeRemaining = intval($pubAfter) - intval($now);
		
		//logToFile("now: $now, pubAfter: $pubAfter, timeRemaining: $timeRemaining");
		if($timeRemaining <= 0) {
			//logToFile("This has turned public going forward, so no protection. Return content as is."); 
			//This has turned public going forward, so no protection. Return content as is.
			return do_shortcode($content);
		}
	}
	
	
	$session = Dap_Session::getSession();
	$user = $session->getUser();


	if( ($isloggedin == "N") && (Dap_Session::isLoggedIn() || isset($user)) ) {
		//logToFile("Shortcode says this is be shown only to those NOT logged in - BUT this person IS logged in, so get out");
		return getErrorMessage($errmsgtemplate);
	} else if( ($isloggedin == "N") && !Dap_Session::isLoggedIn() && !isset($user) ) {
		//logToFile("Shortcode says this is be shown only to those NOT logged in - and this person is NOT logged in, so return content and stop");
		return do_shortcode($content);
	}

	//Arriving here means isloggedin=Y
	if( !Dap_Session::isLoggedIn() || !isset($user) ) {
		//logToFile("Not logged in, returning errmsgtemplate");
		return getErrorMessage($errmsgtemplate);
	}

	//Check the GDPR stuff
	$gdpr_consent = $user->getGDPRConsent();
	if( $gdprstatus == "yes" ) {
		if( $gdpr_consent != "GDPR_CONSENT_YES" ) {
			return getErrorMessage($errmsgtemplate);
		}
	}elseif( $gdprstatus == "no" ) {
		if( $gdpr_consent != "GDPR_CONSENT_NO" ) {
			return getErrorMessage($errmsgtemplate);
		}
	}elseif( $gdprstatus == "notgdpruser" ) {
		if( $gdpr_consent != "NOT_GDPR_USER" ) {
			return getErrorMessage($errmsgtemplate);
		}
	}elseif( $gdprstatus == "unknown" ) {
		if( $gdpr_consent != "" ) {
			return getErrorMessage($errmsgtemplate);
		}
	}

	//Arriving here means user is logged in
	//logToFile("User is valid and logged in. Userid: " . $user->getId());
	//if( ($userid != "ANY") && ($userid != $user->getId()) ) {
		//return getErrorMessage($errmsgtemplate);
	//}
	
	if( $userid != "" ) {
		$userIdArray = explode(",",$userid);
		if ( !in_array($user->getId(),$userIdArray) ) {
			return getErrorMessage($errmsgtemplate);
		}
	}
	
	
	/** 
		hasaccessto means either...
		a) someone who has current access and has not expired, OR
		b) has expired, but post-cancellation access is set to y
	*/
	
	$user_id=$user->getId();
	if ($hasaccessto != "ANY") { 
//		logToFile("DAP-ShortCodes: check hasaccessto rules, hasaccessto=" . $hasaccessto . " userid=" . $user_id, LOG_DEBUG_DAP);
		//User MUST have access to the products listed
		if( !$user->hasAccessToProducts($hasaccessto) ) { 
			//true means user does NOT have access, which is not what we want
			return getErrorMessage($errmsgtemplate);
		}
	}
	
	if ($hasaccesstoand != "") { 
		//User MUST have access to the products listed
		logToFile("DAP-ShortCodes: check hasaccesstoand rules, hasaccesstoand=" . $hasaccesstoand . " userid=" . $user_id, LOG_DEBUG_DAP);
		$hasaccesstoandArr = explode(",",$hasaccesstoand);
		foreach ($hasaccesstoandArr as $hasproduct) {
			if( !$user->hasAccessTo($hasproduct) ) { 
			//true means user does NOT have access, which is not what we want
				return getErrorMessage($errmsgtemplate);
			}
		}
		
		logToFile("DAP-ShortCodes: Yes, user's access has access to all selected products, " . $hasaccesstoand . " userid=" . $user_id, LOG_DEBUG_DAP);
	}
	
	/** 
		hadaccessto "X" means...
		someone whose access to product "X" has expired
		
		hadaccessto to "ANY" means
		someone whose access to ANY product (1 or more) has expired
	*/
	if ($hasexpiredaccessto != "") { 
		logToFile("DAP-ShortCodes: check hasexpiredaccessto rules, hasexpiredaccessto=" . $hasexpiredaccessto . " userid=" . $user_id, LOG_DEBUG_DAP);
	
		//AND Rule... user product row shd exist for every product in the list and access should have expired for each product in the list
		$hasexpiredaccesstoArr = explode(",",$hasexpiredaccessto);
		foreach ($hasexpiredaccesstoArr as $hasproduct) {
			if( $user->hasAccessTo($hasproduct) ) { 
			//true means user has access, which is not what we want
				return getErrorMessage($errmsgtemplate);
			}
			else {
				if( !($user->hasEverHadAccessTo($hasproduct)) ) { 
			//true means user does NOT have access, which is not what we want
			
					return getErrorMessage($errmsgtemplate);
				}
			}
		}
		
		logToFile("DAP-ShortCodes: Yes, user's access has expired to all selected products, " . $hasexpiredaccessto . " userid=" . $user_id, LOG_DEBUG_DAP);
		
		//User MUST have access to the products listed
		
	}
	
	
	if ($hasnoaccessto != "NONE") {
		logToFile("DAP-ShortCodes: check hasnoaccessto rules, hasnoaccessto=" . $hasnoaccessto . " userid=" . $userid, LOG_DEBUG_DAP);
		//User should NOT have access to the products listed
		if( $user->hasAccessToProducts($hasnoaccessto) ) { 
			//true means user DOES have access, which is not what we want
			return getErrorMessage($errmsgtemplate);
		}
		logToFile("DAP-ShortCodes: Yes, user does not have access to all selected products, " . $hasexpiredaccessto . " userid=" . $user_id, LOG_DEBUG_DAP);
	}
	
	
	if ($neverhadaccessto != "") { 
		logToFile("DAP-ShortCodes: check neverhadaccessto rules, neverhadaccessto=" . $neverhadaccessto . " userid=" . $user_id, LOG_DEBUG_DAP);
	
		//AND Rule... user product row shd exist for every product in the list and access should have expired for each product in the list
		$neverhadaccesstoArr = explode(",",$neverhadaccessto);
		foreach ($neverhadaccesstoArr as $neverhadproduct) {
			if( $user->hasAccessTo($neverhadproduct) ) { 
			//true means user has access, which is not what we want
				return getErrorMessage($errmsgtemplate);
			}
			else {
				if( ($user->hasEverHadAccessTo($neverhadproduct)) ) { 
			//true means user does NOT have access, which is not what we want
			
					return getErrorMessage($errmsgtemplate);
				}
			}
		}
		
		logToFile("DAP-ShortCodes: user never had accesss to all selected products, " . $neverhadproduct . " userid=" . $user_id, LOG_DEBUG_DAP);
		
		//User MUST have access to the products listed
		
	}
	
	//Then check startdate and enddate
	
	if( ($startdate != "2008-10-10") || ($enddate != "9999-12-31") ) {
		logToFile("now: $now , startdate: $startdate , strtotime(startdate): " . strtotime($startdate)); 
		//logToFile("now: $now , strtotime(enddate)" . strtotime($enddate)); 
		if (
				( 
						( intval($now) >= intval(strtotime($startdate)) ) && 
						( intval($now) <= intval(strtotime($enddate)) )
					) 
					&& 
					( Dap_UsersProducts::isContentDateValid($user->getId(), $hasaccessto, $startdate) )
				)
				{
					return do_shortcode($content);
				} else {
					return getErrorMessage($errmsgtemplate);
				}
	}
	
	/*if( ($day != "-1") && ($hasaccessto != "ANY") && !$user->isDripEligible($hasaccessto, $day) ) {
		//logToFile("Not Eligible");
		return getErrorMessage($errmsgtemplate);
	} */
	
	
	if( (($startday != "") || ($endday != "")) && ($hasaccessto != "ANY") ) {
		$isDripEligible = false;
		logToFile("DAP-ShortCodes: startday: " . $startday . ", endday: " . $endday . " hasaccessto=" . $hasaccessto , LOG_DEBUG_DAP);
		if( (intval($startday) >= 1) && (intval($endday) >= 1) ) {
			logToFile("Positive"); 
			$isDripEligible = $user->isDripEligible($hasaccessto, $startday, $endday);
		} else if( (intval($startday) < 0) && (intval($endday) < 1) ) {
			logToFile("Negative"); 
			logToFile("startday: " . $startday . ", endday: " . $endday); 
			$isDripEligible = $user->isDripEligibleReverse($hasaccessto, $startday, $endday);
		}
		
		if(!$isDripEligible) {
			logToFile("Not Eligible");
			return getErrorMessage($errmsgtemplate);
		}
	} 
	
	if($ispaiduser == "Y") {
		//logToFile("Must be Paid User"); 
		if(!$user->isPaidUser()) {
			//logToFile("No, not a paid user"); 
			return getErrorMessage($errmsgtemplate);
		}
		
		//Arriving here means user ispaiduser
		if($hasaccessto == "ANY") {
			//Product doesn't matter, so simply return content
			return do_shortcode($content);
		} else {
			//Specific products only
			if($user->hasPaidAccessToProducts($hasaccessto)) {
				return do_shortcode($content);
			} else {
				return getErrorMessage($errmsgtemplate);
			}
		}
	} else { //ispaiduser == "N"
		//logToFile("Doesn't have to be Paid User"); 
	
		if($hasaccessto == "ANY") {
			//Product doesn't matter, so simply return content
			//logToFile("Product doesn't matter - simply returning content"); 
			return do_shortcode($content);
		} else {
			//Specific products only
			if($user->hasAccessToProducts($hasaccessto)) {
				return do_shortcode($content);
			} else {
				return getErrorMessage($errmsgtemplate);
			}
		}
	}
	
	return do_shortcode($content);
}



function getErrorMessage($errmsgtemplate) {
	//logToFile("errmsgtemplate: " . $errmsgtemplate); 
	if($errmsgtemplate == "") {
		return "";
	} else {
		$errMsg = Dap_Templates::getContentByName($errmsgtemplate);
		if($errMsg != "") {//there is such a template in the db
			return $errMsg;
		} else {
			//Check if file name
			if( strpos($errmsgtemplate,"file:") !== false ) {//it's a file name
				//get contents of file and return it
				$fileName = substr($errmsgtemplate,5);
				$errMsg = file_get_contents($fileName);
				return $errMsg;
			} else {
				//It's custom error text - simply return it
				return html_entity_decode($errmsgtemplate);
			}
		}
	}
	return "Sorry, you don't have access to this content";
}

 /******* get template  ********/    
function getDripTemplateDAPShortcodeContent($template_path, $courseTemplateName, $customCourseTemplateName)
{
	
	if(file_exists($template_path.$customCourseTemplateName)) {
	  $course_temp_content = file_get_contents($template_path.$customCourseTemplateName);
	}
	
	if($course_temp_content == "") {
		if(file_exists($template_path.$courseTemplateName)) {
			$course_temp_content = file_get_contents($template_path.$courseTemplateName);
		}
		else{
			$course_temp_content = "";
		}
	  
	//	logToFile("DAP-ShortCodes: no custom template found=".$template_path.$courseTemplateName,LOG_INFO_DAP);
	} else {
	//	logToFile("DAP-ShortCodes: custom template found=".$template_path.$customCourseTemplateName,LOG_INFO_DAP);  
	}	
	
	return $course_temp_content; 
	
}


function dap_memberGroupShortcode($atts, $content=null){
	extract(shortcode_atts(array(
	'id' =>'id',
	), $atts));

	$groupId = $id;
	
	
	ob_start();
	eval("?>" . file_get_contents(plugin_dir_path(__FILE__)."/includes/frontend/groupAccount.php"));	
	$output = ob_get_contents();
	ob_end_clean();
	return do_shortcode($output);  
	
	
}
		

