<?php if ( ! defined( 'ABSPATH' ) ) exit; ?>
<div class="wrap">
<?php
	$logged_in_email = '';
	if (current_user_can('manage_options')) {
		$logged_in_user = wp_get_current_user();
		$logged_in_email = $logged_in_user->user_email;
	} else {
		die('You are not authorized to proceed.');
	}

	global $eotpasettings;
	if(!isset($eotpasettings) || count($eotpasettings) < 5) emailotpauthn_settingsdetails();
	$setupwizardstep = $eotpasettings["setupwizardstep"];
	$issetupfinish = isset( $_GET[ 'setupfinish' ] ) ? $_GET[ 'setupfinish' ] : 0;
	if($issetupfinish == 1 && $setupwizardstep != 12) {
		$setupwizardstep = 12;
		emailotpauthn_settingsdetails("","setupwizardstep[:::]". $setupwizardstep);
	}

	//delete_option("emailotpauthn_templatesdata");
	$templatesdata = get_fix_option('emailotpauthn_templatesdata','not_initiated');
	$dfltemplatedata = "";
	if(strcasecmp($templatesdata,"not_initiated")==0){
		//$dflttemplatepath = esc_url(plugins_url( 'lib/default_template_data.txt', __FILE__ ));
		$dflttemplatepath = sprintf("%s/lib/default_template_data.txt", dirname(__FILE__));
		if(file_exists($dflttemplatepath)){
			$dfltemplatedata = file_get_contents($dflttemplatepath);
			if(empty($dfltemplatedata)){
				$templatesdata = "";
			}else{
				$dfltemplatedata = json_decode($dfltemplatedata,true);
				update_option("emailotpauthn_templatesdata", serialize($dfltemplatedata));
				$templatesdata = $dfltemplatedata;
			}
		} else {
			$templatesdata = "";
		}
	} else {
		$templatesdata = unserialize($templatesdata);
	}
	$thumbpath = plugins_url("imgs", __FILE__);
	
?>
<style>
* {
  box-sizing: border-box;
}

/* Center website */
.eotpatmplmain {
  max-width: 1000px;
  margin: auto;
  font-family: Arial;
}

.notice{
 display:none;
}

h1 {
  font-size: 50px;
  word-break: break-all;
}

.eotpatmplrow {
  margin: 10px -16px;
}

/* Add padding BETWEEN each column */
.eotpatmplrow,
.eotpatmplrow > .eotpatmplcolumn {
  padding: 8px;
}

/* Create three equal columns that floats next to each other */
.eotpatmplcolumn {
  float: left;
  width: 33.33%;
  display: none; /* Hide all elements by default */
}

/* Clear floats after rows */ 
.eotpatmplrow:after {
  content: "";
  display: table;
  clear: both;
}

/* Content */
.eotpatmplcontent img {
  padding: 5px 10px 10px 10px;
}
.eotpatmplcontent .eotpatmpltitle {
  margin: 0;
  padding-top: 5px;
}
.eotpatmplcontent {
  background-color: white;
  //padding: 10px;
  text-align: center;
  position: relative;
}

/* The "show" class is added to the filtered elements */
.eotpatmplshow {
  display: block;
}

/* Style the buttons */
.eotpatmplbtn {
  border: none;
  outline: none;
  padding: 12px 16px;
  background-color: white;
  cursor: pointer;
  margin: 2px 1px;
}

.eotpatmplbtn:hover {
  background-color: #ddd;
}

.eotpatmplbtn.active {
  background-color: #666;
  color: white;
}

.eotpatmplaply {
  border: 1px solid #00d;
  outline: none;
  padding: 5px 8px;
  background-color: #dfd;
  cursor: pointer;
  position: absolute;
  top: auto;
  right: 10px;
  bottom: 10px;
  left: auto;
}

.eotpatmplaply.active:hover,.eotpatmplaply:hover {
  background-color: #7aa;
}

.eotpatmplaply.active {
  background-color: #099;
  color: white;
}
#eotpatmplBtnContainer{
	text-align: center;
}
#eotpamodal {
	margin: 0;
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-45%, -50%);
	height: auto;
    width: 80%;
    background-color: rgba(0,0,0,.5);
    display: flex;
    justify-content: center;
    align-items: center;
	//z-index: 99;
}
#tmpltimg{
	height: 100%;
    width: 100%;
}
.modal__window {
  position: relative;
  background-color: white;
  padding: 10px;
}

</style>
<!-- MAIN (Center website) -->
<div id="eotpatmplmain" class="eotpatmplmain">

<div style="display:block;margin-top:30px;"><h1></h1><h1 style="display:inline;float:left;">TEMPLATES</h1><h1 style="display:inline;float:right;">Email OTP Authenticator</h1></div>
<br><br><hr><br>



<div id="eotpatmplBtnContainer">
  <button class="eotpatmplbtn" onclick="eotpatmplfilterSelection('all')"><?php esc_html_e("All","email-otp-authenticator"); ?></button>
  <button class="eotpatmplbtn" onclick="eotpatmplfilterSelection('sharp')"><?php esc_html_e("Sharp","email-otp-authenticator"); ?></button>
  <button class="eotpatmplbtn" onclick="eotpatmplfilterSelection('curved')"><?php esc_html_e("Curved","email-otp-authenticator"); ?></button>
  <button class="eotpatmplbtn" onclick="eotpatmplfilterSelection('blur')"><?php esc_html_e("Blur","email-otp-authenticator"); ?></button>
  <button class="eotpatmplbtn" onclick="eotpatmplfilterSelection('opaque')"><?php esc_html_e("Opaque","email-otp-authenticator"); ?></button>
  <button class="eotpatmplbtn" onclick="eotpatmplfilterSelection('solid')"><?php esc_html_e("Solid","email-otp-authenticator"); ?></button>
  <button class="eotpatmplbtn" onclick="eotpatmplfilterSelection('colors')"><?php esc_html_e("Colors","email-otp-authenticator"); ?></button>
  <button class="eotpatmplbtn" onclick="eotpatmplfilterSelection('images')"><?php esc_html_e("Images","email-otp-authenticator"); ?></button>
  <button class="eotpatmplbtn" onclick="eotpatmplfilterSelection('patterns')"><?php esc_html_e("Patterns","email-otp-authenticator"); ?></button>
  <button class="eotpatmplbtn" onclick="eotpatmplfilterSelection('left')"><?php esc_html_e("Left","email-otp-authenticator"); ?></button>
  <button class="eotpatmplbtn" onclick="eotpatmplfilterSelection('center')"><?php esc_html_e("Center","email-otp-authenticator"); ?></button>
  <button class="eotpatmplbtn" onclick="eotpatmplfilterSelection('right')"><?php esc_html_e("Right","email-otp-authenticator"); ?></button>
</div>

<!-- Portfolio Gallery Grid -->
<div class="eotpatmplrow">
  <?php
	if(empty($templatesdata)){
		echo '<div id="defaulteotpatmplnote" style="text-align:center;margin-top:25px;"><h2 id="defaulteotpatmplmsg">'. esc_html__("The database does not contain any template data.","email-otp-authenticator") . '</h2><p>'. sprintf( esc_html__("Please complete the setup through the %1\$sSetup Wizard%2\$s to download the template images and files.","email-otp-authenticator"),'<a href="admin.php?page=setupwizard-email-otp-authenticator" style="text-decoration:none;color:#000066;">','</a>') . '</p></div>';
	} else {
		if(is_array($templatesdata)){
			echo '<div id="defaulteotpatmplnote" style="text-align:center;margin-top:25px;"><h2 id="defaulteotpatmplmsg">'. esc_html__("Select A Category","email-otp-authenticator") . '</h2></div>';
			foreach ($templatesdata as $templatedata) {
				$thumbimage = str_ireplace("eotpatmpltimgs", $thumbpath, $templatedata['imagepath']);
				echo '<div class="eotpatmplcolumn" data-eotpatmplid="'.($templatedata['id']+0).'" data-eotpacategories="'.implode(' ', $templatedata['categories']).'"><div class="eotpatmplcontent"><h4 class="eotpatmpltitle">'.$templatedata['id'].' : '.$templatedata['name'].'</h4><img onclick="openeotpamodal(\''.$thumbimage.'\')" src="'.$thumbimage.'" alt="'.$templatedata['name'].'" style="width:100%;display:block;cursor:pointer;"><button class="eotpatmplaply '.((($templatedata['isapplied']+0)==1)?'active':'').'" onclick="">'. esc_html__("Apply","email-otp-authenticator") . '</button></div></div>';
			}
		} else {
			echo '<div id="defaulteotpatmplnote" style="text-align:center;margin-top:25px;"><h2 id="defaulteotpatmplmsg">'. esc_html__("The database does not contain any template data.","email-otp-authenticator") . '</h2></div>';
		}
	}
  ?>
<!-- END GRID -->
</div>
<div id="eotpatmplBtnContainer">
  <button class="eotpatmplbtn" id="eotpatmplprebtn" onclick="eotpatmplfilterSelection('previous')" style="float:left;"><?php esc_html_e("Previous","email-otp-authenticator"); ?></button>
  <span id="eotpatmplitems" data-eotpatmplpage="0" data-eotpatmplcrntctgry="" style="margin-top:12px;display:inline-block;"></span>
  <button class="eotpatmplbtn" id="eotpatmplnxtbtn" onclick="eotpatmplfilterSelection('next')" style="float:right;"><?php esc_html_e("Next","email-otp-authenticator"); ?></button>
</div>
<br><br><hr style="margin-top:20px;"><br>
<div><?php printf( esc_html__("%1\$sCredits:%2\$s Templates include lightweight images and patterns from %4\$sfreepik.com%3\$s, %5\$sfffuel.co%3\$s, and %6\$spattern.monster%3\$s.","email-otp-authenticator"),'<b>','</b>','</a>','<a href="https://freepik.com/" target="_blank" style="text-decoration:none;color:#000066;">','<a href="https://fffuel.co/" target="_blank" style="text-decoration:none;color:#000066;">','<a href="https://pattern.monster/" target="_blank" style="text-decoration:none;color:#000066;">'); ?></div>
<!-- END MAIN -->
</div>
<div id="eotpamodal" style="display:none;cursor:pointer;" onclick="closeeotpamodal()">
  <div class="modal__window">
      <img id="tmpltimg"></img>
  </div>
</div>
<script>
//eotpatmplfilterSelection("all")
function eotpatmplfilterSelection(c) {
	var defaulteotpatmplnote = document.getElementById("defaulteotpatmplnote");
	var eotpatmplprebtn = document.getElementById("eotpatmplprebtn");
	var eotpatmplitems = document.getElementById("eotpatmplitems");
	var eotpatmplnxtbtn = document.getElementById("eotpatmplnxtbtn");
	var x, i, f, g, h, j, k, m;
	x = document.getElementsByClassName("eotpatmplcolumn");
	h = 0;
	j = false;
	if(c=="previous" || c=="next"){
		if(c=="previous") j = true;
		var eotpatmplshown = document.getElementsByClassName("eotpatmplshow");
		if(eotpatmplshown.length == 0) return;
		c = eotpatmplitems.dataset.eotpatmplcrntctgry.toString();
		h = Number(eotpatmplitems.dataset.eotpatmplpage);
		if(j) h = h - 2;
		if(h < 0) h = 0;
	} else {
		eotpatmplitems.dataset.eotpatmplcrntctgry = c.toString();
		h = 0;
	}
	if(defaulteotpatmplnote.style.display != "none") defaulteotpatmplnote.style.display = "none";
	j = true;
	m = false;
	f = 0;
	k = 0;
	if (c == "all") c = "";
	if(x.length > 0){
		for (i = 0; i < x.length; i++) {
			eotpatmplRemoveClass(x[i], "eotpatmplshow");
			if (x[i].dataset.eotpacategories.toLowerCase().indexOf(c.toLowerCase()) > -1) {
				if(j && ((h*9) <= f)) {
					eotpatmplAddClass(x[i], "eotpatmplshow");
					k++;
				} else if(k > 0) {
					m = true;
				}
				f++;
			}
			if(k == 9){
				j = false;
			}
		}
		if(!j && !m) {
			j = true;
		}
		if(k > 0){
			h++;
			eotpatmplitems.dataset.eotpatmplpage = h.toString();
			if(h <= 1){
				eotpatmplprebtn.disabled = true;
			} else {
				eotpatmplprebtn.disabled = false;
			}
			eotpatmplnxtbtn.disabled = j;
			g = (h * 9) - 8;
			k = g + 8;
			if(k > f) k = f;
			eotpatmplitems.innerText = g.toString() + " to " + k.toString() + " of " + f.toString() + " templates.";
		} else if(h > 0) {
		} else {
			eotpatmplitems.innerText = "";
		}
	}
	if(f==0){
		var defaulteotpatmplmsg = document.getElementById('defaulteotpatmplmsg');
		defaulteotpatmplmsg.style.color = "#333";
		defaulteotpatmplmsg.innerText = "<?php esc_html_e("No templates available in this category.","email-otp-authenticator"); ?>";
		defaulteotpatmplnote.style.display = "block";
		eotpatmplprebtn.disabled = true;
		eotpatmplnxtbtn.disabled = true;
	}
}

function eotpatmplAddClass(element, name) {
  var i, arr1, arr2;
  arr1 = element.className.split(" ");
  arr2 = name.split(" ");
  for (i = 0; i < arr2.length; i++) {
    if (arr1.indexOf(arr2[i]) == -1) {element.className += " " + arr2[i];}
  }
}

function eotpatmplRemoveClass(element, name) {
  var i, arr1, arr2;
  arr1 = element.className.split(" ");
  arr2 = name.split(" ");
  for (i = 0; i < arr2.length; i++) {
    while (arr1.indexOf(arr2[i]) > -1) {
      arr1.splice(arr1.indexOf(arr2[i]), 1);     
    }
  }
  element.className = arr1.join(" ");
}


// Add active class to the current category button (highlight it)
var eotpatmplbtnContainer = document.getElementById("eotpatmplBtnContainer");
var eotpatmplbtns = eotpatmplbtnContainer.getElementsByClassName("eotpatmplbtn");
for (var i = 0; i < eotpatmplbtns.length; i++) {
  eotpatmplbtns[i].addEventListener("click", function(){
    var current = document.getElementsByClassName("eotpatmplbtn active");
	if(current.length > 0) current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
}

// Add active class to the current template button (highlight it)
var eotpatmplaply = document.getElementsByClassName("eotpatmplaply");
for (var i = 0; i < eotpatmplaply.length; i++) {
  eotpatmplaply[i].addEventListener("click", function(){
	var rplctmpl = confirm("<?php esc_html_e("Are you sure to REPLACE the current template.?","email-otp-authenticator"); ?>");
	if((rplctmpl?1:0)==1){
		var current = document.getElementsByClassName("eotpatmplaply active");
		if(current.length > 0) current[0].className = current[0].className.replace(" active", "");
		this.className += " active";
		eotpa_applytmpl(this);
	}
  });
}
//*
function eotpa_applytmpl(eotpatmpl_btn){
	var eotpatmplmain = document.getElementById('eotpatmplmain');
	disable_all_eotpatmplelms(true);
	var eotpatmplparent = eotpatmpl_btn.closest('.eotpatmplcolumn');
	var eotpatmplid = eotpatmplparent.dataset.eotpatmplid;

	var request = new XMLHttpRequest();
	request.open('POST', "<?php echo admin_url("admin-ajax.php"); ?>", true);
	request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	request.onload = function () {
		if (this.status >= 200 && this.status < 400) {
			var eotpadata = JSON.parse(this.responseText);
			if(eotpadata.status == 1){
				disable_all_eotpatmplelms();
				show_eotpatmplapplymsg(eotpadata.response,eotpatmpl_btn,1);
			} else {
				disable_all_eotpatmplelms();
				show_eotpatmplapplymsg(eotpadata.response,eotpatmpl_btn);
			}
			//alert(eotpadata.response);
		} else {
			disable_all_eotpatmplelms();
			show_eotpatmplapplymsg("<?php esc_html_e("Server error: ","email-otp-authenticator"); ?>" + this.status + " - " + this.statusText,eotpatmpl_btn);
			//alert("Server error: " + this.status + " - " + this.statusText);
		}
	};
	request.onerror = function() {
		disable_all_eotpatmplelms();
		show_eotpatmplapplymsg("<?php esc_html_e("Network Error or Request Failed.","email-otp-authenticator"); ?>",eotpatmpl_btn);
		//alert("Network Error or Request Failed.");
	};
	request.send('action=emailotpauthntmplaply&emailotpauthntmplsecurity=<?php esc_html_e( wp_create_nonce("emailotpauthn_filed_once_tmplval") ); ?>&applyid=' + eotpatmplid.toString());
}
function show_eotpatmplapplymsg(eotpatmplmsgval,eotpatmplbtn,eotpatmplmsgtype=0){
	var defaulteotpatmplnote = document.getElementById("defaulteotpatmplnote");
	var defaulteotpatmplmsg = document.getElementById('defaulteotpatmplmsg');
	if(eotpatmplmsgtype==0){
		defaulteotpatmplmsg.style.color = "#880000";
	} else {
		defaulteotpatmplmsg.style.color = "#006600";
		eotpatmplbtn.innerText = "<?php esc_html_e("Applied","email-otp-authenticator"); ?>";
		eotpatmplbtn.disabled = true;
	}
	defaulteotpatmplmsg.innerText = eotpatmplmsgval;
	defaulteotpatmplnote.style.display = "block";
	defaulteotpatmplnote.scrollIntoView({behavior: 'smooth',block: 'center'});

}
function disable_all_eotpatmplelms(isdisablethem=false){
	var eotpatmplmain = document.getElementById('eotpatmplmain');
	var eotpatmplchildren = eotpatmplmain.querySelectorAll('button');
	eotpatmplchildren.forEach(element => {element.disabled = isdisablethem;});
}
//*/
function openeotpamodal(imgurl){
	var eotpamodal = document.getElementById("eotpamodal");
	var tmpltimg = document.getElementById("tmpltimg");
	tmpltimg.src = imgurl;
	eotpamodal.style.display = "flex";
}
function closeeotpamodal(){
	var eotpamodal = document.getElementById("eotpamodal");
	eotpamodal.style.display = "none";
}
</script>

</div>
