<?php
$path="../../";
include("../../map.php");
include("../../../deppo/tools/script/SimpleImage.php");
header('Content-Encoding: UTF-8');
header('Content-Type: text/plain; charset=utf-8');

error_log("SESSION user_id: " . ($_SESSION["user_id"] ?? 'yok'));

function downloadAndReplaceImages($html, $saveDir, $baseUrl) {
    if (!is_dir($saveDir)) { mkdir($saveDir, 0755, true);}
    preg_match_all('/<img[^>]+src=["\']([^"\']+)["\']/i', $html, $matches);
    if (empty($matches[1])) return $html; // Resim yoksa orijinal döner
    foreach ($matches[1] as $imgUrl) {
        if (strpos($imgUrl, 'http') !== 0) {
            $fullUrl = rtrim($baseUrl, '/') . '/' . ltrim($imgUrl, '/');
        } else {
            $fullUrl = $imgUrl;
        }
        $filename = basename(parse_url($fullUrl, PHP_URL_PATH));
        $localPath = rtrim($saveDir, '/') . '/' . $filename;
        $imgData = @file_get_contents($fullUrl);
        if ($imgData) {
            file_put_contents($localPath, $imgData);
            $html = str_replace($imgUrl, '/' . trim($localPath, '/'), $html);
        }
    }
    return $html;
}

function getOrCreateCategory($conn, $ne, $name, $lang, $c1 = 0, $c2 = 0, $s3 = 0, $s4 = 0, $s5 = 0, $n2 = '', $n4 = '') {
    $name = addslashes(trim($name));
    if ($name == '' || $ne == '') return 0;
    $sql = " SELECT * FROM kategoriler WHERE ne='$ne' AND Cat_$lang='$name' AND c1=$c1 AND c2=$c2 AND s3=$s3 AND s4=$s4 AND s5=$s5 LIMIT 1 "; $query = mysqli_query($conn, $sql);
    if ($query && mysqli_num_rows($query) > 0) {
        $row = mysqli_fetch_assoc($query);
        return $row["Cat_ID"];
    }
    $insert = " INSERT INTO kategoriler (ne, Cat_$lang, c1, c2, s3, s4, s5, n2, n4) VALUES ('$ne', '$name', $c1, $c2, $s3, $s4, $s5, '$n2', '$n4') "; mysqli_query($conn, $insert);
    return mysqli_insert_id($conn);
}

function irep($metin){
    $metin = str_replace("'", "", $metin);
    $metin = str_replace("×", "x", $metin);
    return $metin;
}

function xls_json_decode_array($value) {
    $value = html_entity_decode(trim((string)$value), ENT_QUOTES, 'UTF-8');
    if ($value === "" || $value === "-") {
        return null;
    }
    $decoded = json_decode($value, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
        return $decoded;
    }
    return null;
}

function xls_n17_base($current) {
    $posted = array_key_exists("n17", $_POST) ? xls_json_decode_array($_POST["n17"]) : null;
    if ($posted !== null) {
        return $posted;
    }
    if (is_array($current)) {
        return $current;
    }
    $decoded = xls_json_decode_array($current);
    return ($decoded !== null) ? $decoded : array();
}

function xls_is_custom_i_field($key) {
    if (substr($key, 0, 1) != "i") {
        return false;
    }
    $blocked = array("iattr" => 1, "images" => 1, "image" => 1, "id" => 1, "ilce" => 1);
    return !isset($blocked[$key]);
}

function xls_extra_value($item, $key) {
    if (!isset($item[$key])) {
        return "";
    }
    if (is_array($item[$key])) {
        return json_encode($item[$key], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
    }
    return (string)$item[$key];
}

function xls_import_maddeli_icerik($conn, $ne, $target_id) {
    if (!array_key_exists("maddeli_icerik", $_POST)) {
        return;
    }
    $items = xls_json_decode_array($_POST["maddeli_icerik"]);
    if ($items === null || intval($target_id) <= 0) {
        return;
    }
    $target_id = intval($target_id);
    $ne = mysqli_real_escape_string($conn, $ne);
    mysqli_autocommit($conn, false);
    $ok = mysqli_query($conn, "delete from t1 where t1='" . $ne . "' and (ne='extra' or ne='' or ne is null) and s1=" . $target_id);
    foreach ($items as $item) {
        if (!$ok || !is_array($item)) {
            continue;
        }
        $t2 = mysqli_real_escape_string($conn, xls_extra_value($item, "t2"));
        $t3 = mysqli_real_escape_string($conn, xls_extra_value($item, "t3"));
        $n1 = mysqli_real_escape_string($conn, xls_extra_value($item, "n1"));
        $n2 = mysqli_real_escape_string($conn, xls_extra_value($item, "n2"));
        $n12 = mysqli_real_escape_string($conn, xls_extra_value($item, "n12"));
        $n17 = mysqli_real_escape_string($conn, xls_extra_value($item, "n17"));
        $s2 = intval(isset($item["s2"]) ? $item["s2"] : 0);
        $s7 = intval(isset($item["s7"]) ? $item["s7"] : 0);
        $s10 = intval(isset($item["s10"]) ? $item["s10"] : 0);
        $s13 = intval(isset($item["s13"]) ? $item["s13"] : 0);
        $ok = mysqli_query($conn, "insert INTO t1(t1,t2,t3,ne,n1,n2,n12,n17,s1,s2,s7,s10,s13) VALUES ('" . $ne . "', '" . $t2 . "', '" . $t3 . "', 'extra', '" . $n1 . "', '" . $n2 . "', '" . $n12 . "', '" . $n17 . "', '" . $target_id . "', '" . $s2 . "', '" . $s7 . "', '" . $s10 . "', '" . $s13 . "')");
    }
    if ($ok) {
        mysqli_commit($conn);
    } else {
        mysqli_rollback($conn);
    }
    mysqli_autocommit($conn, true);
}

if (isset($_POST["lang"])) {
    $_POST["lang"] = preg_replace('/[^a-z0-9_]/i', '', $_POST["lang"]);
    if ($_POST["lang"] == "") {
        $_POST["lang"] = $_SESSION["lang"];
    }
}

if($_GET["ne"]=="kayit"){
    if($_POST["urow"]=="t4"){
        $sorgu="and (t4='".$_POST["t4"]."' or t4='".i2a($_POST["t4"],7)."')";
    }elseif($_POST["urow"]=="t5"){
        $sorgu="and t5='".$_POST["t5"]."'";
    }elseif($_POST["urow"]=="t1"){
        $sorgu="and t1='".$_POST["t1"]."'";
    }
    $kat=explode('>',$_POST["s9"]);
    //--Kategori-->

    $xID = $yID = $zID = $wID = $jID = 0;
    $sqlk=mysqli_query($conn, "select * from ".$_SESSION["lang"]." where ne='kayit' ".$sorgu.""); $rsk=mysqli_fetch_assoc($sqlk);
    if(mysqli_num_rows($sqlk)>0){
        $sqlcx=mysqli_query($conn, "select * from kategoriler where ne='ukategori' and Cat_ID='".$rsk["s9"]."'"); $rscx=mysqli_fetch_assoc($sqlcx); $xID=$rscx["Cat_ID"];
        $sqlcy=mysqli_query($conn, "select * from kategoriler where ne='ualt_kategori' and Cat_ID='".$rsk["s10"]."'"); $rscy=mysqli_fetch_assoc($sqlcy); $yID=$rscy["Cat_ID"];
        $sqlcz=mysqli_query($conn, "select * from kategoriler where ne='ualt_kategori2' and Cat_ID='".$rsk["s11"]."'"); $rscz=mysqli_fetch_assoc($sqlcz); $zID=$rscz["Cat_ID"];
        $sqlcw=mysqli_query($conn, "select * from kategoriler where ne='ualt_kategori3' and Cat_ID='".$rsk["t12"]."'"); $rscw=mysqli_fetch_assoc($sqlcw); $wID=$rscw["Cat_ID"];
        $sqlcj=mysqli_query($conn, "select * from kategoriler where ne='ualt_kategori4' and Cat_ID='".$rsk["t13"]."'"); $rscj=mysqli_fetch_assoc($sqlcj); $jID=$rscj["Cat_ID"];
    }
    
    if ($_POST["s9"] != "" || $kat[0] != "") {
        $s9 = $kat[0] != "" ? $kat[0] : $_POST["s9"];
        $xID = getOrCreateCategory($conn, 'ukategori', $_POST["s9"], $_POST["lang"], 0, 0, 0, 0, 0, $n2, $n4);
    }
    if ($_POST["s10"] != "" || $kat[1] != "") {
        $s10 = $kat[1] != "" ? $kat[1] : $_POST["s10"];
        $yID = getOrCreateCategory($conn, 'ualt_kategori', $_POST["s10"], $_POST["lang"], $xID, 0, 0, 0, 0, $n2, $n4);
    }
    if ($_POST["s11"] != "" || $kat[2] != "") {
        $s11 = $kat[2] != "" ? $kat[2] : $_POST["s11"];
        $zID = getOrCreateCategory($conn, 'ualt_kategori2', $_POST["s11"], $_POST["lang"], $xID, $yID, 0, 0, 0, $n2, $n4);
    }
    if ($_POST["t12"] != "" || $kat[3] != "") {
        $t12 = $kat[3] != "" ? $kat[3] : $_POST["t12"];
        $wID = getOrCreateCategory($conn, 'ualt_kategori3', $_POST["t12"], $_POST["lang"], $xID, $yID, $zID, 0, 0, $n2, $n4);
    }
    if ($_POST["t13"] != "" || $kat[4] != "") {
        $t13 = $kat[4] != "" ? $kat[4] : $_POST["t13"];
        $jID = getOrCreateCategory($conn, 'ualt_kategori4', $_POST["t13"], $_POST["lang"], $xID, $yID, $zID, $wID, 0, $n2, $n4);
    }
    //--Kategori-->

    //--İşlem Sorumlusu-->
    if($_POST["s19"]<>""){
        $sqlcu=mysqli_query($conn, "select * from t5 where t1='".$_POST["s19"]."'"); $rscu=mysqli_fetch_assoc($sqlcu);
        if(mysqli_num_rows($sqlcu)==0){
            $sql = $conn->query("insert into t5 (ne,t1,s9) VALUES ('uye', '".addslashes(stripslashes($_POST["s19"]))."','1')");
            $sqlci=mysqli_query($conn, "select * from t5 order by id desc"); $rsci=mysqli_fetch_assoc($sqlci);
            $s19=$rsci["id"];
        }else{
            $s19=$rscu["id"];
        }
    }
    //--İşlem Sorumlusu-->

    if(mysqli_num_rows($sqlk)>0){
        $jsi = xls_n17_base($rsk["n17"]);
    }else{
        $jsi = xls_n17_base("");
    }
    $larr = array("ulke" => $_POST["ulke"], "sehir" => $_POST["sehir"], "ilce" => $_POST["ilce"], "semt" => $_POST["semt"], "koordinat" => $_POST["mkoordinat"], "adres" => $_POST["madres"]);
    $rjsl = json_encode($larr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
    if($_POST["ifirma"]<>""){ $iarr = $iarr + array('ictip' => 'kurumsal'); }
    foreach($_POST as $key=>$val){
        if(xls_is_custom_i_field($key)){
            $jsi = uparr($jsi, $key, $_POST[$key]);
        }
    }
    $rjsi = json_encode($jsi, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

    if(mysqli_num_rows($sqlk)==0 or $_POST["urow"]==""){
		//Yeni Kayıt ekleme
		// POST verilerini al ve varsayılanları ayarla
		$t2  = !empty($_POST["t2"]) ? $_POST["t2"] : $module["currency"];
		$t4 = trim($_POST["t4"]);
		$t5 = trim($_POST["t5"]);
		if ($t4 == "" && $t5 != "") $t4 = $t5;
		if ($t5 == "" && $t4 != "") $t5 = $t4;
		$t5 = i2a($t5, 13);
		$s4  = !empty($_POST["s4"]) ? $_POST["s4"] : $s12;
		$s5  = !empty($_POST["s5"]) ? $_POST["s5"] : 0;
		$s5  = (!empty($_POST["varyasyon"])) ? 0 : $s5; // varyasyon varsa s5 sıfırla
		$s6  = !empty($_POST["s6"]) ? $_POST["s6"] : 0;
		$pb1 = !empty($_POST["pb1"]) ? $_POST["pb1"] : 0;
		$pb2 = !empty($_POST["pb2"]) ? $_POST["pb2"] : 0;
		//$s19 = !empty($_GET["s19"]) ? $_GET["s19"] : (!empty($_SESSION["user_id"]) ? $_SESSION["user_id"] : (!empty($_SESSION["User_ID"]) ? $_SESSION["User_ID"] : 0));
		if (!empty($_GET["s19"])) {
			$s19 = $_GET["s19"];
			$s13 = 0;
		} elseif (!empty($_SESSION["user_id"])) {
			$s19 = $_SESSION["user_id"];
			$s13 = 1;
		} elseif (!empty($_SESSION["User_ID"])) {
			$s19 = $_SESSION["User_ID"];
			$s13 = 0;
		} else {
			$s19 = 0;
			$s13 = 0;
		}
		$s12 = !empty($_POST["s12"]) ? $_POST["s12"] : 0;

		// Yeni kayıt için lang1 tablosuna ekle
		$conn->query("INSERT INTO lang1 (t1,t2,t4,t5,ne,ts1,s1,s2,s4,s5,s6,pb1,pb2,s9,s10,s11,t12,t13,s12,s13,s19,n1,n2,n3,n4,n16,n17) VALUES ('".addslashes(stripslashes($_POST["t1"]))."','$t2','$t4','$t5','".$_GET["ne"]."',now(),0,0,'$s4','$s5','$s6','".sprice(trim($pb1))."','".sprice(trim($pb2))."','$xID','$yID','$zID','$wID','$jID','$s12','$s13','$s19','".addslashes(stripslashes($_POST["n1"]))."','".addslashes(stripslashes($_POST["n2"]))."','".addslashes(stripslashes($_POST["n3"]))."','".addslashes(stripslashes($_POST["n4"]))."','".addslashes(stripslashes($rjsl))."','".addslashes(stripslashes($rjsi))."')");
		$id = $conn->insert_id; // yeni kaydın ID'si
		xls_import_maddeli_icerik($conn, $_GET["ne"], $id);

		// Eğer varyasyonlar varsa JSON yapısına ekle
		$varyasyon_json = [];
		if (!empty($_POST["varyasyon"])) {
			$vs5_total = $s5;
			$varyasyonlar = explode(',', $_POST["varyasyon"]); // uv1:19.99:5,uv2:19.99:5

			foreach ($varyasyonlar as $index => $v) {
				$parcalar = explode(':', $v);
				$ad    = trim($parcalar[0] ?? "");
				$fiyat = is_numeric($parcalar[1] ?? null) ? $parcalar[1] : 0;
				$stok  = is_numeric($parcalar[2] ?? null) ? $parcalar[2] : 0;
				if ($ad === "") continue;

				$vs5_total += $stok;

				$varyasyon_json[] = [
					"id"   => $index + 1,
					"t1"   => $ad,              	// varyasyon adı
					"t2"   => $fiyat,           	// varyasyon fiyatı
					"pb1"  => $fiyat ?: $pb1, // baz fiyat
					"pb2"  => 0,
					"s5"   => $stok,      		// Stok
					"s6"   => 0,            		// Desi
					"s10"  => 0,
					"kur"  => "TRY",
					"kdv"  => 20,
					"ts1"  => date("Y-m-d H:i:s")
				];
			}

			// JSON olarak kaydet
			$json = json_encode($varyasyon_json, JSON_UNESCAPED_UNICODE);
			$conn->query("UPDATE lang1 SET n19='" . mysqli_real_escape_string($conn, $json) . "' WHERE id=$id");

			// Toplam stok değerini tüm dil tablolarına uygula
			for ($l = 1; $l <= $lx; $l++) {
				$conn->query("UPDATE lang$l SET s5='$vs5_total' WHERE id=$id");
			}
		} else {
			// Varyasyon yoksa s5 zaten tek değer
			for ($l = 1; $l <= $lx; $l++) {
				$conn->query("UPDATE lang$l SET s5='$s5' WHERE id=$id");
			}
		}

		// Eğer gerekirse t1 tablosuna da kaydet
		if (!empty($_GET["s19"])) {
			$conn->query("INSERT INTO t1(ne,s5,pb1,pb2,s13,s19,t1,t5,ts1) 
			VALUES ('post', '$s5', '".sprice(trim($pb1))."', '".sprice(trim($pb2))."', 1, '$s19', '".addslashes(stripslashes($_POST["t1"]))."', '".$_POST["t5"]."', now())");
		}

//--Kayıt Resim İşlem-->
        if($_POST["images"]<>"" and $_POST["iattr"]=="folder"){
            $i=0; $imgs = explode(',',$_POST["images"]); foreach($imgs as $img){$i++;
                $img=trim($img);
				if (empty($img)) continue; // boşsa atla
                $risim  = strtolower(cevir(irep($_POST["t1"])));
                $uzanti = explode('.',$img);
                $rand   = substr(md5(uniqid(rand())),0,10);
                $yeni   = "".$i."-".$rand.".".strtolower($uzanti[count($uzanti)-1])."";
                copy("../../../ixml/".$img."", "../../../deppo/image/".$yeni."");
                if($i==1){$s2="1";}else{$s2="0";}

                $image = new SimpleImage();
                $image->load("../../../deppo/image/".$yeni."");
                $image->resizeToWidth("".$a9."");
                $image->save("../../../deppo/image/".$yeni."");
                $image->resizeToWidth("".$a10."");
                $image->save("../../../deppo/image/k_".$yeni."");
                if ($e1==1){
                    $damga = imagecreatefrompng("../../../deppo/image/".$t50."");
                    $oyeni = imagecreatefromjpeg("../../../deppo/image/".$yeni."");
                    
                    $msag = 10;
                    $malt = 10;
                    $sx = imagesx($damga);
                    $sy = imagesy($damga);
                    
                    imagecopy($oyeni, $damga, imagesx($oyeni) - $sx - $msag, imagesy($oyeni) - $sy - $malt, 0, 0, imagesx($damga), imagesy($damga));
                    $wyeni = "../../../deppo/image/".$yeni."";
                    imagepng($oyeni, $wyeni);
                    imagedestroy($oyeni);
                }
				// WEBP dönüşümü
				if ($module["webp"] == 1) {
					towebp("k_{$yeni}", "../../../deppo/image/");
					$yeni = towebp($yeni, "../../../deppo/image/");
				}

                $conn->query("insert INTO medya (ne,s1,s2,s3,s4,t1,t3,t6,t2) VALUES ('resim', '".$id."', '".$s2."', '0', '0', '".addslashes($yeni)."', '".$_GET["ne"]."', '".$_SESSION["lang"]."', '".addslashes(stripslashes($_POST["t1"]))."')");
            }
        }elseif($_POST["images"]<>"" and $_POST["iattr"]=="sql"){   //Sanal aktarım (sadece isim transfer)
            $i=0; $imgs = explode(',',$_POST["images"]); foreach($imgs as $img){$i++;
                if($i==1){$s2="1";}else{$s2="0";}
                $conn->query("insert INTO medya (ne,s1,s2,s3,s4,t1,t3,t6,t2,s13) VALUES ('resim', '".$id."', '".$s2."', '0', '0', '".$img."', '".$_GET["ne"]."', '".$_SESSION["lang"]."', '".addslashes(stripslashes($_POST["t1"]))."', '1')");
                $img="";$yeni="";
            }

        }elseif($_POST["images"]<>"" and $_POST["iattr"]=="url"){   //Uzak aktarım (Uzak transfer)
            $i = 0;
			$imgs = explode(',', str_replace('"', '', $_POST["images"]));
			foreach ($imgs as $img) {
				$i++;
				if ($img != "") {
					$s2 = ($i == 1) ? "1" : "0";
					$img = trim($img);
					$imageString = file_get_contents($img);
					$parsedUrl = parse_url($img);
					$path = $parsedUrl['path'];
					$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
					$filename = $i . "-" . date('dmYHis') . "." . $extension;
					$savePath = "../../../deppo/image/" . $filename;
					$saveThumbPath = "../../../deppo/image/k_" . $filename;
					file_put_contents($savePath, $imageString);
					file_put_contents($saveThumbPath, $imageString);

					// WEBP dönüşümü, orijinal dosyayı değiştirme
					if ($module["webp"] == 1 && $extension != 'webp') {
						$webpFile = towebp($filename, "../../../deppo/image/"); // webp dosya döner
						if ($webpFile) $filename = $webpFile; // DB için kaydetme ismi WebP olsun
					}

					$conn->query("INSERT INTO medya (ne, s1, s2, s3, s4, t1, t3, t6, t2, s13) VALUES ('resim', '".$id."', '".$s2."', '0', '0', '".addslashes($filename)."', '".$_GET["ne"]."', '".$_SESSION["lang"]."', '".addslashes(stripslashes($_POST["t1"]))."', '1')");
				}
			}
		}
		//--Kayıt Resim İşlem-->

		//--Kayıt Dosya İşlem-->
            if($_POST["files"]<>"" and $_POST["fattr"]=="folder"){
                $i=0; $files = explode(',',$_POST["files"]); foreach($files as $file){$i++;
                    $file=trim($file);
                    $fisim  = strtolower(cevir(irep($_POST["t1"])));
                    $uzanti = explode('.',$file);
                    $rand   = substr(md5(uniqid(rand())),0,10);
                    $yeni   = "".$i."-".$rand.".".strtolower($uzanti[count($uzanti)-1])."";
                    copy("../../../import/".$file."", "../../../deppo/dosya/".$yeni."");
                    if($i==1){$s2="1";}else{$s2="0";}
                    $conn->query("insert INTO medya (ne,s1,s2,s3,s4,t1,t3,t6,t2) VALUES ('dosya', '".$id."', '".$s2."', '0', '0', '".addslashes($yeni)."', '".$_GET["ne"]."', '".$_SESSION["lang"]."', '".addslashes(stripslashes($_POST["t1"]))."')");
                }
			}elseif($_POST["files"]<>"" and $_POST["fattr"]=="sql"){    //Sanal aktarım (sadece isim transfer)
				$i=0; $files = explode(',',$_POST["files"]); foreach($files as $file){$i++;
					if($i==1){$s2="1";}else{$s2="0";}
					$conn->query("insert INTO medya (ne,s1,s2,s3,s4,t1,t3,t6,t2,s13) VALUES ('dosya', '".$id."', '".$s2."', '0', '0', '".$file."', '".$_GET["ne"]."', '".$_SESSION["lang"]."', '".addslashes(stripslashes($_POST["t1"]))."', '1')");
					$file="";$yeni="";
				}
			}
		//--Kayıt Dosya İşlem-->

		$processedHtml = downloadAndReplaceImages($_POST['n1'], "../../../imported_images", $_POST["xipath"]);
        echo '<i class="fas fa-plus text-success" title="Yeni eklendi"></i>';
        echo "<script>  jQuery(document).ready(function(){jQuery('#row".$_GET["row"]."').addClass('v3-bg-success');});</script>";

    }elseif(mysqli_num_rows($sqlk)<>0){
	//--Kayıt Güncelleme-->
        $ids = [ 's9'  => $xID, 's10' => $yID, 's11' => $zID, 't12' => $wID, 't13' => $jID, ];
        foreach ($ids as $field => $value) {
            if (!empty($value) && $value != 0) {
                mysqli_query($conn, "UPDATE {$_POST["lang"]} SET $field='$value' WHERE id={$rsk["id"]}");
            }
        }

        $fields = [ 't1' => 'addslashes', 'n1' => 'addslashes', 'n2' => 'addslashes', 'n4' => 'addslashes', 't2' => null, 'pb1' => 'sprice', 'pb2' => 'sprice', 's4' => null, 's5' => null, ];
        foreach ($fields as $field => $func) {
            if (!empty($_POST[$field])) {
                $value = $_POST[$field];
                if ($func === 'addslashes') {
                    $value = addslashes(stripslashes($value));
                } elseif ($func === 'sprice') {
                    $value = sprice($value);
                }
                mysqli_query($conn, "UPDATE {$_POST["lang"]} SET $field='$value' WHERE id={$rsk["id"]}");
            }
        }
        
        $processedHtml = downloadAndReplaceImages($_POST['n1'], "../../../imported_images", $_POST["xipath"]);
        $Sql = mysqli_query($conn, "update ".$_POST["lang"]." set n16='".addslashes(stripslashes($rjsl))."', n17='".addslashes(stripslashes($rjsi))."' where id=".$rsk["id"]."");
        xls_import_maddeli_icerik($conn, $_GET["ne"], $rsk["id"]);
        echo '<i class="fas fa-sync-alt text-info" title="Update1 > Sku:'.$rsk["t4"].' > #'.$rsk["id"].'"></i>';
        echo "<script>  jQuery(document).ready(function(){jQuery('#row".$_GET["row"]."').removeClass('v3-bg-success').addClass('v3-bg-warning');});</script>";
    }else{
        echo "<script>jQuery(document).ready(function(){jQuery('#row".$_GET["row"]."').addClass('v3-bg-warning');});</script>";
        echo '<i class="fas fa-sync-alt text-info" title="Update0 > Sku:'.$rsk["t4"].' > #'.$rsk["id"].'"></i>';
    }

}elseif($_GET["ne"]=="haber"){
    if($_POST["urow"]=="t1"){
        $sorgu="and t1='".$_POST["t1"]."'";
    }
    $kat=explode('>',$_POST["s2"]);
    //echo $sorgu;
    //--Kategori-->
        //--2.dil Kategori tespit-->
    $sqlk=mysqli_query($conn, "select * from ".$_SESSION["lang"]." where ne='kayit' ".$sorgu.""); $rsk=mysqli_fetch_assoc($sqlk);
    if(mysqli_num_rows($sqlk)>0){
        $sqlcx=mysqli_query($conn, "select * from kategoriler where ne='hkategori' and Cat_ID='".$rsk["s2"]."'"); $rscx=mysqli_fetch_assoc($sqlcx); $xID=$rscx["Cat_ID"];
    }
        //--2.dil Kategori tespit-->
    if($_POST["s2"]<>""){
        if($kat[0]<>""){$s2=$kat[0];}else{$s2=$_POST["s2"];}
        $xID = getOrCreateCategory($conn, 'hkategori', $_POST["s2"], $_POST["lang"], 0, 0, 0, 0, 0, $n2, $n4);
    }
    //--Kategori-->
    //--İşlem Sorumlusu-->
    if($_POST["s19"]<>""){
        $sqlcu=mysqli_query($conn, "select * from t5 where t1='".$_POST["s19"]."'"); $rscu=mysqli_fetch_assoc($sqlcu);
        if(mysqli_num_rows($sqlcu)==0){
            $sql = $conn->query("insert into t5 (ne,t1,s9) VALUES ('uye', '".addslashes(stripslashes($_POST["s19"]))."','1')");
            $sqlci=mysqli_query($conn, "select * from t5 order by id desc"); $rsci=mysqli_fetch_assoc($sqlci);
            $s19=$rsci["id"];
        }else{
            $s19=$rscu["id"];
        }
    }
    //--İşlem Sorumlusu-->
    if(mysqli_num_rows($sqlk)>0){
        $jsi = xls_n17_base($rsk["n17"]);
    }else{
        $jsi = xls_n17_base("");
    }
    foreach($_POST as $key=>$val){
        if(xls_is_custom_i_field($key)){
            $jsi = uparr($jsi, $key, $_POST[$key]);
        }
    }
    $rjsi = json_encode($jsi, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
    if(mysqli_num_rows($sqlk)==0 or $_POST["urow"]==""){
//--Kayıt İşlem-->
        if (!empty($_GET["s19"])) {
			$s19 = $_GET["s19"];
			$s13 = 0;
		} elseif (!empty($_SESSION["user_id"])) {
			$s19 = $_SESSION["user_id"];
			$s13 = 1;
		} elseif (!empty($_SESSION["User_ID"])) {
			$s19 = $_SESSION["User_ID"];
			$s13 = 0;
		} else {
			$s19 = 0;
			$s13 = 0;
		}
        if($xID==""){$xID=0;}
        
        $id = 0;
        for ($l = 1; $l <= $lx; $l++){
            $Sql = $conn->query("insert into lang".$l." (t1,t4,t9,ne,ts1,s2,s13,s19,n1,n2,n4,n17) values ('".addslashes(stripslashes($_POST["t1"]))."', '".$_POST["t4"]."', '".$_POST["t9"]."', '".$_GET["ne"]."', now(), '".$xID."', '0', '".$s19."', '".addslashes(stripslashes($_POST["n1"]))."','".addslashes(stripslashes($_POST["n2"]))."', '".addslashes(stripslashes($_POST["n4"]))."', '".addslashes(stripslashes($rjsi))."')");
            if ($id == 0) {
                $id = $conn->insert_id;
            }
        }
        xls_import_maddeli_icerik($conn, $_GET["ne"], $id);
        $sqlu=mysqli_query($conn, "select * from ".$_SESSION["lang"]." where ne='kayit' order by id desc"); $rsu=mysqli_fetch_assoc($sqlu);
    //--Kayıt Resim İşlem-->
        if($_POST["images"]<>"" and $_POST["iattr"]=="folder"){
            $i=0; $imgs = explode(',',$_POST["images"]); foreach($imgs as $img){$i++;
                $img=trim($img);
                $risim  = strtolower(cevir(irep($_POST["t1"])));
                $uzanti = explode('.',$img);
                $rand   = substr(md5(uniqid(rand())),0,10);
                $yeni   = "".$i."-".$rand.".".strtolower($uzanti[count($uzanti)-1])."";
                copy("../../../ixml/".$img."", "../../../deppo/image/".$yeni."");
                //copy("../../../ixml/".$img."", "../../../deppo/image/k_".$yeni."");
                if($i==1){$s2="1";}else{$s2="0";}
                
                $image = new SimpleImage();
                $image->load("../../../deppo/image/".$yeni."");
                $image->resizeToWidth("".$a9."");
                $image->save("../../../deppo/image/".$yeni."");
                $image->resizeToWidth("".$a10."");
                $image->save("../../../deppo/image/k_".$yeni."");
                if ($e1==1){
                    $damga = imagecreatefrompng("../../../deppo/image/".$t50."");
                    $oyeni = imagecreatefromjpeg("../../../deppo/image/".$yeni."");
                    
                    $msag = 10;
                    $malt = 10;
                    $sx = imagesx($damga);
                    $sy = imagesy($damga);
                    
                    imagecopy($oyeni, $damga, imagesx($oyeni) - $sx - $msag, imagesy($oyeni) - $sy - $malt, 0, 0, imagesx($damga), imagesy($damga));
                    $wyeni = "../../../deppo/image/".$yeni."";
                    imagepng($oyeni, $wyeni);
                    imagedestroy($oyeni);
                }

				// WEBP dönüşümü
				if ($module["webp"] == 1) {
					towebp("k_{$yeni}", "../../../deppo/image/");
					$yeni = towebp($yeni, "../../../deppo/image/");
				}

				$conn->query("insert INTO medya (ne,s1,s2,s3,s4,t1,t3,t6,t2) VALUES ('resim', '".$id."', '".$s2."', '0', '0', '".addslashes($yeni)."', '".$_GET["ne"]."', '".$_SESSION["lang"]."', '".addslashes(stripslashes($_POST["t1"]))."')");
            }
        }elseif($_POST["images"]<>"" and $_POST["iattr"]=="sql"){   //Sanal aktarım (sadece isim transfer)
            $i=0; $imgs = explode(',',$_POST["images"]); foreach($imgs as $img){$i++;
                if($i==1){$s2="1";}else{$s2="0";}
                $conn->query("insert INTO medya (ne,s1,s2,s3,s4,t1,t3,t6,t2,s13) VALUES ('resim', '".$id."', '".$s2."', '0', '0', '".$img."', '".$_GET["ne"]."', '".$_SESSION["lang"]."', '".addslashes(stripslashes($_POST["t1"]))."', '1')");
                $img="";$yeni="";
            }

        }elseif($_POST["images"]<>"" and $_POST["iattr"]=="url"){   //Uzak aktarım (Uzak transfer)
            $i=0; $imgs = explode(',',str_replace('"','',$_POST["images"])); foreach($imgs as $img){$i++;
                if($img<>""){
                    if($i==1){$s2="1";}else{$s2="0";}
                    $imageString = file_get_contents($img);
                    $uzanti = explode('.',$img);
                    $save = file_put_contents("../../../deppo/image/".$i."-".date('dmYHis').".".$uzanti[count($uzanti)-1]."", $imageString);
                    $save = file_put_contents("../../../deppo/image/k_".$i."-".date('dmYHis').".".$uzanti[count($uzanti)-1]."", $imageString);
                    $yeni="".$i."-".date('dmYHis').".".$uzanti[count($uzanti)-1]."";

					// WEBP dönüşümü
					if ($module["webp"] == 1) {
						towebp("k_{$yeni}", "../../../deppo/image/");
						$yeni = towebp($yeni, "../../../deppo/image/");
					}

                    $conn->query("insert INTO medya (ne,s1,s2,s3,s4,t1,t3,t6,t2,s13) VALUES ('resim', '".$id."', '".$s2."', '0', '0', '".addslashes($yeni)."', '".$_GET["ne"]."', '".$_SESSION["lang"]."', '".addslashes(stripslashes($_POST["t1"]))."', '1')");
                    $img="";$yeni="";
                }
            }
        }
    //--Kayıt Resim İşlem-->
        echo '<i class="fas fa-plus text-success" title="Yeni eklendi"></i>';
        echo "<script>  jQuery(document).ready(function(){jQuery('#row".$_GET["row"]."').addClass('v3-bg-success');});</script>";
    }elseif(mysqli_num_rows($sqlk)<>0){
        $fields = [ 't1' => 'addslashes', 'n1' => 'addslashes', 'n2' => 'addslashes', 'n4' => 'addslashes', 't2' => null, 'pb1' => 'sprice', 'pb2' => 'sprice', 's4' => null, 's5' => null, ];
        foreach ($fields as $field => $func) {
            if (!empty($_POST[$field])) {
                $value = $_POST[$field];
                if ($func === 'addslashes') {
                    $value = addslashes(stripslashes($value));
                } elseif ($func === 'sprice') {
                    $value = sprice($value);
                }
                // id'yi intval ile güvenli hale getirelim
                $id = intval($rsk["id"]);
                // Dil tablosunu güvenli hale getirmek için önlem almalısın, örnek:
                $lang = preg_replace('/[^a-z0-9_]/i', '', $_POST["lang"]);
                $sql = "UPDATE `$lang` SET `$field`='$value' WHERE id=$id";
                mysqli_query($conn, $sql);
            }
        }
        $Sql = mysqli_query($conn, "update ".$_POST["lang"]." set n17='".addslashes(stripslashes($rjsi))."' where id=".$rsk["id"]."");
        xls_import_maddeli_icerik($conn, $_GET["ne"], $rsk["id"]);
        echo '<i class="fas fa-sync-alt text-info" title="Güncellendi"  title="Update > #'.$rsk["id"].'"></i>';
        echo "<script>  jQuery(document).ready(function(){jQuery('#row".$_GET["row"]."').removeClass('v3-bg-success').addClass('v3-bg-warning');});</script>";
    }else{
        echo "<script>jQuery(document).ready(function(){jQuery('#row".$_GET["row"]."').addClass('v3-bg-warning');});</script>";
        echo '<i class="fas fa-sync-alt text-info" title="Güncellendi"  title="Update > #'.$rsk["id"].'"></i>';
    }

}elseif($_GET["ne"]=="uye"){
    if($_POST["urow"]=="t4"){
        $sorgu="and t4='".$_POST["t4"]."'";
    }elseif($_POST["urow"]=="t5"){
        $sorgu="and t5='".$_POST["t5"]."'";
    }elseif($_POST["urow"]=="t1"){
        $sorgu="and t1='".$_POST["t1"]."'";
    }elseif($_POST["urow"]=="t2"){
        $sorgu="and t2='".v3e($_POST["t2"])."'";
    }elseif($_POST["urow"]=="t13"){
        $sorgu="and t13='".$_POST["t13"]."'";
    }
    $sqluk=mysqli_query($conn, "select * from t5 where ne<>'' $sorgu"); $rsk=mysqli_fetch_assoc($sqluk); 
    if(mysqli_num_rows($sqluk)>0){
        $jsi = xls_n17_base($rsk["n17"]);
    }else{
        $jsi = xls_n17_base("");
    }
    $larr = array("ulke" => $_POST["ulke"], "sehir" => $_POST["sehir"], "ilce" => $_POST["ilce"], "semt" => $_POST["semt"], "koordinat" => $_POST["mkoordinat"], "adres" => $_POST["madres"]);
    $rjsl = json_encode($larr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
    foreach($_POST as $key=>$val){
        if($key=="ifirma" and $val<>""){
            $jsi = uparr($jsi, 'ictip', 'kurumsal');
        }
        if(xls_is_custom_i_field($key)){
            $jsi = uparr($jsi, $key, $_POST[$key]);
        }
    }
    $rjsi = json_encode($jsi, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
    //--İşlem Sorumlusu-->
    if($_POST["s19"]<>""){
        $sqlcu=mysqli_query($conn, "select * from t5 where t1='".$_POST["s19"]."'"); $rscu=mysqli_fetch_assoc($sqlcu);
        if(mysqli_num_rows($sqlcu)==0){
            $sql = $conn->query("insert into t5 (ne,t1,s9) VALUES ('uye', '".addslashes(stripslashes($_POST["s19"]))."','1')");
            $sqlci=mysqli_query($conn, "select * from t5 order by id desc"); $rsci=mysqli_fetch_assoc($sqlci);
            $s19=$rsci["id"];
        }else{
            $s19=$rscu["id"];
        }
    }
    //--İşlem Sorumlusu-->

    if($_POST["s2"]<>""){$xID = getOrCreateCategory($conn, 'kkategori', $_POST["s2"], $_POST["lang"], 0, 0, 0, 0, 0, $n2, $n4);} //--Kategori-->
    if($xID==""){ $xID="0"; }
    if($_POST["t3"]<>""){ $t3=""; }else{ $t3=base64_encode(generatePassword(6)); }
    if (!empty($_GET["s19"])) {
		$s19 = $_GET["s19"];
		$s13 = 0;
	} elseif (!empty($_SESSION["user_id"])) {
		$s19 = $_SESSION["user_id"];
		$s13 = 1;
	} elseif (!empty($_SESSION["User_ID"])) {
		$s19 = $_SESSION["User_ID"];
		$s13 = 0;
	} else {
		$s19 = 0;
		$s13 = 0;
	}

    if(mysqli_num_rows($sqluk)==0 or $_POST["urow"]==""){
        $sql = $conn->query("insert into t5 (ne,t1,t2,t3,t4,t5,t6,t7,s2,s4,s7,s19,n4,n5,n16,n17,ts1) values ('uye','".$_POST["t1"]."','".base64_encode($_POST["t2"])."', '".$t3."','".$_POST["t4"]."','".$_POST["t5"]."','".$_POST["t6"]."','".$_POST["t7"]."','".$xID."', '0', '0', '".$s19."', '".addslashes(stripslashes($_POST["n4"]))."', '".$_POST["n5"]."', '".addslashes(stripslashes($rjsl))."', '".addslashes(stripslashes($rjsi))."', now())");
        $id = $conn->insert_id;
        xls_import_maddeli_icerik($conn, $_GET["ne"], $id);
        echo '<i class="fas fa-plus text-success" title="Add > Ad Soyad:'.$rsk["t1"].' > #'.$rsk["id"].'"></i>';
        echo "<script>  jQuery(document).ready(function(){jQuery('#row".$_GET["row"]."').removeClass('v3-bg-success').addClass('v3-bg-warning');});</script>";
    }else{
        $fields = [ 't1'  => 'addslashes', 't2'  => 'base64_encode', 't3'  => 'base64_encode', 't4'  => null, 'n4'  => null, 't7'  => null, 't14' => null, 's19' => null ];
        foreach ($fields as $field => $func) {
            if (!empty($_POST[$field])) {
                $value = $_POST[$field];
                if ($func === 'addslashes') {
                    $value = addslashes(stripslashes($value));
                } elseif ($func === 'base64_encode') {
                    $value = base64_encode($value);
                }
                mysqli_query($conn, "UPDATE t5 SET $field='$value' WHERE id=" . intval($rsk["id"]));
            }
        }
        $Sql = mysqli_query($conn, "update t5 set n16='".addslashes(stripslashes($rjsl))."', n17='".addslashes(stripslashes($rjsi))."' where id=".$rsk["id"]."");
        xls_import_maddeli_icerik($conn, $_GET["ne"], $rsk["id"]);
        echo '<i class="fas fa-sync-alt text-info" title="Güncellendi"  title="Update > #'.$rsk["id"].'"></i>';
    }
}
?>
