<?php


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

	$site_url = get_site_url();
	$base_path = dirname(__FILE__);
	$loging_status = false;
	
	if(Dap_Session::isLoggedIn()){ 
		$loging_status = true;
		
	}
	$dap_profile_id = $id;
	$mp_obj = DAP_MemberPages::loadById($id);
	if($mp_obj && $mp_obj->getAction() == 'profile'){
		
		$template =  stripslashes($mp_obj->getTemplateHtml());
		
		$html   =  "<div id='dap_member_profile_frontend_shortcode' class='live-links-bootstrap_outer dap_member_frontend_shortcode dap_member_profile_frontend_shortcode_".$mp_obj->getId()."'>";
		$html   .= DAPMemberCommonCssAndJsWith();		
		$html   .= "<link rel='stylesheet' id='dap_memberprofile-template-css'  href='".dap_member_path."includes/templates/profile/".$mp_obj->getTemplate()."/style.css?".rand(10,1000)."' type='text/css' media='all' />
					<link rel='stylesheet'   href='//cdn.jsdelivr.net/npm/sweetalert2@8/dist/sweetalert2.min.css' type='text/css' media='all' />
					<script type='text/javascript' src='".dap_member_path."includes/js/dap_member_profile_frontend.js?".rand(10,10000)."'></script>		
					<script src='//cdn.jsdelivr.net/npm/sweetalert2@8/dist/sweetalert2.min.js'></script>";		
				
		if($loging_status){
				if($_GET['msg']){
					$html   .= '<div class="text-success text-center dap_porfile_success_div">';
					$html   .= '<h4 class=" mb-3">'.dapMemberGetMessageByKeyAndAction('myprofile','success').'</h4>';
					$html   .= '</div>';
				}else if($_GET['err']){
					$html   .= '<div class="text-error text-center dap_porfile_success_div">';
					$html   .= '<h4 class=" mb-3">'.$_GET['err'].'</h4>';
					$html   .= '</div>';	
					echo '<style>.text-error{color:red;} .live-links-bootstrap_outer .mb-3{font-size:17px; letter-spacing:-0.9px}</style>';
				}
		$admin_email = $mp_obj->getAdminEmail();
		$styling_options = $mp_obj->getStylingOptions();
		$styling_options = explode("|||",$styling_options);
		$custom_fields_selected = array();
		$show_custom_fields_section = false;
		if(count($styling_options) == 10){
			$styling_options[11] = $styling_options[9]	;
		}else if(count($styling_options) == 11){
			$styling_options[11] = $styling_options[10]	;	
		}
		
		if(isset($styling_options[11])){ 
			$cutom_fields_arry = explode("||",$styling_options[11]);
			$show_custom_fields_section = $cutom_fields_arry[0];
			if(isset($cutom_fields_arry[1])){
				$custom_fields_selected = explode(',',$cutom_fields_arry[1]);
				
				if(in_array('all',$custom_fields_selected)){
					$custom_fields_selected = 'all';
				}
			}
		}
	
		if(count($styling_options) == 12){
			if(isset($styling_options[10])){
				$file_options = explode("||",$styling_options[10]);		
				if(isset($file_options[1])){
					$allow_file_upload_data = explode("|",$file_options[0]);
					$allow_file_upload = $allow_file_upload_data[0];
					$show_existing_files = $allow_file_upload_data[1];
					$allowed_types_of_file = $file_options[1];
					$max_upload_size = $file_options[2];
					$max_number_of_file = $file_options[3];
				
				}
			}	
		}
		
		if($allow_file_upload == 'Y'){
			$allowed_file_upload_types =   dapMemberGetMessageByKeyAndAction('myprofile','allowed_file_upload_types');
			$file_upload_max_size =   dapMemberGetMessageByKeyAndAction('myprofile','file_upload_max_size');
			$allowed_types_of_filearr = explode('|' , $allowed_types_of_file);
			$allowedTypesOfFileHidden = array_filter($allowed_types_of_filearr);
			$strallowedTypesOfFileHidden = implode(',' , $allowedTypesOfFileHidden);
			$allowed_file_upload_types = str_replace( '%%ALLOWED_FILES%%',$strallowedTypesOfFileHidden, $allowed_file_upload_types); 
			$file_upload_max_size = str_replace( '%%MAX_UPLOAD_SIZE%%',$max_upload_size.'MB', $file_upload_max_size); 
		}
		
		$show_profile_gdpr_section = 0;
		if(isset($styling_options[4])){
			$display_temp_gdpr = explode("||",$styling_options[4]);
			$show_profile_gdpr_section = $display_temp_gdpr[0];	
			if( $show_profile_gdpr_section == 'true'){
				$show_profile_gdpr_section = 1;
			}else{
				$show_profile_gdpr_section = 0;
			}			
		}
		
		global $wp;   
		$redirect_url = home_url( add_query_arg( array(), $wp->request ) );
		$gdpr_msg_section = '';
		$action_id = $mp_obj->getId();
		$mpv_obj = DAP_MemberPagesValues::loadByActionId($action_id);
		if($mpv_obj){
			$redirect_obj = DAP_MemberPagesValues::loadByActionIdAndName($action_id,'redirect_url');
			if($redirect_obj){
					$redirect_url1 = $redirect_obj->getValue();
					if($redirect_url1 != ''){
						$redirect_url = $redirect_url1; 
					}
			}
			$gdp_msg_obj = DAP_MemberPagesValues::loadByActionIdAndName($action_id,'gdpr_msg_section');
			if($gdp_msg_obj){
					$gdpr_msg_section = $gdp_msg_obj->getValue();
			}
		}
		
		
		
		$session = Dap_Session::getSession();
		$user = $session->getUser();
		$user = Dap_User::loadUserById($user->getId());
		$userId = $user->getId();   
		
		$existingFilesHtml = '';
		if($show_existing_files == 'Y'){
			
			//$existingFilesHtml .= '';		
			$userFiles = Dap_UserFiles::loadByUserId($userId);
			if(isset($userFiles) && $userFiles != false){
				foreach($userFiles as $file){
					$existingFilesHtml .= '<label><a target="_blank" href="'.$file->getUrl().'">'.$file->getFileName().'</a></label></br>';			
				}	
			}else{
				echo '<style>#dap_member_profile_outer .dap_member_profile_inner .enter_name_outer.show_already_uploaded_files_section {display:none}</style>';
			}
			$template =  str_replace('%%ALREADYUPLOADEDFILES%%',$existingFilesHtml,$template);  	
		}
		
		if($show_custom_fields_section != 'false'){			
				
			$template =  str_replace('%%CUSTOMFIELDSSHOW%%',$show_custom_fields_section,$template);  	
			$template =  str_replace('%%CUSTOMFIELDS%%',dapMemberProfileGetCustomFieldsHtml($custom_fields_selected,$userId),$template);
		}else{
			$template =  str_replace('%%CUSTOMFIELDSSHOW%%','d-none',$template);
			
			
		}
	   
		/******GDPR DATA starts*********/
		
		$ip = $_SERVER['HTTP_X_REAL_IP'];

		if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && $ip == '') {
		$ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
		if(isset($ip[0])){
		$ip = $ip[0];
		}
		}

		if (array_key_exists('HTTP_X_SUCURI_CLIENTIP', $_SERVER)) {
		$ip =  $_SERVER['HTTP_X_SUCURI_CLIENTIP'];

		}

		if($ip == ''){
		$ip = $_SERVER['REMOTE_ADDR'];
		}
 
		$user_consent = $user->getGDPRConsent();
		$gdpr_compliance_date = $user->getGDPRCompliance_date();
		$current_date = date('Y-m-d h:i:s'); 
		$gdprcountry = dapGetGDPRStatus($ip); 
		/*$gdprcountry = dapMemberGetCountryNameByIp($ip);
		if(isset($gdprcountry['country_name']) && ($gdprcountry['country_name'] != '')){
			$gdprcountry = 1;
		}else{
			$gdprcountry = 0;
		}
		*/
		//$gdprcountry = 1;
		
	 
	   if($show_profile_gdpr_section && $gdprcountry == 1){
		   $hidden_fields_html  .= "<input type='hidden' name='u_gdpr_consent' id='gdpr_consent' value='".$user_consent."'>"; 
		   $hidden_fields_html  .= "<input type='hidden' name='current_date' value='".$current_date."'>"; 
		   $hidden_fields_html  .= "<input type='hidden' name='u_gdpr_compliance_date' id='gdpr_compliance_date' value='".$gdpr_compliance_date."'>"; 
		   $hidden_fields_html  .= "<input type='hidden' name='allowgdpr' value='Y'>"; 
		  
	   }else{
		   $hidden_fields_html  .= "<input type='hidden' name='allowgdpr' value='N'>"; 
		   $template =  str_replace('%%GDPRSHOW%%','d-none',$template);
		   $hidden_fields_html  .= "<input type='hidden' name='u_gdpr_consent' id='gdpr_consent' value='NOT_GDPR_USER'>"; 
		   $hidden_fields_html  .= "<input type='hidden' name='current_date' value='".$current_date."'>"; 
		   $hidden_fields_html  .= "<input type='hidden' name='u_gdpr_compliance_date' id='gdpr_compliance_date' value=''>"; 
	   }
	   
	    $hidden_fields_html  .= "<input type='hidden' name='redirect' value='".$redirect_url."'>"; 
	    $hidden_fields_html  .= "<input type='hidden' name='button_edit_user' value='Update'>"; 
	    $hidden_fields_html  .= "<input type='hidden' name='gdpr_msg_section' value='".$gdpr_msg_section."'>"; 
	    $hidden_fields_html  .= "<input type='hidden' name='dap_first_name_error' value='".dapMemberGetMessageByKeyAndAction('myprofile','first_name')."'>"; 
	    $hidden_fields_html  .= "<input type='hidden' name='dap_invalid_email' value='".dapMemberGetMessageByKeyAndAction('myprofile','invalid_email')."'>"; 
	    $hidden_fields_html  .= "<input type='hidden' name='dap_password_leangth_error' value='".dapMemberGetMessageByKeyAndAction('myprofile','password_leangth_error')."'>"; 
	    $hidden_fields_html  .= "<input type='hidden' name='dap_password_special_chat_error' value='".dapMemberGetMessageByKeyAndAction('myprofile','password_special_chat_error')."'>"; 
	    $hidden_fields_html  .= "<input type='hidden' name='dap_password_repeat_error' value='".dapMemberGetMessageByKeyAndAction('myprofile','password_repeat_error')."'>"; 
	    $hidden_fields_html  .= "<input type='hidden' name='dap_opted_error' value='".dapMemberGetMessageByKeyAndAction('myprofile','opted_error')."'>"; 
	    $hidden_fields_html  .= "<input type='hidden' name='u_opted_out' >"; 
	    $hidden_fields_html  .= "<input type='hidden' name='u_admin_email'  value='".$admin_email."'>"; 
		$template =  str_replace('%%HIDDENFIELDS%%',$hidden_fields_html,$template);
		
		$html .= DapMemberProfileReplaceMergeTags($template); 			
		
		
			
		}else{
			$not_login_msg = dapMemberGetMessageByKeyAndAction('myprofile','not_login');
			$clickto_log_in_text = dapMemberGetMessageByKeyAndAction('myprofile','clicktologintext');

			if($not_login_msg == ''){
				$not_login_msg = 'Sorry, you must log in before you can view this content.';
			}
			if($clickto_log_in_text == ''){
				$clickto_log_in_text = 'Click here to log in.';	
			}
			
			$not_login_msg = str_replace('%%LINKSTART%%','<a href="'.Dap_Config::get("LOGIN_URL").'">',$not_login_msg);
			$not_login_msg = str_replace('%%LINKEND%%','</a>',$not_login_msg);
			$login_url = Dap_Config::get("LOGIN_URL");
			
			$html .= "<div class='not-login'>".$not_login_msg."<a href='".$login_url."'>".$clickto_log_in_text."</a></div>";
		}
		$html .=  DapMemberShowLoader();	
		
	   $html .= "</div>";
	   
	   $html .= "<script>
						var dap_profile_id = '".$dap_profile_id."';
						var allow_file_upload = '".$allow_file_upload."';
						var allowed_types_of_file = '".$allowed_types_of_file."';
						var max_upload_size = '".$max_upload_size."';
						var max_number_of_file = '".$max_number_of_file."';
						var allowed_file_upload_types = '".$allowed_file_upload_types."';
						var file_upload_max_size = '".$file_upload_max_size."';
						var site_url = '".$site_url."';
						var base_path = '".$base_path."';
						</script>";
	   
	   return  $html; 	
	}
}
 
function dapMemberProfileGetCustomFieldsHtml($customfieldvalues = '',$userId = 0){
	
	$showcustomfields = 'Y';
	$HTML = '';
	if( ($showcustomfields == "Y") || ($showcustomfields != "") ) {
    $customFieldsArray = null;
    if($showcustomfields != "Y") {
      $customFieldsArray = explode(",",$showcustomfields);
    }
    

    $customFields = Dap_CustomFields::loadUserFacingCustomFields();
    if($customfieldvalues != "all"){
      //$customArray = explode(',',$customfieldvalues);
      $customArray = $customfieldvalues;
    }else{
      $customArray = array();
      //$customFields = array_merge($customFields,$customArray);
    }
    
	
    foreach ($customFields as $custom) {
      if((count($customArray) == 0) || in_array($custom['id'],$customArray)){
    
      $required = " ";
      $requiredStar = "";

      if ($custom['showonlytoadmin'] == "Y") {
        continue;
      }
     
      if(!is_null($customFieldsArray) &&  !in_array($custom['name'],$customFieldsArray) ){
        continue;
      }
      
      if($custom['required'] == "Y") {
        $required = "required";
        $requiredStar = "*";
      }
      
      $user_custom_value = Dap_UserCustomFields::loadUserCustomFieldsByCustomFieldId($custom['id'], $userId);
      $value = "";
      
      if ($user_custom_value) {
        foreach ($user_custom_value as $val) {
          $value = $val['custom_value'];
        }
      }
       
      
      if($custom['field_type'] == "textarea"){
		  $html = '<div class="form-group row"><div class="col-sm-4 d-flex align-items-center">
				<label class="form_text">[CUSTOM_FIELD_LABEL][REQUIREDSTAR]</label>
				</div>
				<div class="col-sm-8">
				<textarea class="form_setting form-control" realname="[CUSTOM_FIELD_LABEL]" [REQUIRED] name="custom_[CUSTOM_FIELD_NAME]" id="custom_[CUSTOM_FIELD_NAME]"  cols="20" rows="6" >[CUSTOM_FIELD_VALUE]</textarea>
		`		</div></div>'; 
	  }else{
		$html = '<div class="form-group row"><div class="col-sm-4 d-flex align-items-center">
				<label class="form_text">[CUSTOM_FIELD_LABEL][REQUIREDSTAR]</label>
				</div>
				<div class="col-sm-8">
				<input class="form_setting form-control" realname="[CUSTOM_FIELD_LABEL]" [REQUIRED] name="custom_[CUSTOM_FIELD_NAME]" type="text" id="custom_[CUSTOM_FIELD_NAME]" size="20" value="[CUSTOM_FIELD_VALUE]">
				</div>
				</div>';
	  }
      $html = str_replace( '[REQUIREDSTAR]', $requiredStar, $html);
      $html = str_replace( '[CUSTOM_FIELD_LABEL]', $custom['label'], $html);  
      $html = str_replace( '[CUSTOM_FIELD_NAME]', $custom["name"], $html); 
      $html = str_replace( '[CUSTOM_FIELD_VALUE]', $value, $html); 
      $html = str_replace( '[REQUIRED]', $required, $html); 
      
       $HTML .=  $html;
       
      
     
      } // end if in_array
       
       
    } //end foreach 
  
  }
  return $HTML;
} 
 
/*
* Replace merge tags with products info
*/ 
function DapMemberProfileReplaceMergeTags($html = '',$mp_obj = ''){
	
	 
	 $session = Dap_Session::getSession();
	 if(Dap_Session::isLoggedIn()){
		 
		$user = $session->getUser();
		$user = Dap_User::loadUserById($user->getId());
	
		$html =  str_replace('%%firstname%%',"value='".$user->getFirst_name()."'",$html);
		$html =  str_replace('%%lastname%%', "value='".$user->getLast_name()."'",$html);
		$html =  str_replace('%%phone%%', "value='".$user->getPhone()."'",$html);
		$html =  str_replace('%%email%%', "value='".$user->getEmail()."'",$html);
	
		$html =  str_replace('%%address1%%', "value='".$user->getAddress1()."'",$html);
		$html =  str_replace('%%address2%%', "value='".$user->getAddress2()."'",$html);
		$html =  str_replace('%%city%%', "value='".$user->getCity()."'",$html);
		$html =  str_replace('%%state%%', "value='".$user->getState()."'",$html);
		$html =  str_replace('%%zip%%', "value='".$user->getZip()."'",$html);
		$html =  str_replace('%%country%%', "value='".$user->getCountry()."'",$html);
		
		$html =  str_replace('%%title%%', "value='".$user->getTitle()."'",$html);
		$html =  str_replace('%%fax%%', "value='".$user->getFax()."'",$html);
		$html =  str_replace('%%company%%', "value='".$user->getCompany()."'",$html);
		$html =  str_replace('%%paypalemail%%', "value='".$user->getPaypal_email()."'",$html);
		
		$isChecked = ($user->getOpted_out() == "N") ? " checked" : "";
		$html =  str_replace('%%optedout%%',$isChecked,$html);
		
		
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		$html =  str_replace('%%FIRSTNAME%%',"value='".$user->getFirst_name()."'",$html);
		$html =  str_replace('%%LASTNAME%%', "value='".$user->getLast_name()."'",$html);
		$html =  str_replace('%%PHONE%%', "value='".$user->getPhone()."'",$html);
		$html =  str_replace('%%EMAIL%%', "value='".$user->getEmail()."'",$html);
	
		$html =  str_replace('%%ADDRESS1%%', "value='".$user->getAddress1()."'",$html);
		$html =  str_replace('%%ADDRESS2%%', "value='".$user->getAddress2()."'",$html);
		$html =  str_replace('%%CITY%%', "value='".$user->getCity()."'",$html);
		$html =  str_replace('%%STATE%%', "value='".$user->getState()."'",$html);
		$html =  str_replace('%%ZIP%%', "value='".$user->getZip()."'",$html);
		$html =  str_replace('%%COUNTRY%%', "value='".$user->getCountry()."'",$html);
		
		$html =  str_replace('%%TITLE%%', "value='".$user->getTitle()."'",$html);
		$html =  str_replace('%%FAX%%', "value='".$user->getFax()."'",$html);
		$html =  str_replace('%%COMPANY%%', "value='".$user->getCompany()."'",$html);
		$html =  str_replace('%%PAYPALEMAIL%%', "value='".$user->getPaypal_email()."'",$html);
		
		$isChecked = ($user->getOpted_out() == "N") ? " checked" : "";
		$html =  str_replace('%%OPTEDOUT%%',$isChecked,$html);
		
		
		
	 }
	
	$html =  str_replace('contenteditable="true"','contenteditable="false"',$html);
	
	
	return $html;
}  


function dapMemberGetCountryNameByIp($ipaddress){ /*get country name by IP*/
	$return_data = array('country_code' => '', 'country_name' => '');
 
		
	$url = "http://www.geoplugin.net/json.gp?ip=" . $ipaddress;
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_HEADER, false);
	$data = curl_exec($curl);
	curl_close($curl);
	$data = @json_decode($data);
	
	if ($data && $data->geoplugin_countryName != null) {
		$return_data['country_code'] = $data->geoplugin_countryCode;
		$return_data['region_state'] = $data->geoplugin_regionName;
		$return_data['country_name'] = $data->geoplugin_countryName;
	}
	if($return_data['country_name'] == ''){
		$ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ipaddress));
		if ($ip_data && $ip_data->geoplugin_countryName != null) {
			
			$return_data['country_code'] = $ip_data->geoplugin_countryCode;
			$return_data['region_state'] = $ip_data->geoplugin_regionName;
			$return_data['country_name'] = $ip_data->geoplugin_countryName;
		}else{
			$ip_data = @json_decode(file_get_contents("https://ipfind.co?ip=" . $ipaddress));
		
			if ($ip_data && $ip_data->country != null) {
				
				$return_data['country_code'] = $ip_data->country_code;
				$return_data['region_state'] = $ip_data->city;
				$return_data['country_name'] = $ip_data->country;
			}
		}
		
	}

	return $return_data;
}
