<?php 
define('dap_member_dir', plugin_dir_path(__FILE__));
define('dap_member_path', plugin_dir_url(__FILE__));
define('dap_member_current_date_time', date("Y-m-d H:i:s"));

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

/* define ajax request event */
add_action( 'wp_ajax_dap_member_get_template', 'ajaxDapMemberGetTemplateAjax' );
add_action( 'wp_ajax_dapMemberGenerateWpPage', 'dapMemberGenerateWpPageAjax' );
add_action( 'wp_ajax_saveDapMemberPageAjax', 'saveDapMemberPageAjax' );
add_action( 'wp_ajax_ajaxDapSortProducts', 'ajaxDapSortProducts' );
add_action( 'wp_ajax_dapMemberGetContentTemplate', 'dapMemberGetContentTemplate' );
add_action( 'wp_ajax_dap_check_page_id_status', 'dapCheckPageIdStatusAjax' );
add_action( 'wp_ajax_dap_checked_page_id_and_page_type_used', 'ajaxDapCheckedPageIdAndPageTypeUsed' );
add_action( 'wp_ajax_save_dap_member_affiliate_page_save', 'ajaxDapMemberAffilatePageSave' );
add_action( 'wp_ajax_dap_save_settings_info', 'ajaxDapSaveSettingsInfo' );
add_action( 'wp_ajax_save_dap_member_profile_page_save', 'ajaxDapMemberProfiePageSave' );
add_action( 'wp_ajax_dap_member_invoice_preview', 'ajaxDapMemberInvoicePreview' );
add_action( 'wp_ajax_dapDeleteMemberPageAjax', 'dapDeleteMemberPageAjax' );


add_action( 'wp_ajax_dapPayPerPostEnableAndDisableActionAjax', 'dapPayPerPostEnableAndDisableActionAjax' );
add_action( 'wp_ajax_dapPayPerPostDeleteByPostIdAjax', 'dapPayPerPostDeleteByPostIdAjax' );
add_action( 'wp_ajax_dapPayPerPostCopyActionAjax', 'dapPayPerPostCopyActionAjax' );
add_action( 'wp_ajax_dapFbConnectionAjax', 'dapFbConnectionAjax' );
add_action( 'wp_ajax_nopriv_dapFbConnectionAjax', 'dapFbConnectionAjax' );


function dapFbConnectionAjax(){
	
	$facebookemail = $_REQUEST["email"];  
	$userId= Dap_EmailAlias::findEmailAliasesByEmail($facebookemail);
	$output = array();	
	if($userId !=""){		
		
		$user=Dap_User::loadUserById($userId); 	
		$email = $user->getEmail();	
		$pass = $user->getPassword();		
		$req = $_SESSION['redirecturl1'];	
		$cur_login = $_SESSION["currenturl_login"];	
		$submit = "Y";	
		$action_id = $_REQUEST["action_id"]; 
		$post_login_url  = dapMemberGetPostLoginURl($action_id);
		$form_action = '/dap/authenticate.php';
		
		$output = array('email'=>$email,'pass' =>$pass,'req' =>$req,'cur_login' =>$cur_login,'submit' =>$submit,'post_login_url'=> $post_login_url ,'form_action'=> $form_action);	
	}else{
		$output['error'] = 'User not found';  
	}
	
	echo json_encode($output);
	exit();
}



function dapPayPerPostDeleteByPostIdAjax(){
	$post_id = $_REQUEST['post_id']; 
	Dap_PayPerPost::DeletePayPerPostByPostId($post_id);	
	$button_type = "buynow";
	Dap_PayPerPostMeta::DeletePayPerPostMetaByPostIdAndButtonType($post_id, $button_type);
	$button_type = "rent";
	Dap_PayPerPostMeta::DeletePayPerPostMetaByPostIdAndButtonType($post_id, $button_type);
	$button_type ="membership";
	Dap_PayPerPostMeta::DeletePayPerPostMetaByPostIdAndButtonType($post_id, $button_type);
	$output = array('post_id'=>$post_id);
	echo json_encode($output);
	die;
	
}

function dapPayPerPostCopyActionAjax(){
	
	$source_post_id = $_REQUEST['source_post_id']; 
	
	$source_page_enter_url = $_REQUEST['source_page_enter_url']; 
	$distination_post_ids = $_REQUEST['distination_post_ids']; 
	if($source_post_id == 0){
		
		$source_page_enter_url = trim($source_page_enter_url);
		if(substr($source_page_enter_url , -1) != '/'){
			$source_page_enter_url = $source_page_enter_url.'/';
		}
		$source_post_id = url_to_postid($source_page_enter_url);
	}
	if(!is_array($distination_post_ids) || (count($distination_post_ids) == 0 )){
		$output['error'] == "Please select post to which you want to copy";
	}else if($source_post_id == 0){
		$output['error'] == "Please check main post URL";
	}else{
		$postOjb = Dap_PayPerPost::loadPayPerPostByPostId($source_post_id);
		$post_output = array();
		$post_meta_output = array();
		if(isset($postOjb)){
			foreach($distination_post_ids as $distination_post_id){
				$postOjbExists = Dap_PayPerPost::loadPayPerPostByPostId($distination_post_id);
				if(isset($postOjbExists)){
					continue;
				}
				$postOjb->setPostId($distination_post_id);
				$postOjb->create();
				$post_output[] = 'Post copy for post id '.$distination_post_id; 
				$postMetaOjbs = Dap_PayPerPostMeta::loadPayPerPostMetaByPostId($source_post_id);
				if(count($postMetaOjbs)){
					foreach($postMetaOjbs as $postMetaOjb){
						
						$postMetaOjbExists = Dap_PayPerPostMeta::loadPayPerPostMetaByPostIdAndButtonType($post_id, $postMetaOjb->getButtonType());
						if(isset($postMetaOjbExists)){
							continue;
						}
						$postMetaOjb->setPostId($distination_post_id);
						$buy_link = str_replace("=".$source_post_id,"=".$distination_post_id,$postMetaOjb->getBuyLink());
						$postMetaOjb->setBuyLink($buy_link);
						$postMetaOjb->create();
						$post_meta_output[] = 'PostMeta copy for post id '.$distination_post_id; 
					}
				}
			}
		}
		$output = array('success'=>"Post copy successfully",'post_output'=>$post_output,'post_meta_output'=>$post_meta_output);
	}
	
	echo json_encode($output);
	die;
}

function dapPayPerPostEnableAndDisableActionAjax(){
	
	$post_id = $_REQUEST['post_id'];	
	$dapwp_post_status_checkbox = $_REQUEST['dapwp_post_status_checkbox'];	
	Dap_PayPerPost::updatePostStatusByPostId($post_id,$dapwp_post_status_checkbox);
	$output = array('post_id'=>$post_id,'dapwp_post_status_checkbox'=>$dapwp_post_status_checkbox);
	echo json_encode($output);die;
	
}


function ajaxDapMemberInvoicePreview(){
	
	$csspath = dap_member_path."includes/transactions/invoices/template".$_POST['tmp_no']."/css/style.css";
	$file = dap_member_dir."includes/transactions/invoices/template".$_POST['tmp_no']."/invoicetemplate.html";
	$logo = dap_member_dir."includes/images/dap_invoice_dummy_logo.png";
	$html = file_get_contents($file);
	//$file = str_replace( '%%IMAGESPATH%%', $imgpat$session = Dap_Session::getSession();
	$html =  str_replace('%%COMPANYNAME%%',"Company Name",$html);
	$html =  str_replace('%%adminemail%%',"Admin Email",$html);
	$html =  str_replace('%%ADMINEMAIL%%',"Admin Email",$html);
	$html =  str_replace('%%logo%%',$logo,$html);
	$html =  str_replace('%%TRANSACTIONID%%',"Transaction Id",$html);
	$html =  str_replace('%%TRANSACTIONDATE%%',"Transaction Date",$html);
	$html =  str_replace('%%FIRST_NAME%%',"First Name",$html);
	$html =  str_replace('%%LAST_NAME%%',"Last Name",$html);
	$html =  str_replace('%%ADDRESS1%%',"Address",$html);
	
	$html =  str_replace('%%CITY%%',"City Name",$html);  
	$html =  str_replace('%%STATE%%',"State Name",$html);
	$html =  str_replace('%%ZIP%%',"Zip Code",$html);
	$html =  str_replace('%%EMAIL_ID%%',"Email Id",$html);
	$html =  str_replace('%%PAYMENTTYPE%%',"Payment Type",$html);
	$html =  str_replace('%%ITEMNAME%%', "Item Name",$html);
	$html =  str_replace('%%DESCRIPTION%%',"Description",$html);
	$html =  str_replace('%%AMOUNT%%',"Amount",$html);
	$html =  str_replace('%%CURRENCY%%',"Currency Symbol",$html);
	$html =  str_replace('%%COUNTRY%%',"Country Name",$html);  
	$outpout['html'] = $html;
	$outpout['csspath'] = $csspath;
	
	
    echo json_encode($outpout);
    die;
}
function ajaxDapMemberProfiePageSave(){
	
	if(isset($_POST['styling_options'])){  
		$styling_options = '';
		if(isset($_POST['styling_options'])){
			$styling_options = $_POST['styling_options'];
		}
		
		$template_html = '';
		if(isset($_POST['template_html'])){
			$template_html = $_POST['template_html'];
		}
		
		
		
		$edit_id = '';
		if(isset($_POST['edit_id'])){
			$edit_id = $_POST['edit_id'];
		}
		
		
		$page_id = 0;
		if(isset($_POST['page_id'])){
			$page_id = $_POST['page_id'];
		}
		
		$template_selected_name = '';
		if(isset($_POST['template_selected_name'])){
			$template_selected_name = $_POST['template_selected_name'];
		}
		
		$admin_email = $_POST['admin_email'];
		$notifyFileUploadEmail = $_POST['notifyFileUploadEmail'];
		$name = 'FILEUPLOADNOTIFY';
		Dap_Config::updateConfigName($name , $notifyFileUploadEmail,'N');
				
		$action  = 'profile';
        $obj = new DAP_MemberPages();
		$obj->setPageId($page_id);
		$obj->setAction( $action);
		$obj->setTemplate($template_selected_name);
		$obj->setTemplateHtml( $template_html);
		$obj->setStylingOptions( $styling_options);
		$obj->setAdminEmail( $admin_email);
		$obj->setDate( dap_member_current_date_time );
		
        $id_hash = DAP_MemberPages::loadById($edit_id);
         
        if($id_hash){
			$obj->setId($edit_id);
			$edit_id = $obj->update();
			$message = 'Update Shortcode';
			
			
		}else{
			$edit_id = $obj->create();		  
			$message = 'Shortcode save successfully';
			$shortcode_content = dapMemberGetProfileShortcodeNameById($edit_id);
			$result['save_shortcode_in_a_page']  = dapMemberAddShortcodeINAPage($shortcode_content,$page_id);
		}
		
		$redirect_url = '';
		if(isset($_POST['redirect_url'])){
			$redirect_url = $_POST['redirect_url'];
		}
		$gdpr_msg_section = '';
		if(isset($_POST['gdpr_msg_section'])){
			$gdpr_msg_section = $_POST['gdpr_msg_section'];
		}
		
		
		$member_page_values_array = array('redirect_url'=>$redirect_url,'gdpr_msg_section'=>$gdpr_msg_section);
		foreach($member_page_values_array as $key=>$val){				
				
			$result['member_page_values'][] =  dapMemberPagesUpdateValueByActionIdAndName($edit_id,$key,$val);
		}
		
		
		$short_code_html   = '<span class="check_heading">Here is your Profile page URL:</span>';
		$short_code_html  .= '<a href="'.get_permalink($page_id).'" target="_blank">'.get_permalink($page_id).'</a>';
		$short_code_html .= '<br><br>';
		$short_code_html .= '<div class="">';
		$short_code_html .= '<span class="check_heading">Here is your Profile page Shortcode:</span>';
		$short_code_html .= '<span id="dynamic_copyable_text_'.$edit_id.'" class="d-inline" name="shortcode_display">'.dapMemberGetProfileShortcodeNameById($edit_id).'</span>';
		$short_code_html .= '<span data-id="dynamic_copyable_text_'.$edit_id.'" class="copy-btn theme-button" onclick="dap_member_copy_to_clipboard(this)"><i class="fa fa-files-o" aria-hidden="true"></i> Copy</span>';
		$short_code_html .= '</div>';
		$result['html'] = $short_code_html;
		
        $result['edit_id'] = $edit_id;
		$result['success'] = $message;
		$result['short_code_html'] = dapMemberGetProfileShortcodeNameById($edit_id);
		$result['page_url_html'] = '<a href="'.get_permalink($page_id).'" target="_blank">'.get_permalink($page_id).'</a>';
		
		
	}else{
		$result['error'] = "Something Wrong!";
	}
	
	echo json_encode($result);
	die;
}

function ajaxDapSaveSettingsInfo(){
	
	if(isset($_POST['page_action']) && ($_POST['page_action'] != '')){
		  
		$page_action = $_POST['page_action'];
		$form_data = $_POST['form_data'];
		if(count($form_data )){
			foreach($form_data as $key=>$vala){ 
				$name = $form_data[$key]['name'];
				$value = $form_data[$key]['value'];
				$hashMessage = DAP_MemberPageSettings::loadByActionAndName($page_action,$name);
				$obj = new DAP_MemberPageSettings();
				
				$obj->setName($name);
				$obj->setValue($value);
				$obj->setAction($page_action);
				$obj->setAction($page_action);
				if($hashMessage){
					$obj->update();
				}else{
					$obj->create();
				}
			} 
		
		$result['success'] = 'Update successfully.';
		
		}else{
			
			$result['error'] = "Something Wrong!";
		}
	}else{
		
	}
	
	echo json_encode($result);
	die;
	
	
	die;
}

function ajaxDapMemberAffilatePageSave(){
	
	if(isset($_POST['styling_options'])){  
		$styling_options = '';
		if(isset($_POST['styling_options'])){
			$styling_options = $_POST['styling_options'];
		}
		
		$template_html = '';
		if(isset($_POST['template_html'])){
			$template_html = $_POST['template_html'];
		}
		
		
		
		$edit_id = '';
		if(isset($_POST['edit_id'])){
			$edit_id = $_POST['edit_id'];
		}
		
		
		$page_id = 0;
		if(isset($_POST['page_id'])){
			$page_id = $_POST['page_id'];
		}
		
		$template_selected_name = '';
		if(isset($_POST['template_selected_name'])){
			$template_selected_name = $_POST['template_selected_name'];
		}
		
		$action  = 'affiliate';
        $obj = new DAP_MemberPages();
		$obj->setPageId($page_id);
		$obj->setAction( $action);
		$obj->setTemplate($template_selected_name);
		$obj->setTemplateHtml( $template_html);
		$obj->setStylingOptions( $styling_options);
		$obj->setDate( dap_member_current_date_time );
		
        $id_hash = DAP_MemberPages::loadById($edit_id);
         
        if($id_hash){
			$obj->setId($edit_id);
			$edit_id = $obj->update();
			$message = 'Update Shortcode';
			
			
		}else{
			$edit_id = $obj->create();		  
			$message = 'Shortcode save successfully';
			$shortcode_content = dapMemberGetAffilateShortcodeNameById($edit_id);
			$result['save_shortcode_in_a_page']  = dapMemberAddShortcodeINAPage($shortcode_content,$page_id);
		}
		
		
		$short_code_html   = '<span class="check_heading">Here is your Affiliate page URL:</span>';
		$short_code_html  .= '<a href="'.get_permalink($page_id).'" target="_blank">'.get_permalink($page_id).'</a>';
		$short_code_html .= '<br><br>';
		$short_code_html .= '<div class="">';
		$short_code_html .= '<span class="check_heading">Here is your Affiliate page Shortcode:</span>';
		$short_code_html .= '<span id="dynamic_copyable_text_'.$edit_id.'" class="d-inline" name="shortcode_display">'.dapMemberGetAffilateShortcodeNameById($edit_id).'</span>';
		$short_code_html .= '<span data-id="dynamic_copyable_text_'.$edit_id.'" class="copy-btn theme-button" onclick="dap_member_copy_to_clipboard(this)"><i class="fa fa-files-o" aria-hidden="true"></i> Copy</span>';
		$short_code_html .= '</div>';
		$result['html'] = $short_code_html;
		
        $result['edit_id'] = $edit_id;
		$result['success'] = $message;
		$result['short_code_html'] = dapMemberGetAffilateShortcodeNameById($edit_id);
		$result['page_url_html'] = '<a href="'.get_permalink($page_id).'" target="_blank">'.get_permalink($page_id).'</a>';
		
		
	}else{
		$result['error'] = "Something Wrong!";
	}
	
	echo json_encode($result);
	die;
	
	
}
function ajaxDapMemberGetTemplateAjax(){
	
	$template_name = $_REQUEST['template_name'];
	$template_number_name = $_REQUEST['template_number_name'];
	$file = dap_member_dir."includes/templates/" . $template_name .'/'.$template_number_name. "/template.php";
	$file = include_once($file);
	die;
}
 
function dapMemberGetContentTemplate(){	
	$result = array();
	$template = $_REQUEST['template'];
	$type = $_REQUEST['type'];
	$type = $_REQUEST['type'];
	$temp_type = $_REQUEST['temp_type'];
	$file = dap_member_dir."includes/templates/mycontent/".$temp_type. "/".$type. "/template1.php";
	$csspath = dap_member_path."includes/templates/mycontent/".$temp_type. "/".$type. "/template1.css"; 
	$file = file_get_contents($file);
	$imgpath = plugins_url()."/DAP-WP-LiveLinks/includes/images/mycontentimg.jpg";		
	$contentavailableimg = plugins_url()."/DAP-WP-LiveLinks/includes/templates/mycontent/singlecol/postmetadata/contentavailableimg.jpg";		 
	$upcomingimg = plugins_url()."/DAP-WP-LiveLinks/includes/templates/mycontent/singlecol/postmetadata/upcomingimg.jpg";		 
	$file = str_replace( '%%IMAGESPATH%%', $imgpath, $file);
	$file = str_replace( '%%CONTENTIMG%%', $contentavailableimg, $file);
	$file = str_replace( '%%UPCOMINGIMG%%', $upcomingimg, $file);
 
	$cssstyle =' <link href="'.$csspath.'" rel="stylesheet">'; 
	$result['cssstyle'] = $cssstyle;
	$result['temp_html'] = stripslashes($file);	 
	echo json_encode($result);
	die	;
}
 
function ajaxDapSortProducts(){ 

	$orderBy = $_REQUEST['orderBy'];
	$orderHow = $_REQUEST['orderHow'];
 
	$productListHTML = "";
	try {

		$ProductsList = Dap_Product::loadProducts("","",$orderBy,$orderHow);
		  
		foreach ($ProductsList as $product) {
			$productName = stripslashes($product->getName());
			$productNameShort = trimString($productName,40,30,10);
			
			$productListHTML .= "<option value=\"" . $product->getId() . "\" title=\"".$productName."\">" . $productNameShort . "</option>\n";
		}

	} catch (PDOException $e) {
		$response = ERROR_GENERAL;
	} catch (Exception $e) {
		$response = $e->getMessage() . "<br/>";
	}	
 
	echo $productListHTML;
	die;
}	
	
// create  page in WP
function dapMemberGenerateWpPageAjax(){
	$page_name = $_REQUEST['post_title'];
	$status = dapMemberCheckPageTitleExist($page_name);
	/*$args = array(
	'sort_order' => 'asc',
	'sort_column' => 'post_title',
	'hierarchical' => 1,
	'exclude' => '',
	'include' => '',
	'meta_key' => '',
	'meta_value' => '',
	'authors' => '',
	'child_of' => 0,
	'parent' => -1,
	'exclude_tree' => '',
	'number' => '',
	'offset' => 0,
	'post_type' => 'page',
	'post_status' => 'publish'
	);
	$pages = get_pages($args); 
	$output = array();	
	foreach($pages as $page){
		$id = $page->ID;
		$wp_page_name = $page->post_title;
		if($wp_page_name != ''){
			if(strcmp($wp_page_name,$page_name) == 0 ){
				$status ='yes';
				break;
			}
			else{
				
				$status ='no';
				
			}
		}
	}
	*/
	if($status == "no"){
		$my_post = array(
				'post_title'    => wp_strip_all_tags( $_REQUEST['post_title'] ),
				'post_status'   => 'publish',
				'post_author'   => 1,
				'post_type' =>'page',
				'post_category' => array( 8,39 )
				); 
		
		$post_id = wp_insert_post( $my_post );
		$output['post_id'] = $post_id;
		$output['page_url'] = get_permalink($post_id);
	}
	 $output['status'] =  $status;
	echo json_encode($output);
	die;
} 
function saveDapMemberPageAjax(){
	$page_name = $_REQUEST['post_title'];
	die;
}

// check status of page if the page already is in use
function dapCheckPageIdStatusAjax(){    
    $row = false;
    if(isset($_POST['page_id'])){
		$page_id = $_POST['page_id'];
		$row = DAP_MemberPages::loadByPageId($page_id);
	}
    if($row){
        echo 'yes';       
    }else{
        echo 'no';
    }
    die;
}


// check page is alredy is used or not
function ajaxDapCheckedPageIdAndPageTypeUsed(){    
    $row = false;
    if(isset($_POST['page_id'])){
		$page_id = $_POST['page_id'];
		$page_type = $_POST['page_type'];  
		$row = DAP_MemberPages::loadByPageIdAndAction($page_id,$page_type);
	}
    if($row){
        echo 'yes';       
    }else{
        echo 'no';
    }
    die;
}




add_action( 'wp_ajax_save_dap_member_login_page', 'saveDapMemberLoginPageAjax' );

function saveDapMemberLoginPageAjax(){  
	
	
	$result =  array();
	
	if(isset($_POST['data'])){
		
		$data = $_POST['data'];
		
		$styling_options = '';
		if(isset($data['template_option'])){
			$styling_options = $data['template_option'];
		}
		
		$post_title = '';
		if(isset($data['post_title'])){
			$post_title = $data['post_title'];
		}
		
		$login_page_url = '';
		if(isset($data['login_page_url'])){
			$login_page_url = $data['login_page_url'];
		}
		
		
		$page_id = '';
		if(isset($data['page_id'])){
			$page_id = $data['page_id'];
		}
		if($page_id == ''){
			$page_id = $login_page_url;
		}
		
		$post_login_url = '';
		if(isset($data['post_login_url'])){
			$post_login_url = $data['post_login_url'];
		}
		
		
		$gdpr = '';
		if(isset($data['gdpr'])){
			$gdpr = $data['gdpr'];
		}
		
		$seleted_template = '';
		if(isset($data['seleted_template'])){
			$seleted_template = $data['seleted_template'];
		}
		
		$template_html = '';
		if(isset($data['template_html'])){
			$template_html = urldecode($data['template_html']);
		}
		
		$edit_id = '';
		if(isset($data['edit_id'])){
			$edit_id = $data['edit_id'];
		}
		$registration_link = '';
		if(isset($data['dap_login_create_registration_link'])){
			$registration_link = $data['dap_login_create_registration_link'];
		}
		
		$action  = 'login';
		if(isset($data['template_selected_action'])){
			$action =  $data['template_selected_action'];
		}
		
		
		//$action  = 'login';
        $obj = new DAP_MemberPages();
		$obj->setPageId($page_id);
		$obj->setAction( $action);
		$obj->setTemplate( $seleted_template);
		$obj->setTemplateHtml( $template_html);
		$obj->setStylingOptions( $styling_options);
		$obj->setDate( dap_member_current_date_time );
		
        $id_hash = DAP_MemberPages::loadById($edit_id);
         
        if($id_hash){
			$obj->setId($edit_id);
			
			$edit_id = $obj->update();
			$message = 'Update Shortcode';
			
			
		}else{
			$edit_id = $obj->create();		  
			$message = 'Shortcode save successfully';
			$shortcode_content = dapMemberGetShortcodeNameById($edit_id);
			if($action == 'loginFB'){
			
				$shortcode_content = dapMemberLoginFBGetShortcodeNameById($edit_id);
			}
			
			$result['save_shortcode_in_a_page']  = dapMemberAddShortcodeINAPage($shortcode_content,$page_id);
		}
		$shortcode_content = dapMemberGetShortcodeNameById($edit_id);
		$fb_api_info_content = '';
		if($action == 'loginFB'){
			
			$shortcode_content = dapMemberLoginFBGetShortcodeNameById($edit_id);
			
			$fb_api_info_content = '<div class="dap_member_fb_login_details">';
			$fb_api_info_content .= '<b>Please Note</b>:<br>
									For the Facebook Login to work, you need to create Facebook API Key<br>
									for this domain and enter it in the <a href="'.site_url('').'/dap/admin/addEditProducts.php?t=3&sub_tab=12">DAP Setup >> Config Page >> Social Media Section.</a><br/><br/>
									<a href="https://digitalaccesspass.com/doc/how-to-generate-facebook-api-key/">Please click here to see how to create Facebook API Key.</a>
									</div>';  
			 
		}
		
		$member_page_values_array = array('gdpr'=>$gdpr,'post_login_url'=>$post_login_url,'registration_link'=>$registration_link);
		foreach($member_page_values_array as $key=>$val){				
				
			$result['member_page_values'][] =  dapMemberPagesUpdateValueByActionIdAndName($edit_id,$key,$val);
		}
		
		$short_code_html   = '<span class="check_heading">Here is your Login page URL:</span>';
		$short_code_html  .= '<a href="'.get_permalink($page_id).'" target="_blank">'.get_permalink($page_id).'</a>';
		$short_code_html .= '<br><br>';
		$short_code_html .= '<div class="">';
		$short_code_html .= '<span class="check_heading">Here is your Login page Shortcode:</span><br>';
		$short_code_html .= '<span id="dynamic_copyable_text_'.$edit_id.'" class="d-inline" name="shortcode_display">'.$shortcode_content.'</span>';
		$short_code_html .= '<span data-id="dynamic_copyable_text_'.$edit_id.'" class="copy-btn theme-button" onclick="dap_member_copy_to_clipboard(this)"><i class="fa fa-files-o" aria-hidden="true"></i> Copy</span>';
		$short_code_html .= '</div>';
		$result['html'] = $short_code_html;
		
		
        $result['edit_id'] = $edit_id;
		$result['success'] = $message;
		$result['short_code_html'] = $shortcode_content;
		$result['dap_member_fb_login_details'] = $fb_api_info_content;
		$result['page_id'] = $page_id;
		$result['page_url_html'] = '<a href="'.get_permalink($page_id).'" target="_blank">'.get_permalink($page_id).'</a>';
		
		
	}else{
		$result['error'] = "Something Wrong!";
	}
	$result['configlogin_url_html'] = '';
	global $lldocroot;
	include ($lldocroot . "/dap/dap-config.php"); 
	$configLoginUrl = Dap_Config::get("LOGIN_URL") ;	

	if($configLoginUrl == ''){
		$value = get_permalink($page_id);		 	
		Dap_Config::updateConfigName("LOGIN_URL", $value, "N") ;	
		
		$result['configlogin_url_html'] = '<br><a href="'.$value.'" target="_blank">'.$value.'</a>';
		
	}
	
	echo json_encode($result);
	die;
}		

add_action( 'wp_ajax_dapSavePostMetaData', 'dapSavePostMetaData' );

function dapSavePostMetaData(){  	
	 
	$resource_id = '';
	$image_url = '';
	$post_teaser = '';
	$post_title = '';
	if(isset($_POST['resource_id'])){
		$resource_id = $_POST['resource_id'] ;
	}					
	 
	$obj = new Dap_CourseLessonsMeta();
	$obj->setResourceId($resource_id);
	
	if(isset($_POST['image_url'])){
		$image_url = $_POST['image_url'] ;
		$obj->setImageURL( $image_url);
	}	
	if(isset($_POST['teaser_content'])){
		$teaser_content =$_POST['teaser_content'] ;
		$teaser_content = urldecode($teaser_content);
		$obj->setExcerpt( $teaser_content);
	}
	if(isset($_POST['post_title'])){
		$post_title =$_POST['post_title'] ;
		//update file resouces		 
		$data = Dap_FileResource::updateFileResourceTitle($resource_id, $post_title);
	}
			
	//update in lesson meta
	$id_hash = Dap_CourseLessonsMeta::loadByResourceId($resource_id);
	  
	if(count($id_hash)){
		logToFile("dapSavePostMetaData() update: call",LOG_DEBUG_DAP); 
		$id = $id_hash[0]->getId();
		logToFile("dapSavePostMetaData() update: call11",LOG_DEBUG_DAP); 
		$obj->setId($id);		
		$obj->setResourceId($resource_id);		
		$edit_id = $obj->updateByResourceId();
		$message = 'Update Shortcode';
	}else{
		logToFile("dapSavePostMetaData() create: " ,LOG_DEBUG_DAP); 
		$edit_id = $obj->create();
		logToFile("dapSavePostMetaData() create edit_id: ".$edit_id ,LOG_DEBUG_DAP); 
		$message = 'Insert Shortcode';	
	}	
		
	echo $edit_id;
	die;
}		

function dapMemberLoginFBGetShortcodeNameById($id = 0){
	
	return "[DAPMemberLogin id=".$id."][/DAPMemberLogin]";
	
}

add_action( 'wp_ajax_saveDapMemberContentAjax', 'saveDapMemberContentAjax' );

function saveDapMemberContentAjax(){  
	
	$result =  array();
	
	if(isset($_POST['data'])){
		
		$data = $_POST['data'];
		
		$styling_options = '';
		if(isset($data['template_option'])){
			$styling_options = $data['template_option'];
		}
		
		$post_title = '';
		if(isset($data['post_title'])){
			$post_title = $data['post_title'];
		}		
		
		$page_id = '';
		if(isset($data['page_id'])){
			$page_id = $data['page_id'];
		}

		
		$selected_template = '';
		if(isset($data['selected_template'])){
			$selected_template = $data['selected_template'];
		}
		
		$template_html = '';
		if(isset($data['template_html'])){
			$template_html = stripslashes($data['template_html']);
		}
		
		$edit_id = '';
		if(isset($data['edit_id'])){
			$edit_id = $data['edit_id'];
		}
		$showunavailableproducts = '';
		if(isset($data['showunavailableproducts'])){
			$showunavailableproducts = $data['showunavailableproducts'];
		}
			
		$productid = '';
		if(isset($data['productid'])){
			$productid = $data['productid'];
		}
 
		
		$hideproductid = '';
		if(isset($data['hideproductid'])){
			$hideproductid = $data['hideproductid'];
		}
		
		
		$sel_template = '';
		if(isset($data['sel_template'])){
			$sel_template = $data['sel_template'];
		}
		
		$select_prod = '';
		if(isset($data['select_prod'])){
			$select_prod = $data['select_prod'];
		}
		
		
		
		 
		$action  = 'mycontent';	
		 
        $obj = new DAP_MemberPages();
		$obj->setPageId($page_id);
		$obj->setAction($action);
		$obj->setTemplate($selected_template);
		$obj->setTemplateHtml($template_html);
		$obj->setStylingOptions($styling_options);
		$obj->setDate(dap_member_current_date_time );
		 
        $id_hash = DAP_MemberPages::loadById($edit_id);
        
        $shotcode_name = dapMemberGetMyCntentShortcodeNameById($edit_id);
		if($sel_template == 'payperpost'){
		  $shotcode_name = 	dapMemberGetPayPerPostShortcodeNameById($edit_id);
		}
        
        if($edit_id){
			$obj->setId($edit_id);			
			$edit_id = $obj->update();
			$message = 'Update Shortcode';	
			
		}else{
			$edit_id = $obj->create();				 
			$message = 'Shortcode save successfully';
			$shotcode_name = dapMemberGetMyCntentShortcodeNameById($edit_id);
			if($sel_template == 'payperpost'){
				$shotcode_name = 	dapMemberGetPayPerPostShortcodeNameById($edit_id);
			}
			
			
			$shortcode_content = $shotcode_name;
			$result['save_shortcode_in_a_page']  = dapMemberAddShortcodeINAPage($shortcode_content,$page_id);
		}
		
		$prods = "";
		$hideprods = "";
		 foreach ($productid as $prod) {
			 $prods .= $prod.",";			 
		 }
		 foreach ($hideproductid as $hideprod) {
			 $hideprods .= $hideprod.",";			 
		 }

		$productids = rtrim($prods, ", ");
		$hideproductids = rtrim($hideprods, ", ");
		
		if($sel_template =="contentlinks"){
			$member_page_values_array = array('showunavailableproducts'=>$showunavailableproducts,'productid'=>$productids,'hideproductid'=>$hideproductids,'select_prod'=>$select_prod);
		}else{
			$member_page_values_array = array('showunavailableproducts'=>$showunavailableproducts,'productid'=>$productids,'hideproductid'=>$hideproductids );
		}
		
		foreach($member_page_values_array as $key=>$val){			
				
			$result['member_page_values'][] =  dapMemberPagesUpdateValueByActionIdAndName($edit_id,$key,$val);
		}
        $result['edit_id'] = $edit_id;
       
       if($sel_template == 'payperpost'){
		$short_code_html   = '<span class="check_heading">Here is your Pay-Per-Post Content List URL: </span>';
		$short_code_html  .= '<a href="'.get_permalink($page_id).'" target="_blank">'.get_permalink($page_id).'</a>';
		$short_code_html .= '<br>';
		$short_code_html .= '<div class="shortcode_display1">';
		$short_code_html .= '<span class="check_heading">Here is your Pay-Per-Post Content List shortcode:</span><br>';
		$short_code_html .= '<span id="dynamic_copyable_text_'.$edit_id.'" class="d-inline" name="shortcode_display"> '.$shotcode_name.' </span>';
		$short_code_html .= '<span data-id="dynamic_copyable_text_'.$edit_id.'"  id="copy_shortcode" class="copy-btn theme-button btn btn-warning " onclick="dap_member_copy_to_clipboard(this)"><i class="fa fa-files-o" aria-hidden="true"></i> Copy</span>';
		$short_code_html .= '</div>';
	}else {
		$short_code_html   = '<span class="check_heading">Here is your MyContent page URL: </span>';
		$short_code_html  .= '<a href="'.get_permalink($page_id).'" target="_blank">'.get_permalink($page_id).'</a>';
		$short_code_html .= '<br>';
		$short_code_html .= '<div class="shortcode_display1">';
		$short_code_html .= '<span class="check_heading">Here is your MyContent page shortcode:</span><br>';
		$short_code_html .= '<span id="dynamic_copyable_text_'.$edit_id.'" class="d-inline" name="shortcode_display"> '.$shotcode_name.' </span>';
		$short_code_html .= '<span data-id="dynamic_copyable_text_'.$edit_id.'"  id="copy_shortcode" class="copy-btn theme-button btn btn-warning " onclick="dap_member_copy_to_clipboard(this)"><i class="fa fa-files-o" aria-hidden="true"></i> Copy</span>';
		$short_code_html .= '</div>';
	}
        
		$result['success'] = $message;
		$result['short_code_html'] = $short_code_html;
		
		
	}else{
		$result['error'] = "Something Wrong!";
	}
	
	$result['page_id'] = $page_id;
	
	$result['configlogin_url_html'] = '';
	global $lldocroot;
	include ($lldocroot . "/dap/dap-config.php"); 
	$configLoginUrl = Dap_Config::get("LOGIN_URL") ;	

	if($configLoginUrl == ''){
		$value = get_permalink($page_id);		 	
		Dap_Config::updateConfigName("LOGIN_URL", $value, "N") ;	
		
		$result['configlogin_url_html'] = '<a href="'.$value.'" target="_blank">'.$value.'</a>';
		$result['configlogin_url_html'] .= '<a href="'.SITE_URL_DAP.'/dap/admin/addEditProducts.php?t=3" target="_blank">Click here to change</a>';
	}
	
	echo json_encode($result);
	die;
}

function dapMemberPagesUpdateValueByActionIdAndName($action_id = 0,$name = '',$value = ''){
	    $result = array();
		$objMemberPagesValues = new DAP_MemberPagesValues();		
		$objMemberPagesValues->setName($name);
		$objMemberPagesValues->setValue($value);
		
		$id_hash = DAP_MemberPagesValues::loadByActionIdAndName($action_id,$name);
        if($id_hash){
			$objMemberPagesValues->setId($id_hash->getId());
			$edit_id = $objMemberPagesValues->update();
			$result['message'] = 'Update Shortcode';
		}else{
			$objMemberPagesValues->setActionId($action_id);
			$edit_id = $objMemberPagesValues->create();		  
			$result['message'] = 'Shortcode save successfully';
		}
		
		return $result;
}


function dapMemberGetProfileShortcodeNameById($id = 0){
	
	return "[DAPMemberProfile id=".$id."][/DAPMemberProfile]"; 
}

function dapMemberGetAffilateShortcodeNameById($id = 0){
	
	return "[DAPMemberAffiliateDetails id=".$id."][/DAPMemberAffiliateDetails]"; 
}

function dapMemberGetShortcodeNameById($id = 0){
	
	return "[DAPMemberLogin id=".$id."][/DAPMemberLogin]";
}
function dapMemberGetMyCntentShortcodeNameById($id = 0){
	
	return "[DAPMemberContent id=".$id."][/DAPMemberContent]";
}

function dapMemberGetPayPerPostShortcodeNameById($id = 0){
	
	return "[DAPPayPerPostContent id=".$id."][/DAPPayPerPostContent]";
}

function dapMemberGetInvoiceShortcodeNameById($id = 0){
	return "[DAPMemberInvoice id=".$id."][/DAPMemberInvoice]";	
}

function dapMemberGetCancellationShortcodeNameById($id = 0){
	return "[DAPMemberCancellation id=".$id."][/DAPMemberCancellation]";	
}

function dapMemberGetSubaccountShortcodeNameById($id = 0){
	return "[DAPMemberGroupUser id=".$id."][/DAPMemberGroupUser]";	
}

function dapMemberAddShortcodeINAPage($shortcode_content = '',$page_id = 0){
	global $wpdb;
	$output = array();
  
	$posttable = $wpdb->prefix.'posts';	
	$selectdb = $wpdb->get_results("select `post_content` FROM  `$posttable`  WHERE ID='".$page_id."'");
	if(isset($selectdb[0]) && ($shortcode_content != '')){
		$mycontent= $selectdb[0]->post_content;
		$my_post = array('ID'=> $page_id,
						  'post_content' => $mycontent.$shortcode_content,
						);
						
		wp_update_post( $my_post );			
	$output['msg'] = 'Save shortcode in a page.'.$page_id; 
	}else{
		$output['msg'] = 'Not save shortcode in a page';
	}
	return $output;	 
}


add_action( 'wp_ajax_dapcheckPageAvailabilityAjax', 'dapcheckPageAvailabilityAjax' );

function dapcheckPageAvailabilityAjax(){
	$page_name = lcfirst($_REQUEST['page_name']);	
	$status = dapMemberCheckPageTitleExist($page_name);
	
/*	
	$args = array(
	'sort_order' => 'asc',
	'sort_column' => 'post_title',
	'hierarchical' => 1,
	'exclude' => '',
	'include' => '',
	'meta_key' => '',
	'meta_value' => '',
	'authors' => '',
	'child_of' => 0,
	'parent' => -1,
	'exclude_tree' => '',
	'number' => '',
	'offset' => 0,
	'post_type' => 'page',
	'post_status' => 'publish'
	);
	
	
	$pages = get_pages($args); 
	
	foreach($pages as $page){
		$id = $page->ID;
		$wp_page_name = $page->post_title;
		if($wp_page_name != ''){
			if(strcmp($wp_page_name,$page_name) == 0 ){
				$status ='yes';
				break;
			}
			else{
				$status ='no';
			}
		}
	}
*/ 	
	if($status == "no"){
		$page = get_page_by_title( "invoice-20" );
		if(is_object($page)){
			$id = $page->ID;
		}
	}




	echo $status."||".$id ;
	die;
	
}

add_action( 'wp_ajax_dapSaveMemberLoginAjax', 'dapSaveMemberLoginAjax' );
function dapSaveMemberLoginAjax(){
	$login_data_page = $_REQUEST['login_data_page'];
	$login_data_id = $_REQUEST['login_data_id'];
	$addin_config_login = $_REQUEST['addin_config_login'];
	$all_types = explode('|' , $all_member_types);
	 
	$type = 'login';	
	
	//$page = $login_data_page;
	$page_id = $login_data_id;
	
	if($page_id == '' && !is_numeric($page_id)){
		$status = dapMemberCheckPageTitleExist($login_data_page);
	 
		if($status == "no"){
			$my_post = array(
					'post_title'    => wp_strip_all_tags( $login_data_page ),
					'post_status'   => 'publish',
					'post_author'   => 1,
					'post_type' =>'page',
					'post_category' => array( 8,39 )
					); 
			$page_id = wp_insert_post( $my_post );
			
		}else{
			echo json_encode(array('error' => 'page already exists'));
			die;
		}
		
		
		
	}
	$_SESSION['return_data'] = 'yes';
	$seleted_template = 'template1';
	
	
	$file = dap_member_dir."includes/templates/" . $type .'/'.$seleted_template.'/template.php';
	include_once($file);
	unset($_SESSION['return_data']);
		
	$styling_options = $dm_login_temp_wid."||".$dm_login_temp_border_width."||".$dm_login_temp_border_radius."||".$dm_login_temp_border_color."||".$dm_login_temp_background_color."||".$dm_login_temp_border_style."||".$dm_login_temp_img_show."||".$dap_member_login_image_height."||".$dm_login_temp_captcha."|||".$dm_login_temp_addit_create_account_link."||".$dm_login_temp_addit_width."||".$dm_login_temp_addit_border_width."||".$dm_login_temp_addit_border_radius."||".$dm_login_temp_addit_background_color."||".$dm_login_temp_addit_border_color."||".$dm_login_temp_addit_style."|||".$dm_login_temp_signin_width."||".$dm_login_temp_signin_height."||".$dm_login_temp_signin_border_width."||".$dm_login_temp_signin_radius."||".$dm_login_temp_signin_background_color."||".$dm_login_temp_signin_border_color."||".$dm_login_temp_signin_border_style."|||".$dm_login_temp_shadow_horizontal_length."||".$dm_login_temp_shadow_vertical_length."||".$dm_login_temp_shadow_blur_radius."||".$dm_login_temp_shadow_spread_radius."||".$dm_login_temp_shadow_color."|||".$dm_login_temp_forgot_width."||".$dm_login_temp_forgot_height."||".$dm_login_temp_forgot_background_color."||".$dm_login_temp_forgot_border_width."||".$dm_login_temp_forgot_border_style."||".$dm_login_temp_forgot_border_color."||".$dm_login_temp_frogot_radius."|||".$dm_login_temp_reset_width."||".$dm_login_temp_reset_height."||".$dm_login_temp_reset_background_color."||".$dm_login_temp_reset_border_width."||".$dm_login_temp_reset_border_style."||".$dm_login_temp_reset_border_color."||".$dm_login_temp_reset_radius;
	
	$action  = $type;
	$obj = new DAP_MemberPages();
	$obj->setPageId($page_id);
	$obj->setAction( $action);
	$obj->setTemplate( $seleted_template);
	$obj->setTemplateHtml( $html.'%%DAPMEMBERLOGINTEMPLATE%%'.$html_forgot_pass.'%%DAPMEMBERLOGINTEMPLATE%%'.$html_reset_pass);
	$obj->setStylingOptions( $styling_options);
	$obj->setDate( dap_member_current_date_time ); 
		
	
	
	$edit_id = $obj->create();	
	$message = 'Shortcode save successfully';
	$shortcode_content = dapMemberGetShortcodeNameById($edit_id);
	$result['save_shortcode_in_a_page']  = dapMemberAddShortcodeINAPage($shortcode_content,$page_id);
	$gdpr = 'no';
	$post_login_url = '';
	$registration_link = '';
	$member_page_values_array = array('gdpr'=>$gdpr,'post_login_url'=>$post_login_url,'registration_link'=>$registration_link);
	foreach($member_page_values_array as $key=>$val){				
		$result['member_page_values'][] =  dapMemberPagesUpdateValueByActionIdAndName($edit_id,$key,$val);
	}
	$result['edit_id'] = $edit_id;
	
	$short_code_html = '<div class="">';
	$short_code_html .= '<h3 class="shortcode_inner_heading">Here is your Login page URL: <span class="shortcode_page_link"><a href="'.get_permalink($page_id) .'" target="_blank">'.get_permalink($page_id) .'</a></span></h3>';
	$short_code_html .= '<span class="check_heading">Here is your Login page Shortcode: </span>';
	$short_code_html .= '<span id="dynamic_copyable_text_'.$edit_id.'" class="d-inline" name="shortcode_display">'.dapMemberGetShortcodeNameById($edit_id).'</span>';
	$short_code_html .= '<span data-id="dynamic_copyable_text_'.$edit_id.'" class="copy-btn theme-button" onclick="dap_member_copy_to_clipboard(this)"><i class="fa fa-files-o" aria-hidden="true"></i> Copy</span>';
	$short_code_html .= '</div>'; 
	
	dapMemberGetShortcodeNameById($edit_id);
	$result['success'] = $message;
	$result['short_code_html'] = $short_code_html;
	$html = stripslashes($html);
	$short_code_html = stripslashes($short_code_html);
	echo json_encode(array('short_code_html' => $short_code_html));
	
	//update in dap_config
	global $lldocroot;
	include ($lldocroot . "/dap/dap-config.php"); 
	$configLoginUrl = Dap_Config::get("LOGIN_URL") ;	
	if($addin_config_login == "yes"){
		 $value = get_permalink($page_id);		 	
		Dap_Config::updateConfigName("LOGIN_URL", $value, "N") ;	
		  
	}else if($configLoginUrl == ''){
		$value = get_permalink($page_id);		 	
		Dap_Config::updateConfigName("LOGIN_URL", $value, "N") ;	
	}
	
	die;
	
}


add_action( 'wp_ajax_dapSaveMemberContentAjax', 'dapSaveMemberContentAjax' );
function dapSaveMemberContentAjax(){
	$content_data_page = $_REQUEST['content_data_page'];
	$content_data_id = $_REQUEST['content_data_id'];
	$addin_config_content = $_REQUEST['addin_config_content'];	
	$type = 'mycontent';	
	
	$page = $content_data_page;
	$page_id = $content_data_id;
	
	if($page_id == '' && !is_numeric($page_id)){
		
		$status = dapMemberCheckPageTitleExist($content_data_page);		 
		
		if($status == "no"){
			$my_post = array(
					'post_title'    => wp_strip_all_tags( $content_data_page ),
					'post_status'   => 'publish',
					'post_author'   => 1,
					'post_type' =>'page',
					'post_category' => array( 8,39 )
					); 
			$page_id = wp_insert_post( $my_post );
			
		}else{
			echo json_encode(array('error' => 'page already exists'));
			die;
		}
			
	}
	$_SESSION['return_data'] = 'yes';
	$seleted_template = 'inpage||template1||singlecol';
	$file = dap_member_dir.'includes/templates/mycontent/singlecol/inpage/template1.php';
	$html="";
	$html = file_get_contents($file);
	
	$html .= '|:| <div class="dap_member_tiny_editor mce-content-body" id="mce_10" contenteditable="true" spellcheck="false" style="position: relative;">Click to Start</div>';
	$html .= '|:|<div class="dap_member_tiny_editor notallowtoedit_cls mce-content-body" id="mce_14" contenteditable="true" spellcheck="false" style="position: relative;">4 Days</div>';
	$html .= '|:|Lorem Ipsum is simply dummy text|:|Lorem Ipsum has been the|:|available_up_data';
		
	$styling_options = "700||solid||2||#17a2b8||20||15||25||25||#ffffff||#c44343||#ebebeb||#18cba3||#028da2||col-sm-4||850||none|||yes||img_slider||25||285||235|||true||true||true||true||true||true|||150||8||#17a2b8||dashed||0||#17a2b8||5|||0||0||0||0||#f1f1f1";
	
	$action  = $type;
	
 
	$obj = new DAP_MemberPages();
	$obj->setPageId($page_id);
	$obj->setAction($action);
	$obj->setTemplate( $seleted_template);
	$obj->setTemplateHtml( $html);
	$obj->setStylingOptions( $styling_options);
	$obj->setDate( dap_member_current_date_time ); 
	
	$edit_id = $obj->create();	
	
	$shortcode_content = dapMemberGetMyCntentShortcodeNameById($edit_id);
	$result['save_shortcode_in_a_page']  = dapMemberAddShortcodeINAPage($shortcode_content,$page_id);
	/*
	$my_post = array(
		'ID'           => $page_id,
		'post_content' => $content.'[DAPMemberContent id='. $edit_id.'][/DAPMemberContent]',
	);*/
	wp_update_post( $my_post );
	
	$message = 'Shortcode save successfully';
	$shortcode_content = dapMemberGetShortcodeNameById($edit_id);
	//$result['save_shortcode_in_a_page']  = '[DAPMemberContent id='. $edit_id.'][/DAPMemberContent]';
	 
	$member_page_values_array = array('showunavailableproducts'=>"N",'productid'=>"ALL",'hideproductid'=>"NONE" );
	foreach($member_page_values_array as $key=>$val){				
		$result['member_page_values'][] =  dapMemberPagesUpdateValueByActionIdAndName($edit_id,$key,$val);
	}
	$result['edit_id'] = $edit_id;

	$short_code_html = '<div class="">';
	$short_code_html .= '<h3 class="shortcode_inner_heading">Here is your Content page URL: <span class="shortcode_page_link"><a href="'.get_permalink($page_id) .'" target="_blank">'.get_permalink($page_id) .'</a></span></h3>';
	$short_code_html .= '<span class="check_heading">Here is your Content page Shortcode: </span>';
	$short_code_html .= '<span id="dynamic_copyable_text_'.$edit_id.'" class="d-inline" name="shortcode_display">'.dapMemberGetMyCntentShortcodeNameById($edit_id).'</span>';
	$short_code_html .= '<span data-id="dynamic_copyable_text_'.$edit_id.'" class="copy-btn theme-button" onclick="dap_member_copy_to_clipboard(this)"><i class="fa fa-files-o" aria-hidden="true"></i> Copy</span>';
	$short_code_html .= '</div>'; 
	

	dapMemberGetMyCntentShortcodeNameById($edit_id);
	$result['success'] = $message;
	$result['short_code_html'] = $short_code_html;
	$html = stripslashes($html);
	$short_code_html = stripslashes($short_code_html);
	echo json_encode(array('short_code_html' => $short_code_html));
	
	//update in dap_config
	global $lldocroot;
	include ($lldocroot . "/dap/dap-config.php"); 
	if($addin_config_content == "yes"){
		 $value = get_permalink($page_id);			
		 Dap_Config::updateConfigName("MYCONTENT", $value) ;		
	}
	die;
	
}


add_action( 'wp_ajax_dapSaveMemberAffiliateAjax', 'dapSaveMemberAffiliateAjax' );
function dapSaveMemberAffiliateAjax(){
	$affiliate_data_page = $_REQUEST['affiliate_data_page'];
	$affiliate_data_id = $_REQUEST['affiliate_data_id'];
	$addin_config_affiliate = $_REQUEST['addin_config_affiliate'];	
	$type = 'affiliate';	
	
	$page = $affiliate_data_page;
	$page_id = $affiliate_data_id;
	
	if($page_id == '' && !is_numeric($page_id)){
		$status = dapMemberCheckPageTitleExist($affiliate_data_page);		 
		
		if($status == "no"){
			$my_post = array(
					'post_title'    => wp_strip_all_tags( $affiliate_data_page ),
					'post_status'   => 'publish',
					'post_author'   => 1,
					'post_type' =>'page',
					'post_category' => array( 8,39 )
					); 
			$page_id = wp_insert_post( $my_post );
			
		}else{
			echo json_encode(array('error' => 'page already exists'));
			die;
		}
		
		
		
	}
	$_SESSION['return_data'] = 'yes';
	$seleted_template = 'template1';
	$file = dap_member_dir.'includes/templates/affiliate/template1/template.php';
	include_once($file);
	unset($_SESSION['return_data']);
	
	$dispaly_opitons = $aff_link_show.'||'.$aff_performace_summary_show.'||'.$aff_payment_details_show.'||'.$aff_earnings_details_show.'||'.$aff_traffic_statistics_show;
	
	$dispaly_opitons_new = explode('||' ,$dispaly_opitons);
    $dispaly_opitons = '';
    $i = 0;
    foreach($dispaly_opitons_new as $option){
		if($i > 0){
			$dispaly_opitons .= '||';	
		}
		
		if($option == 1){
			$dispaly_opitons .= 'true';	
		}else{
			$dispaly_opitons .= 'false';				
		}
		
		$i++;
	}
	
	
	$external_shadow_customizer  = $affi_spread_radius.'||'.$affi_blur_radius.'||'.$affi_hor_lnth.'||'.$affi_ver_lnth.'||'.$affi_shad_clr;
	
	$template_Style = $affi_tmp_wid.'||'.$affi_tmp_bdr_style.'||'.$affi_tmp_bdr_wid.'||'.$affi_tmp_br_radius.'||'.$affi_tmp_border_color.'||'.$affi_tmp_padd_top.'||'.$affi_tmp_padd_bottom;
	
	$background_color = $affi_tmp_affi_background.'||'.$affi_tmp_performace_background.'||'.$affi_tmp_payment_background.'||'.$affi_tmp_earnnings_background.'||'.$affi_tmp_traffic_background;
	
	
	$styling_options = $dispaly_opitons.'|||'.$external_shadow_customizer.'|||'.$template_Style.'|||'.$background_color;
		
	//$styling_options = "true||true||true||true||||true|||0||12||0||0||#999999|||400||none||0||0||||0||0|||||||||||";
	
	$action  = $type;
	$obj = new DAP_MemberPages();
	$obj->setPageId($page_id);
	$obj->setAction( $action);
	$obj->setTemplate( $seleted_template);
	$obj->setTemplateHtml( $html);
	$obj->setStylingOptions( $styling_options);
	$obj->setDate( dap_member_current_date_time ); 
		
	
	
	$edit_id = $obj->create();	
	$shortcode_content = dapMemberGetAffilateShortcodeNameById($edit_id);
	dapMemberAddShortcodeINAPage($shortcode_content,$page_id);
	
	/*$my_post = array(
		'ID'           => $page_id,
		'post_content' => $content.'[DAPMemberAffiliateDetails id='. $edit_id.'][/DAPMemberAffiliateDetails]',
	);*/
	wp_update_post( $my_post );
	$message = 'Shortcode save successfully';
	$result['edit_id'] = $edit_id;
     
    $short_code_html = '<div class="">';
	$short_code_html .= '<h3 class="shortcode_inner_heading">Here is your affiliate details URL: <span class="shortcode_page_link"><a href="'.get_permalink($page_id) .'" target="_blank">'.get_permalink($page_id) .'</a></span></h3>';
	$short_code_html .= '<span class="check_heading">Here is your affiliate details Shortcode: </span>';
	$short_code_html .= '<span id="dynamic_copyable_text_'.$edit_id.'" class="d-inline" name="shortcode_display">'.dapMemberGetAffilateShortcodeNameById($edit_id).'</span>';
	$short_code_html .= '<span data-id="dynamic_copyable_text_'.$edit_id.'" class="copy-btn theme-button" onclick="dap_member_copy_to_clipboard(this)"><i class="fa fa-files-o" aria-hidden="true"></i> Copy</span>';
	$short_code_html .= '</div>'; 
    
	$result['success'] = $message;
	$result['short_code_html'] = $short_code_html;

	echo json_encode(array('short_code_html' => $short_code_html));
	
	//update in dap_config
	global $lldocroot;
	include ($lldocroot . "/dap/dap-config.php"); 
	if($addin_config_affiliate == "yes"){
		 $value = get_permalink($page_id);			
		 Dap_Config::updateConfigName("AFFILIATE", $value) ;		
	}
	die;
	
}

add_action( 'wp_ajax_dapSaveMemberInvoiceAjax', 'dapSaveMemberInvoiceAjax' );
function dapSaveMemberInvoiceAjax(){
	$invoice_data_page = $_REQUEST['invoice_data_page'];
	$invoice_data_id = $_REQUEST['invoice_data_id'];
	$edit_id = $_REQUEST['edit_id'];
	$addin_config_invoice = $_REQUEST['addin_config_invoice'];	 
	$type = 'invoice';	
	
	$page = $invoice_data_page;
	$page_id = $invoice_data_id;
	if($edit_id == ''){
		if($page_id == '' && !is_numeric($page_id)){
			$status = dapMemberCheckPageTitleExist($invoice_data_page);
			 
			if($status == "no"){
				$my_post = array(
						'post_title'    => wp_strip_all_tags( $invoice_data_page ),
						'post_status'   => 'publish',
						'post_author'   => 1,
						'post_type' =>'page',
						'post_category' => array( 8,39 )
						); 
				$page_id = wp_insert_post( $my_post );
				
			}else{
				echo json_encode(array('error' => 'page already exists'));
				die;
			}			
			
		}
	}
	
	
//	$page_id = 0;
	$seleted_template = $_REQUEST['template'];
	$page_template = $_REQUEST['page_template'];
	$view_invoice_link = $_REQUEST['view_invoice_link'];
	$admin_email = $_REQUEST['admin_email'];
	$company_name = $_REQUEST['company_name'];
	$company_url = $_REQUEST['company_url'];
	$no_transaction_msg = $_REQUEST['no_transaction_msg'];
	$logo = $_REQUEST['logo'];
	
	$html = '';
		
	$styling_options = "";
	
	$action  = 'invoice';
	$obj = new DAP_MemberPages();
	$obj->setPageId($page_id);
	$obj->setAction( $action);
	$obj->setTemplate( $seleted_template);
	$obj->setTemplateHtml( $html);
	$obj->setStylingOptions( $styling_options);
	$obj->setDate( dap_member_current_date_time ); 
	
	
	$id_hash = DAP_MemberPages::loadById($edit_id);
	 
	if($id_hash){
		$obj->setId($edit_id);
		$edit_id = $obj->update();
		$message = 'Update Shortcode';
	}else{
		$edit_id = $obj->create();		  
		$message = 'Shortcode save successfully';
		$shortcode_content = dapMemberGetInvoiceShortcodeNameById($edit_id);
		$result['save_shortcode_in_a_page']  = dapMemberAddShortcodeINAPage($shortcode_content,$page_id);
	}
	
	$member_page_values_array = array('page_template'=>$page_template,'view_invoice_link'=>$view_invoice_link,'admin_email'=>$admin_email, 'company_name' => $company_name , 'company_url' => $company_url, 'no_transaction_msg' => $no_transaction_msg , 'logo' => $logo);
	foreach($member_page_values_array as $key=>$val){				
		$result['member_page_values'][] =  dapMemberPagesUpdateValueByActionIdAndName($edit_id,$key,$val);
	}
	
	$message = 'Shortcode save successfully';
	$result['edit_id'] = $edit_id;
       

	$short_code_html = '<div class="">';
	$short_code_html .= '<h3 class="shortcode_inner_heading">Here is your Invoice page URL: <span class="shortcode_page_link"><a href="'.get_permalink($page_id) .'" target="_blank">'.get_permalink($page_id) .'</a></span></h3>';
	$short_code_html .= '<span class="check_heading">Here is your Invoice page Shortcode: </span>';
	$short_code_html .= '<span id="dynamic_copyable_text_'.$edit_id.'" class="d-inline" name="shortcode_display">'.dapMemberGetInvoiceShortcodeNameById($edit_id).'</span>';
	$short_code_html .= '<span data-id="dynamic_copyable_text_'.$edit_id.'" class="copy-btn theme-button" onclick="dap_member_copy_to_clipboard(this)"><i class="fa fa-files-o" aria-hidden="true"></i> Copy</span>';
	$short_code_html .= '</div>';
	
	$result['success'] = $message; 
	$result['short_code_html'] = $short_code_html;
	$result['short_code_html_with_heading'] = "<h3>Here is your shortocde:</h3>".$short_code_html;
	
	echo json_encode(array('short_code_html' => $short_code_html , 'id' => $edit_id, 'page_id' => $page_id));
	
	//update in dap_config
	global $lldocroot;
	include ($lldocroot . "/dap/dap-config.php"); 
	if($addin_config_invoice == "yes"){
		 $value = get_permalink($page_id);			
		 Dap_Config::updateConfigName("INVOICE", $value) ;		
	}
	die;	
}

add_action( 'wp_ajax_dapSaveMemberCancelAjax', 'dapSaveMemberCancelAjax' );
function dapSaveMemberCancelAjax(){
	$edit_id = $_REQUEST['id'];
	$cancellation_data_page = $_REQUEST['create_cancellation_page'];
	$cancellation_data_id = $_REQUEST['cancellation_data_id'];
	$show_all_transactions = $_REQUEST['show_all_transactions'];
	$product_type = $_REQUEST['product_type'];
	$show_cancel = $_REQUEST['show_cancel'];
	$cancelled_text = $_REQUEST['cancelled_text'];
	$success_cancel_msg = $_REQUEST['success_cancel_msg'];
	$failed_cancel_msg = $_REQUEST['failed_cancel_msg'];
	$cancel_cancel_msg = $_REQUEST['cancel_cancel_msg'];
	$pause_resume_select = $_REQUEST['pause_resume_select'];
	$dateformat = $_REQUEST['dateformat'];
	$bgcolor = $_REQUEST['bgcolor'];
	$payment = $_REQUEST['payment'];
	$showrenewal = $_REQUEST['showrenewal'];
	$templatetextcolor = $_REQUEST['templatetextcolor'];
	$cancelimage = $_REQUEST['cancelimage'];
	$cancelcontact = $_REQUEST['contact_us'];
	$cancelcontacturl = $_REQUEST['contact_us_link'];
	$cancelbuttonstyle = $_REQUEST['cancelbuttonstyle'];
	$cancelbuttontext = $_REQUEST['cancelbuttontext'];
	$upgradelink = $_REQUEST['upgradelink'];
	$upgradetext = $_REQUEST['upgradetext'];
	$upgradetextcolor = $_REQUEST['upgradetextcolor'];
	$canceltext = $_REQUEST['canceltext'];
	$canceltextcolor = $_REQUEST['canceltextcolor'];
	$cancelledtextcolor = $_REQUEST['cancelledtextcolor'];
	$notransfoundmsg = $_REQUEST['notransfoundmsg'];
	$showpause = $_REQUEST['showpause'];
	$pausesuccess = $_REQUEST['pausesuccess'];
	$pausefail = $_REQUEST['pausefail'];
	$pauseconfirm = $_REQUEST['pauseconfirm'];
	$pauseurl = $_REQUEST['pauseurl'];
	$pausebuttonstyle = $_REQUEST['pausebuttonstyle'];
	$pausebuttontext = $_REQUEST['pausebuttontext'];
	$resumesuccess = $_REQUEST['resumesuccess'];
	$resumefail = $_REQUEST['resumefail'];
	$resumeconfirm = $_REQUEST['resumeconfirm'];
	$resumeurl = $_REQUEST['resumeurl'];
	$resumebuttonstyle = $_REQUEST['resumebuttonstyle'];
	$resumebuttontext = $_REQUEST['resumebuttontext'];
	$cancelbuttonstyleNew = $_REQUEST['cancelbuttonstyleNew'];
	$pausebuttonstyleNew = $_REQUEST['pausebuttonstyleNew'];
	$resumebuttonstyleNew = $_REQUEST['resumebuttonstyleNew'];
	$addin_config_cancellation = $_REQUEST['addin_config_cancellation'];
	
	$member_page_values_array = array(
		'show_all_transactions'=>$show_all_transactions,
		'product_type'=>$product_type,
		'notransfoundmsg'=>$notransfoundmsg,
		'contact_us' => $contact_us , 
		'contact_us_link' => $contact_us_link, 
		'show_cancel' => $show_cancel , 
		'cancelled_text' => $cancelled_text, 
		'success_cancel_msg' => $success_cancel_msg, 
		'failed_cancel_msg' => $failed_cancel_msg,
		 'cancel_cancel_msg' => $cancel_cancel_msg, 
		 'pause_resume_select' => $pause_resume_select,
		 'dateformat' => $dateformat,
		 'bgcolor' => $bgcolor,
		 'payment' => $payment,
		 'showrenewal' => $showrenewal,
		 'templatetextcolor' => $templatetextcolor,
		 'cancelbuttonstyle' => $cancelbuttonstyle,
		 'upgradetextcolor' => $upgradetextcolor,
		 'cancelimage' => $cancelimage,
		 'cancelcontact' => $cancelcontact,
		 'cancelcontacturl' => $cancelcontacturl,
		 'canceltext' => $canceltext,
		 'canceltextcolor' => $canceltextcolor,
		 'cancelledtextcolor' => $cancelledtextcolor,
		 'showpause' => $showpause,	
		 'pausesuccess' => $pausesuccess,
		 'pausefail' => $pausefail,
		 'upgradelink' => $upgradelink,
		 'notransfoundmsg' => $notransfoundmsg,
		 'pauseconfirm' => $pauseconfirm,
		 'pauseurl' => $pauseurl,
		 'pausebuttonstyle' => $pausebuttonstyle,
		 'pausebuttontext' => $pausebuttontext,
		 'resumesuccess' => $resumesuccess,
		 'resumefail' => $resumefail,
		 'resumeconfirm' => $resumeconfirm,
		 'resumeurl' => $resumeurl,
		 'resumebuttonstyle' => $resumebuttonstyle,
		 'resumebuttontext' => $resumebuttontext,
		 'cancelbuttonstyleNew' => $cancelbuttonstyleNew,
		 'pausebuttonstyleNew' => $pausebuttonstyleNew,
		 'resumebuttonstyleNew' => $resumebuttonstyleNew
		 );
	
	 
	$action = 'cancellation';	
	
	$page = $cancellation_data_page;
	$page_id = $cancellation_data_id;
	if($edit_id == ''){
		if($page_id == '' && !is_numeric($page_id)){
			$status = dapMemberCheckPageTitleExist($cancellation_data_page);
			 
			if($status == "no"){
				$my_post = array(
						'post_title'    => wp_strip_all_tags( $cancellation_data_page ),
						'post_status'   => 'publish',
						'post_author'   => 1,
						'post_type' =>'page',
						'post_category' => array( 8,39 )
						); 
				$page_id = wp_insert_post( $my_post );
				
			}else{
				echo json_encode(array('error' => 'page already exists'));
				die;
			}
			
			
			
		}
	}
	$seleted_template = $_REQUEST['template'];
	
	$file = dap_member_dir.'cancel/'.$seleted_template.'/autocanceltemplate.html';
	$html = file_get_contents($file);
	$html = '';
		
	$styling_options = "";
	
	 
	$action  = 'cancellation';
	$obj = new DAP_MemberPages();
	$obj->setPageId($page_id);
	$obj->setAction( $action);
	$obj->setTemplate( $seleted_template);
	$obj->setTemplateHtml( $html);
	$obj->setStylingOptions( $styling_options);
	$obj->setDate( dap_member_current_date_time ); 
	if($edit_id == ''){
		$edit_id = $obj->create();	
		$post = get_post($page_id);
		$content = $post->post_content;
		$my_post = array(
				'ID'           => $page_id,
				'post_content' => $content.'[DAPMemberCancellation id='. $edit_id.'][/DAPMemberCancellation]',
		);
		wp_update_post( $my_post );
	}else{
		$obj->setId($edit_id);
		$edit_id = $obj->update();		
	}
	
	
	
	
	
	foreach($member_page_values_array as $key=>$val){				
		if($val != ''){
			$result['member_page_values'][] =  dapMemberPagesUpdateValueByActionIdAndName($edit_id,$key,$val);
		}
	}
	
	$message = 'Shortcode save successfully';
	$result['edit_id'] = $edit_id;
       
		
	$short_code_html = '<div class="">';
	$short_code_html .= '<h3 class="shortcode_inner_heading">Here is your Cancellation page URL: <span class="shortcode_page_link"><a href="'.get_permalink($page_id) .'" target="_blank">'.get_permalink($page_id) .'</a></span></h3>';
	$short_code_html .= '<span class="check_heading">Here is your Cancellation page Shortcode: </span>';
	$short_code_html .= '<span id="dynamic_copyable_text_'.$edit_id.'" class="d-inline" name="shortcode_display">'.dapMemberGetCancellationShortcodeNameById($edit_id).'</span>';
	$short_code_html .= '<span data-id="dynamic_copyable_text_'.$edit_id.'" class="copy-btn theme-button" onclick="dap_member_copy_to_clipboard(this)"><i class="fa fa-files-o" aria-hidden="true"></i> Copy</span>';
	$short_code_html .= '</div>';
	
	$result['success'] = $message; 
	$result['short_code_html'] = $short_code_html;

	echo json_encode(array('short_code_html' => $short_code_html , 'id' => $edit_id, 'page_id' => $page_id));
	
	//update in dap_config
	global $lldocroot;
	include ($lldocroot . "/dap/dap-config.php");
	
	logToFile("addin_config_cancellation: ". $addin_config_cancellation,LOG_DEBUG_DAP); 
	if($addin_config_cancellation == "yes"){
		 $value = get_permalink($page_id);	
		 logToFile("addin_config_cancellation: value= ". $value,LOG_DEBUG_DAP); 		
		 Dap_Config::updateConfigName("CANCELLATION", $value) ;		
	}
	die;	
}

add_action( 'wp_ajax_dapSaveMemberProfileAjax', 'dapSaveMemberProfileAjax' );
function dapSaveMemberProfileAjax(){
	
	$profile_data_page = $_REQUEST['create_profile_page'];
	$page_id = $profile_data_id = $_REQUEST['profile_page_url'];
	$addin_config_profile = $_REQUEST['addin_config_profile'];
	 
	if($page_id == '' && !is_numeric($page_id)){
		$status = dapMemberCheckPageTitleExist($profile_data_page);
		 
		if($status == "no"){
			$my_post = array(
					'post_title'    => wp_strip_all_tags( $profile_data_page),
					'post_status'   => 'publish',
					'post_author'   => 1,
					'post_type' =>'page',
					'post_category' => array( 8,39 )
					); 
			$page_id = wp_insert_post( $my_post );
			
		}else{
			echo json_encode(array('error' => 'page already exists'));
			die;
		}	
		
	}
	
	$styling_options = '';
	
	$seleted_template = 'template1';
	$file = dap_member_dir.'includes/templates/profile/template1/template.php';
	$_SESSION['return_data'] = 'yes';
	include_once($file);
	unset($_SESSION['return_data']);
	$template_html = $html;
	
	$edit_id = '';
	
    $dispaly_opitons1 =  $show_profile_account_info_section.'||'.$show_first_name_section.'||'.$show_last_name_section.'||'.$show_email_section;
    
    $dispaly_opitons_new = explode('||' ,$dispaly_opitons1);
    $dispaly_opitons1 = '';
    $i = 0;
    foreach($dispaly_opitons_new as $option){
		if($i > 0){
			$dispaly_opitons1 .= '||';	
		}
		
		if($option == 1){
			$dispaly_opitons1 .= 'true';	
		}else{
			$dispaly_opitons1 .= 'false';				
		}
		$i++;
		
	}
    
    
    $dispaly_opitons2 = $show_profile_change_password_section;
    
    $dispaly_opitons_new = explode('||' ,$dispaly_opitons2);
    $dispaly_opitons2 = '';
     $i = 0;
    foreach($dispaly_opitons_new as $option){
		if($i > 0){
			$dispaly_opitons2 .= '||';	
		}
		
		
		if($option == 1){
			$dispaly_opitons2 .= 'true';	
		}else{
			$dispaly_opitons2 .= 'false';				
		}
		
		$i++;
	}
    
    
    $dispaly_opitons3 = $show_profile_billing_info_section.'||'.$show_profile_billing_address1_section.'||'.$show_profile_billing_address2_section.'||'.$show_profile_billing_city_section.'||'.$show_profile_billing_state_section.'||'.$show_profile_billing_postal_code_section.'||'.$show_profile_billing_country_section;
    
    $dispaly_opitons_new = explode('||' ,$dispaly_opitons3);
    $dispaly_opitons3 = '';
    $i = 0;
    foreach($dispaly_opitons_new as $option){
		if($i > 0){
			$dispaly_opitons3 .= '||';	
		}
		
		if($option == 1){
			$dispaly_opitons3 .= 'true';	
		}else{
			$dispaly_opitons3 .= 'false';				
		}
		
		$i++;
	}
    
    $dispaly_opitons4 = $show_profile_additional_info_section.'||'.$show_profile_additional_phone_section.'||'.$show_profile_additional_fax_section.'||'.$show_profile_additional_company_section.'||'.$show_additional_title_section.'||'.$show_profile_additional_paypal_email_section.'||'.$show_profile_additional_opted_out_section;
   
    $dispaly_opitons_new = explode('||' ,$dispaly_opitons4);
    $dispaly_opitons4 = '';
    $i = 0;
    foreach($dispaly_opitons_new as $option){
		if($i > 0){
			$dispaly_opitons4 .= '||';	
		}
		
		if($option == 1){
			$dispaly_opitons4 .= 'true';	
		}else{
			$dispaly_opitons4 .= 'false';				
		}
		
		$i++;
	}
    
    
    $dispaly_opitons5 = $show_profile_gdpr_section;
    if($dispaly_opitons5 == 1){
		$dispaly_opitons5 .= 'true';	
	}else{
		$dispaly_opitons5 .= 'false';				
	}
    
    
    $dispaly_opitons7 = $update_btn_background_outer_color.'||'.$update_btn_frnt_bdr_style.'||'.$update_btn_frnt_bdr_wid.'||'.$update_btn_frnt_br_radius.'||'.$update_btn_frnt_bdr_color.'||'.$update_btn_frnt_wid;
   /*
	$dispaly_opitons_new = explode('||' ,$dispaly_opitons7);
    $dispaly_opitons7 = '';
    $i = 0;
    foreach($dispaly_opitons_new as $option){
		if($i > 0){
			$dispaly_opitons7 .= '||';	
		}
		
		if($option == 1){
			$dispaly_opitons7 .= 'true';	
		}else{
			$dispaly_opitons7 .= 'false';				
		}
		
		$i++;
	}
   */
    $dispaly_opitons8 = $show_custom_fields_section;
    
    $dispaly_opitons_new = explode('||' ,$dispaly_opitons8);
    $dispaly_opitons8 = '';
    $i = 0;
    foreach($dispaly_opitons_new as $option){
		if($i > 0){
			$dispaly_opitons8 .= '||';	
		}
		
		if($option == 1){
			$dispaly_opitons8 .= 'true';	
		}else{
			$dispaly_opitons8 .= 'false';				
		}
		
		$i++;
	}
    $dispaly_opitons8 = $dispaly_opitons8.'||'.$custom_fields_style;
    
    $dispaly_opitons = $dispaly_opitons1.'|||'.$dispaly_opitons2.'|||'.$dispaly_opitons3.'|||'.$dispaly_opitons4.'|||'.$dispaly_opitons5;  
    $external_shadow_customizer  = $sprd_radius.'||'.$blur_radius.'||'.$hor_lnth.'||'.$ver_lnth.'||'.$shad_clr;
    
    $template_Style = $temp_frnt_wid.'||'.$temp_background_outer_color.'||'.$temp_frnt_bdr_style.'||'.$temp_frnt_bdr_wid.'||'.$temp_frnt_br_radius.'||'.$temp_frnt_bdr_color.'||'.$temp_frnt_padd_top.'||'.$temp_frnt_padd_bottom;		
    
    $background_color = $account_background_color.'||'.$change_pass_background_color.'||'.$billing_background_color.'||'.$additional_background_color.'||'.$gdpr_background_color;	
    $styling_options = $dispaly_opitons.'|||'.$external_shadow_customizer.'|||'.$template_Style.'|||'.$background_color."|||".$dispaly_opitons7.'|||'.$dispaly_opitons8;
    		
	$action  = 'profile'; 
    $obj = new DAP_MemberPages();
	$obj->setPageId($page_id);
	$obj->setAction( $action);
	$obj->setTemplate($seleted_template);
	$obj->setTemplateHtml( $html);
	$obj->setStylingOptions( $styling_options);
	$obj->setDate( dap_member_current_date_time );
		
    //$id_hash = DAP_MemberPages::loadById($edit_id);
    $id_hash = false;
         
    if($id_hash){
		$obj->setId($edit_id);
		$edit_id = $obj->update();
		$message = 'Update Shortcode';
	}else{
		$edit_id = $obj->create();		  
		$message = 'Shortcode save successfully';
		$shortcode_content = dapMemberGetProfileShortcodeNameById($edit_id);
		$result['save_shortcode_in_a_page']  = dapMemberAddShortcodeINAPage($shortcode_content,$page_id);
		$member_page_values_array = array('redirect_url'=>'','gdpr_msg_section'=>'Are you sure you do not want to give GDPR consent?');
		foreach($member_page_values_array as $key=>$val){				
			dapMemberPagesUpdateValueByActionIdAndName($edit_id,$key,$val);
		}
	}
	
	$short_code_html = '<div class="">';
	$short_code_html .= '<h3 class="shortcode_inner_heading">Here is your Profile details URL: <span class="shortcode_page_link"><a href="'.get_permalink($page_id) .'" target="_blank">'.get_permalink($page_id) .'</a></span></h3>';
	$short_code_html .= '<span class="check_heading">Here is your Profile details Shortcode: </span>';
	$short_code_html .= '<span id="dynamic_copyable_text_'.$edit_id.'" class="d-inline" name="shortcode_display">'.dapMemberGetProfileShortcodeNameById($edit_id).'</span>';
	$short_code_html .= '<span data-id="dynamic_copyable_text_'.$edit_id.'" class="copy-btn theme-button" onclick="dap_member_copy_to_clipboard(this)"><i class="fa fa-files-o" aria-hidden="true"></i> Copy</span>';
	$short_code_html .= '</div>'; 
   
    $result['edit_id'] = $edit_id;
	$result['success'] = $message;
	$result['short_code_html'] = $short_code_html;
	$result['page_url_html'] = '<a href="'.get_permalink($page_id).'" target="_blank">'.get_permalink($page_id).'</a>';
	
	echo json_encode($result);
	
	//update in dap_config
	global $lldocroot;
	include ($lldocroot . "/dap/dap-config.php"); 
	if($addin_config_profile == "yes"){
		 $value = get_permalink($page_id);			
		 Dap_Config::updateConfigName("PROFILE", $value) ;		
	}
	die;
}

function dapDeleteMemberPageAjax(){
	DAP_MemberPages::deleteById($_REQUEST['id']);	
	DAP_MemberPagesValues::deleteByActionId($_REQUEST['id']);	
	
}

/* check admin or not */
if(!is_admin() && $GLOBALS['pagenow'] !== 'wp-login.php'){
	
	include_once(dap_member_dir.'DAP-Member-Frontend.php');
}
 

function dapMemberGetMessageByKeyAndAction($action = '',$name =''){
	$obj = DAP_MemberPageSettings::loadByActionAndName($action,$name);
	
	if($obj){
		return $obj->getValue();
	}
	return '';
}


function dapMemberCheckPageTitleExist($page_name = ''){
	
	$page = get_page_by_title( $page_name );
	if(is_object($page)){
		$status ='yes';
	}else{
		$status ='no';
	}
	return $status;
}

add_action( 'wp_ajax_dapSaveSubaccountDataAjax', 'dapSaveSubaccountDataAjax' );
function dapSaveSubaccountDataAjax(){
	$edit_id = $_REQUEST['edit_id'];
	$overallData = $_REQUEST['overallData'];
	$actionType = $_REQUEST['actionType'];
	$template = $_REQUEST['template'];
	$styling_options = $_REQUEST['styling_options'];
//	$pageType = $_REQUEST['pageType'];
//	$pageName = $_REQUEST['pageName'];
	$success_added_msg = $_REQUEST['success_added_msg'];
	$limit_reached_msg = $_REQUEST['limit_reached_msg'];
	$delete_confirm_msg = $_REQUEST['delete_confirm_msg'];
	$deleted_msg = $_REQUEST['deleted_msg'];
	$not_logged_in = $_REQUEST['not_logged_in'];
	$no_access = $_REQUEST['no_access'];
	$bulkNoAddUserMsg = $_REQUEST['bulkNoAddUserMsg'];
	$no_field_select_msg = $_REQUEST['no_field_select_msg'];
	$limit_reached_bulk = $_REQUEST['limit_reached_bulk'];
	
	$member_page_values_array = array(
		'success_added_msg'=>$success_added_msg,
		'limit_reached_msg'=>$limit_reached_msg,
		'delete_confirm_msg'=>$delete_confirm_msg,
		'deleted_msg' => $deleted_msg ,
		'not_logged_in' => $not_logged_in ,
		'no_access' => $no_access ,
		'bulkNoAddUserMsg' => $bulkNoAddUserMsg ,
		'no_field_select_msg' => $no_field_select_msg, 
		'limit_reached_bulk' => $limit_reached_bulk 
	);
	
	//$page_id = $pageName;
	
	/*if($edit_id == ''){
		if($pageType == 'new'){
			$status = dapMemberCheckPageTitleExist($pageName);
			
			if($status == "no"){
				$my_post = array(
						'post_title'    => wp_strip_all_tags( $pageName ),
						'post_status'   => 'publish',
						'post_author'   => 1,
						'post_type' =>'page',
						'post_category' => array( 8,39 )
						); 
				$page_id = wp_insert_post( $my_post );
				
			}else{
				echo json_encode(array('error' => 'page already exists'));
				die;
			}
			
			
			
		}
	}*/
	/*$seleted_template = $_REQUEST['template'];
	
	$file = dap_member_dir.'cancel/'.$seleted_template.'/autocanceltemplate.html';
	$html = file_get_contents($file);
	$html = '';*/
		
	
	 
	$obj = new DAP_MemberPages();
	$obj->setPageId(0);
	$obj->setAction($actionType);
	$obj->setTemplate($template);
	$obj->setTemplateHtml($overallData);
	$obj->setStylingOptions($styling_options);
	$obj->setDate( dap_member_current_date_time ); 
	
	if($edit_id == ''){
		$edit_id = $obj->create();	
	}else{
		$obj->setId($edit_id);
		$edit_id = $obj->update();		
	}
	
	
	
	
	
	foreach($member_page_values_array as $key=>$val){				
		if($val != ''){
			$result['member_page_values'][] =  dapMemberPagesUpdateValueByActionIdAndName($edit_id,$key,$val);
		}
	}
	
	$message = 'Shortcode save successfully';
	$result['edit_id'] = $edit_id;
	
	$shortcode = dapMemberGetSubaccountShortcodeNameById($edit_id);
       
		
	/*$short_code_html = '<div class="">';
	$short_code_html .= '<h3 class="shortcode_inner_heading">Here is your Cancellation page URL: <span class="shortcode_page_link"><a href="'.get_permalink($page_id) .'" target="_blank">'.get_permalink($page_id) .'</a></span></h3>';
	$short_code_html .= '<span class="check_heading">Here is your Cancellation page Shortcode: </span>';
	$short_code_html .= '<span id="dynamic_copyable_text_'.$edit_id.'" class="d-inline" name="shortcode_display">'.dapMemberGetCancellationShortcodeNameById($edit_id).'</span>';
	$short_code_html .= '<span data-id="dynamic_copyable_text_'.$edit_id.'" class="copy-btn theme-button" onclick="dap_member_copy_to_clipboard(this)"><i class="fa fa-files-o" aria-hidden="true"></i> Copy</span>';
	$short_code_html .= '</div>';*/
	
	$result['success'] = $message; 
	$result['short_code_html'] = $shortcode;

	echo json_encode(array('short_code_html' => $shortcode , 'id' => $edit_id, 'page_id' => $page_id));
	die;	
}


/*****Save the post meta data*****/

add_action( 'wp_ajax_savePostMetaDataAjax', 'savePostMetaDataAjax' );
function savePostMetaDataAjax(){	
	
		$_REQUEST = stripslashes_deep($_REQUEST);
		
		if(isset($_REQUEST['pay_post_data'])){
		   
		    $data  = $_REQUEST['pay_post_data'];
		    
		    /*
		    echo "<pre>";
			print_r($data);
			echo "</pre>";
			die;
			*/	
			$post_id = $data['post_id'];
			$product_id = $data['product_id'];
			$enable_pay_per_post = $data['enable_pay_per_post'];
			$post_image = $data['post_image'];
			
			
			// general 
			$not_logged_in = $data['not_logged_in'];
			$not_have_access = $data['not_have_access'];
			$currency_symbol = $data['currency_symbol']; 
			$currency_code = $data['currency_code'];
			$payment_mode = $data['payment_mode'];
			
			//pricing 
			$payment_options_arr = $data['payment_options_arr'];
			$pricing_arr = $data['pricing_arr'];
			$btn_config_arr = $data['btn_config_arr'];
			$btn_links_arr = $data['btn_links_arr'];
			
			// messages
			$show_teaser_content = $data['show_teaser_content'];
			$teaser_content = urldecode($data['teaser_content']);	
			$not_logged_in_msg = urldecode($data['not_logged_in_msg']);
			$no_access_msg = urldecode($data['no_access_msg']);	
			
			// button config
			$spc = $data['spc'];
			$other_buy_button_link_select = $data['other_buy_button_link_select'];
			
			
			// button layout
			$button_layout_option   = $data['button_layout_option'];
		
			// landing page
			$after_payment_action = $data['after_payment_action'];
			$landing_url = $data['landing_url'];
			
			$post_url = get_permalink($post_id);
			if($data['after_payment_action'] == 'same_page'){
				$landing_url = $post_url;
			}
			
			$spc_checkout_id = 0;
			if(isset($data['spc_checkout_id'])){
				$spc_checkout_id = $data['spc_checkout_id'];
			}
			
			
			$enable_above_btn_msg = $data['enable_above_btn_msg'];
			
			$post_title  = get_the_title($post_id);
			
			$payperpost = new DAP_PayPerPost();		  
			$payperpost->setPostId( stripslashes($post_id) );
			$payperpost->setEnablePayPerPost( stripslashes($enable_pay_per_post) );
			$payperpost->setPostImage( stripslashes($post_image) );
			$payperpost->setProductId( stripslashes($product_id) );
			$payperpost->setShowTeaserContent( $show_teaser_content);
			$payperpost->setTeaserContent( $teaser_content );
			
			$payperpost->setNotLoggedIn( $not_logged_in_msg );
			
			$payperpost->setNotHaveAccess( $no_access_msg );
			$payperpost->setCurrencySymbol( $currency_symbol );
			$payperpost->setCurrencyCode( $currency_code );
			$payperpost->setPaymentMode( $payment_mode );
			$payperpost->setShowMsgAboveBtn( $enable_above_btn_msg );
			
			
			$payperpost->setPostTitle( $post_title );
		
			$payperpost->setAfterPaymentAction( $after_payment_action );
			$payperpost->setLandingURL( $landing_url );	
			$payperpost->setButtonLayoutoption( $button_layout_option );	
			$payperpost->setSpcCheckoutId( $spc_checkout_id );	
			$payperpost->setPostUrl( $post_url );	
			
			$id_exist = DAP_PayPerPost::loadPayPerPostByPostId($post_id);
			if(isset($id_exist)){  
				
				$payperpost->setId($id_exist->getId());
				$edit_id = $payperpost->update();	
				$edit_id = $id_exist->getId();	
				$action = 'update';	 
				$msg1 = "Update successfully";
			}else{
				//echo "hello+2";die;
				$edit_id = $payperpost->create();			
				$action = 'create';
				$msg1 = "Save successfully";
			}
			
			$outputMeta = array();
			//payment field
			if(isset($data['payment_options_arr']) && is_array($data['payment_options_arr'])){
				$payments_data = array();
				
				foreach($data['payment_options_arr'] as $payment_type){
					
					$price = 0;
					$access_day = 0;
					if(isset($data['pricing_arr']) && is_array($data['pricing_arr'])){
						$price = $data['pricing_arr'][$payment_type]['price']; 
						$access_day = $data['pricing_arr'][$payment_type]['access_day']; 
						$btn_links = $data['btn_links_arr'][$payment_type]; 
						$buynow_above_text = urldecode($data['btn_config_arr'][$payment_type]['buynow_above_text']);	
						//$other_buy_button_link_select
						$buynow_text = $data['btn_config_arr'][$payment_type]['buynow_text'];
					}
					
					$payments_data[] = array('post_id'=>$post_id,'button_type'=>$payment_type,'price'=>$price,'access_days'=>$access_day,'buylink'=>$btn_links,'btn_text'=>$buynow_text,'btn_above_text'=>$buynow_above_text, 'shoppingcart' => ($spc));
				}
				
				if(count($payments_data)){
					$get_all_data_obj = Dap_PayPerPostMeta::loadPayPerPostMetaByPostId($post_id); 
					
					$get_all_data_type = array();
					if(count($get_all_data_obj)){
						foreach($get_all_data_obj as $row){
							$get_all_data_type[$row->getButtonType()] = $row->getButtonType();
						}
					}
					
					foreach($payments_data as $key=>$row){
						if(in_array($row["button_type"],$get_all_data_type)){
							unset($get_all_data_type[$row["button_type"]]);
						}
						$PayPerPostMetaObj = new Dap_PayPerPostMeta();
						$row["date"] = date("Y-m-d");  
						$PayPerPostMetaObj->setPostId( stripslashes($row["post_id"]) );
						$PayPerPostMetaObj->setButtonType( stripslashes($row["button_type"]) );
						$PayPerPostMetaObj->setPrice( stripslashes($row["price"]) );
						$PayPerPostMetaObj->setAccessDays( stripslashes($row["access_days"]) );
						$PayPerPostMetaObj->setBtnAboveText( $row["btn_above_text"] );
						$PayPerPostMetaObj->setBtnText( $row["btn_text"] );
						$PayPerPostMetaObj->setShoppingCart( $row["shoppingcart"] );
						$PayPerPostMetaObj->setBuyLink( $row["buylink"] );
						$PayPerPostMetaObj->setDate( $row["date"] );
						
						$button_type = $row["button_type"];
						$post_id = $row["post_id"];
						
						$postMeta_id_exist = Dap_PayPerPostMeta::loadPayPerPostMetaByPostIdAndButtonType($post_id, $button_type);
						
						if(isset($postMeta_id_exist)){
							
							$PayPerPostMetaObj->setId($postMeta_id_exist->getId());
							$edit_id = $PayPerPostMetaObj->update();	
							$edit_id = $id_exist->getId();	
							$action = 'update';	 
							$msg = "Update successfully";
						}else{
							
							$edit_id = $PayPerPostMetaObj->create();			
							$action = 'create';
							$msg = "Save successfully";
						}
						
						
						
						$outputMeta[] = array('edit_id'=>$edit_id,'action' => $action,'msg'=>$msg,'success'=>true);	
					}
					foreach($get_all_data_type as $button_type){
							Dap_PayPerPostMeta::DeletePayPerPostMetaByPostIdAndButtonType($post_id, $button_type);
							$delete_type[] = $button_type;
					}
					$outputMeta[] = array('delete_type'=>$delete_type);	
					
					
				}
				
			}
			
			
		$output = array('edit_id'=>$edit_id,'action' => $action,'msg'=>$msg1,'success'=>true,'$outputMeta' =>$outputMeta);	
	
	}else{
		$output = array('error'=>'something Wrong!');	
	}
	echo json_encode($output);die;
}

// save the pay-per-post button settings
add_action( 'wp_ajax_savePayPerPostButtonCustomizerAjax', 'savePayPerPostButtonCustomizerAjax' );
function savePayPerPostButtonCustomizerAjax(){
	 
		$buy_btn_option = '';
		if(isset($_POST['buy_btn_option'])){
			$buy_btn_option = stripslashes($_POST['buy_btn_option']);
		}
		
		$rent_btn_option = '';
		if(isset($_POST['rent_btn_option'])){
			$rent_btn_option = stripslashes($_POST['rent_btn_option']);
		}
		
		$membership_btn_option = '';
		if(isset($_POST['membership_btn_option'])){
			$membership_btn_option = ($_POST['membership_btn_option']);
		}
		
		$buy_btn_html = '';
		if(isset($_POST['buy_btn_html'])){
			$buy_btn_html = stripslashes($_POST['buy_btn_html']);
		}
		$rent_btn_html = '';
		if(isset($_POST['rent_btn_html'])){
			$rent_btn_html = stripslashes($_POST['rent_btn_html']);
		}
		$membership_btn_html = '';
		if(isset($_POST['membership_btn_html'])){
			$membership_btn_html = stripslashes($_POST['membership_btn_html']);
		}		 
	  
        $obj = new DAP_PayPerPostCustomizer();
		
			
		$button_type ="buynow";
		$button_type1="rent";
		$button_type2 ="membership";
		
		 if($button_type =="buynow"){
			$obj->setButtonType($button_type);
			$obj->setButtonHtml( $buy_btn_html);
			$obj->setButtonCustomizer($buy_btn_option);	
			 
			$id_hash = DAP_PayPerPostCustomizer::loadByType($button_type);
			
			if(isset($id_hash)){
				 
				$edit_id =$id_hash->getId();
				$obj->setId($edit_id);
				$edit_id = $obj->update();
				$message = 'Update Sucessfully';
			}else{
			 
				$edit_id = $obj->create();		  
				$message = 'Save successfully';
			}
		 }
		 
		 if($button_type1 =="rent"){
			$obj->setButtonType($button_type1);
			$obj->setButtonHtml( $rent_btn_html);
			$obj->setButtonCustomizer($rent_btn_option);	
			 $id_hash = DAP_PayPerPostCustomizer::loadByType($button_type1);
			 if(isset($id_hash)){
				$edit_id =$id_hash->getId();
				$obj->setId($edit_id);
				$edit_id = $obj->update();
				$message = 'Update Sucessfully';
			}else{
				$edit_id = $obj->create();		  
				$message = 'Save successfully';
			}
		 }
		 
		 if($button_type2 =="membership"){
			$obj->setButtonType($button_type2);
			$obj->setButtonHtml( $membership_btn_html);
			$obj->setButtonCustomizer($membership_btn_option);	
			$id_hash = DAP_PayPerPostCustomizer::loadByType($button_type2);
			if(isset($id_hash)){
				$edit_id =$id_hash->getId();
				$obj->setId($edit_id);
				$edit_id = $obj->update();
				$message = 'Update Sucessfully';
			}else{
				$edit_id = $obj->create();		  
				$message = 'Save successfully';
			}
		 }
	 
       
		echo $message;
		die;
}


add_action( 'wp_ajax_dap_member_login_save_to_config', 'dap_member_login_save_to_config' );

function dap_member_login_save_to_config(){
	$pageId = $_REQUEST['page_id'];
	global $lldocroot;
	include ($lldocroot . "/dap/dap-config.php"); 
	
	$pageUrl = get_permalink($pageId);
	
	Dap_Config::updateConfigName("LOGIN_URL", $pageUrl, "N") ;	
	
}

