<?php

if ( !is_admin() ){
	add_shortcode('DAPLessonComplete', 'dap_lessoncompleteshortcode');
	add_shortcode('DAPCourseOutline', 'dap_courseoutlineshortcode');
}
 
// Mark as complete button page functionality
 function dap_lessoncompleteshortcode($atts, $content=null){ 
	
	/***Added this line to fix the elementor ,  for non-admin users content was not showing*****/
	if(isset($_REQUEST['tve']) && $_REQUEST['tve'] == true){return $posts;}		
	if(isset($_REQUEST['action']) && ($_REQUEST['action']  == "elementor" || isset($_REQUEST['elementor-preview']))){
		return $posts;
	} 
	
	global $wpdb;
    extract(shortcode_atts(array(
        'course_id' => '',
    ), $atts));    
     
	
	/*if(isset($_POST['form_course_id']) && !empty($_POST['form_course_id'])){
		$course_id = $_POST['form_course_id'];
	}*/
    
    if(isset($_SESSION["DAPCOURSEID"]) && !empty($_SESSION["DAPCOURSEID"])){
		$course_id = $_SESSION["DAPCOURSEID"];
	}
    
    
    if( !Dap_Session::isLoggedIn() ) {
       return;
    } 
	
	   // user is logged in 
			
		//get userid
		$session = Dap_Session::getSession();
		$user = $session->getUser();
		$htmldata ="";
		$course_message ="";
		$module_message ="";
		$unit_message ="";	 
		$sendcourseemail ="";
		$sendmoduleemail ="";
		$sendlessonemail ="";
		$module_id =0;
		$mod_name= "";
		$style ="";
		$style1 ="";
		$unlock_markas ="";
		$notshownextbuttonmessage ='';
		$quizHtml ='';
		if (isset($user)) {
			
			//get markacomplete data			
			$userId = $user->getId(); 
			$userEmail = $user->getEmail(); 
			$first_name = $user->getFirst_name(); 
			$productobj = Dap_Product::loadProduct($course_id) ;
			if(isset($productobj)){
				  $course_message = $productobj->getCourseCompleteMessage();			
				  $module_message =  $productobj->getModuleCompleteMessage();			
				  $unit_message = $productobj->getLessonCompleteMessage();			
				  $course_progress = $productobj->getCourseProgress();
				  $sendcourseemail = $productobj->getSendCourseComplete();
				  $sendmoduleemail = $productobj->getSendModuleComplete();
				  $sendlessonemail = $productobj->getSendLessonComplete();
				  $product_type = $productobj->getProductType();
				  $product_structure = $productobj->getProductStructure();					 
			} 						
			 
			$siteurl = SITE_URL_DAP;
			$remove = array("http:","https:");
			$siteurl =  str_replace($remove,"",$siteurl);		
			$start_date = date('Y-m-d H:i:s');
			$cssurl =  '<link rel="stylesheet" href="'.$siteurl.'/dap/admin/templates/courseoutline/template1.css"> <link rel="stylesheet" href="'.plugin_dir_url( __FILE__ ).'includes/css/dap_courselesson_fe.css?v=1">';  			
		
			//currentpage url
			$current_url = home_url(add_query_arg(array()));	 
			$pageid = url_to_postid($current_url); 
		    $permalink = get_permalink($pageid);
		    $permalink = getResourceFromString($permalink);		
		 	$page_name = get_the_title($pageid);
		 
			 //get the lessons using courseid and moduleid
			if($product_structure == "lesson"){						
				$lessonurls  =  Dap_Product::displayFileResourcesWithCourseId($course_id);	 
			}else{
				$moduledata = DAP_CourseModule::loadByCourseId($course_id) ;
				if(isset($moduledata)) {					 				
					// module loop					
					foreach($moduledata as $mod){													
						 $lessonurls[]  =  Dap_Product::displayFileResourcesWithModuleIdCourseId($course_id, $mod->getId());										
					}
					if(count($lessonurls)){
						$lessonurls_new = array();
						foreach($lessonurls as $lessonurl){
							foreach($lessonurl as $lessonurl_single){
								$lessonurls_new[] = $lessonurl_single;
							}
						}
						
						$lessonurls = $lessonurls_new;
					}
				}
			}
			  
			 
			$lesson_name="";
			$unit_url_list1 = array();		
			if(isset($lessonurls)) {	
				// lesson loop	
			
				$next_url_status = false;
				$next_url = '';
				$current_lesson_id ="";
				$add_lessclass = " disable_lessclass ";
				$lesson_exist = true;
				foreach($lessonurls as $lessonurl){
					
					  	
					  $lesson_name = $lessonurl['name'];
					  $lesson_id = $lessonurl['id'];
					  $lesson_url= $lessonurl['url'];	
					  $add_lessclass = " enable_lessclass ";
					  
					  if($permalink == 	$lesson_url){
						  $lesson_exist = false;
					  }	
					  
					 // $module_id = $lessonurl['module_id'];	
					  $unit_url_list1[]= $lessonurl['url'];	
					  
					  $next_url = $lessonurl['url'];	 
					  if($next_url_status){
						 break;
					 }
					 if($lessonurl['url'] == $permalink){
				      $next_url_status	= true;	 
				      $next_url = '';
				      $current_lesson_id =$lessonurl['id'];
					 }
				  }
				  
				  			  			   
			  }	
			
			if($lesson_exist){
				 $notshownextbuttonmessage = '<div class="nextbutton_notshowmsg_container" >Sorry, cannot display the "Mark as Complete" button as this lesson is not a part of this course. 
If you want to add this lesson to the course, you can do so in DAP Products page >> Content Responder tab.</div>';
				return "<div class='lesson_container_outer' id='lesson_container_id'>".$cssurl.$notshownextbuttonmessage."</div>";  
			 
			}
			
			
			if($next_url == ''){ 
				//new code starts
				//get the moduls using courseid  
				
				$coursemoduledata = DAP_CourseModule::loadByCourseId($course_id) ;
				if(isset($coursemoduledata)) {				
					$unit_url_list = array();		
					// module loop					
					foreach($coursemoduledata as $mod){
						 					  
						if($product_structure == "lesson"){						
							$lessonurls  =  Dap_Product::displayFileResourcesWithCourseId($course_id);	 
						}else{
							
							if(isset($moduledata)) {
								$lessonurls = array();				
								// module loop					
								foreach($moduledata as $mod){													
									 $lessonurls[]  =  Dap_Product::displayFileResourcesWithModuleIdCourseId($course_id, $mod->getId());										
								}
								if(count($lessonurls)){
									$lessonurls_new = array();
									foreach($lessonurls as $lessonurl){
										foreach($lessonurl as $lessonurl_single){
											$lessonurls_new[] = $lessonurl_single;
										}
									}									
									$lessonurls = $lessonurls_new;
								}
							}
						}
						 
						 if(isset($lessonurls)) {							 
							 foreach($lessonurls as $lessonurl){
								$unit_url_list[]  = $lessonurl['url'];								 
							 }							  
						 }									 
					 }
					$key = array_search ($permalink, $unit_url_list);
					if(isset($permalink, $unit_url_list[$key+1])){
						$next_url = $unit_url_list[$key+1];
					}					 
										
				 } 
			}			
			
			//get next and markascomplete button data
			$markascomplete = Dap_OnlineCourse::loadByName('markascomplete') ;
			$nextbuttondata = Dap_OnlineCourse::loadByName('nextbutton') ;
						
			$nextbutton=  ''; 													
			if(count($nextbuttondata)){
				$nextbutton=  $nextbuttondata[0]->getHtml(); 
			}else{
				$nextbutton='<div class="dap_btn_container dap_member_tiny_editor nextlesson_btn mce-content-body mce-edit-focus" style="background: rgb(33, 195, 197); color: rgb(255, 255, 255); padding: 10px 14px; border-radius: 3px; display: inline-block; font-size: 16px; line-height: normal; text-decoration: none; font-weight: 600; max-width: 100%; float: none; margin: 22px auto; font-family: &quot;Open Sans&quot;, sans-serif; text-align: center; width: 150px; cursor: pointer; position: relative;"   ><div>Next Lesson »</div></div>';
			}													
			$nextbutton =  str_replace('contenteditable="true"', "", $nextbutton); 
			
			//added for quiz for lessons starts from here
			$quizHtml= calulationForDAPSQBQuizCourseLessons($course_id, $current_lesson_id, $userId);
			//quiz for lessons ends from here
			 
			//check if unit is already in progress table
			$lessonexist = DAP_UserCourseProgress::loadByCourseIdlessonIduserId($course_id , $current_lesson_id, $userId );			
			  	
			if(isset($lessonexist)  ){	
				if($unit_message !=""){
					$markascompletemsg = "<div class='lesson_container' style='display:table;  '>".$unit_message."</div><input type='hidden' value='Y' class='markedAsCompleted'>";
				}else{
					$markascompletemsg ="<input type='hidden' value='Y' class='markedAsCompleted'>";
				}	 
				
				if(isset($nextbutton)  ){
					if($next_url != ''){
						$next_unit = '<a href="'.$siteurl.$next_url.'" class="next_btn_cont" style="display:flex">'.$nextbutton.'</a>'; 	
					}
				}
				
				//call the next button course rule
				$script = scriptForNextButton($course_id,$current_lesson_id ,$userId, $product_structure,$start_date , $current_url);
				
			}else{			 
			
				if(isset($markascomplete) ){					 
					$markascompletehtml =  $markascomplete[0]->getHtml(); 		
					if($markascompletehtml==""){					 
						$markascompletehtml ='<div class="border_outer btn_data markas_completed_btn_outer">
													<div class="dap_btn_container dap_member_tiny_editor markas_completed_btn" style=" background: #7db817;  color: #fff;  padding: 18px 18px;  border-radius: 30px;  border: 0px;  font-size: 16px;line-height: normal;  font-weight: 600;    max-width: 100%;  float: none;  margin: 22px auto; text-align: center;   width: 380px; cursor:pointer;font-family: "Open Sans", sans-serif; " >
														<div >Mark As Complete</div>
													</div>
												</div>';
					}												
					$markascompletehtml =  str_replace('contenteditable="true"', "", $markascompletehtml); 	
					$script ="";								
					 			 		
					$mod_data = DAP_CourseModule::loadByCourseId($course_id);
					$productobj = Dap_Product::loadProduct($course_id) ;
					if(isset($productobj)){
						$course_name = $productobj->getName();
					}						
					if(isset($mod_data) ){
						//$mod_name = $mod_data->getModuleName();						
						
						if(isset($lesson_name)){
							if($lesson_name !=""){
								$lesson_name =  $lesson_name;
							}else{
								$lesson_name =  $page_name;
							}								
						}else{
							$lesson_name =  $page_name;
						}
						 
						 $getmodid = Dap_Product::displayFileResourcesWithCourseIdLessonId($course_id, $current_lesson_id);
						 
						  if(isset($getmodid)) {
							$module_id= $getmodid['module_id'];							  
						  }
						   
						//call the MarkAsCompleteButton
						$script = scriptForMarkAsCompleteButton($course_id,$module_id, $current_lesson_id ,$userId, $product_structure,$start_date, $mod_name, $lesson_name,  $sendcourseemail, $sendmoduleemail, $sendlessonemail, $current_url, $course_name);
											
					}
				}
				  
				if($unit_message !=""){
					$markascompletemsg = "<div class='lesson_container' style='display:none;  '>".$unit_message."</div>";
				}else{
					$markascompletemsg ="";
				}	
				
				//allow next button click or not				 
				 if($course_progress == 'notallow'){				 
					if(isset($nextbutton)  ){
						if($next_url != ''){
							$next_unit = '<a href="'.$siteurl.$next_url.'" class="next_btn_cont" style="display:none">'.$nextbutton.'</a>'; 	
						}
					}
					 
				 }else{			 
					if(isset($nextbutton)  ){
						if($next_url != ''){
							$next_unit = '<a href="'.$siteurl.$next_url.'" class="next_btn_cont"  style="display:flex">'.$nextbutton.'</a>'; 	
						}
					}
				 }		
				
			}
				 
			   if(in_array($permalink,  $unit_url_list1 )){
					$htmldata = $markascompletehtml.$script.$markascompletemsg.$next_unit.$cssurl;
			  }	
			
			 if($permalink ==  end($unit_url_list1)){			 
				 $style="<style>.next_btn_cont, .nextlesson_btn{ display:none !important; } </style>";				 
			} 
			 
			 
				$lessonurlcount1 =0;
				$lessoncount=0;			 			 				
				$unit_url_list = array();		
				// module loop	
				
				if($product_structure == "lesson"){						
						$lessonurls  =  Dap_Product::displayFileResourcesWithCourseId($course_id);
						$lessoncount = DAP_UserCourseProgress::lessonCountByCourseIduserId($course_id , $userId );	 
				}else{
					
					$moduledata = DAP_CourseModule::loadByCourseId($course_id) ;	
					if(isset($moduledata)) {							 
						$lessonurls = array();
						
						// module loop					
						foreach($moduledata as $mod){													
							 $lessonurls[]  =  Dap_Product::displayFileResourcesWithModuleIdCourseId($course_id, $mod->getId());
							 $lessoncount += DAP_UserCourseProgress::lessonCountByCourseIdModuleIduserId($course_id , $mod->getId(), $userId );				 							
						}							
						
						if(count($lessonurls)){
							$lessonurls_new = array();
							foreach($lessonurls as $lessonurl){
								foreach($lessonurl as $lessonurl_single){
									$lessonurls_new[] = $lessonurl_single;										 
								}
							}								
							$lessonurls = $lessonurls_new;								
						}				 
				}
			}				
			
			if(isset($lessonurls)) {							 
				 foreach($lessonurls as $lessonurl){
					$unit_url_list[]  = $lessonurl['url'];							 					 
				 }						  
			 }	
			 
			$lessonurlcount1 = count($unit_url_list);		 
			if($lessoncount == $lessonurlcount1 &&  $permalink ==  end($unit_url_list1)){	
							 
				//certificate download code
				$download_btn = dapCheckIfCertificateDownloadShouldDisplay($course_id,$userId , "COMPLETECOURSE" ,"Y");
				//$download_btn =downloadCertificateButton(62,1);			
			}	else if($permalink ==  end($unit_url_list1)){
				//certificate download code
				$download_btn  = dapCheckIfCertificateDownloadShouldDisplay($course_id,$userId , "LASTLESSON","Y");				
			}
			if($lessoncount == $lessonurlcount1 &&  $permalink ==  end($unit_url_list1)){
				if($course_message == ""){
					$style1 ="<style>.co_container{ display:none ; }  </style>";
				}else{
					$style1 ="<style>.co_container{ display:table !important; }  </style>";
				}
			}					
			 
			// $coursecompletemsg = "<div class='certificate_container' style='display:none;'>Download Certificate</div>";
			 $coursecompletemsg = "<div class='co_container course_cont' style='display:none;'>".$course_message."</div><style> .lesson_container_outer .dap_btn_container{ clear: both}</style>";
			
			//for timer	
			$t=time();
			$tdemo='<input id="start_time" type="hidden" value="'. $t.'"/><input id="already_clicked" type="hidden" value="n"/>';		
		 return "<div class='lesson_container_outer' id='lesson_container_id'> ".$tdemo.$quizHtml.$htmldata.$style.$style1.$coursecompletemsg.$notshownextbuttonmessage.$download_btn."</div>";
		
	}    
}

//for DAP SQB Course lessons
function calulationForDAPSQBQuizCourseLessons($course_id, $current_lesson_id, $userId){
	$unlock_markas ='';
	$quizHtml ='';
	if(class_exists('SQB_ManageLeads')){
		 
		$courseQuizData = Dap_SQBQuizCourseLessons::loadByCourseId($course_id);			 
					
		$dap_id = $userId;
		// destroy session
		unset($_SESSION['course_id']);
		unset($_SESSION['current_lesson_id']);
		unset($_SESSION['dap_id']);
		unset($_SESSION['user_has_taken_quiz']);
		unset($_SESSION['first_name']);
		$_SESSION['course_id'] = "";	 		
		$_SESSION['current_lesson_id'] = "";
		$_SESSION['dap_id'] = "";	 
		$_SESSION['user_has_taken_quiz'] = "";	 
		$_SESSION['first_name'] = ""; 	 
		  
		if(isset($courseQuizData) && is_array($courseQuizData)){ //for quiz course 
			$quizIds = dapGetQuizIds($courseQuizData, $current_lesson_id);
			  
			if(is_array($quizIds)){
				$showQuiz = true;
				$leadsObj_count = 0;
				$sqb_insert_quiz = "automatic";
				$status ="N";
				foreach ($quizIds as $id) {
					
					//if($dap_id != '' && $dap_id != 0){
						$leadsObj = SQB_ManageLeads::loadByQuizIdAndUserId($id, $dap_id);							
						if( isset($leadsObj)){
							$leadsObj_count =count($leadsObj);
						}
											
						//get the user details using quiz id
						$sqbloadquestionsobj = SQB_UserQuizDetails::loadUserDeatilsByUserIdAndQuizId($dap_id, $id);							 
						$sqbObj =  SQB_Quiz::loadById($id);
						 
						if(isset($sqbObj)){									
							$sqb_insert_quiz =  $sqbObj->getSqbInsertQuiz();
							$status =  $sqbObj->getStatus() ;
							if($sqb_insert_quiz ==""){
								$sqb_insert_quiz = "automatic";
							}
						}	
						
										
						if($sqbloadquestionsobj != false){
							$points_scored = $sqbloadquestionsobj->getPointsScored();
							$total_points = $sqbloadquestionsobj->getTotalPoints(); 
							$percentage = round($points_scored / ($total_points / 100),0);						
						}							 		 
					//}
					
					//set the session for lesson_id, user_id
					$_SESSION['course_id'] = $course_id;	 		
					$_SESSION['current_lesson_id'] = $current_lesson_id;
					$_SESSION['dap_id'] = $dap_id;	 
					$_SESSION['user_has_taken_quiz'] =  count($sqbloadquestionsobj);	 
					$_SESSION['first_name'] = $first_name;	 
					
					if($status =="Y"){
						if($sqb_insert_quiz =="automatic"){
							//get the quiz html
							$quizHtml .= sqb_show_quiz_by_id($id, $leadsObj_count);	
						}				 
					}else{
						$_SESSION['current_lesson_id'] ="";
					}				 
				}					
				
				// enable the_markas_complete button
				$show_quiz =  unlocking_markascomplete($percentage, $leadsObj_count);	
				if($show_quiz == true){	
					$unlock_markas ='';	
				}else{		 
					$unlock_markas ='<input type="hidden" class="show_not_passed_msg" value= "y"/> ';'<script> jQuery(document).ready(function() { 
					 jQuery(".markas_completed_btn").addClass("disableMarkBtn"); 
					 </script>';
				}

			}
			
		}
	}
	return $unlock_markas.$quizHtml;
}

//function to get the MarkAsCompleteButton
function scriptForMarkAsCompleteButton($course_id,$module_id, $current_lesson_id ,$userId, $product_structure,$start_date, $mod_name, $lesson_name,  $sendcourseemail, $sendmoduleemail, $sendlessonemail, $current_url ,$course_name){ 
	 
	//script
	$script =' <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>	
		<script>
			jQuery(document).ready(function() {
				var ajaxurl = "' . admin_url("admin-ajax.php") . '";			
				var get_current_time = new Date().getTime();
				jQuery("#start_time").val(get_current_time);
				var rule_applied = jQuery("#rule_applied").val();
				if(rule_applied =="y"){
					var lesson_time = jQuery("#lesson_time").val();
					if(lesson_time >0){
						jQuery(".markas_completed_btn, .nextlesson_btn ").hide(); 
						jQuery(".course_rule_con_container").show(); 
						var time = Math.floor(lesson_time*60*1000);  

						setTimeout(function(){					 
							jQuery(".markas_completed_btn, .nextlesson_btn ").show(); 
							jQuery(".course_rule_con_container").hide(); 					 
						}, time);				
					}
				}			
										
				jQuery(".markas_completed_btn").click(function() {  
				 
					var start_time  = jQuery("#start_time").val();
					// Get todays date and time
					var now = new Date().getTime();							  
					var initialtime = parseInt(now) - parseInt(start_time) ;
					// Time calculations for days, hours, minutes and seconds							 
					var seconds = Math.floor((initialtime % (1000 * 60)) / 1000);

					jQuery.post(ajaxurl, {
						action: "dap_lesson_status",
						course_id: '.$course_id.',
						module_id: '.$module_id.',
						lesson_id: '.$current_lesson_id.',
						mod_name: "'.$mod_name. '",
						course_name: "'.$course_name. '",
						lesson_name: "'.$lesson_name. '",
						user_id: '.$userId.',
						sendcourseemail:"'.$sendcourseemail.'",
						sendmoduleemail: "'.$sendmoduleemail.'",
						sendlessonemail: "'.$sendlessonemail.'",
						product_structure: "'.$product_structure.'",
						start_date: "'.$start_date.'",
						seconds: seconds,
						next_btn: "no",
						current_url:  "'.$current_url.'",
						
					}, function(response) {
							response = JSON.parse(response);
							console.log(response);
							var course_complete =  response.course_complete ;
							var give_lesson_points = response.give_lesson_points;	
							var animation = response.animation;
							var animationval = response.animationval;
							var message = response.message;			
							
							jQuery(".lesson_container").css("display","table"); 							 
							jQuery("#already_clicked").val("y");  								 
							course_complete=  jQuery.trim(course_complete);  
							give_lesson_points=  jQuery.trim(give_lesson_points);  
							animation=  jQuery.trim(animation);
							message=  jQuery.trim(message);
							 
							if(animation =="Y"){
								jQuery(".lesson_container_outer").before(animationval);
								setTimeout(function(){ jQuery(".animation_container").hide(); }, 7000);			
							}
							if(message !=""){
								jQuery(".lesson_container_outer").before(message);
							}							
								 
							if(course_complete =="yes"){
								 
								var course_cont_text = jQuery(".course_cont").text();  								
								if(course_cont_text ==""){
									jQuery(".course_cont").css("display","none"); 
								}else{
									jQuery(".course_cont").css("display","table"); 
									jQuery(".course_cont").css("display","table !important"); 
								}																		
								jQuery(".nextbutton_notshowmsg_container").show();										
								jQuery(".next_btn_cont, .nextlesson_btn").hide();	
								var certification_btn_show = jQuery(".certification_btn_show").val();	
								  
								if(certification_btn_show == "y"){
									 
									jQuery.post(ajaxurl, {
										action: "dap_insert_course_certificate",		 
										course_id: '.$course_id.',
										user_id: '.$userId.', 
										use_ajax: "y", 
										
									}, function(response) {
										 
										jQuery(".certificate_container").show(); jQuery(".certificate_container").css("display","block !important"); 
									});  
								}											
																		
							}else{
								 
								jQuery(".next_btn_cont").css("display","flex");
								jQuery(".nextlesson_btn").show();
							}
														 
						 jQuery(".markas_completed_btn").hide();
						 
					});  	        
				});
			});  
		</script>';
		
	 //for course rule
	$course_rule_data =  checkCourseRule($course_id, $module_id, $current_lesson_id);
	
	return  $script.$course_rule_data;
 }
 
 //function to get the NextButton
 function  scriptForNextButton($course_id,$current_lesson_id,$userId,$product_structure,$start_date , $current_url ){
	 $script =' <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>	<script>
				jQuery(document).ready(function() { 
				
					var get_current_time = new Date().getTime();
					jQuery("#start_time").val(get_current_time);
					var ajaxurl = "' . admin_url("admin-ajax.php") . '";
					
					jQuery(".next_btn_cont").click(function(event) { 
					 event.preventDefault();
					//console.log(event.target.nodeName);
					var self = this;
						var start_time  = jQuery("#start_time").val();
					 // Get todays date and time
					  var now = new Date().getTime();							  
					  var initialtime = parseInt(now) - parseInt(start_time) ;
					  // Time calculations for days, hours, minutes and seconds							 
					  var seconds = Math.floor((initialtime % (1000 * 60)) / 1000);
					  var already_clicked = jQuery("#already_clicked").val(); 
					if(already_clicked =="y"){
					return false;
					}	
					jQuery.post(ajaxurl, {
							action: "dap_lesson_status",
							course_id: '.$course_id.',
							module_id: "",
							lesson_id: '.$current_lesson_id.',
							mod_name: "module",
							lesson_name: "lesson",
							course_name: "course",
							user_id: '.$userId.',
							sendcourseemail:"course",
							sendmoduleemail: "module",
							sendlessonemail: "lesson",
							product_structure: "'.$product_structure.'",			
							start_date: "'.$start_date.'",			
							seconds: seconds,
							next_btn: "yes",
							current_url:  "'.$current_url.'",
							
						}, function(response) {
							 location.href = self.href;
						});
						 
					});							
								
					 
				});  
				 </script>';
	 return  $script;
 }
 
 //check the course rule
 function checkCourseRule($course_id, $module_id, $lesson_id){
	  
	 $showMarkAsComplete = true;
	 $time = 0;
	 $checkIfRuleExist =  DAP_CourseRules::loadByCourseIdAndLessonIdAndModuleIdAndName($course_id,0, 0, 'rule_status');
	 if(isset($checkIfRuleExist)){
		 
		  $rule_status = $checkIfRuleExist->getValue();
		 // if rule_status ==y then move further
		 if($rule_status == "Y"){
			 $checkIfTimeRuleExist =  DAP_CourseRules::loadByCourseIdAndLessonIdAndModuleIdAndName($course_id,$lesson_id, $module_id, 'time_rule');
			 if(isset($checkIfTimeRuleExist)){
				 $time_rule = $checkIfTimeRuleExist->getValue();
				  // if rule_status ==y then move further
				 if($time_rule == "set_limit"){
					  $checkIfTimeExist =  DAP_CourseRules::loadByCourseIdAndLessonIdAndModuleIdAndName($course_id,$lesson_id, $module_id, 'time');
					   if(isset($checkIfTimeExist)){
							$time = $checkIfTimeExist->getValue();							 
							if($time >0){
								$showMarkAsComplete = false;
								$time = $time;
							}else{
								$showMarkAsComplete = true;
							}
					   }
				 }else{
					 $showMarkAsComplete = true;
				 }//time rule end
			 }
		 }else{
			  $showMarkAsComplete = true;
		 }//rule_status  end
	 }
	 
	 // for course rule
	  $checkIfMessageExist =  DAP_CourseRules::loadByCourseIdAndLessonIdAndModuleIdAndName($course_id,$lesson_id, $module_id, 'message');
	  $course_rule_con="";
	  if(isset($checkIfMessageExist)){
		$rule_message = $checkIfMessageExist->getValue();
		 $rule_message =  str_replace('contenteditable="true"', "", $rule_message); 
		 if($rule_message !=""){
			 $course_rule_con = "<div class='course_rule_con_container' style='display:none;  '><div>".$rule_message."</div></div>";
		 }
	  }
	    
	 $rule_data ="";
	 if($showMarkAsComplete == false){
		 $rule_data .= '<input type="hidden" id="rule_applied" value="y"/>';
		 $rule_data .= '<input type="hidden" id="lesson_time" value="'.$time.'"/>';		  
	 }else{
		 $rule_data .= '<input type="hidden" id="rule_applied" value="n"/>';
	 }
	 
	 return $course_rule_con.$rule_data;
 }
 
 
// enable the_markas_completebutton
function unlocking_markascomplete($percentage, $leadsObj_count){
	
	$showquiz = false; 
	$quiz_blocking = $_SESSION['quiz_blocking'];	 		
	$quiz_passmark = $_SESSION['quiz_passmark'];
	$pass_criteria = $_SESSION['pass_criteria'];	 
	$sqb_quiz_type = $_SESSION['sqb_quiz_type'];	
	
	if($quiz_blocking == "Y"){
		if($pass_criteria == "pass"){
			if($sqb_quiz_type == "assessment" || $sqb_quiz_type == "scoring" ){
				
				if($quiz_passmark <= $percentage){
					$showquiz = true;	
				}else{
					$showquiz = false;	
				} 	
			}else{ //else	 pass_criteria
				$showquiz = true;	
			}
					
		}else{	 //else	 pass_criteria=complete
			if($leadsObj_count > 0){
				$showquiz = true;
			}else{
				$showquiz = false;
			}
						
		}		
	}else{	//else	 quiz_blocking
		$showquiz = true;
	}
	 
	return $showquiz;		 
} 
  
  
/*********Quiz Course start****************/  

function dapGetQuizIds($courseData , $lessonId){
	$quizIds = array();
	foreach ($courseData as $data) {
		 
		$quizLessonIds = $data->getLessonIds();
		if($quizLessonIds != ''){
			$quizLessonIds = explode(',', $quizLessonIds);

			if(in_array($lessonId, $quizLessonIds)){
				array_push($quizIds, $data->getQuizId());
			}
		}
	}
	return $quizIds;
}
/*********Quiz Course end****************/  

 //courseoutline
 function dap_courseoutlineshortcode($atts, $content=null){ 
 	if(isset($_REQUEST['tve']) && $_REQUEST['tve'] == true){return $posts;}		
	if(isset($_REQUEST['action']) && ($_REQUEST['action']  == "elementor" || isset($_REQUEST['elementor-preview']))){
		return $posts;
	} 
  
	global $wpdb;
    extract(shortcode_atts(array(
        'id' => '', 
    ), $atts));     
    
 
    /*if( !Dap_Session::isLoggedIn() ) {
 
        //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;
    }*/
	   // user is logged in 
			
		//get userid
		$session = Dap_Session::getSession();
		$user = $session->getUser();
		 
			//get courseoutline data
 
			$courseoutline = Dap_OnlineCourse::loadById($id) ;	
 
			if(isset($courseoutline) ){
				 
				$siteurl = SITE_URL_DAP;
				$remove = array("http:","https:");
				$siteurl =  str_replace($remove,"",$siteurl);
				$siteurl1 = plugin_dir_url( __FILE__ );
				 
				$siteurl1 =  str_replace($remove,"",$siteurl1);
				
				 
				 $course_ids =  $courseoutline->getCourseId(); 
				  
				 $courseoutlinehtml =  $courseoutline->getHtml(); 
				 $courseCustomizedData =  $courseoutline->getCustomizeData(); 
				 $courseoutlinehtml =  str_replace('contenteditable="true"', "", $courseoutlinehtml); 		
				 $courseoutlinehtml =  str_replace('role="tab1"', 'role="tab"', $courseoutlinehtml); 
				 $courseoutlinehtml =  str_replace('data-toggle="collapse"', 'data-toggle="collapse"  href="#collapseOne1" ', $courseoutlinehtml); 		
				// $cssurl =  '<link rel="stylesheet" href="'.$siteurl.'/dap/admin/templates/courseoutline/template1.css?v=1"><link rel="stylesheet" href="'.$siteurl1.'includes/css/dap_courselesson_fe.css">'; 
				  $cssurl =  '<link rel="stylesheet" href="'.$siteurl.'/dap/admin/templates/courseoutline/template1.css?v=1"><link rel="stylesheet" href="'.$siteurl1.'includes/css/dap_courselesson_fe.css?v=1">';  
				 
				 $courseCustomized =  explode("|||", $courseCustomizedData); 
				 
				 $display_Options = explode("||" , $courseCustomized[0]);
				 $courseOptions = explode("||" , $courseCustomized[1]);
				 $shadowOptions = explode("||" , $courseCustomized[2]);
				 $showLessonsNum = $courseCustomized[3];
				 $modules_collapsed = $courseCustomized[4];
				 
				 if($modules_collapsed == 'y'){
					$modules_collapsed_cls = '';	
					$collapsed_cls = ' collapsed ';	
				 } else{
					$modules_collapsed_cls = ' show1 ';	  
					$collapsed_cls = ' ';	  
				 }
				 
				 if($showLessonsNum == '' || $showLessonsNum == 0){
					$showLessonsNum = 'all';	
				 }
				 
				 $courseWidth = $courseOptions[0]; 
				 $courseBackground = $courseOptions[2]; 
				 $courseBorderStyle = $courseOptions[3]; 
				 $courseBorderWidth = $courseOptions[4]; 
				 $courseBorderColor = $courseOptions[5]; 
				 $startButtonBackgroundColor = $courseOptions[6]; 
				 $modBackground = $courseOptions[7]; 
				 
				$sprd_radius = $shadowOptions[0];
				$blur_radius = $shadowOptions[1];
				$hor_lnth = $shadowOptions[2];
				$ver_lnth = $shadowOptions[3];
				$shad_clr = $shadowOptions[4];
				 
				$box_shadow = $shad_clr.' '.$sprd_radius.'px '.$blur_radius.'px '.$hor_lnth.'px '.$ver_lnth.'px ';
				 
				 $courseoutlinehtml =  explode("|||", $courseoutlinehtml); 
				 $coursehtml =  $courseoutlinehtml[1];
				 $modulehtml =  $courseoutlinehtml[2];
				 $lessonhtml =  $courseoutlinehtml[3];
				 $btnhtml =  $courseoutlinehtml[4];
				 
				$modulehtml =  explode("||", $modulehtml); 
				$modulenamehtml =  $modulehtml[0];
				$moduledeschtml =  $modulehtml[1];	
				
				$showcname= $display_Options[0];			 
				$showcdesc= $display_Options[1];			 
				$showmname= $display_Options[2];			 
				$showmdesc= $display_Options[3];				
				
				$course_ids_arr = explode(",", $course_ids);
				
				$anyoneprodaccess = false;
				foreach($course_ids_arr as $course_id){ 
					$productobj = Dap_Product::loadProduct($course_id) ;
					if (isset($user)) {
						$userId =$user->getId();		
		 
						 
						$user_obj = new Dap_User();
						$user_obj->setId($userId);
						$hasAccess = $user_obj->hasAccessTo($course_id);
						 
						if(!$hasAccess){						 
							continue;
						}
						$anyoneprodaccess = true;
					}
					
					$lessonhtml1 ="";	
					$lessonhtml2 ="";			
					if(isset($productobj)){
						$course_name = $productobj->getName();			
						$course_desc= $productobj->getDescription();			
						$course_message = $productobj->getCourseCompleteMessage();			
						$module_message =  $productobj->getModuleCompleteMessage();			
						$unit_message = $productobj->getLessonCompleteMessage();	
						$course_progress = $productobj->getCourseProgress();
						$product_type = $productobj->getProductType();
						$product_structure = $productobj->getProductStructure();						 
						
						$coursehtmlnew  =  str_replace('%%CourseName%%', $course_name, $coursehtml); 	
						$coursehtmlnew  =  str_replace('%%CourseDescription%%', $course_desc, $coursehtmlnew); 					
						
						$combined_data ="";
						$combined_data .= '<div class=" manage_porduct_shortcode_wrapper dap_course_wrapper_outer" id="courtse_outlineid" style="width:'.$courseWidth.'px">
							<div class="manage_porduct_shortcode dap_course_wrapper" style="border-style:'.$courseBorderStyle.';border-width:'.$courseBorderWidth.'px;border-color:'.$courseBorderColor.';box-shadow:'.$box_shadow.'">
								  <div class="heading_shortcode_template" style="background-color:'.$courseBackground.'">
									'.$coursehtmlnew.'
								  </div>';
						$combined_mdata ="";	
						
						
						 
						$moduledata = DAP_CourseModule::loadByCourseId($course_id) ;	
						$course_progress_allow = false;
						
						$cssdata  ="";
						if($showcname =="n"	){						
							$cssdata .= "<style>.course_name{ display:none }	</style>";
							
						}							 
						if($showcdesc =="n"	){						
							$cssdata .= "<style>.course_desc{ display:none }	</style>";
							
						}							 
						if($showmname =="n"	){						
							$cssdata .= "<style>.module_name{ display:none } .module_data .card-header	{ display:none }</style>";
							
						}							 
						if($showmdesc =="n"	){						
							$cssdata .= "<style>.module_data_desc{ display:none }	</style>";						
						}		
						if($showcname =="n"	&& $showcdesc =="n"){						
							$cssdata .= "<style>.heading_shortcode_template{ display:none }	</style>";
							
						}
										
						
						$cssdata .=	'<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">';		
						
						//if modulename and desc is hide, then show all the lessons	
							
						if($product_structure == "lesson"){						
							  $lessonurls  =  Dap_Product::displayFileResourcesWithCourseId($course_id);
							  //check if unit is already in progress table
							
							  $combined_data .= ' 
											<div class="accordion md-accordion custom_accordion course_outline_inner_wrapper" id="accordionEx" role="tablist" aria-multiselectable="true" data-courseid="'.$course_id.'">								   
													<div class="card module_data"><input type="hidden" value="'.$showLessonsNum.'" id="showLessonsNum">
														  
														  
														  <div  class="collapse in show show1" role="tabpanel" aria-labelledby="headingOne1" data-parent="#accordionEx">
																<div class="card-body custom_body_part">
																	 ';
							 
								if(isset($lessonurls)) {	
										// lesson loop		
										
										 foreach($lessonurls as $lessonurl){
											 //get the user progress table data	
											  
											 $btndisable = '';
											 $lesson_url = $siteurl.$lessonurl['url'];
											  $add_lessclass = " enable_lessclass ";
											 if($course_progress_allow){
												 $lesson_url = 'javascript:void(0)';
												 $btndisable = 'btndisable';
												 $add_lessclass = " disable_lessclass ";
											 }	 
												 
											 
											 
											 if($course_progress == 'notallow'){
												 
												 $course_progress_allow = true;
											 }
											  
											 $lessonexist = DAP_UserCourseProgress::loadByCourseIdlessonIduserId($course_id ,  $lessonurl['id'], $userId );
											//checked_tick
											 $checked_tick = '';
											 if(isset($lessonexist) ){
												  $checked_tick = 'checked_tick';
												   $course_progress_allow = false;
												   $btndisable = '';
												   $lesson_url = $siteurl.$lessonurl['url'];
												   $add_lessclass = " enable_lessclass ";
											  }
																									 
											$lessonhtml1 ="";	
											$lessonname = $lessonurl['name'];
											if($lessonname== ""){
												 $lessonname =  $lessonurl['url'];
											}					 
											 
											 $lessonhtml1  =  str_replace('%%LessonTITLE%%', $lessonname, $lessonhtml);								 								 
											 $lessonhtml1   =  str_replace('%%LessonURL%%', $lessonurl['url'], $lessonhtml1); 
											 
																			 
											 $combined_data .= ' 							 
														   <div class="cardbody_text" id="lesson_outer_id'.$lessonurl['id'].'"><div class="lesson_container"><i class="fa fa-check green_tick '.$checked_tick.'"></i>  <div class="dap_member_tiny_editor lesson_data">
															<a class="'.$add_lessclass.'" href="'.$lesson_url.'">  '.$lessonhtml1 .'</a>
														  </div></div>
														  <div class="dap_member_tiny_editor btn access_content_btn btn_template_start '.$btndisable.'" style="background-color:'.$startButtonBackgroundColor.'"><a id="start_button_link" href="'.$lesson_url.'"> '.$btnhtml.'</a></div> </div> ';
											 
										  }
								}
								
								$combined_data .= ' 	    
																</div>
														  </div>
													  
													</div>       
											</div>';
											
							$script = '<script>var showLessonsNum = jQuery("#showLessonsNum").val(); 
							if(showLessonsNum != "all"){
								var  max_height = 0;
								var i = 1; 
								jQuery(".cardbody_text").each(function(){
									if(i <= showLessonsNum){
										var tempHeight = jQuery(this).css("height");
										tempHeight = tempHeight.split("px");
										tempHeight = tempHeight[0];
										max_height = parseFloat(tempHeight) + parseFloat(max_height);
										
									}
									i++;
								});
								jQuery(".custom_body_part").css("height" ,max_height+"px");
								jQuery(".custom_body_part").css("overflow" ,"auto");
							}
						</script>';	
									
						} else{
							
							
								if(isset($moduledata)) {	
									$mods = 1; 
									
									$lessonsNumTemp = 1 ;
									$i = 0;
									
									if(isset($showLessonsNum) && $showLessonsNum != '' && $showLessonsNum != 'all'){$combined_data .= '<div class="mod_lesson_outer"><input type="hidden" value="'.$showLessonsNum.'" id="showLessonsNum">';}
									// module loop					
									foreach($moduledata as $mod){
										 $mod_id = $mod->getId();
										 $modulenamehtml1 =  str_replace('%%ModuleName%%', $mod->getModuleName(), $modulenamehtml); 	
										 $moduledeschtml1 =  str_replace('%%ModuleDescription%%', $mod->getModuleDesc(), $moduledeschtml); 	
										 
										if($i != 0 && $lessonsNumTemp < $showLessonsNum){
											$mods++;
										}
										 
										 $lessonurls  =  Dap_Product::displayFileResourcesWithModuleIdCourseId($course_id, $mod->getId());
										$lessonurlinproduct= 0;
										 $checked_tick_outer= "";
										 if(isset($lessonurls)) { 
											 $lessonurlinproducts = count($lessonurls); 
										 }
										 if (isset($user)) {
											 $lessoncountinprogress = DAP_UserCourseProgress::lessonCountByCourseIdModuleIduserId($course_id , $mod_id, $userId );
										 
											 if($lessoncountinprogress >= $lessonurlinproducts){
												 $checked_tick_outer= "checked_tick_outer";
											 }
										 }
										 
										   $combined_data .= ' 
											<div class="accordion md-accordion custom_accordion course_outline_inner_wrapper" id="accordionEx" role="tablist" aria-multiselectable="true" data-courseid="'.$course_id.'">								   
													<div class="card module_data">
														  <div class="card-header '.$checked_tick_outer.'" role="tab" id="headingOne'.$mod_id.'" style="background-color:'.$modBackground.'">
															<a data-toggle="collapse" href="#collapseOne'.$mod_id.'" data-parent="#accordionEx" aria-controls="collapseOne1" class="'.$collapsed_cls.'">
															  '.$modulenamehtml1.'
															</a>
														  </div>
														  
														  <div id="collapseOne'.$mod_id.'" class="collapse in show '.$modules_collapsed_cls.'" role="tabpanel" aria-labelledby="headingOne1" data-parent="#accordionEx">
																<div class="card-body custom_body_part">
																	<div class="dap_member_tiny_editor module_data_desc">  '.$moduledeschtml1.'</div>';													
										
										 
										if(isset($lessonurls)) {	
												// lesson loop		
												
												 foreach($lessonurls as $lessonurl){
													 //get the user progress table data	
													 if($lessonsNumTemp < $showLessonsNum){
														$i++;
														$lessonsNumTemp++;
													}
													 $btndisable = '';
													 $lesson_url = $siteurl.$lessonurl['url'];
													  $add_lessclass = " enable_lessclass ";
													 if($course_progress_allow){
														 $lesson_url = 'javascript:void(0)';
														 $btndisable = 'btndisable';
														 $add_lessclass = " disable_lessclass ";
													 }	 
														 
													 
													 
													 if($course_progress == 'notallow'){
														 
														 $course_progress_allow = true;
													 }
													 $checked_tick = '';
													 if (isset($user)) {
														$lessonexist = DAP_UserCourseProgress::loadByCourseIdModuleIdlessonIduserId($course_id , $mod_id, $lessonurl['id'], $userId );
														//checked_tick														 
														 if(isset($lessonexist) ){
															  $checked_tick = 'checked_tick';
															   $course_progress_allow = false;
															   $btndisable = '';
															   $lesson_url = $siteurl.$lessonurl['url'];
															   $add_lessclass = " enable_lessclass ";
														  }
													  }
																											 
													$lessonhtml1 ="";	
													$lessonname = $lessonurl['name'];
													if($lessonname== ""){
														 $lessonname =  $lessonurl['url'];
													}					 
													 
													 $lessonhtml1  =  str_replace('%%LessonTITLE%%', $lessonname, $lessonhtml);								 								 
													 $lessonhtml1   =  str_replace('%%LessonURL%%', $lessonurl['url'], $lessonhtml1); 
													 
																					 
													 $combined_data .= ' 							 
																   <div class="cardbody_text" id="lesson_outer_id'.$lessonurl['id'].'"><div class="lesson_container"><i class="fa fa-check green_tick '.$checked_tick.'"></i>  <div class="dap_member_tiny_editor lesson_data">
																	<a class="'.$add_lessclass.'" href="'.$lesson_url.'">  '.$lessonhtml1 .'</a>
																  </div></div>
																  <div class="dap_member_tiny_editor btn access_content_btn btn_template_start '.$btndisable.'" style="background-color:'.$startButtonBackgroundColor.'"><a id="start_button_link" href="'.$lesson_url.'"> '.$btnhtml.'</a></div> </div> ';
													 
												  }
										}		
										
										$combined_data .= ' 	    
																</div>
														  </div>
													  
													</div>       
											</div>';							
									}
									
									$script = '<script>
									var mods = '.$mods.';
									var showLessonsNum = jQuery("#showLessonsNum").val(); 
							if(showLessonsNum != "all"){
								var  max_height = 0;
								var i = 1; 
								jQuery(".cardbody_text").each(function(){
									if(i <= showLessonsNum){
										var tempHeight = jQuery(this).css("height");
										tempHeight = tempHeight.split("px");
										tempHeight = tempHeight[0];
										max_height = parseFloat(tempHeight) + parseFloat(max_height);
									}
									i++;
								});
								
								var i = 1; 
								jQuery(".card-header").each(function(){
									if(i <= mods){
										var tempHeight = jQuery(this).css("height");
										tempHeight = tempHeight.split("px");
										tempHeight = tempHeight[0];
										max_height = parseFloat(tempHeight) + parseFloat(max_height);
									}
									i++;
								});
								jQuery(".mod_lesson_outer").css("height" ,max_height+"px");
								jQuery(".mod_lesson_outer").css("overflow" ,"auto");
							}
						</script>';	
						if(isset($showLessonsNum) && $showLessonsNum != '' && $showLessonsNum != 'all'){$combined_data .= '</div>';}
								}	
						}
						
															
					
								
						$combined_data .= '  
							</div>
						</div>';
						
						$cohtmldata .= $combined_data.$style.$script; 
						
						//return $cssurl.$cohtmldata.$cssdata ;
						
					}	
					
				} //close foreach loop
			
				if (isset($user)) {
					if(!$anyoneprodaccess){						
						return NOT_HAVE_ACCESS_COURSE_TEXT;						 
					}
					//disable the pointer of start button  
					$style_startbtn ='<style>#outline_continer .btndisable  {						 
						pointer-events: none;
					}</style>';
				}else{
					//added to disable the start button for not logged in user
					$style_startbtn ='<style>#outline_continer .btn_template_start  {
						background: #d4d4d4 !important;
						pointer-events: none;
					}</style>';
				}
			
				 $script =' <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>					 
					<script>
					jQuery(document).ready(function() { 						
						
						jQuery(".card-header a").click(function(e){
							e.preventDefault();
							 
							if(jQuery(this).hasClass("collapsed") == true){
									jQuery(this).removeClass("collapsed");
									var target = jQuery(this).attr("href");								 
									jQuery(target).addClass("show1");
							}else{
									jQuery(this).addClass("collapsed");
									var target = jQuery(this).attr("href");							 
									jQuery(target).removeClass("show1");
							}											
									
						});
						
						/*jQuery(".btn_template_start a").on("click",function(e){
							 
								e.preventDefault();
								var href = jQuery(this).attr("href");
								
								jQuery("#courseoutlineform").attr("action",href);     
								var courseid = jQuery(this).closest(".course_outline_inner_wrapper").attr("data-courseid");
								jQuery("#courseoutlineform").find("#form_course_id").val(courseid);
								jQuery("#courseoutlineform #form_course_submit").trigger("click");
						});*/
						
						jQuery(".btn_template_start a").click(function() {  
							var ahref = jQuery(this).attr("href");
							jQuery(this).removeAttr("href");
							 var courseid = jQuery(this).closest(".course_outline_inner_wrapper").attr("data-courseid");
							 var ajaxurl = "' . admin_url('admin-ajax.php') . '";				 
						 
								jQuery.post(ajaxurl, {
									action: "dap_setcoursesession",
									course_id: courseid,				 
									
								}, function(response) {
									 
									 window.location= ahref;
								});  	        
							});
							
					});
					
					 </script>';		
					
					
					
					
				ob_start();				 
				$output = "<div class='courselesson_container_outer'><div class='courselesson_container' id='outline_continer'>".$cssurl.$cohtmldata.$script.$cssdata.$style_startbtn."</div></div>"; 
				$output .= "<div style='display:none!important'><form action='' method='post' id='courseoutlineform'><input type='text' name='form_course_id' value='' id='form_course_id'><input type='submit' id='form_course_submit' name='submit' value='click to view'></form></div>"; 
				ob_end_clean();
				return do_shortcode($output);  			 
					 
			}
		 
    
}
  
 
/*for certificate download start*/
function dapCheckIfCertificateDownloadShouldDisplay($course_id,$userID, $action,$insertInTable = 'Y'){
	//get course certificate
	$courseCertificate = Dap_CourseCertificate::loadByCourseId($course_id);
	if($courseCertificate){
		$certificate_id = $courseCertificate->getCertificateId();
		$shortcode_type = $courseCertificate->getShortcodeType();
		$certificate_gen = $courseCertificate->getCertificateGenerationCriteria();
		$status = $courseCertificate->getStatus();
		$btnText = $courseCertificate->getDownloadBtnHtml();
		$downloadbtn = "";
		$style1 = "";
		
		//check if status is active not in dap_certificate table
		$certObj = Dap_Certificate::loadById($certificate_id);
		if(isset($courseCertificate)){
			$cert_status = $certObj->getStatus();		
			if($cert_status != 'Y'){
				return false;
			}
		}else{
			return false;
		}
		
		//if status is active not in dap_course_certificate table
		if($status != 'Y'){
			return false;
		}
		
		//if($certificate_gen == 'LASTLESSON'){
			//$userCourseProgessDetails  = DAP_UserCourseProgress::loadAllByCourseIduserId($course_id,$userID);
			$userCourseDetails  = Dap_UserCertificate::loadByCourseIdAndUserId($course_id,$userID);
			
			//for when we click on markas_completed_btn, setting some hidden field data
			   
			//when course is already completed
			if($action == "COMPLETECOURSE"){ // if course is already completed
				 
				$style1 .='<style>   .certificate_container{ display:block !important; }  </style>';	
				$downloadbtn = downloadCertificateButton($course_id,$certificate_id,'', $btnText)	;			
				if(  $userCourseDetails == false){					 
					$insert_certificate_data = insertUserCertificate($course_id ,$userID, "n");	
				}
				 
			}else{
				 
				if(isset($userCourseDetails) && $userCourseDetails != false){						 
					$style1 ="<style>   .certificate_container{ display:block !important; }  </style>";	
					$downloadbtn =   downloadCertificateButton($course_id,$certificate_id,'', $btnText);
				 
				}else{ 
					 
					//not completed the course  and user is in last lesson
					$style1 .='<input type="hidden" class="certificate_gen" value= "'.$certificate_gen.'"/>';
					if($insertInTable == 'Y'){
						if($certificate_gen == 'LASTLESSON'){
							 
							$style1 .='<style>   .certificate_container{ display:block !important; }  </style>';	
							$insert_certificate_data = insertUserCertificate($course_id ,$userID, "n");	 
							$downloadbtn =  downloadCertificateButton($course_id,$certificate_id,'', $btnText);	
							
						}else{
							if($shortcode_type == "automatic"){
								$style1 .='<input type="hidden" class="certification_btn_show" value="y"/>';
							}else{
								$style1 .='<input type="hidden" class="certification_btn_show" value="n"/>';
							}
							
							$downloadbtn =  downloadCertificateButton($course_id,$certificate_id,'', $btnText);
						}
					}
					
				}
			}
			return $style1.$downloadbtn;
	 	
	}
} 

