<?php
$path="../../";
include("../../map.php");
header("Content-Type: text/html;charset=utf-8");
if($_POST["msec"]<>""){$msec=$_POST["msec"];}else{$msec="1000";}

if ($_GET["durum"]=="send"){ //---------------------->Gönderim
	$konu		= $_SESSION["tm_konu"];
	$gonderen	= $_SESSION["tm_gonderen"];
	$malici		= $_POST["malici"];
	$gsm		= $_POST["t4"];
	$id			= $_POST["id"];
	$mgonderen = $mail;
	$mesaj		= $_POST["mesaj"];
	$path		= "../../../";
	if ($_GET["islem"]=="tmail"){
		if(validate($malici,"mail")=="ok"){
			echo	"<i class=\"fas fa-paper-plane\" style=\"margin-right:5px\"></i>";
			echo	"<script>jQuery(document).ready(function(){jQuery('#row".$_GET["row"]."').removeClass('v3-bg-warning').addClass('v3-bg-success');});</script>";
			$mesaj	= $design_top.$mesaj.$design_bottom;
			if ($_GET["test"]=="true"){echo "E-mail test OK!";}else{
				emailgonder($malici,$konu,$cc,$mesaj);
			}
		}else{
			echo "<i class=\"fas fa-exclamation-triangle\" title=\"\"></i>";
			echo "<script>	jQuery(document).ready(function(){jQuery('#row".$_GET["row"]."').removeClass('v3-bg-warning').addClass('v3-bg-danger');});</script>";
		}
	}elseif ($_GET["islem"]=="tsms"){
		if(validate($gsm,"phone")=="ok"){
			echo "<i class=\"fas fa-paper-plane\" style=\"margin-right:5px\"></i>";
			echo "<script>	jQuery(document).ready(function(){jQuery('#row".$_GET["row"]."').removeClass('v3-bg-warning').addClass('v3-bg-success');});</script>";
			if ($_GET["test"]=="true"){echo "Sms test OK!";}else{
				smsgonder($mesaj,$gsm);
			}
		}else{
			echo "<i class=\"fas fa-exclamation-triangle\" title=\"\"></i>";
			echo "<script>	jQuery(document).ready(function(){jQuery('#row".$_GET["row"]."').removeClass('v3-bg-warning').addClass('v3-bg-danger');});</script>";
		}
		
	}elseif ($_GET["islem"]=="notifications"){
		echo "<i class=\"fas fa-paper-plane\" style=\"margin-right:5px\"></i>";
		echo "<script>	jQuery(document).ready(function(){jQuery('#row".$_GET["row"]."').removeClass('v3-bg-warning').addClass('v3-bg-success');});</script>";
		$Sql = $conn->query("insert into genel(s1,s2,s3,ne,t1,t4,n1,n6,ts1) values ('".$_SESSION['user_id']."', '".$id."', '0', 'notification', '".addslashes(stripslashes($konu))."', '".date("Y-m-d")."', '".addslashes(stripslashes($mesaj))."', '".addslashes(stripslashes($rjsi))."', now())");
		if ($_GET["test"]=="true"){echo "App test OK!";}else{
			sNotification($konu, $mesaj, "App", $id);
		}
	}

}else{
	include("../../scripts.php");
	foreach ($_POST as $key => $value){ $_SESSION["tm_".$key] = $value;}
	echo "<table class=\"table\">";

	if(substr($_SESSION["tm_s2"],-4)=="xlsx"){	//------------------> Gönderi xlsx ise;
		require_once "../../../deppo/tools/script/simple_xlsx.php";
		$dosya="../../../deppo/excel/".$_SESSION["tm_s2"]."";
		if($xlsx = SimpleXLSX::parse($dosya)){
			$result=$xlsx->rows();
		}else{
			$result=SimpleXLSX::parseError();
		}
		$i=0;foreach($result as $row){$i++;
			$c=0;foreach($row as $col){$c++;
				echo "<form id=\"if".$i."\" enctype=\"multipart/form-data\" class=\"xls\">";
				echo "<input type='hidden' value='".$col."' name='malici'>";
				echo "<input type='hidden' value='".$col."' name='t4'>";
				echo "<input type='hidden' value='".$i."' name='id'>";
				echo "<textarea name='mesaj' style='display:none;'>".$mesaj."</textarea>";
				echo "</form>";
				echo "<tr id=\"row".$i."\" class=\"v3-bg-warning\" onclick=\"AjaxPResult('ajax.php?ne=".$_GET["ne"]."&islem=".$_GET["islem"]."&durum=send&row=".$i."','#if".$i."','#r".$i."','nopl');\">";
				echo "<td style='width: 3%;'>".$i."</td>";
				echo "<td><div id=\"r".$i."\" style=\"cursor:pointer;\"><i class=\"fas fa-clock\"></i> Kuyruğa Eklendi</td>";
				echo "<td style='width: 25%;'>".$col."</td>";
				echo "<td style='width: 25%;'></td>";
				echo "</tr>";
				if ($i == 1) {
					echo "<script>
					jQuery(document).ready(function(){
						var msec = ".$msec.";
						var processQueue = function(index){
							var form = document.querySelector('#if'+index);
							if(form){
								var url = 'ajax.php?ne=".$_GET["ne"]."&islem=".$_GET["islem"]."&durum=send&test=".$_POST["test"]."&row='+index;
								var formId = '#if'+index;
								var resultDiv = '#r'+index;
								var nextCall = function(){var rem = document.getElementById('remainder1'); if(rem) rem.innerText = parseInt(rem.innerText) + 1;processQueue(index + 1);};
								if(msec > 0){
									setTimeout(function(){
										AjaxPResult(url, formId, resultDiv, 'nopl', '', nextCall);}, msec);
										} else {
											AjaxPResult(url, formId, resultDiv, 'nopl', '', nextCall);
										}
									}
								};
								processQueue(1);
								});
								</script>";
							}
						}
					}

				}else{ //------------------> Gönderi sql ise;
					if($_SESSION["tm_s2"]<>""){ $qry="and s2=".$_SESSION["tm_s2"]."";}
					$x=0;$y=0;

					if (!empty($_POST['q']) && array_filter($_POST['q'])) {
						$i = 0;
						$x = 0;
						$y = 0;
						$mselect = implode(',', $_POST["q"]);
						$uids = explode(',', $mselect);

						foreach ($uids as $uid) {
				$i++; $sql = mysqli_query($conn, "SELECT * FROM t5 WHERE id='" . $uid . "' AND s4=1 ORDER BY id DESC"); $rs = mysqli_fetch_assoc($sql); $jsi = json_decode($rs["n17"], true); $jsa = json_decode($rs["n8"], true);  // Cihaz bilgileri

				if (mysqli_num_rows($sql) > 0) {
					// Geçerli iletişim türüne göre doğrulama
					$valid = ($_GET["islem"] == "tmail" && validate(base64_decode($rs["t2"]), "mail") == "ok") || ($_GET["islem"] == "tsms" && validate(telefon($rs["t4"]), "phone") == "ok") || ($_GET["islem"] == "notifications" && $jsa["Device"] != ""); $valid ? $x++ : $y++;
					// Mesaj şablonunu kişisel verilerle doldur
					$mesaj = $_SESSION["tm_mesaj"];
					$placeholders = [ '{AdSoyad}' => $rs["t1"], '{FirmaAdi}' => $jsi["ifirma"], '{Unvan}' => $jsi["iunvan"], '{Telefon}' => telefon($rs["t4"]), '{Email}' => base64_decode($rs["t2"]), '{Sifre}' => base64_decode($rs["t3"]), '{firma}' => $firma, '{ftel}' => $ftel, '{ftel2}' => $ftel2, '{fgsm}' => $fgsm, '{fweb}' => $fweb, '{fadres}' => $fadres ];
					$mesaj = str_replace(array_keys($placeholders), array_values($placeholders), $mesaj);

					// Uygun iletişim türü varsa formu ve satırı oluştur
					if (($_GET["islem"] == "tmail" && $rs["t2"] != "") || ($_GET["islem"] == "tsms" && substr(telefon($rs["t4"]), 0, 1) == "5") || ($_GET["islem"] != "tmail" && $_GET["islem"] != "tsms")) {
						echo "<form id='if{$i}' class='f0' enctype='multipart/form-data'> <input type='hidden' name='malici' value='" . base64_decode($rs["t2"]) . "'> <input type='hidden' name='t4' value='" . telefon($rs["t4"]) . "'> <input type='hidden' name='id' value='{$rs["id"]}'> <textarea name='mesaj' style='display:none;'>{$mesaj}</textarea> </form>";
						echo "<tr id='row{$i}' class='v3-bg-warning' onclick=\"AjaxPResult('ajax.php?ne={$_GET["ne"]}&islem={$_GET["islem"]}&durum=send&test={$_POST["test"]}&row={$i}','#if{$i}','#r{$i}','nopl');\">
						<td style='width: 3%;'>{$i}</td>
						<td><div id='r{$i}' style='cursor:pointer;'><i class='fas fa-clock'></i> Kuyruğa Eklendi</div></td>
						<td style='width: 25%;'>{$rs["t1"]}</td>";

						if ($_GET["islem"] == "tmail") {
							echo "<td style='width: 25%;'>" . base64_decode($rs["t2"]) . "</td>";
						} elseif ($_GET["islem"] == "tsms") {
							echo "<td style='width: 25%;'>" . telefon($rs["t4"]) . "</td>";
						} elseif ($_GET["islem"] == "notifications") {
							echo "<td style='width: 25%;'>{$jsa["Device"]}</td>";
						}

						echo "</tr>";

						if ($i == 1) {
							echo "<script>
							jQuery(document).ready(function(){
								var msec = ".$msec.";
								if (msec <= 0) msec = 1;

								var processQueue = function(index){
									var form = document.querySelector('#if'+index);
									if(form){
										var url = 'ajax.php?ne=".$_GET["ne"]."&islem=".$_GET["islem"]."&durum=send&test=".$_POST["test"]."&row='+index;
										var formId = '#if'+index;
										var resultDiv = '#r'+index;
										var nextCall = function(){ var rem = document.getElementById('remainder1'); if(rem) rem.innerText = parseInt(rem.innerText) + 1; processQueue(index + 1); };
										setTimeout(function(){ AjaxPResult(url, formId, resultDiv, 'nopl', '', nextCall);}, msec);
									}
								};
								processQueue(1);
								});
								</script>";
							}
						}

					} else {
						// UID doğrudan e-posta veya telefon olabilir
						$valid = ($_GET["islem"] == "tmail" && validate($uid, "mail") == "ok") || ($_GET["islem"] == "tsms" && validate($uid, "phone") == "ok"); $valid ? $x++ : $y++;
						$mesaj = $_SESSION["tm_mesaj"];
						$placeholders = [ '{firma}' => $firma, '{ftel}' => $ftel, '{ftel2}' => $ftel2, '{fgsm}' => $fgsm, '{fweb}' => $fweb, '{fadres}' => $fadres ];
						$mesaj = str_replace(array_keys($placeholders), array_values($placeholders), $mesaj);

						echo "<form id='if{$i}' class='f1' enctype='multipart/form-data'> <input type='hidden' name='malici' value='{$uid}'> <input type='hidden' name='t4' value='" . telefon($uid) . "'> <textarea name='mesaj' style='display:none;'>{$mesaj}</textarea> </form>";

						echo "<tr id='row{$i}' class='v3-bg-warning' onclick=\"AjaxPResult('ajax.php?ne={$_GET["ne"]}&islem={$_GET["islem"]}&durum=send&test={$_POST["test"]}&row={$i}','#if{$i}','#r{$i}','nopl');\">
						<td><div id='r{$i}' style='cursor:pointer;'><i class='fas fa-clock'></i> Kuyruğa Eklendi</div></td>
						<td style='width: 25%;'>...</td>";

						if ($_GET["islem"] == "tmail") {
							echo "<td style='width: 25%;'>{$uid}</td>";
						} elseif ($_GET["islem"] == "tsms") {
							echo "<td style='width: 25%;'>" . telefon($uid) . "</td>";
						} elseif ($_GET["islem"] == "notifications") {
							echo "<td style='width: 25%;'>{$uid}</td>";
						}

						echo "</tr>";

						if ($i == 1) {
							echo "<script>
							jQuery(document).ready(function(){
								var msec = ".$msec.";
								if (msec <= 0) msec = 1;

								var processQueue = function(index){
									var form = document.querySelector('#if'+index);
									if(form){
										var url = 'ajax.php?ne=".$_GET["ne"]."&islem=".$_GET["islem"]."&durum=send&test=".$_POST["test"]."&row='+index;
										var formId = '#if'+index;
										var resultDiv = '#r'+index;
										var nextCall = function(){ var rem = document.getElementById('remainder1'); if(rem) rem.innerText = parseInt(rem.innerText) + 1; processQueue(index + 1); };
										setTimeout(function(){ AjaxPResult(url, formId, resultDiv, 'nopl', '', nextCall);}, msec);
									}
								};
								processQueue(1);
								});
								</script>";
							}
						}
					}

				} else {
					// Arama yapılmadıysa tüm uygun kayıtları listele
					if ($_POST["key"] != "") {
						$qry .= " AND (n17 LIKE '%{$_POST["key"]}%' OR n4 LIKE '%{$_POST["key"]}%')";
					}

					$i = 0;$sql = mysqli_query($conn, "SELECT * FROM t5 WHERE ne<>'' AND s4=1 {$qry} {$luye} ORDER BY id DESC"); while ($rs = mysqli_fetch_assoc($sql)) { $i++; $jsa = json_decode($rs["n8"], true); $jsi = json_decode($rs["n17"], true);
					$valid = ($_GET["islem"] == "tmail" && validate(base64_decode($rs["t2"]), "mail") == "ok") || ($_GET["islem"] == "tsms" && validate(telefon($rs["t4"]), "phone") == "ok") || ($_GET["islem"] == "notifications" && $jsa["Device"] != ""); $valid ? $x++ : $y++;
					$mesaj = $_SESSION["tm_mesaj"];
					$placeholders = [ '{AdSoyad}' => $rs["t1"], '{FirmaAdi}' => $jsi["ifirma"], '{Unvan}' => $jsi["iunvan"], '{Telefon}' => telefon($rs["t4"]), '{Email}' => base64_decode($rs["t2"]), '{Sifre}' => base64_decode($rs["t3"]), '{firma}' => $firma, '{ftel}' => $ftel, '{ftel2}' => $ftel2, '{fgsm}' => $fgsm, '{fweb}' => $fweb, '{fadres}' => $fadres ];
					$mesaj = str_replace(array_keys($placeholders), array_values($placeholders), $mesaj);

					if (($_GET["islem"] == "tmail" && $rs["t2"] != "") || ($_GET["islem"] == "tsms" && substr(telefon($rs["t4"]), 0, 1) == "5") || ($_GET["islem"] != "tmail" && $_GET["islem"] != "tsms")) {
						echo "<form id='if{$i}' class='f2' enctype='multipart/form-data'> <input type='hidden' name='malici' value='" . base64_decode($rs["t2"]) . "'> <input type='hidden' name='t4' value='" . telefon($rs["t4"]) . "'> <input type='hidden' name='id' value='{$rs["id"]}'> <textarea name='mesaj' style='display:none;'>{$mesaj}</textarea> </form>";
						echo "<tr id='row{$i}' class='v3-bg-warning' onclick=\"AjaxPResult('ajax.php?ne={$_GET["ne"]}&islem={$_GET["islem"]}&durum=send&test={$_POST["test"]}&row={$i}','#if{$i}','#r{$i}','nopl');\">
						<td style='width: 3%;'>{$i}</td>
						<td><div id='r{$i}' style='cursor:pointer;'><i class='fas fa-clock'></i> Kuyruğa Eklendi</div></td>
						<td style='width: 25%;'>{$rs["t1"]}</td>";

						if ($_GET["islem"] == "tmail") {
							echo "<td style='width: 25%;'>" . base64_decode($rs["t2"]) . "</td>";
						} elseif ($_GET["islem"] == "tsms") {
							echo "<td style='width: 25%;'>" . telefon($rs["t4"]) . "</td>";
						} elseif ($_GET["islem"] == "notifications") {
							echo "<td style='width: 25%;'>{$jsa["Device"]}</td>";
						}

						echo "</tr>";

						if ($i == 1) {
							echo "<script>
							jQuery(document).ready(function(){
								var msec = ".$msec.";
								if (msec <= 0) msec = 1;

								var processQueue = function(index){
									var form = document.querySelector('#if'+index);
									if(form){
										var url = 'ajax.php?ne=".$_GET["ne"]."&islem=".$_GET["islem"]."&durum=send&test=".$_POST["test"]."&row='+index;
										var formId = '#if'+index;
										var resultDiv = '#r'+index;
										var nextCall = function(){ var rem = document.getElementById('remainder1'); if(rem) rem.innerText = parseInt(rem.innerText) + 1; processQueue(index + 1); };
										setTimeout(function(){ AjaxPResult(url, formId, resultDiv, 'nopl', '', nextCall);}, msec);
									}
								};
								processQueue(1);
								});
								</script>";
							}
						}
					}
				}
			}

			echo "</table>";
		}

		if ($_GET["durum"]<>"send"){
			echo "<div class=\"v3-bg-info\" style=\"padding: 5px;\"><i class=\"fa-solid fa-circle-info\"></i> Toplam : ".($x+$y)." | Başarılı : ".$x." | Başarısız : ".$y."</div>";
			if ($_GET["tmail"]=="tmail"){
				$ln1="Toplam : ".($x+$y)." | Başarılı : ".$x." | Başarısız : ".$y." E-mail Gönderildi";
			}elseif ($_GET["tmail"]=="tsms"){
				$ln1="Toplam : ".($x+$y)." | Başarılı : ".$x." | Başarısız : ".$y." Sms Gönderildi";
			}elseif ($_GET["tmail"]=="notifications"){
				$ln1="Toplam : ".($x+$y)." | Başarılı : ".$x." | Başarısız : ".$y." Notification Gönderildi";
			}
			include("../public/log.php");
		}
	?>