<?php 
include_once(dap_member_dir.'DAP_Mycontent_Frontend.php');
include_once(dap_member_dir.'DAP_Myprofile_Frontend.php');
unset($_SESSION["dap_more_login_form"]);


function DAPMemberCommonCssAndJsWith(){
	 
	//added jquery here, checking if already exist or not
	if(wp_script_is('jquery')) {
		$jquerymain =" ";
 
	} else {
		$jquerymain ="<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>";
	}
	 
	$cssAndJs  = "<link rel='stylesheet' id='dap_member_bootstrap4-css'  href='".dap_member_path."includes/css/bootstrap4.min.css' type='text/css' media='all' />
					<link rel='stylesheet' id='dap_member_sweetalert-css'  href='//cdnjs.cloudflare.com/ajax/libs/bootstrap-sweetalert/1.0.1/sweetalert.css' type='text/css' media='all' />
					<link rel='stylesheet' id='dap_member_font_awesome-css'  href='//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css' type='text/css' media='all' />
					<link rel='stylesheet' id='dap_member_font-css'  href='//fonts.googleapis.com/css?family=Open+Sans%3A400%2C600%2C700&#038;display=swap' type='text/css' media='all' />
					<link rel='stylesheet' id='dap_member_font-css'  href='//cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css' type='text/css' media='all' />
					<link rel='stylesheet' id='dap_member_dataTables-css'  href='".dap_member_path."includes/css/dap_member_frontend_common.css?10' type='text/css' media='all' />
					<script type='text/javascript' src='//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js'></script>
					<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js'></script>
					<script type='text/javascript' src='".dap_member_path."includes/js/dap_member_frontend_common.js?".rand(10,1000)."'></script>";
	return $jquerymain.$cssAndJs;							
					
}

add_shortcode('DAPMemberAffiliateDetails', 'DAPMemberAffiliateDetails');
function DAPMemberAffiliateDetails($atts, $content = null) {
	
	extract(shortcode_atts(array(
	'id' => '',
	), $atts));
	
	$loging_status = false;
	
	if(Dap_Session::isLoggedIn()){ 
		$loging_status = true;
		
	}
	$html = '';
	$mp_obj = DAP_MemberPages::loadById($id);
	if($mp_obj && $mp_obj->getAction() == 'affiliate'){
		
		$template =  stripslashes($mp_obj->getTemplateHtml());
		$styling_options = $mp_obj->getStylingOptions();
		$styling_options = explode("|||",$styling_options);
		$show_aff_coupon_details = false;	
		if(isset($styling_options[4])){
			if($styling_options[4] == 'true'){
				$show_aff_coupon_details = true;	
			}	
		}
		
		$html   = "<div id='dap_member_affiliate_frontend_shortcode' class='live-links-bootstrap_outer dap_member_frontend_shortcode dap_member_affiliate_frontend_shortcode_".$mp_obj->getId()."'>";
		$html  .= "<link rel='stylesheet' id='dap_member_bootstrap4-css'  href='".dap_member_path."includes/css/bootstrap4.min.css' type='text/css' media='all' />					
					<link rel='stylesheet' id='dap_member_dataTables-css'  href='".dap_member_path."includes/css/dap_member_frontend_common.css?10' type='text/css' media='all' />";
					
		if($loging_status){
			
		$html  .= "
					<link rel='stylesheet' id='dap_member_sweetalert-css'  href='//cdnjs.cloudflare.com/ajax/libs/bootstrap-sweetalert/1.0.1/sweetalert.css' type='text/css' media='all' />
					<link rel='stylesheet' id='dap_member_font-css'  href='//fonts.googleapis.com/css?family=Open+Sans%3A400%2C600%2C700&#038;display=swap' type='text/css' media='all' />
					<link rel='stylesheet' id='dap_member_font-css'  href='//cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css' type='text/css' media='all' />
					
					
					<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
					<link rel='stylesheet' id='dap_member_affiliate-template-css'  href='".dap_member_path."includes/templates/affiliate/".$mp_obj->getTemplate()."/style.css?".rand(10,1000)."' type='text/css' media='all' />
					<script type='text/javascript' src='//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js'></script>
					<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js'></script>
					<script type='text/javascript' src='".dap_member_path."includes/js/dap_member_frontend_common.js?".rand(10,1000)."'></script>
					<script type='text/javascript' src='".dap_member_path."includes/js/dap_member_affiliate_frontend.js?".rand(10,1000)."'></script>
					
					";	
			
			$session = Dap_Session::getSession();
			$user = $session->getUser();
			$user_email = $user->getEmail();
			$user_id = $user->getID();
			$account_type = $user->getAccount_type();
			$admin_login = false;
			$admin_login_class = "";
			
			$affCouponHtml = '';	
			if($show_aff_coupon_details){
				$affCouponHtml = getDapAffiliateCouponSummaryHtml($user_id);
				//$template =  str_replace('<tr><td colspan="9">%%AFFCOUPONDETAILS%%</td></tr>',$affCouponHtml,$template);
				
			}
			
			
			if( $session->isAdmin()){
				$admin_login = true;
				$admin_login_class = "admin_loign";
			}
			$html .="<div class='user_account_type user_account_type_".$account_type." $admin_login_class'>"; 
	        //replace merge tag	
			$template =  str_replace('contenteditable="true"','contenteditable="false"',$template);
			$template =  str_replace('<tr><td colspan="9">%%AFFILIATESUMMARYDATAREPLACEDINFRONTEND%%</td></tr>',getDapAffiliatePerformanceSummaryHtml($user_email),$template);
			$template =  str_replace('<tr><td colspan="5">%%TRAFFICSTATISTICSDATAREPLACEDINFRONTEND%%</td></tr>',getDapAffiliateStatsHtml($user_email),$template);
			$template =  str_replace('<tr class="frontendVisibility"><td colspan="9">%%AFFCOUPONDETAILS%%</td></tr>',$affCouponHtml,$template);
			if($admin_login){
				$template =  str_replace('%%ADMINEARNINGSDETAILSDATAREPLACEDINFRONTEND%%',getDapAffiliateEarningsDetailsHtml($user_email),$template);
				$template =  str_replace('%%ADMINEARNINGSDETAILSDATAREPLACEDINFRONTENDCLASS%%','d-none',$template);
			}else{
				$template =  str_replace('%%ADMINEARNINGSDETAILSDATAREPLACEDINFRONTEND%%','',$template);
				$template =  str_replace('<tr><td colspan="12">%%EARNINGSDETAILSDATAREPLACEDINFRONTEND%%</td></tr>',getDapAffiliateEarningsDetailsHtml($user_email),$template);
			}
			$template =  str_replace('<tr><td colspan="6">%%PAYMENTDETAILSDATAREPLACEDINFRONTEND%%</td></tr>',getDapAffiliatePaymentsDetailsHtml($user_email,$account_type),$template);
			$template =  str_replace('%%USERID%%',$user_id,$template);
			$template =  str_replace('%%AFFBACKEND%%','d-none',$template);
			$html  .= $template;
			$html  .= "</div>";
			
			if($affCouponHtml == ''){
				$html  .= "<style>#dap_member_affiliate_inner .aff_coupon_details_outer{display:none !important}</style>";	
			}
			
		}else{
			
			//$html .= "Sorry, you must log in before you can view this content. <a href='#'>Click here to login</a>";
			$not_login_msg = dapMemberGetMessageByKeyAndAction('affiliate','not_login');
			
			if($not_login_msg == ''){
				$not_login_msg = 'Sorry, you must log in before you can view this content. %%LINKSTART%%  Click to login %%LINKEND%%.';
			}
		
			
			$not_login_msg = str_replace('%%LINKSTART%%','<a href="'.Dap_Config::get("LOGIN_URL").'">',$not_login_msg);
			$not_login_msg = str_replace('%%LINKEND%%','</a>',$not_login_msg);
			$html .= "<div class='not-login'>".$not_login_msg."</div>";
			

		}			
					
	 
	 
	   $html .= "</div><style>#aff_coupon_details_table .backendVisibility{display:none}</style>";
   }
	   
	  return   $html; 
	   
	
}	

add_shortcode('DAPMemberLogin', 'DAPMemberLoginShortcode');
function DAPMemberLoginShortcode($atts, $content = null) {
	
	extract(shortcode_atts(array(
	'id' => '',
	), $atts));
	
	$loging_status = false;
	
	if(!Dap_Session::isLoggedIn()){ 
		$loging_status = true;
		
	}
	// for unset the login session
	$_SESSION['daploginform']="";
	unset($_SESSION['daploginform']);
	
	$mp_obj = DAP_MemberPages::loadById($id);
	if($mp_obj){
		
		if($mp_obj->getAction() == 'loginFB'){
			ob_start();
			eval("?>" . file_get_contents(plugin_dir_path(__FILE__)."/includes/frontend/dapmemberloginFB.php"));		
			$output = ob_get_contents();
			ob_end_clean();
			return do_shortcode($output);
		}
		
		
		//add_action('wp_footer', 'dap_member_login_frontend_print_scripts', 5);
		$action_id = $mp_obj->getId();
		$template =  $mp_obj->getTemplateHtml();
		$template = explode("%%DAPMEMBERLOGINTEMPLATE%%",$template);
		
		$template1 = '';
		if(isset($template[0])){
			$template1 = $template[0];
		}
		if(isset($template[1])){
			$template2 = $template[1];
		}
		if(isset($template[2])){
			$template3 = $template[2];
		}
		
		
		$dap_login_ajax_url =  admin_url( 'admin-ajax.php' );		
        $dap_login_ajax_url = "<script> var  dap_login_ajax_url = '".$dap_login_ajax_url."'</script>";	
		$html   = "<div id='dap_member_login_frontend_shortcode' class='live-links-bootstrap_outer dap_member_frontend_shortcode dap_member_login_frontend_shortcode_".$mp_obj->getId()."'>";
		$html  .= "<link rel='stylesheet' id='dap_member_frontend_common-css'  href='".dap_member_path."includes/css/dap_member_frontend_common.css?10' type='text/css' media='all' />";
		$html  .= "<link name='dap_member_login_style' rel='stylesheet' href='".dap_member_path."includes/templates/".$mp_obj->getAction()."/".$mp_obj->getTemplate()."/style.css?".rand(10,1000)."'>";
		 				 
		if($loging_status){	 
			
				// fix for the jquery exist in wp or not. So if exist then we will not include
			$script_style = "";
			if(wp_script_is('jquery')) {
		  
				//added for if the jquery from wp is including in the footer
				wp_enqueue_style( 'dap_member_frontend_common-css', dap_member_path."includes/css/dap_member_frontend_common.css?10" ); 				 		
				wp_enqueue_style( 'dap_member_login-css', dap_member_path."includes/templates/".$mp_obj->getAction()."/".$mp_obj->getTemplate()."/style.css" ); 		 		
				wp_enqueue_style( 'dap_member_frontend_bootstrap4', dap_member_path."includes/css/bootstrap4.min.css" ); 			
				wp_enqueue_style( 'dap_member_frontend_sweetalert', "//cdnjs.cloudflare.com/ajax/libs/bootstrap-sweetalert/1.0.1/sweetalert.css" ); 			
				wp_enqueue_style( 'dap_member_frontend_awesome', "//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" ); 			
				wp_enqueue_style( 'dap_member_frontend_googleapis', "//fonts.googleapis.com/css?family=Open+Sans%3A400%2C600%2C700&#038;display=swap" ); 				 		
				wp_enqueue_script( 'dap_member_frontend_sweetalert', "//cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js", '', true);		
				wp_enqueue_script( 'dap_member_frontend_common', dap_member_path."includes/js/dap_member_frontend_common.js?".rand(10,1000), '', true);		
				wp_enqueue_script( 'dap_member_frontend_login', dap_member_path."includes/js/dap_member_frontend_login.js?".rand(10,1000), '', true);		
				
				 //THie check is only for DIVI theme
				$theme = wp_get_theme(); // gets the current theme	
				 
				if ( 'Hello Elementor' == $theme->name || 'Hello Elementor' == $theme->parent_theme  ||  'Divi Medical Child Theme' == $theme->name || 'Divi Medical Child Theme' == $theme->parent_theme  ||  'BuddyBoss Child' == $theme->name ||   'BuddyBoss Child'  == $theme->parent_theme  ) {
					 
					$html .= "<link rel='stylesheet' id='dap_member_bootstrap4-css'  href='".dap_member_path."includes/css/bootstrap4.min.css' type='text/css' media='all' />
						<link rel='stylesheet' id='dap_member_sweetalert-css'  href='//cdnjs.cloudflare.com/ajax/libs/bootstrap-sweetalert/1.0.1/sweetalert.css' type='text/css' media='all' />
						<link rel='stylesheet' id='dap_member_font_awesome-css'  href='//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css' type='text/css' media='all' />
						<link rel='stylesheet' id='dap_member_font-css'  href='//fonts.googleapis.com/css?family=Open+Sans%3A400%2C600%2C700&#038;display=swap' type='text/css' media='all' />									
						<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js'></script>
						<script type='text/javascript' src='".dap_member_path."includes/js/dap_member_frontend_common.js?".rand(10,1000)."'></script>
						<script type='text/javascript' src='".dap_member_path."includes/js/dap_member_frontend_login.js?".rand(10,1000)."'></script>";
				}
				
				
			} else {
				 
				// insert jQuery
				$html .='		 <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>	';
				$html  .= "<link rel='stylesheet' id='dap_member_bootstrap4-css'  href='".dap_member_path."includes/css/bootstrap4.min.css' type='text/css' media='all' />
						<link rel='stylesheet' id='dap_member_sweetalert-css'  href='//cdnjs.cloudflare.com/ajax/libs/bootstrap-sweetalert/1.0.1/sweetalert.css' type='text/css' media='all' />
						<link rel='stylesheet' id='dap_member_font_awesome-css'  href='//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css' type='text/css' media='all' />
						<link rel='stylesheet' id='dap_member_font-css'  href='//fonts.googleapis.com/css?family=Open+Sans%3A400%2C600%2C700&#038;display=swap' type='text/css' media='all' />	
										
						<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js'></script>
						<script type='text/javascript' src='".dap_member_path."includes/js/dap_member_frontend_common.js?".rand(10,1000)."'></script>
						<script type='text/javascript' src='".dap_member_path."includes/js/dap_member_frontend_login.js?".rand(10,1000)."'></script>
						";
			
			}
			
			$signin_display = 'display:none';
			if(isset($_GET['action']) && ($_GET['action'] == 'rp')){
				$html  .= "<div class='user_login reset_password_div' style='display:none' id='reset_password_div_id_".rand(10,10000)."'>";
				$html  .= DapMemberLoginReplaceMergeTags($template1);
				$html  .= "<div class='dap_reset_template_static_div' style='display:none'>".DapMemberLoginReplaceMergeTags($template3)."</div>";
				$html  .= "<input type='hidden' name='dm_reset_pass_key' value='".$_GET['key']."'>";		
				$html .= "</div>";
				//$html .= "<div>";
			}else{
				$signin_display = '';
			}	
			
			if(dapMemberLoginCheckedCaptchaEnable($mp_obj->getId())){			
				$html  .= '<script src="//www.google.com/recaptcha/api.js" async defer></script>';	
				$dm_login_temp_captcha = 'yes';
			}	
			$html  .= "<div class='user_login signin_forgot_password_div' id='parent_outer_class_".rand(10,1000)."' style='".$signin_display."'>";
			$html  .= DapMemberLoginReplaceMergeTags($template1,$mp_obj);
			$html  .= "<div class='dap_forgot_template_static_div' style='display:none'>".DapMemberLoginReplaceMergeTags($template2)."</div>";
			
			
			
		   //$html .= "</div>";
		   $html .= "<div>";
		   $html .= "<input type='hidden' name='action_id' value='".$action_id."'>";		
		   $html .= "<input type='hidden' name='dm_login_temp_captcha' value='".$dm_login_temp_captcha."'>";	
		   $html .= '<input  type="hidden" name="dap_email_empty" value="'.dapMemberGetMessageByKeyAndAction('login','email_empty').'">
				     <input  type="hidden"  name="dap_password_empty" value="'.dapMemberGetMessageByKeyAndAction('login','password_empty').'">
					<input  type="hidden"  name="dap_email_valid" value="'.dapMemberGetMessageByKeyAndAction('login','email_valid').' ">
					<input  type="hidden"  name="dap_email_password_wrong" value="'.dapMemberGetMessageByKeyAndAction('login','email_password_wrong').' ">
					<input  type="hidden"  name="dap_login_success" value="'.dapMemberGetMessageByKeyAndAction('login','login_success').' ">
					<input  type="hidden"  name="dap_email_not_found" value="'.dapMemberGetMessageByKeyAndAction('login','email_not_found').'">
					<input  type="hidden"  name="dap_reset_link" value="'.dapMemberGetMessageByKeyAndAction('login','reset_link').'">
					<input  type="hidden"  name="dap_password_not_match" value="'.dapMemberGetMessageByKeyAndAction('login','password_not_match').'">
					<input  type="hidden"  name="dap_reset_password_success" value="'.dapMemberGetMessageByKeyAndAction('login','reset_password_success').'">
					<input  type="hidden"  name="dap_reset_key_expired" value="'.dapMemberGetMessageByKeyAndAction('login','reset_key_expired').'">
					<input  type="hidden"  name="dap_captcha_not_select" value="'.dapMemberGetMessageByKeyAndAction('login','captcha_not_select').'">
					<span style="display:none" class="dap_login_btn_html"></span>
					<span style="display:none" class="dap_loader_html"><i class="fa fa-spinner fa-pulse fa-3x fa-fw" style="font-size:36px;"></i></span>
					<input  type="hidden"  name="invalid_captcha" value="'.dapMemberGetMessageByKeyAndAction('login','invalid_captcha').'">';	 
		   
		   if(isset($_GET['request'])){
				$dap_request = 1;
			}else{
				$dap_request = 0;
			}			
			$html .= '<input  type="hidden"  name="dap_request" value="'.$dap_request.'">';	  
			$html .= '<input  type="hidden"  name="dap_login_stie_url" value="'.site_url().$_GET['request'].'">';			
					
					 
				
		   $html .= "</div>";	
		   $html .= "</div>";	
		   
		   //For CS login to set the login session	   
		   $_SESSION["daploginform"]="yes";	
		   	
		   $html .= $dap_login_ajax_url;		
		   $html .= DapMemberShowLoader();	
		}else{
			//$html .= "You are already logged in. <a href='".dapMemberGetPostLoginURl($action_id)."'>Click here to continue...</a>";
			$already_login_msg = stripslashes(dapMemberGetMessageByKeyAndAction('login','already_login'));
			
			$redirectURL = Dap_UsersProducts::getLoggedInURL();
			$already_login_msg = str_replace('%%LINKSTART%%','<a href="'.$redirectURL.'">',$already_login_msg);
			$already_login_msg = str_replace('%%LINKEND%%','</a>',$already_login_msg);
			$already_login_msg = str_replace('%%HERE%%','<a href="'.$redirectURL.'">here</a>',$already_login_msg);
			$html .= "<div class='dap_alredy_login'>".$already_login_msg."</div>";
			
			$session = DAP_Session::getSession();
			$user = $session->getUser();	
			if( $session->isAdmin() ) {
				$dap_admin_login_msg = stripslashes(dapMemberGetMessageByKeyAndAction('login','dap_admin_already_login'));
				
				$dap_admin_login_msg = str_replace('%%LINKSTART%%',"<a href='/dap/admin/'>",$dap_admin_login_msg);
				$dap_admin_login_msg = str_replace('%%LINKEND%%','</a>',$dap_admin_login_msg);
				$html .= "<div class='dap_admin_alredy_login dap_alredy_login'>".$dap_admin_login_msg."</div>";
			
				
			
			}else if($user->getAccount_type() == "C" && $user->getCustom_role_id() != ""){	
				try{
					$role = Dap_UserRoles::loadRoleById($user->getCustom_role_id());
					if(isset($role) && $role != ""){
						$dap_account_type_roll_login = dapMemberGetMessageByKeyAndAction('login','dap_account_type_roll_login');
											
						$dap_account_type_roll_login = str_replace('%%LINKSTART%%',"<a href='/dap/admin/'>",$dap_account_type_roll_login);
						$dap_account_type_roll_login = str_replace('%%LINKEND%%','</a>',$dap_account_type_roll_login);
						$dap_account_type_roll_login = str_replace('%%USERROLL%%',$role['name'],$dap_account_type_roll_login);
						$html .= "<div class='dap_alredy_login dap_account_type_c_login'>".$dap_account_type_roll_login."</div>";
						//$html = $html . ">>> <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');
				}
			
			}
			
			
			

		}
	   $html  .= "</div>";	
	   return do_shortcode($html);	
		
	}
	
	
}

function getDapMemberAuthenticateUrl(){
	return $authenticate_url = "/dap/authenticate.php";
}
/*
* Replace merge tags with products info
*/ 
function DapMemberLoginReplaceMergeTags($html = '',$mp_obj = ''){
	
	
	if($mp_obj != ''){
		
		
		if(dapMemberLoginCheckedCaptchaEnable($mp_obj->getId())){			
			$google_site_key = Dap_Config::get("GOOGLE_SITE_KEY");
			if($google_site_key != ''){
				$html = str_replace( '%%CAPTCHAVAL%%','yes', $html);
				$html = str_replace( '%%GOOGLESITEKEY%%',$google_site_key, $html);
				$html = str_replace( '%%CAPTCHAFRONTEND%%','block', $html);
				
			}
		}
	}
	$html =  str_replace('contenteditable="true"','contenteditable="false"',$html);
	$html = str_replace("%%BACKENDDISPLAY%%", 'none', $html );
	
	return $html;
}

function dap_member_login_frontend_print_scripts(){
	
	 wp_enqueue_style( 'dap_member_bootstrap4', dap_member_path."includes/css/bootstrap4.min.css" ); 
	 
	 wp_enqueue_style( 'dap_member_sweetalert', '//cdnjs.cloudflare.com/ajax/libs/bootstrap-sweetalert/1.0.1/sweetalert.css' ); 
	 
	 wp_enqueue_style( 'dap_member_font_awesome', '//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css' ); 
	 wp_enqueue_style( 'dap_member_font', '//fonts.googleapis.com/css?family=Open+Sans:400,600,700&display=swap' ); 
	 wp_enqueue_style( 'dap_member_frontend_common', dap_member_path.'includes/css/dap_member_frontend_common.css?'.rand(10,1000) ); 
	 wp_enqueue_script( 'dap_member_bootstrap',  '//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js','', true);
	 wp_enqueue_script( 'dap_member_sweetalert',  '//cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js','', true);
	 wp_enqueue_script( 'dap_member_frontend_common',  dap_member_path.'includes/js/dap_member_frontend_common.js?'.rand(10,1000),'', true);
	 
	 echo DapMemberShowLoader();	
}


function getDapAffiliatePerformanceSummaryHtml($user_email = ''){
	
    $start_date = '01-01-2008';
    $end_date = '';
	$html  = '';
	$session = Dap_Session::getSession();
	$admin_login = false;
	if( $session->isAdmin() ) {
		$admin_login = true;
	}
	$results = Dap_AffStats::loadAffiliatePerformanceSummary($user_email, $start_date, $end_date);
	foreach($results as $element){
		
		
		if($admin_login){
			$epc = "";
			if(intval($element['clicks']) != 0) {
				$epc = number_format(intval($element['amt_earned_cash'])/intval($element['clicks']), 2, '.', '');
			}	
			if($epc == 0.00) $epc = "";
		}else{
			
			$clicks = (intval($element['clicks']) == 0) ? 1 : intval($element['clicks']);
			$epc = number_format(intval($element['amt_earned_cash'])/$clicks, 2, '.', '');
		}
		
		$html  .= '<tr>';
		$html  .= "<td><a href='/dap/admin/addEditUsers.php?userId=".$element['id']."' target='_blank'>".$element['id']."</a></td>";
		$html  .= "<td>".$element['first_name']. " " .$element['last_name']."</td>";
		$html  .= "<td>".$element['email']."</td>";
		$html  .= "<td>".$element['clicks']."</td>";
		$html  .= "<td>".$element['leads']."</td>";
		$html  .= "<td>".$element['amt_earned_cash']."</td>";
		$html  .= "<td>".$element['amt_earned_credits']."</td>";
		$html  .= "<td>".$element['sales']."</td>";
		$html  .= "<td>".$epc."</td>";
		$html  .= '</tr>';
	}

	
	
	return $html;
}

function getDapAffiliateCouponSummaryHtml($user_id){
	$userCoupons = Dap_Coupon::loadCouponByUserId($user_id);
	$affCouponHtml = '';
	if(count($userCoupons)){
		foreach($userCoupons as $coupon){
			$discount_amt = $coupon->getDiscount_amt();
			$discount_percent = $coupon->getDiscount_amt_percent();
			$finalAmount = 0;
			if($discount_amt > 0){
				$finalAmount = $discount_amt ;		
			}else if($discount_percent > 0){
				$finalAmount = $discount_percent.'%' ;		
			}
			$actual_usage = $coupon->getActual_usage();
			$max_usage = $coupon->getMax_usage();
			$start_date = $coupon->getStart_date();
			$start_date = date("m-d-Y", strtotime($start_date));
			$end_date = $coupon->getEnd_date();
			$end_date = date("m-d-Y", strtotime($end_date));
			$affCouponHtml .= '<tr>';		
			$affCouponHtml .= '<td>'.$coupon->getCode().'</td>';		
			$affCouponHtml .= '<td>'.$finalAmount.'</td>';		
			$affCouponHtml .= '<td>'.$actual_usage.'</td>';		
			$affCouponHtml .= '<td>'.$max_usage.'</td>';		
			$affCouponHtml .= '<td>'.$start_date.'</td>';		
			$affCouponHtml .= '<td>'.$end_date.'</td>';		
			$affCouponHtml .= '</tr>';		
		}
		
	}	
	return $affCouponHtml;
}


function getDapAffiliateStatsHtml($user_email = ''){
	
	$start_date = '01-01-2008';
    $end_date = '';
	$html  = '';
	$session = Dap_Session::getSession();
	$admin_login = false;
	if( $session->isAdmin() ) {
		$admin_login = true;
	}
	$html = '';
	$results = Dap_AffCommissions::loadAffiliateStats($user_email, $start_date, $end_date);
	foreach($results as $element){
		
		$html  .= '<tr>';
		if($admin_login){
			$html  .= "<td><a href='/dap/admin/addEditUsers.php?userId=".$element['user_id']."' target='_blank'>".$element['user_id']."</a></td>";
			$html  .= "<td>".$element['first_name']. " " .$element['last_name']."</td>";
		}else{
			$html  .= "<td></td>";
			$html  .= "<td></td>";
		}
		
		$html  .= "<td><a href='".$element['http_referer']."' target='_blank' title=".$element['http_referer'].">".trimString($element['http_referer'],80,45,30)."</a></td>";
		$html  .= "<td><a href='".$element['dest_url']."' target='_blank' >".trimString($element['dest_url'],80,45,30)."</a></td>";
		$html  .= "<td>".$element['datetime']."</td>";
		
		$html  .= '</tr>';
	}
	
	return $html;
}


function getDapAffiliateEarningsDetailsHtml($user_email = ''){
	
	$start_date = '01-01-2008';
    $end_date = '';
	$html  = '';
	$session = Dap_Session::getSession();
	$admin_login = false;
	$html = '';
	$earningTypes = "'L','S','C','T2','T3'";
	
	if( $session->isAdmin() ) {
		$admin_login = true;
		$html  = '<br><strong><span>NOTE: You are seeing this message only because you are a DAP Admin</span></strong><br/><br/><span>Sorry, this table has too much data to view within WordPress. <a href="/dap/">Click here to view it on your Admin Home Page</a></span>';
	}else{
		$user = $session->getUser();
	
		if( $user->getAccount_type() == "U" ) {
			$result = Dap_AffCommissions::loadAffiliateEarningsDetails($user_email, $start_date, $end_date);
			$showReferralDetails = Dap_Config::get("SHOW_REFERRAL_DETAIL");
			foreach($result as $element) {
				
				if(!isset($element['refund_date'])) $element['refund_date'] = "";
				
				if($showReferralDetails == "F-L") {
					$referralDetails = $element['first_name_buyer'] . " " . $element['last_name_buyer'];
				} else if($showReferralDetails == "F-L-E") {
					$referralDetails = $element['first_name_buyer'] . " " . $element['last_name_buyer'] . "<br/> " .$element['email_buyer'];
				} else if($showReferralDetails == "F-L-E-P") {
					$referralDetails = $element['first_name_buyer'] . " " . $element['last_name_buyer'] . "<br/> ".$element['email_buyer'] . "<br/>Ph: " . $element['phone_buyer'];
				}
				
				//GDPR stuff for email 
				if(isset($element['email_buyer']) && $element['email_buyer']!= ""){
					try{
						$user = Dap_User::loadUserByEmail($element['email_buyer']);
						if(isset($user) && $user!=""){
							// NOW GET THE GDPR FIELD
							
							$gdpr_consent = $user->getGDPRConsent();	
							if($gdpr_consent == "GDPR_CONSENT_NO"){ // This means we don't have to show email
								$referralDetails = "GDPR USER";
							}
						}
					}catch(Exception $e){
						logToFile("DAP-Member-Frontend.php:getDapAffiliateEarningsDetailsHtml(), cant fetch user info, exception is ".$e->getMessage());
					}
				}
				
				
				$transNum = $element['trans_num'];
			if(intval($element["amount_earned"]) < 0) {
				$element['referral_date'] = "";
				//$transNum = substr($transNum,-6);
				
			} else {
				$element['refund_date'] = "";
				//$transNum = substr($transNum,-4);
			}
				
			$html .= "<tr >
						<td>".$referralDetails . "</td>
						<td >".$element['referral_date']."</td>
						<td >".$element['refund_date']."</td>
						<td >".$element['product_name']."</td>
						<td >".$element['earning_type']."</td>
						<td >".$element['amount_earned']."</td>
						
					  </tr>";	
			
			}
			
		}else if( $user->getAccount_type() == "A" ) {
			/*$earningTypes = stripslashes($earningTypes);
			$result = Dap_AffCommissions::loadAffiliateEarningsDetails($user_email, $start_date, $end_date, $earningTypes);
			$totalEarnedCash = 0;
		    $totalEarnedCredits = 0;
		    foreach($result as $element) {
				$isPaid = "Yes";
				if( is_null($element['aff_exports_id']) || ($element['aff_exports_id'] == "") ) {
					$isPaid = "";
				}
				$transIdHTML = ($element['transaction_id'] == 0) ? 	"-"	: "<a href='/dap/admin/manageTransactions.php?transactionId=".$element['transaction_id']."'>".$element['transaction_id']."</a>";
				$deleteHTML = ($isPaid != "") ? "" : "<a href='#' onclick=\"javascript:deleteCommissionRow(".$element['earnings_id']."); return false;\"><img src='/dap/images/ximage.jpg' height='13' width='13' border='0' title='You can only delete unpaid commissions'></a>";

			$html .= "<tr >
						<td ><a href='/dap/admin/addEditUsers.php?userId=".$element['affiliate_id']."'>".$element['affiliate_id']."</a></td>
						<td >".$element['first_name']." ".$element['last_name']."</td>
						<td >".$element['email']."</td>
						<td >".$element['product_name']."</td>
						<td >".$element['referral_date']."</td>
						<td >".$element['datetime']."</td>
						<td>$transIdHTML</td>
						<td >".$element['amount_earned']."</td>
						<td>".$element['earning_type']."</td> 
						<td><a href='/dap/admin/addEditUsers.php?userId=".$element['user_id']."' target='_blank'>".$element['user_id']."</a></td>
						<td><strong>".$isPaid."</strong></td>
						<td >$deleteHTML</td>
					  </tr>";
			
			if($element['earning_type'] == "C") {
				$totalEarnedCredits += floatval($element['amount_earned']);
			} else if( ($element['earning_type'] == "L") || ($element['earning_type'] == "S") ) {
				$totalEarnedCash += floatval($element['amount_earned']);
			}
		}
		
		if(count($result)){
			//$html .= "<tr><td><h2>Total Earned</h2></td><td ><h2>Cash: $totalEarnedCash<br/><br/>Credits: $totalEarnedCredits</h2></td><td colspan='4'>&nbsp;</td></tr>";
		}	
		*/
		}
	}
	
	return $html ;
}
	

function getDapAffiliatePaymentsDetailsHtml($user_email = '',$user_type = ''){
	
	$start_date = '01-01-2008';
    $end_date = '';
	$html = '';
	$result = Dap_AffCommissions::loadAffiliatePayments($user_email, $start_date, $end_date);
	foreach($result as $element) {
		
		if($user_type == "U"){
			$html .= "<tr>
						<td ></td>
						<td ></td>
						<td > </td>
						<td >".$element['datetime']." </td>
						<td >".$element['amount_paid']." </td>
						<td ></td>
				 </tr>";
			
			
			
		}else if($user_type == "A"){
		
		$html .= "<tr>
						<td ><a href='/dap/admin/addEditUsers.php?userId=".$element['affiliate_id']."'>".$element['affiliate_id']."</a> </td>
						<td >".$element['first_name']." ".$element['last_name']." </td>
						<td >".$element['email']." </td>
						<td >".$element['datetime']." </td>
						<td >".$element['amount_paid']." </td>
						<td >".strtolower($element['earning_type'])." </td>
				 </tr>";
		}
	}
	
	return $html;
}
