<?php
error_reporting(0);
header("Content-Type: text/html; charset=UTF-8");
$path="../../";
include("../../map.php");
include("../../scripts.php");
include("../../secure.php");
include("Simplexml.php");

// -------------------------------------
// XML kaynak kontrol ve yükleme
// -------------------------------------
$xmlData = false;
$xmlSource = '';
if (!empty($_POST['dosya'])) {
    $xmlSource = trim($_POST['dosya']);

    // Eğer URL formatındaysa
    if (filter_var($xmlSource, FILTER_VALIDATE_URL)) {
        $xmlData = @simplexml_load_file($xmlSource);
    } else {
        // Değilse deppo/excel klasöründen oku
        $localPath = '../../../deppo/excel/' . basename($xmlSource);
        if (file_exists($localPath)) {
            $xmlData = @simplexml_load_file($localPath);
        }
    }
}

// XML verisinden örnek satırları al
$xmlPreview = [];
if ($xmlData) {
    $count = 0;
    foreach ($xmlData->children() as $item) {
        $row = [];
        foreach ($item->children() as $key => $val) {
            $row[$key] = trim((string)$val);
        }
        $xmlPreview[] = $row;
        if (++$count >= 5) break;
    }
}

// -------------------------------------
// Kayıt tipine göre kolon tanımları
// -------------------------------------
if ($_GET["ne"] == "kayit") {
    $ilist = array("Başlık"=>"t1","Kısa Açıklama"=>"n2","Açıklama"=>"n1","Keywords"=>"n4","Stok No"=>"t4","Resim"=>"images","Kategori[1]"=>"s9","Kategori[2]"=>"s10","Kategori[3]"=>"s11","Sıra"=>"s12","İşlem Sorumlusu"=>"s19");
    if($g8==1){$ilist["Marka"]="i1";}
    if($a7==1){$ilist["Varyasyon"]="varyasyon";}
    if($e5==1){$newItems=array("Barkod No"=>"t5","Liste Fiyatı"=>"pb2","Satış Fiyatı"=>"pb1","Para Birimi"=>"t2","Kdv"=>"s4");$ilist=array_merge($ilist,$newItems);}
    if($a7==1){$ilist["Dosya"]="files";}
    if($m16==1){$ilist["Stok"]="s5";$ilist["Desi"]="s6";}
} elseif ($_GET["ne"]=="uye" && $_GET["durum"]=="exml") {
    $ilist = array("Üye Kodu"=>"t5","Ad Soyad"=>"t1","Doğum Tarihi"=>"t12","IDN"=>"t11","Gsm No"=>"t4","Telefon"=>"t7","E-Mail"=>"t2","Şifre"=>"t3","Firma"=>"ifirma","Kategori"=>"s2","Şehir"=>"sehir","İlce"=>"ilce","Adres"=>"n5","Puan"=>"puan","İşlem Sorumlusu"=>"s19");
} elseif ($_GET["ne"]=="uye") {
    $ilist = array("Üye Kodu"=>"t5","Ad Soyad"=>"t1","Doğum Tarihi"=>"t12","IDN"=>"t11","Gsm No"=>"t4","Telefon"=>"t7","E-Mail"=>"t2","Şifre"=>"t3","Kategori"=>"s2","Adres"=>"n5","İşlem Sorumlusu"=>"s19","Etiketler"=>"n4");
} elseif ($_GET["ne"]=="haber") {
    $ilist = array("Başlık"=>"t1","Özet"=>"n2","Keywords"=>"n4","Detay"=>"n1","Başlama Tarihi"=>"t4","Bitiş Tarihi"=>"t9","Etkinlik Alanı"=>"ievent_location","Resim"=>"images","Kategori"=>"s2","İşlem Sorumlusu"=>"s19");
}

$q = ($_GET["ne"]=="kayit") ? "u" : (($_GET["ne"]=="uye") ? "k" : substr($_GET["ne"],0,1));

// -------------------------------------
// Limit & Sayfa kontrolü
// -------------------------------------
if (!empty($_POST["rows"])) {
    $rowLimit = intval($_POST["rows"]);
    $maxLimit = !empty($module["limit_xml"]) ? intval($module["limit_xml"]) : 999;
    if ($rowLimit > $maxLimit) $rowLimit = $maxLimit;
    $_SESSION["limit_xml"] = $rowLimit;
} elseif (!isset($_SESSION["limit_xml"])) {
    $_SESSION["limit_xml"] = !empty($module["limit_xml"]) ? intval($module["limit_xml"]) : 999;
}

$page = (isset($_GET["sayfa"]) && is_numeric($_GET["sayfa"])) ? intval($_GET["sayfa"]) : 1;
$flimit = ($_SESSION["limit_xml"] * ($page - 1));
$llimit = $flimit + $_SESSION["limit_xml"];
$ucats = json_decode(GetArr($q, "categories"), true);

// -------------------------------------
// XML Dosya listesi
// -------------------------------------
function getXmlFiles(){
    $files = glob('../../../deppo/excel/*.xml*');
    usort($files,function($a,$b){return filemtime($b)-filemtime($a);});
    return $files;
}

if($_GET["durum"]=="ixml"){$fID="ixml-form"; $btntext="Dosya Yükle";}elseif($_GET["durum"]=="view"){$fID="view-form"; $btntext="İçe Aktar";}elseif($_GET["durum"]=="match"){$fID="match-form"; $btntext="Göster";}elseif($_GET["durum"]=="exml"){$fID="exml-form"; $btntext="Dışa Aktar";}
?>
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>.xml <?php echo $sdil[119]; //Yönetimi !?></title>
</head>

<body>
	<div class="qmodal">
		<div class="qmodal-content">
			<!-- Header with Action Buttons -->
			<div class="qmodal-header">
				<div class="header-title">
					<nav aria-label="breadcrumb">
						<ol class="breadcrumb">
							<li class="breadcrumb-item"><a href="#"><i class="fa fa-home"></i></a></li>
							<li class="breadcrumb-item"><a href="#">Xml</a></li>
							<li class="breadcrumb-item active" aria-current="page">.xml <?php echo $sdil[119]; //Yönetimi !?></li>
						</ol>
					</nav>
				</div>

				<?php if($_GET["durum"]=="view"){?>
					<input type="text" id="filtre" class="filter-input" placeholder="Tabloda ara..." style="margin-right: 90px;">
				<?php }elseif($_GET["durum"]=="import"){?>

					<a class="mb-1 mt-1 mr-1 btn btn-default" href="#"><i class="fa fa-pause"  onclick="pauseQueue()"></i></a>
					<a class="mb-1 mt-1 mr-1 btn btn-default" title="#"><i class="fa fa-play" onclick="resumeQueue()"></i></a>
				<?php }elseif($_GET["durum"]=="exml"){?>
					<a class="mb-1 mt-1 mr-1 btn btn-default" href="#c0"><input type="checkbox" id="c0" onclick="Checks(this);" style="float: left; width: 16px; height: 16px; margin-top: 1px; margin-right: 5px;"> Select All</i></a>
					<a class="mb-1 mt-1 mr-1 btn btn-default" href="#ebtn" title=""><i class="fa fa-file-excel-o" aria-hidden="true"></i> Export</a>
				<?php }?>
					<?php if($btntext<>""){?><button class="v3-btn-xs v3-btn-info" type="button" onclick="jQuery('#<?php echo $fID?>').submit();"><?php echo translate($btntext)?> <i class="fa fa-angle-right" aria-hidden="true"></i></button><?php }?>
			</div>

			<!-- Left Tab Menu -->
			<div class="v8-columns">
				<div class="v8-col200pxL-left">
					<ul class="v8-side-tabs v8-js-tabs v8-same-height">
						<li class="current"><a href="<?php if($_GET["durum"]<>"exml"){?>?ne=<?php echo $_GET["ne"]?>&islem=<?php echo $_GET["islem"]?>&durum=ixml<?php }else{?>?ne=<?php echo $_GET["ne"]?>&islem=<?php echo $_GET["islem"]?>&durum=exml<?php }?>" title=""><i class="fa fa-table"></i> <span> .xml <?php echo translate("Dosyası")?></span></a></li>
					</ul>
					<div id="switchs">
						<div class="v3-alert v3-alert-warning ddn">
							<i class="fas fa-arrow-right" onclick="hide('switchs')" style="float: right; margin-bottom:10px;"></i>
						</div>

						<div class="grey-bg msa mdn" style="">
							<label>ID <span style="font-size:8px; color:#ccc;">(id)</span></label>
							<input class="form-control" type="text" name="id" value="<?php echo $rs["id"];?>" class="form-control">
						</div>
						
						<div class="grey-bg e <?php if (empty($_SESSION["cgiris"])) {echo "dn";}?>">
							<label><i class="fa fa-user-plus" aria-hidden="true"></i> <?php echo ctranslate("İşlem Sorumlusu")?> <span style="font-size:8px; color:#ccc;">(s19)</span></label>
							<select size="1" name="s19" class="form-control chosen-select">
								<option value="0" <?php if($rs["s19"]==0){echo "Selected";}?>>Admin</option>
								<?php $s19S = explode(',',$rs["s19"]); $sql=mysqli_query($conn, "select s2,id,t1 from t5 where (s9=1 or s1=1) $luye"); while($rsm=mysqli_fetch_assoc($sql)){?>
									<option class="" value="<?php echo $rsm["id"];?>" title="<?php echo $rsm["t1"];?>" alt="<?php echo $rsm["t1"];?>" <?php foreach($s19S as $s19){if($s19==$rsm["id"]){echo "Selected";}}?>><?php echo $rsm["t1"];?></option>
								<?php }?>
							</select>
						</div>

					</div>
				</div>

				<!-- Content Area -->
				<div class="v8-col200pxL-right">
					<div id="tab-detay" class="v8-tabs-content" style="height: 80vh !important; width: 100%; overflow-y: scroll; overflow-x: auto;">
						<?php if($_GET["durum"]=="ixml"){?>
							<form class="form" name="rall" method="post" action="?ne=<?php echo $_GET["ne"]?>&islem=<?php echo $_GET["islem"]?>&durum=match" enctype="multipart/form-data" id="<?php echo $_GET["durum"]?>-form">
								<fieldset class="grey-bg no-margin p-3 rounded">
								  <legend><?php echo translate("Excel Dosyası") ?></legend>
								  <div class="mb-3">
									<label for="xmlFile" class="form-label fw-semibold"><?php echo translate(".xml Dosyası") ?></label>
									<div class="input-group" style="width: 100%;">
									  <input type="text" name="dosya" id="xmlFile" class="form-control" accept=".xml">
									  <button type="submit" class="btn btn-info" style="display:none;"><?php echo translate("Yükle") ?></button>
									</div>
								  </div>
								</fieldset>

								<fieldset class="grey-bg no-margin ">
									<label class="<?php if (empty($_SESSION["cgiris"])) {echo "dn";}?>">Önceki Yüklemeler</label>
									<div class="input-with-button <?php if (empty($_SESSION["cgiris"])) {echo "dn";}?>">
										<label for="simple-action">.xml file</label>
										<?php $excelFiles = getExcelFiles($directory);?>
										<select name="excel_files" onChange="self.location.href=this.options[this.selectedIndex].value;">
											<option value="">Dosya Seçin</option>
											<?php foreach ($excelFiles as $file): ?>
												<option value="?ne=<?php echo $_GET["ne"]?>&islem=<?php echo $_GET["islem"]?>&durum=match&file=<?= htmlspecialchars($file) ?>">
													<?= htmlspecialchars(basename($file)) ?>
												</option>
											<?php endforeach; ?>
										</select>
									</div>

									<p class="db">
										<h3>Lütfen Dikkat</h3>
										- <strong>Kayıt limiti: <?php echo $klimit ?></strong><br><br>
										- <strong>Yükleyeceğiniz dosya yalnızca ".xml" uzantılı olmalıdır.</strong><br><br>
										<span class="text-success">
											* <strong>Yeni Kayıt (Ekleme)</strong><br>
											- Görsel dosya adlarında boşluk ve özel karakter bulunmamalıdır.<br>
											&nbsp;&nbsp;&nbsp;Örnek: <del>ürün 1 görseli.jpg</del> → <code>urun1_gorseli.jpg</code><br>
											- .xml dosyasındaki görsellerin isimleri, klasördeki görsel dosyalarıyla birebir aynı olmalıdır.<br>
											- Resim Upload, kategori ve varyasyon işlemleri sadece ekleme esnasında yapılabilir.<br><br>
										</span>
										<span class="text-warning">
											* <strong>Güncelleme</strong><br>
											- Yalnızca renkle vurgulanmış hücreler güncellenebilir. Tüm alanların doldurulması zorunlu değildir.<br>
											- “Eşleştirme sütunu” belirtilirse, mevcut kayıt güncellenir; belirtilmezse yeni kayıt olarak eklenir.<br>
											- Eşleştirme sütunu belirtildiğinde, dosyada ilgili sütun mutlaka bulunmalıdır.<br><br>
										</span>
										- <strong>Veri kaybı yaşamamak için “Örnek Excel Dosyası”nı kullanmanız ve açıklamaları dikkatlice okumanız tavsiye edilir.</strong>
									</p>
								</div>
							</fieldset>

						</form>
					<?php
						}elseif($_GET["durum"]=="match"){
						$jsonData = getJsonFromPostUrl($_POST['dosya']);
						//print_r($jsonData); // Bulunan JSON verisi array olarak döner

						$dosya=$_POST["dosya"];
						if($xml = Simplexml::parse($dosya)){
							$result = $xml->rows();
						} else {
							$result = Simplexml::parseError();
						}
						?>
						<form action="?ne=<?php echo $_GET["ne"]?>&islem=<?php echo $_GET["islem"]?>&durum=view" method="post" id="<?php echo $_GET["durum"]?>-form">
							<input type="hidden" name="xml" value="<?php echo $dosya;?>">
							<?php
							$e = 0; foreach ($ilist as $key => $value) {$e++;
								if ($e > 20) {$e = 1;}
								?>
								<fieldset class="grey-bg v3-col-md-3 <?php echo $value;?>" style="">
									<label><?php echo $key;?> <span style="font-size:8px; color:#ccc;"> (<?php echo $value;?>)</span> 
										<?php if($value=="varyasyon"){?><i class="fa fa-question-circle" title="Adı|fiyat|stok, şeklinde alınacak"></i><?php }?>
										<?php if($value=="images"){?><i class="fa fa-question-circle" title="[Folder] için ixml, [Sql] Aktar, [Url] (https) çekme"></i><?php }?>
										<?php if($value=="files"){?><i class="fa fa-question-circle" title="[Folder] için ixml, [Sql] Aktar, [Url] (https) çekme"></i><?php }?>
									</label>
									<?php
									if($value<>"images" and $value<>"files"){
										echo "<select name=\"".$value."\" id=\"".$value."\" style=\"width:95%;\">";
									}else{
										echo "<select name=\"".$value."\" id=\"".$value."\" style=\"width:70%; float:left;\">";
									}
									echo "<option value=\"\">...</option>";
									foreach($result[0] as $option){
										$col = array_search($option, $result[0]);
										if($option<>""){?>
											<option value="<?php echo $option?>,<?php echo $col?>,<?php echo $key?>" <?= (!empty($jsonData[0][$value]) && $jsonData[0][$value] === $option.','.$col.','.$key) ? 'selected' : '' ?>><?php echo ihb($option)?></option>
										<?php }
									}
									echo "</select>";
									if($value=="images"){
										echo "<select style='float:right;text-align:right;width:29%;' name='iattr'>
											<option value='url' ".((!empty($jsonData[0]['iattr']) && $jsonData[0]['iattr']==='url')?'selected':'').">Url</option>
											<option value='folder' ".((!empty($jsonData[0]['iattr']) && $jsonData[0]['iattr']==='folder')?'selected':'').">ixml</option>
											<option value='sql' ".((!empty($jsonData[0]['iattr']) && $jsonData[0]['iattr']==='sql')?'selected':'').">Sql</option>
										</select>";
									}
									if($value=="files"){
										echo "<select style='float:right;text-align:right;width:29%;' name='fattr'>
											<option value='url' ".((!empty($jsonData[0]['fattr']) && $jsonData[0]['fattr']==='url')?'selected':'').">Url</option>
											<option value='folder' ".((!empty($jsonData[0]['fattr']) && $jsonData[0]['fattr']==='folder')?'selected':'').">ixml</option>
											<option value='sql' ".((!empty($jsonData[0]['fattr']) && $jsonData[0]['fattr']==='sql')?'selected':'').">Sql Aktar</option>
										</select>";
									}

									?>
									<?php if($value=="t2" || $value=="s4"){?>
										<p style="right: 10px; bottom: -20px;"><?php if($value=="t2"){echo "Varsayılan <b>".$kpb."</b>";}elseif($value=="s4"){echo "Varsayılan <b>%".$s12."</b>";}?></p>
									<?php }elseif($value=="images" || $value=="files"){?>
										<p style="right: 10px; bottom: -20px;">[Folder] için ixml, [Sql] Aktar, [Url] (https) çekme</p>
									<?php }?>
								</fieldset>
							<?php }?>
							<?php if($_GET["ne"]=="uye" and $module["cinfo"]=="1"){?>
								<fieldset class="grey-bg v3-col-md-3" style="">
									<label><i class="<?php echo $rsi["n14"]?>"></i> <?php echo translate("Firma Adı");?> <span style="font-size:8px; color:#ccc;"> (ifirma)</span></label>
									<?php
									echo "<select name='ifirma' style='width:95%;'><option value=''>...</option>";
									foreach($result[0] as $value){
										$col = array_search($value, $result[0]);
										if($value<>""){
											$optVal = $value.",".$col.",".translate("Firma Adı");
											echo "<option value='$optVal' ".((!empty($jsonData[0]['ifirma']) && $jsonData[0]['ifirma']===$optVal)?'selected':'').">".ihb($value)."</option>";
										}
									}
									echo "</select>";
									?>
								</fieldset>
								<fieldset class="grey-bg v3-col-md-3" style="">
									<label><i class="<?php echo $rsi["n14"]?>"></i> <?php echo translate("Unvanı");?> <span style="font-size:8px; color:#ccc;"> (iunvan)</span></label>
									<?php
									echo "<select name='iunvan' style='width:95%;'><option value=''>...</option>";
									foreach($result[0] as $value){
										$col = array_search($value, $result[0]);
										if($value<>""){
											$optVal = $value.",".$col.",".translate("Unvanı");
											echo "<option value='$optVal' ".((!empty($jsonData[0]['iunvan']) && $jsonData[0]['iunvan']===$optVal)?'selected':'').">".ihb($value)."</option>";
										}
									}
									echo "</select>";
									?>
								</fieldset>
								<fieldset class="grey-bg v3-col-md-3" style="">
									<label><i class="<?php echo $rsi["n14"]?>"></i> <?php echo translate("Vergi Dairesi");?> <span style="font-size:8px; color:#ccc;"> (ivdaire)</span></label>
									<?php
									echo "<select name='ivdaire' style='width:95%;'><option value=''>...</option>";
									foreach($result[0] as $value){
										$col = array_search($value, $result[0]);
										if($value<>""){
											$optVal = $value.",".$col.",".translate("Vergi Dairesi");
											echo "<option value='$optVal' ".((!empty($jsonData[0]['ivdaire']) && $jsonData[0]['ivdaire']===$optVal)?'selected':'').">".ihb($value)."</option>";
										}
									}
									echo "</select>";
									?>
								</fieldset>
								<fieldset class="grey-bg v3-col-md-3" style="">
									<label><i class="<?php echo $rsi["n14"]?>"></i> <?php echo translate("Vergi Numarası");?> <span style="font-size:8px; color:#ccc;"> (ivnumara)</span></label>
									<?php
									echo "<select name=\"ivnumara\" style=\"width:95%;\">";
									echo "<option value=\"\">...</option>";
									foreach($result[0] as $value){
										$col = array_search($value, $result[0]);
										if($value<>""){
											echo "<option value=\"".$value.",".$col.",".translate("Vergi Numarası")."\">".ihb($value)."</option>";
										}
									}
									echo "</select>";
									?>
								</fieldset>
							<?php }?>
							<?php if($_GET["ne"]=="uye" and $module["uye_bankinfo"]=="1"){?>
								<fieldset class="grey-bg v3-col-md-3" style="">
									<label><?php echo translate("Hesap Adı");?> <span style="font-size:8px; color:#ccc;"> (ihesap1_adi)</span></label>
									<?php
									echo "<select name=\"ihesap1_adi\" style=\"width:95%;\">";
									echo "<option value=\"\">...</option>";
									foreach($result[0] as $value){
										$col = array_search($value, $result[0]);
										if($value<>""){
											echo "<option value=\"".$value.",".$col.",".translate("Hesap Adı")."\">".ihb($value)."</option>";
										}
									}
									echo "</select>";
									?>
								</fieldset>
								<fieldset class="grey-bg v3-col-md-3" style="">
									<label><?php echo translate("Hesap Şube");?> <span style="font-size:8px; color:#ccc;"> (ihesap1_sube)</span></label>
									<?php
									echo "<select name=\"ihesap1_sube\" style=\"width:95%;\">";
									echo "<option value=\"\">...</option>";
									foreach($result[0] as $value){
										$col = array_search($value, $result[0]);
										if($value<>""){
											echo "<option value=\"".$value.",".$col.",".translate("Hesap Şube")."\">".ihb($value)."</option>";
										}
									}
									echo "</select>";
									?>
								</fieldset>
								<fieldset class="grey-bg v3-col-md-3" style="">
									<label><i class="<?php echo $rsi["n14"]?>"></i> <?php echo translate("Hesap No");?> <span style="font-size:8px; color:#ccc;"> (ihesap1_no)</span></label>
									<?php
									echo "<select name=\"ihesap1_no\" style=\"width:95%;\">";
									echo "<option value=\"\">...</option>";
									foreach($result[0] as $value){
										$col = array_search($value, $result[0]);
										if($value<>""){
											echo "<option value=\"".$value.",".$col.",".translate("Hesap No")."\">".ihb($value)."</option>";
										}
									}
									echo "</select>";
									?>
								</fieldset>
								<fieldset class="grey-bg v3-col-md-3" style="">
									<label><i class="<?php echo $rsi["n14"]?>"></i> <?php echo translate("Hesap Pb");?> <span style="font-size:8px; color:#ccc;"> (ihesap1_pb)</span></label>
									<?php
									echo "<select name=\"ihesap1_pb\" style=\"width:95%;\">";
									echo "<option value=\"\">...</option>";
									foreach($result[0] as $value){
										$col = array_search($value, $result[0]);
										if($value<>""){
											echo "<option value=\"".$value.",".$col.",".translate("Hesap Pb")."\">".ihb($value)."</option>";
										}
									}
									echo "</select>";
									?>
								</fieldset>
								<fieldset class="grey-bg v3-col-md-3" style="">
									<label><i class="<?php echo $rsi["n14"]?>"></i> <?php echo translate("Hesap Iban");?> <span style="font-size:8px; color:#ccc;"> (ihesap1_iban)</span></label>
									<?php
									echo "<select name=\"ihesap1_iban\" style=\"width:95%;\">";
									echo "<option value=\"\">...</option>";
									foreach($result[0] as $value){
										$col = array_search($value, $result[0]);
										if($value<>""){
											echo "<option value=\"".$value.",".$col.",".translate("Hesap Iban")."\">".ihb($value)."</option>";
										}
									}
									echo "</select>";
									?>
								</fieldset>
							<?php }?>
							<?php
							$i=0;$sqli=mysqli_query($conn, "select * from genel where ne='inputs' and n3='".$_GET["ne"]."' and n4<>'switch' and s1=0 order by s10,id asc"); while($rsi=mysqli_fetch_assoc($sqli)){$i++;
								if($rsi["t3"]<>""){$ival=$rsi["t3"];}else{$ival = "i".$i."";}
								?>
								<fieldset class="grey-bg v3-col-md-3" style="">
									<label><i class="<?php echo $rsi["n14"]?>"></i> <?php echo $rsi["n1"];?> <span style="font-size:8px; color:#ccc;"> (i<?php echo $ival;?>)</span></label>
									<?php
									echo "<select name=\"".$ival."\" style=\"width:75%;\" id=\"".$ival."\">";
									echo "<option value=\"\">...</option>";
									foreach($result[0] as $value){
										$col = array_search($value, $result[0]);
										if($value<>""){ echo "<option value=\"".$value.",".$col.",".$rsi["n1"]."\" data-value=\"".$value.",".$col.",".$rsi["n1"]."\">".ihb($value)."</option>"; }
									}
									echo "</select>";
									echo "
									<select style=\"float:right;text-align: right;padding: 5px; font-size: 12px;\" id=\"t".$ival."\" onchange=\"setvalue('".$ival."')\">
									<option value=\"\">...</option>
									<option value=\"money\">Fiyat</option>
									<option value=\"select\">Seçenek</option>
									</select>
									";
									?>
								</fieldset>
							<?php }?>
							<fieldset class="grey-bg v3-col-md-3 lang" style="">
								<label>Dil <i class="fa fa-question-circle" title="Sadece Update için kullanılır."></i></label>
								<select name="lang" style="width:95%;">
									<option value="">...</option>
									<?php
									if(!empty($m1)){
										$i = 0;$diller = explode(',',$m1); foreach($diller as $dil) {$i++; if($i > 99) {$i = 1;}
										?>
										<option value="lang<?php echo $i?>" <?php if($_SESSION["lang"]=="lang".$i.""){echo "Selected";}?>><?php echo $dil;?></option>";
									<?php }}?>
								</select>
							</fieldset>
							<fieldset class="grey-bg v3-col-md-3 urow" style="">
								<label>Eşleştirme Sütunu <i class="fa fa-question-circle" title="Güncelleme işleminde Eşleştirme Sütunu"></i></label>
								<select name="urow" style="width:95%;">
									<option value="">...</option>
									<?php if($_GET["ne"]=="kayit"){ ?>
										<option value="t1" <?= (!empty($jsonData[0]['urow']) && $jsonData[0]['urow']==='t1')?'selected':'' ?>>Başlık</option>
										<option value="t4" <?= (!empty($jsonData[0]['urow']) && $jsonData[0]['urow']==='t4') || empty($jsonData[0]['urow'])?'selected':'' ?>>Stok No</option>
										<option value="t5" <?= (!empty($jsonData[0]['urow']) && $jsonData[0]['urow']==='t5')?'selected':'' ?>>Barkod No</option>
									<?php } elseif($_GET["ne"]=="haber"){ ?>
										<option value="t1" <?= (!empty($jsonData[0]['urow']) && $jsonData[0]['urow']==='t1')?'selected':'' ?>>Başlık</option>
									<?php } else { ?>
										<option value="t1" <?= (!empty($jsonData[0]['urow']) && $jsonData[0]['urow']==='t1')?'selected':'' ?>>Ad Soyad</option>
										<option value="t4" <?= (!empty($jsonData[0]['urow']) && $jsonData[0]['urow']==='t4') || empty($jsonData[0]['urow'])?'selected':'' ?>>Gsm</option>
										<option value="t2" <?= (!empty($jsonData[0]['urow']) && $jsonData[0]['urow']==='t2')?'selected':'' ?>>Email</option>
										<option value="t5" <?= (!empty($jsonData[0]['urow']) && $jsonData[0]['urow']==='t5')?'selected':'' ?>>Üye Kod</option>
										<option value="t13" <?= (!empty($jsonData[0]['urow']) && $jsonData[0]['urow']==='t13')?'selected':'' ?>>Kimlik No</option>
									<?php } ?>
								</select>
							</fieldset>
							<fieldset class="grey-bg v3-col-md-3 rows" style="">
								<label>Import Limit <i class="fa fa-question-circle" title="Boş olması durumunda tüm kayılar, min:2"></i></label>
								<input type="text" name="rows" class="form-control fl" style="width:95%" placeholder="<?php echo $_SESSION["limit_xml"]?>" value="<?php echo $_SESSION["limit_xml"];?>">
							</fieldset>
							<fieldset class="grey-bg v3-col-md-3 rows" style="">											
								<label>Detay resim URL <i class="fa fa-question-circle" title="detay resim URL"></i></label>
								<input type="text" name="xipath" class="form-control fl" style="width:95%" placeholder="detay resim URL" value="<?php echo $_SESSION["xipath"];?>" title="Eğer ürün açıklamasında kullanılan görseller varsa, her biri için tam URL girilmelidir. import_images/ klasörüne upload edilir">
								<p style="right: 10px; bottom: -20px;">*Ürün açıklamasındaki görselleri çekmek için URL girilmelidir </p>
							</fieldset>
							<fieldset class="grey-bg v3-col-md-3 dn" style="">
								<label>Kategorileri İşleme! <i class="fa fa-question-circle" title="Mevcut kategorilere ekleme yapma"></i></label>
								<input type="checkbox" value="1" name="kategorisiz">
							</fieldset>
							<button class="v3-btn-xs v3-btn-warning" style="display:none;" type="submit"><?php echo translate("Önizle")?> <i class="fa fa-angle-right" aria-hidden="true"></i></button>
						</form>
						<?php
							}elseif($_GET["durum"]=="import" or $_GET["durum"]=="view"){
								$savedFile = savePostToJson($_POST, $_POST['xml']);
								if($xml = Simplexml::parse($_POST["xml"])){
									$result=$xml->rows(); // her satır = array, ilk satır = header
								} else {
									$result=Simplexml::parseError();
								}

								$available = 0; $unavailable = 0;

								// eşleştirme yapılacak ana kolon (örnek: stok kodu)
								$urow = $_POST["urow"];
								$urowInfo = explode(",", $_POST[$urow]);
								$columnIndex = (int) $urowInfo[1];
								$fieldName = $urow;

								$importedKeys = [];
								foreach ($result as $rowIndex => $value) {
									if ($rowIndex > $flimit && $rowIndex <= $llimit) {
										$cellValue = trim($value[$columnIndex]);
										if ($cellValue !== "") $importedKeys[] = mysqli_real_escape_string($conn, $cellValue);
									}
								}

								// mevcut kayıt kontrolü
								if (count($importedKeys) > 0) {
									$inClause = "'" . implode("','", $importedKeys) . "'";
									$existingKeys = [];
									$checkQuery = mysqli_query($conn, "SELECT `$fieldName` FROM `{$_SESSION['lang']}` WHERE ne='kayit' AND `$fieldName` IN ($inClause)");
									while ($row = mysqli_fetch_assoc($checkQuery)) $existingKeys[] = $row[$fieldName];
									$existingKeys = array_flip($existingKeys);
								}

								echo "<script>var formQueue = [];</script>";
								$row = -1;
								foreach ($result as $value) {
									$row++;
									if ($row > $flimit && $row <= $llimit) echo "<script>formQueue.push('if".$row."');</script>";
								}

								echo "<table style='width:100%; font-size:12px;' class=\"table table-hover filterable\">";
								echo "<tr>";
								echo "<td class=\"w1\" style=\"background-color:#ccc; color:#fff;\">Durum</td>";
								echo "<td style=\"background-color:#ccc; color:#fff;\">ID</td>";
								foreach ($_POST as $iname => $ival){
									$_SESSION[$iname] = $ival;
									if($_POST[$iname]<>"" and $iname<>"xml"){
										$iss = explode(',',$ival);
										echo "<td style=\"background-color:#ccc; color:#fff;\">".$iss[2]."</td>";
									}
								}
								echo "</tr>";

								$row=-1; $total = count($result);
								foreach($result as $value){ $row++;
									if ($row > $flimit && $row <= $llimit){
										$cellValue = trim($value[$columnIndex]);
										$isExisting = isset($existingKeys[$cellValue]);
										$icon = $isExisting ? '<i class="fas fa-database text-success" title="Zaten mevcut" style="opacity:0.6;"></i>' : '<i class="fas fa-database text-warning" title="Yeni eklenecek" style="opacity:0.7;"></i>';
										if ($isExisting) $available++; else $unavailable++;

										echo "<form id=\"if".$row."\" enctype=\"multipart/form-data\">";
										echo "<tr id=\"row".$row."\" class=\"addrow\" style=\"cursor:pointer;\" onclick=\"AjaxPResult('../xls/xls_import.php?ne=".$_GET["ne"]."&islem=".$_GET["islem"]."&durum=kaydet&row=".$row."','#if".$row."','#r".$row."','0');\">";
										echo "<td><div id=\"r".$row."\">".$icon."</td>";
										echo "<td>".$row."</td>";

										// gizli alanlar
										echo "<input type='hidden' name='iattr' value='".$_POST["iattr"]."'>";
										echo "<input type='hidden' name='fattr' value='".$_POST["fattr"]."'>";
										echo "<input type='hidden' name='urow' value='".$_POST["urow"]."'>";
										echo "<input type='hidden' name='lang' value='".$_POST["lang"]."'>";
										echo "<input type='hidden' name='xipath' value='".$_POST["xipath"]."'>";

										foreach ($_POST as $iname => $ival){
											if($_POST[$iname]<>"" and $iname<>"xml"){
												$iss = explode(',',$ival);
												$deger = isset($value[$iss[1]]) ? $value[$iss[1]] : "";
												$short = htmlspecialchars(kisalt(strip_tags($deger), 30));
												$title = htmlspecialchars($deger);

												if($iname=="n1"){
													echo "<td>".$short."</td><textarea name=\"".$iname."\" style=\"display:none;\">".$deger."</textarea>";
												}elseif($iname=="t1" or $iname=="n2"){
													echo "<td title=\"".$title."\">".kisalt($deger,30)."</td><textarea name=\"".$iname."\" style=\"display:none;\">".$deger."</textarea>";
												}elseif($iname=="images"){
													$imgs = array_filter(explode(',', $deger));
													$thumbs = '';
													$maxShow = 3;
													$count = count($imgs);
													foreach(array_slice($imgs, 0, $maxShow) as $img){
														$thumbs .= "<a href='".trim($img)."' target='_blank'><img src='".trim($img)."' style='width:40px;height:40px;object-fit:cover;border-radius:4px;margin-right:3px;border:1px solid #ccc;'></a>";
													}
													if($count > $maxShow) $thumbs .= "<span style='font-size:10px;color:#999;'>+".($count-$maxShow)."</span>";
													echo "<td>".$thumbs."</td><textarea name=\"".$iname."\" style=\"display:none;\">".$deger."</textarea>";

												}elseif($iname=="pb1" or $iname=="pb2"){
													echo "<td>".wpara($deger)."</td><textarea name=\"".$iname."\" style=\"display:none;\">".wprice($deger)."</textarea>";
												}else{
													echo "<td title=\"".$title."\">".$deger."</td><textarea name=\"".$iname."\" style=\"display:none;\">".$deger."</textarea>";
												}
											}
										}
										echo "</tr>";
										echo "</form>";
									}
								}
								echo "</table>";

								$totalpage = ceil($total / $_SESSION["limit_xml"]);
								$start_row = ($page - 1) * $_SESSION["limit_xml"] + 1;
								$end_row = min($total, $page * $_SESSION["limit_xml"]);

							?>
							<script>
							let isPaused = false, currentIndex = 0;
							function processQueue(index){
								<?php if($page < $totalpage){ ?>
								if(index >= formQueue.length){ document.getElementById('NextForm').submit(); return; }
								<?php } ?>
								if(isPaused) return;
								currentIndex = index;
								let formId = '#' + formQueue[index];
								let rowNum = formQueue[index].replace('if','');
								let resultDiv = '#r' + rowNum;
								let url = '../xls/xls_import.php?ne=<?= $_GET["ne"] ?>&islem=<?= $_GET["islem"] ?>&durum=kaydet&row=' + rowNum;
								AjaxPResult(url, formId, resultDiv, 'nopl', '', function(){
									let rem1 = document.getElementById('remainder1');
									if(rem1) rem1.innerText = parseInt(rem1.innerText) + 1;
									processQueue(index+1);
								});
							}
							function pauseQueue(){isPaused=true;}
							function resumeQueue(){if(!isPaused)return; isPaused=false; processQueue(currentIndex);}
							<?php if ($_GET["durum"] == "import"){ ?>jQuery(document).ready(function(){processQueue(0);});<?php } ?>
							</script>

								<?php if($_GET["durum"]=="view"){?>
									<form action="?ne=<?php echo $_GET["ne"]?>&islem=<?php echo $_GET["islem"]?>&durum=import&sayfa=<?php echo $_GET["sayfa"]?>" method="post" id="<?php echo $_GET["durum"]?>-form">
										<?php foreach ($_POST as $iname => $ival){ ?>
											<input type="hidden" name="<?php echo $iname?>" value="<?php echo $ival?>">
										<?php }?>
										<button class="v3-btn-xs v3-btn-danger" id="ibtn" style="display:none;" type="submit"><?php echo translate("İçe Aktar")?> <i class="fa fa-angle-right" aria-hidden="true"></i></button>
									</form>
								<?php }?>

								<div style="font-size: 12px; width: 183px; position: fixed; left: 10px; bottom: 30px; padding: 10px; background: #f9f9f94a;">
									<?php
									$limit = $_SESSION["limit_xml"]; $durumMetni = "";
									if ($available == $limit) {$durumMetni = "Liste <b>Ekli</b>";} elseif ($unavailable == $limit) {$durumMetni = "Liste <b>Eklenecek</b>";} else {$durumMetni = "Listede <b>$available</b> ekli, <b>$unavailable</b> eklenecek";}
									?>
									<?php echo "Toplam <b>$total</b> kayıttan <b>$start_row - $end_row</b> arasındaki kayıtlar, her sayfada <b>$limit</b> (<span id='remainder1'>0</span> kayıt aktarıldı)<br>Sayfa: <b>" . $page . "</b> / <b>$totalpage</b><br>$durumMetni<br><br>";?>
									
									<?php if($page <= $totalpage){ ?>
										<center>
											<form id="PrevForm" method="post" action="?ne=<?php echo $_GET["ne"]?>&islem=<?php echo $_GET["islem"]?>&durum=<?php echo $_GET["durum"]?>&sayfa=<?php echo $page-1;?>" style="float:left;">
												<?php foreach ($_POST as $iname => $ival){echo "<input type=\"hidden\" name=\"".$iname."\" value=\"".$ival."\">";}?>
												<button class="v3-btn v3-btn-info" style="" type="submit"><i class="fas fa-angle-left"></i> Geri </button>
											</form>

											<form id="NextForm" method="post" action="?ne=<?php echo $_GET["ne"]?>&islem=<?php echo $_GET["islem"]?>&durum=<?php echo $_GET["durum"]?>&sayfa=<?php echo $page+1;?>" style="float:right;">
												<?php foreach ($_POST as $iname => $ival){echo "<input type=\"hidden\" name=\"".$iname."\" value=\"".$ival."\">";}?>
												<button class="v3-btn v3-btn-warning" style="" type="submit"> İleri <span style="font-size:12px;"><?php echo $totalpage?> <i class="fas fa-angle-right"></i> <?php echo $page+1;?></span></button>
											</form>
										</center>
									<?php }?>
								</div>

							<?php }elseif($_GET["durum"]=="exml"){ ?>
								<form action="../xml/xml_export.php?ne=<?php echo $_GET["ne"]?>&islem=<?php echo $_GET["islem"]?>&durum=exml&py=<?php echo $_GET["py"]?>" target="_blank" method="post" id="exml-form">
									<div class="v3-col-md-12 v3-col-xs-12">
										<input type="text" class="v3-form-control" name="q" value="" style="" placeholder="filtre">
									</div>
									<div class="v3-col-md-4 v3-col-xs-12">
										<select name="c1" id="sc1" class="form-control">
											<option value="0">...</option>
											<?php
											foreach($ucats as $key=>$value){
												if(($value["ne"]=="".$q."kategori" or ($value["t1"]=="".$_GET["ne"]."" and $value["s1"]=="0"))){$value["id"]==$rs["s9"] ? $selected="selected" : $selected="";
												echo "<option value=\"".$value["id"]."\" id=\"".$value["id"]."\" ".$selected.">".$value["item"]."</option>";
											}
										}
										?>
									</select>
								</div>
								<div class="v3-col-md-4 v3-col-xs-12">
									<select name="c2" id="sc2" class="form-control">
										<option value="0">...</option>
									</select>
								</div>
								<div class="v3-col-md-4 v3-col-xs-12">
									<select name="c3" id="sc3" class="form-control">
										<option value="0">...</option>
									</select>
								</div>
								<script type="text/javascript">
									jQuery('#sc1').on('change', function(){
										var ID = jQuery('#sc1 option:selected').attr('ID');
										jQuery('#sc2').load('../ajax/categorie<?php if($module["ajax_categories"]<>""){echo "s";}?>_ajax.php?ne=<?php echo $_GET["ne"]?>&islem=kategori&islem=<?php echo $q?>alt_kategori&c='+ID);
									});
									jQuery('#sc2').on('change', function(){
										var ID = jQuery('#sc2 option:selected').attr('ID');
										jQuery('#sc3').load('../ajax/categorie<?php if($module["ajax_categories"]<>""){echo "s";}?>_ajax.php?ne=<?php echo $_GET["ne"]?>&islem=kategori&islem=<?php echo $q?>alt_kategori2&c='+ID);
									})
								</script>
								<?php $i = 0; foreach($ilist as $label => $value) { $i++; ?>
									<div class="v3-col-md-2 v3-col-xs-6">
										<label><?php echo $label; ?></label>
										<input type="checkbox" name="exp[]" class="dchck" value="<?php echo $label . ':' . $value; ?>" style="width: 24px; height: 24px;">
									</div>
								<?php } ?>
								<?php
								$i=0;$sqli=mysqli_query($conn, "select * from genel where ne='inputs' and t2='".$_SESSION["lang"]."' and n3='".$_GET["ne"]."' and n4<>'switch' and s1=0 order by s10 asc"); while($rsi=mysqli_fetch_assoc($sqli)){$i++;
									if($rsi["t3"]<>""){$ival=$rsi["t3"];}else{$ival = "i".$i."";}
									?>
									<div class="v3-col-md-2 v3-col-xs-6">
										<label><?php echo $rsi["n1"];?></label>
										<input type="checkbox" name="exp[]" class="dchck" value="<?php echo $rsi["n1"].":".$ival;?>" style="width: 24px; height: 24px;">
									</div>
								<?php }?>
								<div class="v3-col-md-12" style="clear:both;">
									<button type="submit" id="ebtn" class="v3-btn v3-btn-success" style="float:right;display:none">Export</button>
								</div>
							</form>
						<?php }?>
					</div>
				</div>
			</body>

		<script>
			function setvalue(id){
				var addval = jQuery("#t"+id+" option:selected").val();
				jQuery("#"+id+" option").each(function(){
					var getval = jQuery(this).attr("data-value");
					if(this.value!=""){
						jQuery(this).val(''+getval+','+addval+'');
					}
				});
				return false;
			}
			jQuery( ".continue" ).click(function() {
				jQuery('.addrow').each(function(i, obj) {
					jQuery('.addrow').trigger('click');
				});
			});
			jQuery(document).ready(function() {
				check_urow();
			});
			jQuery("[name='t1'], [name='t2'], [name='t4'], [name='t5'], [name='urow']").change(function() {
				check_urow();
			});
			function check_urow(){
				var urow = jQuery('select[name="urow"]').find(":selected").val();
				var t1 = jQuery('select[name="t1"]').find(":selected").val();
				var t2 = jQuery('select[name="t2"]').find(":selected").val();
				var t4 = jQuery('select[name="t4"]').find(":selected").val();
				var t5 = jQuery('select[name="t5"]').find(":selected").val();
				var pb1 = jQuery('select[name="pb1"]').find(":selected").val();
				var s5 = jQuery('select[name="s5"]').find(":selected").val();
				jQuery('.t1, .t2, .t4, .t5').removeClass('bg-danger');
				jQuery('.'+urow+'').addClass('bg-danger');
				<?php if($_GET["ne"]=="kayit"){?>
					if((urow=="t1" && t1=="Ürün Adı,0, Stok No") || (urow=="t4" && t4=="Stok No,4, Stok No") || (urow=="t5" && t5=="Barkod No,5, Barkod No")){
						//jQuery('.v3-btn-warning').removeAttr('disabled');
					}else{
						//jQuery('.v3-btn-warning').attr('disabled', 'disabled');
					}
				<?php }elseif($_GET["ne"]=="uye"){?>
					if((urow=="t2" && t2=="Email,6, Gsm No") || (urow=="t4" && t4=="Gsm,5, Gsm No")){
						//jQuery('.v3-btn-warning').removeAttr('disabled');
					}else{
						//jQuery('.v3-btn-warning').attr('disabled', 'disabled');
					}
				<?php }?>
				jQuery('.t1').addClass('bg-warning');
				return false;
			}
		</script>
		<?php
		if($_GET["durum"]=="uxmlfiles"){
			unlink("../../../ixml");
			$kaydedilecekyer = "../../../";
			$adi		= $_FILES["dosya"]["name"];
			move_uploaded_file ($_FILES['dosya']['tmp_name'], $kaydedilecekyer . "/".$_FILES["dosya"]["name"]);
			$zip = new ZipArchive;
			$res = $zip->open("../../../".$_FILES["dosya"]["name"]."");
			if ($res === TRUE) {
				$zip->extractTo('../../../ixml/');
				$zip->close();
				unlink("../../../".$_FILES["dosya"]["name"]."");
			}else{
				echo "Zip Err";
			}
			echo location("?ne=kayit&islem=xml&durum=ixml",self,500,1);
		}
		include("../public/log.php");
		?>
		</html>