<?php
$max_upload = ini_get('upload_max_filesize');
$max_post = ini_get('post_max_size');

function updater($ver, $path, $folders, $result = "") {
	global $conn, $cdnurl, $lx, $power, $opow1, $opow3, $opow4, $opow5, $pow1, $pow3, $pow4, $pow5, $mmail, $weburl, $cc, $arrContextOptions, $i3, $i4, $i5;

	// Zaman damgası ile dosya ismi oluştur
	$filename = date("YmdHis");

	// Uzak sunucudan zipleme isteği
	$folder_organizer = HTTPPOST("https://cloud.$cdnurl/setup/restore.php?file=$filename&folders=$folders", "");
	if(empty($folder_organizer)) return updater_result(false,"Sunucu bağlantısı başarısız. Yanıt alınamadı.",$result);
	if(preg_match('/(error|fail|hata|not found|denied|invalid)/i',$folder_organizer)) return updater_result(false,"Sunucu hata bildirdi: $folder_organizer",$result);

	// Zip dosyası yolu
	$localZip = $path . "deppo/$filename.zip";
	$sourceURL = "$i4/$filename.zip";

	// Dosya transferi
	if (!filetransfer($sourceURL, $localZip)) return updater_result(false, "Dosya Hata", $result);

	// Zip açma
	if (!class_exists('ZipArchive')) return updater_result(false, "ZipArchive bulunamadi", $result);
	$zip = new ZipArchive;
	if ($zip->open($localZip) !== TRUE) return updater_result(false, "Zip Hata", $result);
	$streamContext = stream_context_create($arrContextOptions);

	// JSON ayarlarını DB'ye yaz
	for ($l = 1; $l <= $lx; $l++) {
		$arr = isJson($power) == "1" ? 
			['company'=>$pow1,'ver'=>$ver,'web'=>$pow3,'phone'=>$pow4,'email'=>$pow5,'date'=>date("Y-m-d H:i:s")] :
			['company'=>$opow1,'ver'=>$ver,'web'=>$opow3,'phone'=>$opow4,'email'=>$opow5,'date'=>date("Y-m-d H:i:s")];
		$jset = json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
		mysqli_query($conn, "UPDATE lang$l SET n10='".mysqli_real_escape_string($conn,$jset)."' WHERE ne='ayarlar'");
	}

	// Dosyaları çıkar, BOM temizliği ve cache invalidation
	$zip->extractTo($path);
	for ($i = 0; $i < $zip->numFiles; $i++) {
		$stat = $zip->statIndex($i);
		if (substr($stat['name'], -4) === ".php") {
			$fileParts = explode("/", $stat['name']);
			$file = end($fileParts);
			$subPath = str_replace($file, "", $stat['name']);
			$original = $path.$subPath.$file;
			$temp = $path.$subPath.'_'.$file;

			if (file_exists($original)) {
				$content = @file_get_contents($original, false, $streamContext);
				if ($content === false) continue;
				if (substr($content, 0, 3) === "\xEF\xBB\xBF") $content = substr($content, 3);
				file_put_contents($temp, $content, LOCK_EX);
				unlink($original);
				rename($temp, $original);
				if (function_exists('opcache_invalidate')) opcache_invalidate($original, true);
			}
		}
	}
	$zip->close();
	unlink($localZip);
	HTTPPOST("https://cloud.$cdnurl/setup/restore.php?file=$filename&islem=delete", "");

	// Bildirim maili
	$Mesaj = "{$weburl} => CrmPlus+ {$ver} Versiyonuna Yükseltildi";
	$konu = "{$weburl} Update {$ver}";
	include("../deppo/tools/script/design.php");
	$mesaj = $design_top . $Mesaj . $design_bottom;
	emailgonder($mmail, $konu, $cc, $mesaj);

	// Çıkış
	return updater_result(true, "CrmPlus+ Güncellendi", $result);
}

// -- Yardımcı fonksiyon: result türüne göre çıktı döndürür --
function updater_result($status, $msg, $result) {
	if ($result === "true" || $result === true) {
		header('Content-Type: application/json; charset=utf-8');
		echo json_encode(["status"=>$status, "message"=>$msg], JSON_UNESCAPED_UNICODE);
	} else {
		if ($status) {
			echo '<div id="check" style="position:fixed;width:50%;margin-left:25%;margin-top:15%;font-size:24px;text-align:center">
					<i class="fa fa-check-square-o" style="color:#34a917;font-size:100px;"></i><br>'.$msg.'
				  </div>';
		} else {
			echo '<div style="color:red;text-align:center;font-size:20px;margin-top:15%;">'.$msg.'</div>';
		}
	}
	return $status;
}

function filters($filters=""){
	global $s16; global $sayfa; global $sayfa1;
	$actionReset = 'reset';
	$actionAdd = 'add';
	$actionDel = 'del';
	$filter = explode(':',$filters);
	if(!isset($_SESSION['filters']) || !is_array($_SESSION['filters']) || $filter[0]==$actionReset){ $_SESSION['filters']=array(); unset($_SESSION['filters_qry']); unset($_SESSION['filters_keys']);}
	foreach($_SESSION['filters'] as $fkey=>$fvalue){
		if($filter[0]==$actionAdd && isset($filter[1]) && $fkey==$filter[1]){
			unset($_SESSION['filters'][$filter[1]]);
		}
	}
	if($filter[0]==$actionDel && isset($filter[1])){
		unset($_SESSION['filters'][$filter[1]]);
	}
	if($filter[0]==$actionAdd && isset($filter[1])){
		if($filter[1]<>"columns" and $filter[1]<>"sort" and $filter[1]<>"items"){
			$filter_keys = explode(":",v3d($filter[1]));
			if (!empty($filter_keys[0])) {
				$_SESSION['filters']["".$filter_keys[0].""]=$filter[1];
			}
		}else{
			$_SESSION['filters'] = $_SESSION['filters'] + array($filter[1] => (isset($filter[2]) ? $filter[2] : ''));
		}
	}
	//add:color:Red
	//del:color:Red
	//reset
	//Array Filter
	//---------------------------------------------------/#Order/-------
	$sort = isset($_SESSION['filters']["sort"]) ? $_SESSION['filters']["sort"] : "";
	if($sort==""){
		$_SESSION["order"]="order by id desc";
	}elseif($sort=="ida"){
		$_SESSION["order"]="order by id asc";
	}elseif($sort=="idd"){
		$_SESSION["order"]="order by id desc";
	}elseif($sort=="t1a"){
		$_SESSION["order"]="order by t1 asc";
	}elseif($sort=="t1d"){
		$_SESSION["order"]="order by t1 desc";
	}elseif($sort=="pb1a"){
		$_SESSION["order"]="order by pb1 asc";
	}elseif($sort=="pb1d"){
		$_SESSION["order"]="order by pb1 desc";
	}elseif($sort=="bec"){
		$_SESSION["order"]="order by s14 desc";
	}elseif($sort=="bez"){
		$_SESSION["order"]="order by s14 asc";
	}
	//---------------------------------------------------/#Order/-------
	//---------------------------------------------------/#Fiyat/-------
	if(!empty($_POST)){
		unset($_SESSION['post_keys']);
		$_SESSION['filter_post_keys'] = '';
		foreach($_SESSION as $fskey=>$fsval){
			if(substr($fskey,0,12)=="filter_post_"){
				unset($_SESSION[$fskey]);
			}
		}
		foreach($_POST as $pkey=>$pval){
			if($pkey<>"min_price" and $pkey<>"max_price"){
				//echo "filter_post_".$pkey; echo $pval;
				$_SESSION["filter_post_".$pkey]=$pval;
			}
			if($pkey=="x" and $pval<>""){
				$_SESSION['filter_post_keys'] .= "and s9='".$pval."' ";
			}elseif($pkey=="y" and $pval<>""){
				$_SESSION['filter_post_keys'] .= "and s10='".$pval."' ";
			}elseif($pkey=="z" and $pval<>""){
				$_SESSION['filter_post_keys'] .= "and s11='".$pval."' ";
			}elseif(($pkey=="il" or $pkey=="ilce" or $pkey=="semt") and $pval<>""){
				$_SESSION['filter_post_keys'] .= "and n16 like '%".$pval."%' ";
			}
		}
		if(isset($_POST["min_price"]) && $_POST["min_price"]>0){
			$_SESSION["filter_post_min_price"]=$_POST["min_price"];
		}else{
			$_SESSION["filter_post_min_price"]=0;
		}
		if(isset($_POST["max_price"]) && $_POST["max_price"]>0){
			$_SESSION["filter_post_max_price"]=$_POST["max_price"];
		}else{
			$_SESSION["filter_post_max_price"]=9999999999999;
		}
		if($_SESSION['filter_post_min_price']>0 or $_SESSION['filter_post_max_price']>0){
			$_SESSION['filter_post_keys'] .= "and pb1 >= '".$_SESSION['filter_post_min_price']."' and pb1 <= '".$_SESSION['filter_post_max_price']."' ";
		}
	}
	//---------------------------------------------------/#Fiyat/-------
	if(isset($_SESSION['filters']["items"]) && $_SESSION['filters']["items"]<>""){
		$_SESSION['lsay']=trim($_SESSION['filters']["items"]);
	}else{
		$_SESSION['lsay']=$s16;
	}
	$_SESSION['filter_keys']=""; $_SESSION['filters_qry']="";
	foreach($_SESSION['filters'] as $fkey=>$fval){
		if($fkey<>"columns" and $fkey<>"sort" and $fkey<>"items"){
			$filter_keys = explode(":",v3d($fval));
			$filterValue = isset($filter_keys[3]) ? $filter_keys[3] : '';
			$filterLabel = isset($filter_keys[1]) ? $filter_keys[1] : $fkey;
			$filterText = isset($filter_keys[2]) ? $filter_keys[2] : $fval;
			$_SESSION['filters_qry'] .="and (t1 LIKE '%".$filterValue."%' or n2 LIKE '%".$filterValue."%' or n4 LIKE '%".$filterValue."%' or n17 LIKE '%".$filterValue."%') ";
			$_SESSION['filter_keys'].="<a href=\"?".$sayfa."/".$sayfa1."/del:".$fkey.":".$fval."\" class=\"filters v3-btn-success\">";
			$_SESSION['filter_keys'].="<i class=\"fa fa-remove\" style=\"\"></i>";
			$_SESSION['filter_keys'].="<span class=\"filter-content\">";
			$_SESSION['filter_keys'].="<span class=\"\">".$filterLabel.":".$filterText."</span>";
			$_SESSION['filter_keys'].="</span>";
			$_SESSION['filter_keys'].="</a>";
		}
	}
	//Print_r($_SESSION['filters_qry']);
	if(!empty($_SESSION['filters'])){
		$_SESSION['filter_keys'].="<a href=\"?".$sayfa."/".$sayfa1."/reset\" title=\"Reset Filter\" class=\"reset-filters v3-btn-danger\" style=\"\"><i class=\"fa fa-remove\"></i> ".translate("Filtreleri Temizle")." </a>";
	}
}
$arrContextOptions = array("ssl"=>array("verify_peer"=>false,"verify_peer_name"=>false));

function clonerow($table,$source_id,$modules=[],$is_main=true){
    global $conn;
    $source_id=(int)$source_id;

    // -------- MODÜL / MEDYA AYRIŞTIRMA --------
    $mediaKeys=['resim','video','dosya'];
    $media=[];$mods=[];

    foreach($modules as $k=>$v){
        if(in_array($k,$mediaKeys)) $media[$k]=1;
        else $mods[$k]=1;
    }

    // ---------------- ANA KAYIT ----------------
    $cols=[];$sel=[];
    $q=$conn->query("SHOW COLUMNS FROM `$table`"); while($c=$q->fetch_assoc()){
        if($c['Extra']=='auto_increment')continue;
        $f=$c['Field'];
        $cols[]=$f;
        if($f=='t1' && $is_main) $sel[]="CONCAT(t1,' (Kopya)')"; elseif($f=='ts1') $sel[]="NOW()"; else $sel[]=$f;
    }

    $sql="INSERT INTO `$table` (".implode(',',$cols).") SELECT ".implode(',',$sel)." FROM `$table` WHERE id=$source_id LIMIT 1";
    if(!$conn->query($sql)) return "HATA: ".$conn->error;
    $new_id=$conn->insert_id;
    $msg="<b>BAŞARILI:</b> Ana kayıt klonlandı (ID:$new_id)<br>";

    // ---------------- ALT MODÜLLER ----------------
    if(!$modules) return $msg;

    $cloneModule=function($tbl,$ne) use ($conn,$source_id,$new_id){
        $c=[];$s=[];
        $q=$conn->query("SHOW COLUMNS FROM `$tbl`"); while($r=$q->fetch_assoc()){
            if($r['Extra']=='auto_increment')continue;
            $f=$r['Field'];
            $c[]=$f;
            if($f=='s1') $s[]=$new_id; elseif($f=='ts1') $s[]="NOW()"; else $s[]=$f;
        }
        $sql="INSERT INTO `$tbl` (".implode(',',$c).") SELECT ".implode(',',$s)." FROM `$tbl` WHERE s1=$source_id AND ne='$ne'"; $conn->query($sql);
        return $conn->affected_rows;
    };

    if(!empty($modules['isayfa'])) $msg.="&nbsp;→ ".$cloneModule('t1','isayfa')." Alt Sayfa klonlandı<br>";
    if(!empty($modules['extra'])) $msg.="&nbsp;→ ".$cloneModule('t1','extra')." Maddeli İçerik klonlandı<br>";
    if(!empty($modules['recipe'])) $msg.="&nbsp;→ ".$cloneModule('genel','recipe')." Varyasyon klonlandı<br>";

    // ---------------- MEDYA ----------------
    if($media){
        $paths=['resim'=>'../deppo/image/','dosya'=>'../deppo/dosya/','video'=>'../deppo/video/'];

        $typeList="'".implode("','",array_keys($media))."'";
        $mq=$conn->query("SELECT * FROM medya WHERE s1=$source_id AND ne IN($typeList)"); $mcount=0; while($m=$mq->fetch_assoc()){
            $ne=$m['ne']; $dir=$paths[$ne];
            $uniq=time().'_'.rand(1000,9999);

            $new=$m;
            unset($new['id']);
            $new['s1']=$new_id;
            $new['ts1']=date('Y-m-d H:i:s');

            if($ne=='resim'){
                if(!file_exists($dir.$m['t1'])) continue;
                $nt1=$uniq.'_'.$m['t1'];
                copy($dir.$m['t1'],$dir.$nt1);
                copy($dir.'k_'.$m['t1'],$dir.'k_'.$nt1);
                $new['t1']=$nt1;
            }

            if($ne=='dosya'){
                if(!file_exists($dir.$m['t1'])) continue;
                $nt1=$uniq.'_'.$m['t1'];
                $nt5=$uniq.'_'.$m['t5'];
                copy($dir.$m['t1'],$dir.$nt1);
                copy($dir.$m['t5'],$dir.$nt5);
                $new['t1']=$nt1;
                $new['t5']=$nt5;
            }

            if($ne=='video'){
                if(!file_exists($dir.$m['t1'])) continue;
                $nt1=$uniq.'_'.$m['t1'];
                copy($dir.$m['t1'],$dir.$nt1);
                $new['t1']=$nt1;
            }

            $cols=array_keys($new);
            $vals=array_map([$conn,'real_escape_string'],array_values($new));
            $conn->query("INSERT INTO medya (".implode(',',$cols).") VALUES ('".implode("','",$vals)."')");
            $mcount++;
        }

        if($mcount) $msg.="→ $mcount Medya klonlandı<br>";
    }

    return $msg;
}


function GetUser($id = "", $stn = "", $qry = "") {
	$users = json_decode(GetArr("", "users", $qry), true);
	$out = "";
	if ($id != "") {
		$ids = multivalues($id);
		if (in_array("0", $ids)) $out .= '<span class="btn btn-warning btn-sm" style="padding: 2px; margin: 0px 2px; font-size: 11px;">Admin</span>';
		foreach ($users as $u) {
			if (in_array($u["id"], $ids)) {
				$out .= "<span class='btn btn-info btn-sm' style='padding: 2px; margin: 0px 2px; font-size: 11px;'>{$u[$stn]}</span>";
			}
		}
	} else {
		$out = "...";
	}
	return $out != "" ? $out : "...";
}

function GetJson($ne="",$stn="",$qry=""){
	global $weburl; global $conn; global $module;
	if($qry<>""){$qry="and ".$qry."";}
	if ($ne=="sayfa" or $ne=="haber" or $ne=="msayfa"){ $tbl=$_SESSION["lang"]; $s="s2"; $id="id";}else if ($ne=="kayit"){ $tbl=$_SESSION["lang"]; $s="s9"; $id="id";}else if ($ne=="kategori"){ $tbl="kategori"; $id="Cat_ID";}else if($ne=="isayfa" or $ne=="extra"){$tbl="t1"; $s="s2"; $id="id";}else if($ne=="uye"){$tbl="t5";  $s="s2"; $id="id";}else{$tbl=$_SESSION["lang"];  $s="s2"; $id="id";}
	$cstn = $stn;
	$stn = str_replace(",resim", "", $stn);
	$stn = str_replace(",video", "", $stn);
	$stn = str_replace(",kategori", "", $stn);
	$iarr = array();
	$cstns = explode(',',$cstn);
	$sqls = mysqli_query($conn, "select $stn from $tbl where ne='".$ne."' $qry"); while($rss=mysqli_fetch_assoc($sqls)){
		$stns = explode(',',$stn); foreach($stns as $key){
			$row_array[$key] = $rss[$key];
		}
		if (in_array("resim", $cstns)) {
			$row_array['image_src'] = medya($rss[$id],1,"kresim","t1","");
		}
		if (in_array("video", $cstns)) {
			$row_array['video_src'] = medya($rss[$id],1,"video","n1","");
			$row_array['video_image'] = medya($rss[$id],1,"video","n2","");
			$row_array['video_title'] = medya($rss[$id],1,"video","t2","");
		}
		if (in_array("kategori", $cstns)) {
			$row_array['Cat'] = kategori($rss[$s]);
		}
		array_push($iarr,$row_array);
	}
	
	return  json_encode($iarr);
}
//GetJson('kayit','id,t1,n2,s9,resim,kategori','s1=1 and s13=1 limit 0,10');		//kategori veya resim isteniyorsa id;

function GetArr($ne="", $type="", $qry="", $order="", $path="") { 
	global $weburl, $conn, $module, $cdnurl;
	$arr = array();
	$lang = $_SESSION["lang"];
	switch ($ne) { case "u": $q = "kayit"; break; case "s": $q = "sayfa"; break; case "h": $q = "haber"; break; case "m": $q = "msayfa"; break; case "n": $q = "marka"; break; case "k": $q = "uye"; break; case "r": $q = "reklam"; break; case "f": $q = "forum"; break; default:  $q = ""; break; }
	$qry          = ($qry != "") ? "AND $qry" : "";
	if ($type == "categories") {
		$sqlx = mysqli_query($conn, "SELECT ne,Cat_ID,Cat_$lang,t1,n1,c1,c2,s1,s2,s3,s4,s5 FROM kategoriler WHERE ((ne='".$ne[0]."kategori' OR ne='".$ne[0]."alt_kategori' OR ne='".$ne[0]."alt_kategori2' OR ne='".$ne[0]."alt_kategori3' OR ne='".$ne[0]."alt_kategori4') OR (t1='$q')) $qry $order"); while ($rsx = mysqli_fetch_assoc($sqlx)) { $jscx = json_decode($rsx["n1"], true);
			$arr[] = [ 'id' => $rsx["Cat_ID"], 'ne' => $rsx["ne"], 't1' => $rsx["t1"], 'c1' => $rsx["c1"], 's1' => $rsx["s1"], 'c2' => $rsx["c2"], 's2' => $rsx["s2"], 's3' => $rsx["s3"], 's4' => $rsx["s4"], 's5' => $rsx["s5"], 'item' => $jscx[$lang] != "" ? $jscx[$lang] : $rsx["Cat_$lang"] ];
		}
	} elseif ($type == "xmodules") {
		$sqlxm = mysqli_query($conn, "SELECT id,ne,n1,n2,n4,t1 FROM genel WHERE ne='xmodules' $order"); while ($rsm = mysqli_fetch_assoc($sqlxm)){
			$arr[] = [ 'id' => $rsm["id"], 'ne' => $rsm["ne"], 'type' => "xmodule", 'n2' => $rsm["n2"], 'n4' => $rsm["n4"], 'item' => $rsm["n1"]];
			$sqlx = mysqli_query($conn, "SELECT Cat_ID,Cat_$lang,t1,n1 FROM kategoriler WHERE (ne='".$rsm["n4"]."kategori' OR t1='".$rsm["n2"]."') $order"); while ($rsx = mysqli_fetch_assoc($sqlx)) {
				$jscx = json_decode($rsx["n1"], true);
				$arr[] = [ 'id' => $rsx["Cat_ID"], 'ne' => $rsx["ne"], 'type' => "category", 't1' => $rsx["t1"], 'item' => $jscx[$lang] != "" ? $jscx[$lang] : $rsx["Cat_$lang"]];
			}
			$sqlxs = mysqli_query($conn, "SELECT id,ne,t1 FROM $lang WHERE ne='".$rsm["n2"]."' AND s5=1 $order"); while ($rxs = mysqli_fetch_assoc($sqlxs)) {
				$arr[] = ['id' => $rxs["id"], 'ne' => $rxs["ne"], 'type' => "page", 'item' => $rxs["t1"]];
			}
		}
	} elseif ($type == "slide") {
		$sqli = mysqli_query($conn, "SELECT id,t1,t6,n1,n3 FROM medya WHERE ne='slide' $qry $order"); while ($rsi = mysqli_fetch_assoc($sqli)) {
			$arr[] = ['id' => $rsi["id"], 't1' => $rsi["t1"], 't6' => $rsi["t6"], 'n1' => $rsi["n1"], 'n3' => $rsi["n3"], 'item' => $rsi["t1"]];
		}
	} elseif ($type == "users") {
		$sqli = mysqli_query($conn, "SELECT id,t1,s9 FROM t5 WHERE ne<>'' $qry $order"); while ($rsu = mysqli_fetch_assoc($sqli)) {$jsi = json_decode($rsu["n17"],true);
		$arr[] = ['id' => $rsu["id"], 't1' => $rsu["t1"], 'item' => $rsu["t1"], 'json' => $jsi];
	}
} elseif ($type == "media") {
	$t1="//cdn.".$cdnurl."/images/crm-plus-stamp.png";
	$sqli = mysqli_query($conn, "SELECT id,t1,t2,t3,t4,t5,n1,n3 FROM medya WHERE ne='$ne' $qry $order"); while ($rsi = mysqli_fetch_assoc($sqli)) {
		if (mysqli_num_rows($sqli) > 0) {
			$filepath = $path."deppo/image/" . $rsi["t1"];
			if (file_exists($filepath)){
				$t1 = $weburl."/deppo/image/".$rsi["t1"];
			}

			$arr[] = [ 'id' => $rsi["id"], 't1' => $t1, 't2' => $rsi["t2"], 't3' => $rsi["t3"], 't4' => $rsi["t4"], 't5' => $rsi["t5"], 'n1' => $rsi["n1"], 'n3' => $rsi["n3"], 'item' => $rsi["t1"] ];
		} else {
			$arr[] = [ 'id'   => 0, 't1'   => $t1, 't2'   => "Resim Yok", 't3'   => '', 't4'   => '', 't5'   => '', 'n1'   => '', 'n3'   => '', 'item' => $t1 ];
		}
	}
} elseif ($type == "ads") {
	$sqli = mysqli_query($conn, "SELECT id,t1 FROM genel WHERE ne='$ne' $qry $order"); while ($rsi = mysqli_fetch_assoc($sqli)) {
		$arr[] = ['id' => $rsi["id"], 'item' => $rsi["t1"]];
	}
} else {
	$sqli = mysqli_query($conn, "SELECT id,ne,t1,t2,pb1,s5,s9,s10,ts1 FROM $lang WHERE ne='$ne' AND s13=1 $qry $order"); while ($rsi = mysqli_fetch_assoc($sqli)) {$jsi = json_decode($rsi["n17"],true);
	$arr[] = [ 'id' => $rsi["id"], 'ne' => $rsi["ne"], 't1' => $rsi["t1"], 't2' => $rsi["t2"], 'pb1' => $rsi["pb1"], 's5' => $rsi["s5"], 's9' => $rsi["s9"], 's10' => $rsi["s10"], 'ts1' => $rsi["ts1"], 'item' => $rsi["t1"], 'json' => $jsi ];
}
}
return json_encode($arr);
}

function GetAdress($coordinates=""){
	$url = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?latlng=".$coordinates."&sensor=true&key=".tanim("mkey","n1",0)."");
	$result = json_decode($url, true);
	$iarr = array();
	foreach($result["results"][0]["address_components"] as $key=>$value){
		if($value["types"][0]=="country"){
			$iarr = $iarr + array('ulke' => $value["long_name"]);
			$ulke = $value["long_name"];
		}elseif($value["types"][0]=="administrative_area_level_1"){
			$iarr = $iarr + array('sehir' => $value["long_name"]);
			$sehir = $value["long_name"];
		}elseif($value["types"][0]=="administrative_area_level_2"){
			$iarr = $iarr + array('ilce' => $value["long_name"]);
			$ilce = $value["long_name"];
		}elseif($value["types"][0]=="administrative_area_level_3"){
			$iarr = $iarr + array('semt' => $value["long_name"]);
			$semt = $value["long_name"];
		}elseif($value["types"][0]=="postal_code"){
			$iarr = $iarr + array('posta_kodu' => $value["long_name"]);
			$posta_kodu = $value["long_name"];
		}
	}
	$iarr = $iarr + array('adres' => "".$result["results"][0]["formatted_address"]."");
	$rjsi = json_encode($iarr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
	return $rjsi;
}

function GetCoordinate($adress=""){
	$url = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address=".$adress."&sensor=true&key=".tanim("mkey","n1",0)."");
	$result = json_decode($url, true);
	$iarr = array();
	$iarr = $iarr + array('lat' => $result["results"][0]["geometry"]["location"]["lat"]);
	$iarr = $iarr + array('lng' => $result["results"][0]["geometry"]["location"]["lng"]);
	$rjsi = json_encode($iarr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
	return $rjsi;
}

function getinfo(){
	global $weburl; global $conn; global $module;
	$userId	=	$_SESSION["User_ID"];
	$json	= "".$_SERVER['DOCUMENT_ROOT']."/deppo/datas/infos.json"; 
	if (!file_exists("".$_SERVER['DOCUMENT_ROOT']."/deppo/datas")) {
		mkdir("".$_SERVER['DOCUMENT_ROOT']."/deppo/datas", 0755, true);
	}
	if(!file_exists($json)){
		$create = fopen($json, 'w') or die("Err sd".__LINE__."");
		fclose($create);
	}
	$result	= file_get_contents($json);
	$datas	= json_decode($result, true);
	$jset		= array();
	foreach($datas as $key=>$value){
		if ($value[UserIp]==$_SERVER['REMOTE_ADDR'] and $value[Url]==$_SERVER['REQUEST_URI']) {
			$jset = $jset + array($value => $gvalue);
		}else{
			$jset = $jset + array($key => $value);
			$pcontrol=0;
		}
	}
	if($pcontrol==0){
		$arr_new[id] = date("YmdHis");
		$arr_new[UserId] = $userId;
		$arr_new[UserIp] = $_SERVER['REMOTE_ADDR'];
		$arr_new[Url] = $_SERVER['REQUEST_URI'];
		$arr_new[Date] = date('Y-m-d H:i:s');
		array_push($jset,$arr_new);
	}
	$data = json_encode($jset, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
	$fp	  = fopen($json, 'w');
	fwrite($fp, $data);
	fclose($fp);
}

function multivalues($id){
    if (empty($id)) return [];

    $results = [];

    // 1. Durum: {2},{26} formatındaki tüm değerleri yakala
    if (preg_match_all('/\{(\d+)\}/', $id, $matches)) {
        $results = $matches[1];
    } 
    
    // 2. Durum: Eğer format eşleşmediyse ve değer sadece sayıysa (örn: "18")
    if (empty($results) && is_numeric($id)) {
        $results[] = (string)$id;
    }

    return $results; // Çıktı her zaman bir array olur: ["18"] veya ["2", "26"]
}

function basket($id,$qty){
	if($id=="0" and $qty=="0"){$_SESSION["jbasket"]="";}
	global $conn;
	$sql = mysqli_query($conn, "select * FROM ".$_SESSION['lang']." where ne='kayit' and id=".$id.""); $rs=mysqli_fetch_assoc($sql);
	if($_SESSION["jbasket"]==""){
		$datas = array();
	}else{
		$result	= $_SESSION["jbasket"];
		$datas	= json_decode($result, true);
	}
	$jset = array();
	foreach($datas as $key=>$val){
		if ($val[id]==$id){	//qty
			$jset = $jset + array("qty" => $qty);
		}else{
			if($val<>0){
				$jset = $jset + array($key => $val);
			}
			$ichck=0;
		}
	}
	if($ichck==0 and $qty>0){
		$arr_new[id] = $id;
		$arr_new[ProductCode] = $rs["t4"];
		$arr_new[Product] = $rs["t1"];
		$arr_new[Qty] = $qty;
		$arr_new[ProductImg] = medya($rs["id"],1,"resim","t1", $weburl);
		$arr_new[Date] = date('Y-m-d H:i:s');
		array_push($jset,$arr_new);
	}
	$data = json_encode($jset, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
	$_SESSION["jbasket"]=$data;
}
//basket(0,0); //=>empty
//basket(4097,0); //=>del
//basket(4097,1); //=>Add/Update

function setdata($process="", $eventId="", $gname="", $gvalue="", $path=""){
	global $weburl; global $conn; global $module;
	$eventIds = explode(",",$eventId);
	if($eventIds[1]<>""){$eventId=$eventIds[1]; $eventgId=$eventIds[0];}else{$eventId=$eventIds[0]; $eventgId="0";}
	$userId=	$_SESSION["User_ID"];
	$json	= "".$_SERVER['DOCUMENT_ROOT']."/deppo/datas/data.json"; 
	if (!file_exists("".$_SERVER['DOCUMENT_ROOT']."/deppo/datas")) {
		mkdir("".$_SERVER['DOCUMENT_ROOT']."/deppo/datas", 0755, true);
	}
	if(!file_exists($json)){
		$create = fopen($file, 'w') or die("Err sd".__LINE__."");
		fclose($create);
	}
	$result	= file_get_contents($json);
	$datas	= json_decode($result, true);
	$jset		= array();
	foreach($datas as $key=>$value){
		if ($value[UserId]==$userId and $value[Process]==$process and $value[EventId]==$eventId) {
			$jset = $jset + array($value => $gvalue);
		}else{
			$jset = $jset + array($key => $value);
			$pcontrol=0;
		}
	}
	if($pcontrol==0){
		$arr_new[id] = date("YmdHis");
		$arr_new[UserId] = $userId;
		$arr_new[Process] = $process;
		$arr_new[EventId] = $eventId;
		$arr_new[Name] = $gname;
		$arr_new[Value] = $gvalue;
		$arr_new[Date] = date('Y-m-d H:i:s');
		array_push($jset,$arr_new);
	}
	$data = json_encode($jset, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
	$fp	  = fopen($json, 'w');
	fwrite($fp, $data);
	fclose($fp);
}

function getdata(){
	global $weburl; global $jsf; $weburl=uri("domain");
	if($jsf==""){$jsf="data";}
	$json	= "".$_SERVER['DOCUMENT_ROOT']."/deppo/datas/".$jsf.".json";
	$result	= file_get_contents($json);
	$datas	= json_decode($result, true);
	$jset		= array();
	foreach($datas as $key=>$value){
		if ($value[UserId]==$_SESSION["User_ID"] or $value[UserId]==$_SESSION["user_id"] or $_SESSION["user_id"]==0) {
			$jset = $jset + array($key => $value);
		}
	}
	$data = json_encode($jset, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
	return $jset;
}

function deldata($id=""){
	$weburl=uri("domain");
	$json	= "".$_SERVER['DOCUMENT_ROOT']."/deppo/datas/data.json"; 
	$result	= file_get_contents($json);
	$datas	= json_decode($result, true);
	$jset		= array();
	foreach($datas as $key=>$value){
		if($value[id]<>$id){
			$jset = $jset + array( $key => $value);
		}
	}
	$data = json_encode($jset, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
	$fp	  = fopen($json, 'w');
	fwrite($fp, $data);
	fclose($fp);
}

function ccMasking($number='') {
	return substr($number, 0, 4)." ".substr($number, 4, 4)." ".substr($number, 8, 4)." ".substr($number, 12, 4);
}

function uparr($arr="", $ukey="", $uval=""){
	if(is_array($arr)<>1){ $arr = json_decode($arr, true); $type="json"; }else{ $type="array"; }	//Array vs Json
	$iarr = array();
	foreach ($arr as $key => $value){
		if($key==$ukey){	//update
			$iarr = $iarr + array($key => $uval);
		}else{
			$iarr = $iarr + array($key => $value);
		}
		if(isset($ukey)){
			$iarr = $iarr + array($ukey => $uval); //insert
		}
	}
	if(isset($ukey) and is_array($jsi)<>1){
		$iarr = $iarr + array($ukey => $uval); //insert
	}
	if($type=="json"){ $result = json_encode($iarr, true); }else{ $result = $iarr; } 						//Array vs Json
	return $result;
}

function setcard($path="", $userId=""){
	global $weburl; global $conn;
	if($userId==""){$userId=$_SESSION["User_ID"];}
	$sqlu = mysqli_query($conn, "select * from t5 where id='".$userId."'"); $user = mysqli_fetch_assoc($sqlu);
	$json  = "".$_SERVER['DOCUMENT_ROOT']."/deppo/card/cards.json";
	if (!file_exists("".$_SERVER['DOCUMENT_ROOT']."/deppo/card")) {
		mkdir("".$_SERVER['DOCUMENT_ROOT']."/deppo/card", 0755, true);
	}
	if(!file_exists("".$_SERVER['DOCUMENT_ROOT']."/deppo/card/cards.json")){
		$create = fopen($json, 'w') or die("Err sc".__LINE__."");
		fclose($create);
	}
	$result	= file_get_contents($json);
	$cards	= json_decode($result, true);
	$jset		= array();
	foreach($cards as $key=>$value){
		if ($value[UserId]==$userId) { $control=1; }
		$jset = $jset + array($key => $value);
	}
	if($control<>1 and $userId<>""){
		$arr_new[UserId] = $userId;
		$arr_new[Number] = generatenumber(16);
		$arr_new[Name] = $user["t1"];
		$arr_new[Date] = date('Y-m-d');
		array_push($jset,$arr_new);
		$data = json_encode($jset, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
		$fp	  = fopen($json, 'w');
		fwrite($fp, $data);
		fclose($fp);
	}
}

function getcard($data="", $userId=""){
	global $weburl;
	if($userId==""){$userId=$_SESSION["User_ID"];}
	if($data==""){$data="Number";}
	$json		= "".$_SERVER['DOCUMENT_ROOT']."/deppo/card/cards.json";
	$result	= file_get_contents($json);
	$cards	= json_decode($result, true);
	$jset		= array();
	foreach($cards as $key=>$value){
		if ($value[UserId]==$userId) { $result=$value[$data]; }
	}
	return ccMasking($result);
}

function setpoint($process="", $eventId="", $userId="", $url=""){
	setcard($path,$userId); global $conn; global $module;
	$processes = explode(",",$process); if($processes[1]<>""){$process=$processes[1]; $point=$processes[0];}
	$eventIds = explode(",",$eventId); if($eventIds[1]<>""){$eventId=$eventIds[1]; $eventgId=$eventIds[0];}else{$eventgId="0";}
	$userIds = explode(",",$userId); if($userIds[1]<>""){$userId=$userIds[1]; $usergId=$userIds[0];}else{$usergId="0";}
	$sqlp = mysqli_query($conn, "select * from genel where ne='point' and t2='".$process."'"); $rsp = mysqli_fetch_assoc($sqlp);
	$sqle = mysqli_query($conn, "select * from ".$_SESSION["lang"]." where ne='haber' and id='".$eventId."' "); $rse = mysqli_fetch_assoc($sqle); $jsei = json_decode($rse["n17"],true);
	if($url<>""){$url="".$url."/";}else{$url=$_SERVER['DOCUMENT_ROOT'];}
	if($userId==""){$userId=$_SESSION["User_ID"];}
	$json  = "".$url."/deppo/card/points.json";
	if (!file_exists("".$url."/deppo/card")) {
		mkdir("".$url."/deppo/card", 0755, true);
	}
	if(!file_exists("".$url."/deppo/card/points.json")){
		$create = fopen($json, 'w') or die("Err sp".__LINE__."");
		fclose($create);
	}
	$result	= file_get_contents($json);
	$points	= json_decode($result, true);
	$jset		= array();
	if($process<>"events"){
		$point_type=$rsp["s2"];
		if($point==""){ $point=$rsp["t1"]; $process = $rsp["n1"]; }
	}else{
		$point_type=$jsei["ievent_point_type"];
		if($point==""){ $point=$jsei["ievent_point"]; $process = $rse["t1"]; }
	}
	foreach($points as $key=>$value){
		if(mysqli_num_rows($sqlp)>0 and $point_type==0){
			if ($value[UserId]==$userId and $value[EventId]==$eventId or $point<0) { $pcontrol=1; }
		}elseif(mysqli_num_rows($sqlp)>0 and $point_type==1){
			if ($value[UserId]==$userId and $value[EventId]==$eventId and $value[Date]==date('Y-m-d')) { $pcontrol=1; }
		}
		$jset = $jset + array($key => $value);
		if ($value[UserId]==$userId and $value[Date]==date('Y-m-d') and ($value[Desc]==$process or substr($value[Desc],0,11)=='Etkinlik_ID')) { $total_point=$total_point+$value[Point];}
	}
	if(mysqli_num_rows($sqlp)==0 and ($point==0 or $point=="")){$pcontrol=1;}
	if(($module["point_limit"]=="" or ($module["point_limit"]<>"" and $module["point_limit"] >= ($total_point+$point))) and ($rsp["t3"]=="" or ($rsp["t3"]<>"" and $rsp["t3"] >= ($total_point+$point)))){ $pass=1; }
	if($pass<>1){
		echo "
		<script type=\"text/javascript\">
		jQuery(document).ready(function(){
			jQuery('#v3-notification').html('".translate("Günlük puan limitine ulaştığınız için, <br>puan alamadınız")."');
			stime('#v3-notification', 'show', '3200');
			});
			</script>
			";
/*
		}else{
			echo "
				<script type=\"text/javascript\">
				jQuery(document).ready(function(){
						jQuery('#v3-notification').html('".$point." ".translate("Puan Kazandınız")."');
						stime('#v3-notification', 'show', '3200');
				});
				</script>
			";
*/
		}
		if($pcontrol<>1){
			$arr_new[Id] = date("ymdhis");
			$arr_new[EventgId] = $eventgId;
			$arr_new[EventId] = $eventId;
			$arr_new[UsergId] = $usergId;
			$arr_new[UserId] = $userId;
			$arr_new[Point] = $point;
			$arr_new[Desc] = $process;
			$arr_new[Date] = date('Y-m-d');
			array_push($jset,$arr_new);
			$data = json_encode($jset, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
			$fp	 = fopen($json, 'w');
			fwrite($fp, $data);
			fclose($fp);
		}
	}

	function delpoint($id="", $url=""){
		if($url<>""){$url="".$url."/";}else{$url=$_SERVER['DOCUMENT_ROOT'];}
		$json	= "".$url."/deppo/card/points.json"; 
		$result	= file_get_contents($json);
		$datas	= json_decode($result, true);
		$jset		= array();
		foreach($datas as $key=>$value){
			if($value[Id]<>$id){
				$jset = $jset + array( $key => $value);
			}
		}
		$data = json_encode($jset, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
		$fp	  = fopen($json, 'w');
		fwrite($fp, $data);
		fclose($fp);
	}

	function getpoint($userId="", $type="", $url=""){
		global $weburl;
		if($userId==""){$userId=$_SESSION["User_ID"];}
		$json	= "".$weburl."/deppo/card/points.json"; 
		$result	= file_get_contents($json);
		$points	= json_decode($result, true);
		$jset		= array();
		
		foreach($points as $key=>$value){
			if ($value[UserId]==$userId and $userId<>0){
				$point=$point+$value[Point];
				$jset = $jset + array($key => $value);
			}elseif ($userId==0){
				$point=$point+$value[Point];
				$jset = $jset + array($key => $value);
			}
		}
		$list = json_encode($jset, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
		if($type==""){$result=$point;}else{$result=$list;}
		return $result;
	}

	function parapuan($ne="", $ID=""){
		global $conn; global $module;
		if($ID<>""){$ID=$ID;}else{$ID=$_SESSION["User_ID"];}
		$sqlp = mysqli_query($conn, "select t1 from genel where ne='point' and t2='".$ne."'"); $point = mysqli_fetch_assoc($sqlp);
		$sqlu = mysqli_query($conn, "select s11 from t5 where id='".$ID."'"); $user = mysqli_fetch_assoc($sqlu);
		if(mysqli_num_rows($sqlp)>0){
			$upuan=$user["s11"]+$point["t1"];
			$sql = mysqli_query($conn, "update t5 set s11='".$upuan."' where id=".$ID."");
		}
	}

	function hediyeceki($ne="", $ID=""){
//$_SESSION["Order_Total_Tax"]
		global $conn; global $module;
		if($ID<>""){$ID=$ID;}else{$ID=$_SESSION["User_ID"];}
		if($ne=="tavsiye"){$s2="3";}elseif($ne=="kayit"){$s2="2";}elseif($ne=="siparis"){$s2="4";}
		if($module["hediye_ceki"]==1){
			$sqld = mysqli_query($conn, "select t2,pb1,pb2,s1,s2,s3,ts2 from genel where ne='i-kod' and s2=".$s2.""); $dcode = mysqli_fetch_assoc($sqld);
			$sqlco = mysqli_query($conn, "select id from eticaret where ne='siparis' and t6='".$dcode["t1"]."' and s1='".$_SESSION["s19"]."'"); $corder = mysqli_fetch_assoc($sqlco);
			$sqlcc = mysqli_query($conn, "select id from genel where ne='i-kod' and s2=4 and s19='".$ID."'"); $ccode = mysqli_fetch_assoc($sqlcc);
			if(mysqli_num_rows($sqld)<>0 and ((mysqli_num_rows($sqlco)==0 and $s2==4 and mysqli_num_rows($sqlcc)==0) or $s2<>4)){
				$sql = $conn->query("insert into genel(ne,t1,t3,pb1,pb2,s1,s2,s3,s19,ts1,ts2) values ('i-kod', '".generateSPassword(8)."', 'autocreate', '".$dcode["pb1"]."', '".$dcode["pb2"]."', '".$dcode["s1"]."', '".$dcode["s2"]."', '".$dcode["s3"]."', '".$ID."', now(), '".$dcode["ts2"]."')");
			}
		}
	}
	function folderSize($directory){
		$size = 0;
		foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
			$size += $file->getSize();
		}
		if($size<1024){$size=$size." Bytes";}
		elseif(($size<1048576)&&($size>1023)){$size=round($size/1024, 1)." KB";}
		elseif(($size<1073741824)&&($size>1048575)){$size=round($size/1048576, 1)." MB";}
		else{$size=round($size/1073741824, 1)." GB";}
		return $size;
	}
// Klasör varlığını kontrol eden fonksiyon

	function findDirectoryPath($directoryName) {
		$path = "";
		for ($i = 0; $i < 5; $i++) {
			if (is_dir($path . $directoryName)) {
				return $path.$directoryName;
			}
			$path .= "../";
		}
		return $path;
	}
	function extract_file($file_path, $to_path = "./"){
		$file_type = substr($file_path, strrpos($file_path, '.') - strlen($file_path) + 1);
		if ("zip" === $file_type) {
			$xmlZip = new ZipArchive();
			if ($xmlZip->open(__DIR__."/xml.zip") === true) {
				$xmlZip->extractTo($to_path);
				echo "extract success";
			} else {
				echo "extract fail";
				return false;
			}
		} elseif ("rar" == $file_type) {
			$rar_file = rar_open($file_path) or die("Err ef".__LINE__."");
			$entries = rar_list($rar_file);
			if ($entries) {
				foreach ($entries as $entry) {
					echo 'Filename: ' . $entry->getName() . "\n";
					$entry->extract($to_path);
				}
				rar_close($rar_file);
			} else{
				echo "extract fail";
				return false;
			}
		}
	}

	function tanim($t2 = "", $stn = "", $no = "", $n5 = "") {
		global $conn; static $cache = []; $n4 = "";
		if (isset($cache[$t2][$stn][$no][$n5])) {
			return $cache[$t2][$stn][$no][$n5]; // Eğer cache'de varsa, önceden döndürülmüş değeri döndür
		}
		
		// '+' ile bölme işlemi ve adres düzenleme
		$st2 = explode("+", $t2); $t2 = $st2[0];
		$adres = str_replace("www.", "", $_SERVER['SERVER_NAME']);
		
		// Koşulların belirlenmesi
		if (in_array($t2, ["analytics", "dogrula", "sms", "email", "mkey", "App"])) { $n4 = " AND (n4='' OR n4='" . $adres . "' OR n4='all')"; }
		if (in_array($t2, ["pay", "sp"])) { $tsql = " AND (n4='" . $st2[1] . "')"; }		
		if ($n5 != "") { $tsql .= " AND (n5='" . $n5 . "')"; } else { $s10 = " AND s10='" . $no . "'"; }
		
		// Sorguyu optimize etme: Tek bir sorguda öncelikli kontrol
		$query = "SELECT * FROM genel WHERE ne='tanim' AND t2='" . $t2 . "' $tsql $n4 $s10 ORDER BY id ASC LIMIT 1";
		$sqld = mysqli_query($conn, $query);
		
		if (mysqli_num_rows($sqld) > 0) {
			$rsd = mysqli_fetch_assoc($sqld);
			// Veriyi base64 decode etme veya olduğu gibi alma
			$tanim = ($stn == "n1" || $stn == "n2") ? base64_decode($rsd[$stn]) : $rsd[$stn];
		} else {
			// Alternatif sorgu: fallback durumu
			$query_fallback = "SELECT * FROM genel WHERE ne='tanim' AND t2='" . $t2 . "' AND (n5='all' OR n5='') $n4 $s10 ORDER BY id ASC LIMIT 1"; $sqldf = mysqli_query($conn, $query_fallback); $rsdf = mysqli_fetch_assoc($sqldf);
			// Veriyi base64 decode etme veya olduğu gibi alma
			$tanim = ($stn == "n1" || $stn == "n2") ? base64_decode($rsdf[$stn]) : $rsdf[$stn];
		}
		
		// Cache'e kaydetme
		$cache[$t2][$stn][$no][$n5] = $tanim;
		return $tanim;
	}

function reviews($clear = false){
	global $sayfa, $id;
	$review_cookie_name = "review_" . $_SESSION["User_ID"];
	if ($clear) {
		setcookie($review_cookie_name, '', time() - 3600, "/");
		return ["status" => "cleared"];
	}
	if (!empty($_SESSION["User_ID"]) && $sayfa[0] == "d"){
		$review_data = isset($_COOKIE[$review_cookie_name]) ? json_decode($_COOKIE[$review_cookie_name], true) : [];
		if (!is_array($review_data)){ $review_data = []; }
		if (!in_array($id, $review_data)) {$review_data[] = $id;}
		setcookie($review_cookie_name, json_encode($review_data), time() + 604800, "/");
		return ["status" => "updated", "data" => $review_data];
	}
	
	return ["status" => "no_action"];
}

function set_cookies($name, $values, $days) {
	if (empty($values)) {
		setcookie($name, "", time() - 3600, "/");
        return; // Daha fazla işlem yapma
    }
    $expiry = time() + ($days * 24 * 60 * 60); // Gün bazlı süre
    $value = json_encode($values); // Veriyi JSON formatında sakla
    setcookie($name, $value, $expiry, "/");
}

function publisher(){
	global $conn; $i=0;
	$sqlp=mysqli_query($conn, "select * from ".$_SESSION["lang"]." where s13=0"); while($rsp=mysqli_fetch_assoc($sqlp)){
		if($rsp["ts3"]<>"" and $rsp["ts3"]<>"0000-00-00 00:00:00" and $rsp["ne"]=="haber"){$i++;}
		if($rsp["ts3"]<>"" and $rsp["ts3"]<>"0000-00-00 00:00:00" and $rsp["ts3"]<=date("Y-m-d H:i:s")){
			$Rs = mysqli_query($conn, "update ".$_SESSION["lang"]." set s13='1' where id=".$rsp["id"]."");
		}
	}
	return $i;
}

function publish_date($date){
	if(date("l",(strtotime ($date)))=="Tuesday"){
		$pdate=date("Y-m-d",strtotime('friday this week', strtotime($date)));
	}elseif(date("l",(strtotime ($date)))=="Friday"){
		$pdate=date("Y-m-d",strtotime('tuesday next week', strtotime($date)));
	}elseif(date("l",(strtotime ($date)))=="Monday"){
		$pdate=date("Y-m-d",strtotime('thursday this week', strtotime($date)));
	}elseif(date("l",(strtotime ($date)))=="Thursday"){
		$pdate=date("Y-m-d",strtotime('monday next week', strtotime($date)));
	}elseif(date("l",(strtotime ($date)))=="Wednesday"){
		$pdate=date("Y-m-d",strtotime('saturday this week', strtotime($date)));
	}elseif(date("l",(strtotime ($date)))=="Saturday"){
		$pdate=date("Y-m-d",strtotime('wednesday next week', strtotime($date)));
	}elseif(date("l",(strtotime ($date)))=="Sunday"){
		$pdate=date("Y-m-d",strtotime('wednesday next week', strtotime($date)));
	}
	return $pdate;
}

function publish_date_viewer($ts1, $ts3) {
	$today = date("Y-m-d");
	if (!empty($ts3) && $ts3 != "0000-00-00 00:00:00" && $ts3 != NULL) {
		$ts3_date = date("Y-m-d", strtotime($ts3));
		if ($ts3_date <= $today) {
				$pdc = "bg-success"; // Bugün veya geçmiş tarih
			} else {
				$pdc = "bg-warning"; // Gelecek tarih
			}
			$pdate = dtarih($ts3, "gg ka yy"); // Yayın tarihi
		} else {
			$pdc = "bg-info"; // Yayın tarihi yoksa, eklenme tarihi gösterilecek
			$pdate = dtarih($ts1, "gg ka yy"); // Eklenme tarihi
		}
		return [
			'class' => $pdc,
			'formattedDate' => $pdate
		];
	}

	function csablon($metin){
		foreach ($_POST as $key => $value){
			$metin = str_replace("{".$key."}", $value, $metin);
		}
		foreach ($_SESSION as $key => $value){
			$metin = str_replace("{".$key."}", $value, $metin);
		}
		return $metin;
	}

	function sablon($id){
		global $conn;
		$sql_temp=mysqli_query($conn, "select * from genel where id='".$id."'"); $rs_temp=mysqli_fetch_assoc($sql_temp);
		if(mysqli_num_rows($sql_temp)>0){
			$design_top		= $rs_temp["n7"];
			$design_main	= $rs_temp["n1"];
			$design_bottom = $rs_temp["n6"];
			$mgonderen		= $rs_temp["t10"];
			$gonderen		= $rs_temp["t11"];
		}
		$mesaj = $design_top_temp.$design_top.$design_main.$design_bottom.$design_bottom_temp;
		return csablon($mesaj);
	}
//sablon($id,$mesaj); => post edilen verileri {t1} gibi kullanabilirsin

	function emailgonder($malici="", $konu="", $cc="", $mesaj="", $ne="noreply"){
		global $conn; global $mgonderen; global $path; global $firma; global $sunucu; global $mail; global $msifre; global $c4; global $cpath;
		$sqlk=mysqli_query($conn, "select id from genel where ne='unsubscribe' and t1='".$malici."'"); $rsk=mysqli_fetch_assoc($sqlk);
		if(mysqli_num_rows($sqlk)==0){
			if($mgonderen==""){$mgonderen=tanim("email","n1",0,''); $msifre=tanim("email","n2",0,''); $sunucu=tanim("email","n3",0,'');}
			if($malici==""){$malici=tanim("email","n1",0,$ne);}
		//echo "ma:".$malici." mg:".$mgonderen." si:".$msifre." su:".$sunucu."";
		//$mesaj .="<br><center><a href=\"".surl("http://".$_SERVER['SERVER_NAME']."/unsubscribe/".$malici."")."\">".translate("Listeden Çık")."</a></center>";
			$mesaj = str_replace("{malici}",base64_encode($malici),$mesaj);
			include("mail/index.php");
		}else{
			echo "Unsubscribed";
		}
	}

	function isJson($string){
		json_decode($string);
		return json_last_error() === JSON_ERROR_NONE;
	}

	function string_to_float($string) {
		//$float_val = str_replace(array('.', ','), array('', '.'), $string);
		//return floatval($float_val);
		return (float) str_replace(",", ".", $string);
	}

	function smsgonder($smstxt="", $gsm=""){
		global $conn;
		$sqlk=mysqli_query($conn, "select id from genel where ne='unsubscribe' and t1='".$gsm."'"); $rsk=mysqli_fetch_assoc($sqlk);
		if(mysqli_num_rows($sqlk)==0){
		//$smstxt .=" Listeden Çık => ".surl("http://".$_SERVER['SERVER_NAME']."/unsubscribe/".$gsm."")."";
			if(tanim("sms","n6",0)=="netgsm"){
				$startdate=date('d.m.Y H:i');
				$startdate=str_replace('.', '',$startdate);
				$startdate=str_replace(':', '',$startdate);
				$startdate=str_replace(' ', '',$startdate);
				$stopdate=date('d.m.Y H:i', strtotime('+1 day'));
				$stopdate=str_replace('.', '',$stopdate);
				$stopdate=str_replace(':', '',$stopdate);
				$stopdate=str_replace(' ', '',$stopdate);
				HTTPPOST("http://api.netgsm.com.tr/bulkhttppost.asp?usercode=".tanim("sms","n1",0)."&password=".tanim("sms","n2",0)."&gsmno=".$gsm."&message=".urlencode($smstxt)."&msgheader=".tanim("sms","n3",0)."&startdate=".$startdate."&stopdate=".$stopdate."");
			}elseif(tanim("sms","n6",0)=="smsvitrini"){
				echo HTTPPOST("http://api.smsvitrini.com/index.php", "islem=1&user=".tanim("sms","n1",0)."&pass=".tanim("sms","n2",0)."&mesaj=".$smstxt."&numaralar=".telefon($gsm)."&baslik=".tanim("sms","n3",0)."");
			}elseif(tanim("sms","n6",0)=="iletimerkezi"){
				function sendRequest($url, $xml) {
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLOPT_POST, 1);
					curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
					curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
					curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
					curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-Type: text/xml');
					curl_setopt($ch, CURLOPT_HEADER, 0);
					curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
					curl_setopt($ch, CURLOPT_TIMEOUT, 120);
					return curl_exec($ch);
				}
				$api_key = tanim("sms","n1",0);
				$api_hash = tanim("sms","n2",0);
				$sender   = tanim("sms","n3",0);
				$xml = <<<EOS
				<request>
				<authentication>
				<key>{$api_key}</key>
				<hash>{$api_hash}</hash>
				</authentication>
				<order>
				<sender>{$sender}</sender>
				<sendDateTime></sendDateTime>
				<message>
				<text><![CDATA[$smstxt]]></text>
				<receipents>
				<number>".telefon($gsm)."</number>
				</receipents>
				</message>
				</order>
				</request>
				EOS;
				$result = sendRequest('http://api.iletimerkezi.com/v1/send-sms', $xml);
			}elseif(tanim("sms","n6",0)=="asist"){
				$keys = explode(',',tanim("sms","n5",0));
				ini_set('soap.wsdl_cache_enabled', 0);
				ini_set('soap.wsdl_cache_ttl', 900);
				ini_set('default_socket_timeout', 15);
				$params = array(
					'Username'=>tanim("sms","n1",0),
					'Password'=>tanim("sms","n2",0),
					'UserCode'=>$keys[0],
					'AccountId'=>$keys[1],
					'Originator'=>tanim("sms","n3",0),
					'SendDate' => '',
					'ValidityPeriod'=> 60,
					'MessageText'=>''.$smstxt.'',
					'IsCheckBlackList'=>'1',
					'ReceiverList'=>[''.$gsm.'',],
				);
				$wsdl = 'https://webservice.asistiletisim.com.tr/SmsProxy.asmx?WSDL';
				$options = array(
					'uri'=>'http://schemas.xmlsoap.org/soap/envelope',
					'style'=>SOAP_RPC,
					'use'=>SOAP_ENCODED,
					'soap_version'=>SOAP_1_1,
					'cache_wsdl'=>WSDL_CACHE_NONE,
					'connection_timeout'=>15,
					'trace'=>true,
					'encoding'=>'UTF-8',
					'exceptions'=>true,
				);
				$SendSms = new SimpleXMLElement('<SendSms/>');
				foreach($params as $Key=>$Value){
					if(in_array($Key,['ReceiverList'])){
						$ReceiverList = $SendSms->addChild('ReceiverList');
						foreach($Value as $Tmp=>$Gsm){
							$ReceiverList->addChild('Receiver',$Gsm);
						}
					}else{
						$SendSms->addChild($Key,$Value);
					}
				}
				$Send=['requestXml'=>str_replace('<?xml version="1.0"?>','',trim($SendSms->asXML()))];
			//echo "Request:<br/>\n<pre>".htmlentities(var_export($Send,true))."</pre>";
				try {
					$soap = new SoapClient($wsdl, $options);
					$data = $soap->sendSms($Send);
				}
				catch(Exception $e) {
					$data = $e;
				}
			//echo "<hr>response:<br/>\n<pre>".htmlentities(var_export($data,true))."</pre>";
			}elseif(tanim("sms","n6",0)=="verimor"){
				$sms_msg = array("username" => tanim("sms","n1",0), "password" => tanim("sms","n2",0), "source_addr" => tanim("sms","n3",0), "custom_id" => "1424441160.9331344", "messages" => array( array("msg" => $smstxt,"dest" => "90".$gsm."") ) );
				$ch = curl_init('http://sms.verimor.com.tr/v2/send.json');
				curl_setopt_array($ch, array( CURLOPT_POST => TRUE, CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_HTTPHEADER => array('Content-Type: application/json'), CURLOPT_POSTFIELDS => json_encode($sms_msg), ));
				$http_response = curl_exec($ch);
				$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
				if($http_code != 200){
					echo "$http_code $http_response\n";
					return false;
				}
			//return $http_response;
			}
		}
	}

	function smsbakiye(){
		$suser=tanim("sms","n1",0);
		$spass=tanim("sms","n2",0);
		if(tanim("sms","n6",0)=="netgsm"){
			$kbakiye = HTTPPOST("https://api.netgsm.com.tr/get_kredi.asp?usercode=".$suser."&password=".$spass."");
		}elseif(tanim("sms","n6",0)=="verimor"){
			$username=$suser;
			$password=urlencode($spass);
			$url= "http://sms.verimor.com.tr/v2/balance?username=$username&password=$password";
			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
			$http_response = curl_exec($ch);
			$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			if($http_code != 200){
				echo "$http_code $http_response\n";
				return false;
			}
			$kbakiye = $http_response;
		}elseif(tanim("sms","n6",0)=="smsvitrini"){
			require_once "smsvitrini_class.php";
			try {
				$credentials = new CredentialsHash('8450b5a166e4a75b103f7c49b3a5ac256bd8a5eb');
				$smsApi = new MesajPaneliApi($credentials);
				Print_r($smsApi->baslikliKrediSorgula());
			}
			catch ( Exception $e ) {
				echo $e->getMessage();
			}
		}elseif(tanim("sms","n6",0)=="iletimerkezi"){
			function sendRequest($url, $xml) {
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-Type: text/xml');
				curl_setopt($ch, CURLOPT_HEADER, 0);
				curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
				curl_setopt($ch, CURLOPT_TIMEOUT, 120);
				return curl_exec($ch);
			}
			$api_key = tanim("sms","n1",0);
			$api_hash = tanim("sms","n2",0);
			$sender   = tanim("sms","n3",0);
			$xml = <<<EOS
			<request>
			<authentication>
			<key>{$api_key}</key>
			<hash>{$api_hash}</hash>
			</authentication>
			</request>
			EOS;
			$xmlString = sendRequest('https://api.iletimerkezi.com/v1/get-balance', $xml);
			$xml = new SimpleXMLElement($xmlString);
			$kbakiye=($xml->balance->sms);
		}
		return $kbakiye;
	}

	function jsonToCSV($jfilename, $cfilename){
		if (($json = file_get_contents($jfilename)) == false)
			die('Error reading json file...');
		$data = json_decode($json, true);
		$fp = fopen($cfilename, 'w');
		$header = false;
		foreach ($data as $row){
			if (empty($header)){
				$header = array_keys($row);
				fputcsv($fp, $header);
				$header = array_flip($header);
			}
			fputcsv($fp, array_merge($header, $row));
		}
		fclose($fp);
		return;
	}

//======================> Tarih -->	
	$yfd = new DateTime('first day of January');
	$yld = new DateTime('last day of December');
	$mfd = new DateTime('first day of this month');
	$mld = new DateTime('last day of this month');
	$yilbasi=$yfd->format('Y-m-d');
	$yilsonu=$yld->format('Y-m-d');
	$aybasi=$mfd->format('Y-m-d');
	$aysonu=$mld->format('Y-m-d');
	$haftabasi=date('Y-m-d', strtotime("this week"));
	function isWeekend($date="") {
		$weekDay = date('w', strtotime($date));
		return ($weekDay == 0 || $weekDay == 6);
	}
//echo isweekend(date('Y-m-d'));

	$gunler = array('Pazartesi', 'Salı', 'Çarşamba', 'Persembe', 'Cuma', 'Cumartesi', 'Pazar');
	$aylar = array('Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık');
	$kgunler = array('Pt', 'Sa', 'Ça', 'Pe', 'Cu', 'Ct', 'Paz');
	$kaylar = array('Ock', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara');

	function dt($dtarihi="",$tekrar=""){
		$starih = explode('-',$dtarihi);
		$xtarih = strtotime("".date('Y')."-".$starih[1]."-".$starih[2]."  00:00:00");
		$ytarih = strtotime("".date('Y')."-".date('m')."-".date('d')."  00:00:00");
		$gun=($xtarih - $ytarih) / (60*60*24);
		if($tekrar==""){
			if($gun<0){ $gun=$gun+365; }
		}
		if($gun<0){ $gun="..."; }
		return $gun;
	}

	function tfark2($t1="",$t2="",$type=""){
		if($type=="" and $type="number"){
			$xtarih = strtotime("".substr($t1,0,10)."  00:00:00");
			$ytarih = strtotime("".substr($t2,0,10)."  00:00:00");
			$result=($ytarih - $xtarih) / (60*60*24);
		}else{
			$datetime1 = new DateTime($t2);
			$datetime2 = new DateTime($t1);
			$difference = $datetime1->diff($datetime2);
			if($difference->y<>0){
				$result .= ''.$difference->y.' Yıl, ';
			}
			if($difference->m<>0){
				$result .= '' .$difference->m.' Ay, ';
			}
			$result .= '' .$difference->d.' Gün';
		}
		return $result;
	}

	function vade($ts1="",$fark=""){
		$datetime = new DateTime(substr($ts1,0,10));
		$datetime->modify('+'.$fark.' day');
		$ts2=$datetime->format('Y-m-d');
		return $ts2;
	}
	// vade("2020-01-01",120); => 2020-01-01

	function dleft($dleft=""){
		$starih = explode('-',$dleft);
		$xtarih = strtotime("".date('Y')."-".$starih[1]."-".$starih[2]."  00:00:00");
		$ytarih = strtotime("".date('Y')."-".date('m')."-".date('d')."  00:00:00");
		$gun=($xtarih - $ytarih);
		if($dleft==""){ $gun="0";}
		return $gun;
	}
	//Belirtilen tarih ile bugünün tarihi arasındaki gün farkını hesaplar.

	function daynow($zaman = "", $maxgun = "") {
		$starih2 = explode(' ', $zaman);
		$starih = explode('-', $starih2[0]);
		$xtarih = strtotime("{$starih[0]}-{$starih[1]}-{$starih[2]} 00:00:00");
		if ($maxgun != "") {
			$xtarih = strtotime("{$maxgun} day", $xtarih);
		}
		$ytarih = strtotime(date('Y-m-d') . " 00:00:00");
		$gun = ($xtarih - $ytarih) / (60 * 60 * 24);
		return $gun; // "Bugün" ifadesi kaldırıldı, sadece gün sayısı döndürülüyor
	}
	//daynow(now(),"max Gün sınırı");	//now() cinsinden gün

	function daydmy($zaman="",$maxgun=""){
		$starih = explode('-',$zaman);
		$xtarih = strtotime("".$starih[0]."-".$starih[1]."-".$starih[2]." 00:00:00");
		if($maxgun<>""){
			$xtarih = strtotime("".$maxgun." day",strtotime($xtarih));
		}
		$ytarih = strtotime("".date('Y')."-".date('m')."-".date('d')." 00:00:00");
		$gun=($xtarih - $ytarih) / (60*60*24);
		return $gun;
	}
	//daydmy("g.a.yyyy","max Gün sınırı");	//g.a.yyyy cinsinden gün
	//-- Süre -->

	function timeAgo ($zaman=""){
		$zaman =  strtotime($zaman);
		$zaman_farki = time() - $zaman;
		$saniye = $zaman_farki;
		$dakika = round($zaman_farki/60);
		$saat = round($zaman_farki/3600);
		$gun = round($zaman_farki/86400);
		$hafta = round($zaman_farki/604800);
		$ay = round($zaman_farki/2419200);
		$yil = round($zaman_farki/29030400);
		if( $saniye < 60 ){
			if ($saniye == 0){
				return "az önce";
			} else {
				return $saniye .' saniye önce';
			}
		} else if ( $dakika < 60 ){
			return $dakika .' dakika önce';
		} else if ( $saat < 24 ){
			return $saat.' saat önce';
		} else if ( $gun < 7 ){
			return $gun .' gün önce';
		} else if ( $hafta < 4 ){
			return $hafta.' hafta önce';
		} else if ( $ay < 12 ){
			return $ay .' ay önce';
		} else {
			return $yil.' yıl önce';
		}
	}
	//echo timeAgo($tarih);
	//-- Tarih Kısa -->
	function dts($ts1=""){
		$tbol = explode('-',$ts1);
		$tarih="".substr($tbol[2],0,2)." ".uzunay($tbol[1])." ".$tbol[0]."";
		return $tarih;
	}
	//-- Tarih Düzenle -->
	function dtarih($tarih="", $format=""){
		if($tarih==""){$tarih="00-00-0000 00:00:00";}
		$format=str_replace("+"," ",$format);
		$sbol = explode(' ',$tarih); $tbol = explode('-',$sbol[0]);
		if ($sbol[1]<>""){
			$date=" ".$sbol[1]."";
			$times = explode(':',$sbol[1]); $time="".$times[0].":".$times[1]."";
		}
		$format = str_replace("gg", substr($tbol[2],0,2), $format);
		$format = str_replace("aa", $tbol[1], $format);
		$format = str_replace("ka", kisaay($tbol[1]), $format);
		$format = str_replace("ua", uzunay($tbol[1]), $format);
		$format = str_replace("yyyy", $tbol[0], $format);
		$format = str_replace("yy", substr($tbol[0],2,2), $format);
		$format = str_replace("time", $time, $format);
		$format = str_replace("kg", kisagun(date('D', strtotime($tarih))), $format);
		$format = str_replace("ug", uzungun(date('l', strtotime($tarih))), $format);
		return $format;
	}
	//echo dtarih(date('Y-m-d H:i:s'), 'gg.ua.yy time/kg/ug');
	//======================> Para -->
	function yaziile($sayi="", $kurusbasamak="", $parabirimi="", $parakurus="", $karakter="") {
		$b1 = array("", "bir", "iki", "üç", "dört", "beş", "altı", "yedi", "sekiz", "dokuz");
		$b2 = array("", "on", "yirmi", "otuz", "kırk", "elli", "altmış", "yetmiş", "seksen", "doksan");
		$b3 = array("", "yüz", "bin", "milyon", "milyar", "trilyon", "katrilyon");
		$say1="";
		$say2 = ""; 
		$sonuc = "";
		$sayi = str_replace(",", ".",$sayi); 
		$nokta = strpos($sayi,"."); 
		if ($nokta>0) { 
			$say1 = substr($sayi,0, $nokta); 
			$say2 = substr($sayi,$nokta, strlen($sayi)); 
		} else {
			$say1 = $sayi; 
		}
		$son;
		$w = 1; 
		$sonaekle = 0; 
		$kac = strlen($say1); 
		$sonint; 
		$uclubasamak = 0; 
		$artan = 0; 
		$gecici;
		if ($kac > 0) {  
			for ($i = 0; $i < $kac; $i++) {
				$son = $say1[$kac - 1 - $i]; 
				$sonint = $son;  
				if ($w == 1) { 
					$sonuc = $b1[$sonint] . $sonuc;
				} else if ($w == 2) { 
					$sonuc = $b2[$sonint] . $sonuc;
				} else if ($w == 3) { 
					if ($sonint == 1) {
						$sonuc = $b3[1] . $sonuc;
					} else if ($sonint > 1) {
						$sonuc = $b1[$sonint] . $b3[1] . $sonuc;
					}
					$uclubasamak++;
				}
				if ($w > 3) { 
					if ($uclubasamak == 1) {
						if ($sonint > 0) {
							$sonuc = $b1[$sonint] . $b3[2 + $artan] . $sonuc;
							if ($artan == 0) { 
								$sonuc = str_replace($b1[1] . $b3[2], $b3[2],$sonuc);
							}
							$sonaekle = 1; 
						} else {
							$sonaekle = 0;
						}
						$uclubasamak++;
					} else if ($uclubasamak == 2) {
						if ($sonint > 0) {
							if ($sonaekle > 0) {
								$sonuc = $b2[$sonint] . $sonuc;
								$sonaekle++;
							} else {
								$sonuc = $b2[$sonint] . $b3[2 + $artan] . $sonuc;
								$sonaekle++;
							}
						}
						$uclubasamak++;
					} else if ($uclubasamak == 3) {
						if ($sonint > 0) {
							if ($sonint == 1) {
								$gecici = $b3[1];
							} else {
								$gecici = $b1[$sonint] . $b3[1];
							}
							if ($sonaekle == 0) {
								$gecici = $gecici . $b3[2 + $artan];
							}
							$sonuc = $gecici . $sonuc;
						}
						$uclubasamak = 1;
						$artan++;
					}
				}
				$w++; 
			}
		}
		if ($sonuc=="") { 
			$parabirimi = "";
		}
		$say2 = str_replace(".", "",$say2);
		$kurus = "";
		if ($say2!=""){
			if ($kurusbasamak > 3){ 
				$kurusbasamak = 3;
			}
			$kacc = strlen($say2);
			if ($kacc == 1){
				$say2 = $say2."0";
				$kurusbasamak = 2;
			}
			if (strlen($say2) > $kurusbasamak){ 
				$say2 = substr($say2,0, $kurusbasamak);
			}
			$kac = strlen($say2);
			$w = 1;
			for ($i = 0; $i < $kac; $i++){
				$son = $say2[$kac - 1 - $i]; 
				$sonint = $son;
				if ($w == 1){
					if ($kurusbasamak > 0){
						$kurus = $b1[$sonint] . $kurus;
					}
				} else if ($w == 2){
					if ($kurusbasamak > 1){
						$kurus = $b2[$sonint] . $kurus;
					}
				} else if ($w == 3) { 
					if ($kurusbasamak > 2) {
						if ($sonint == 1) {
							$kurus = $b3[1] . $kurus;
						} else if ($sonint > 1) {
							$kurus = $b1[$sonint] . $b3[1] . $kurus;
						}
					}
				}
				$w++;
			}
			if ($kurus=="") { 
				$parakurus = "";
			} else {
				$kurus = $kurus . " ";
			}
			$kurus = $kurus . $parakurus; 
		}
		$sonuc = $karakter . $sonuc . " " . $parabirimi . " " . $kurus . $karakter;
		return $sonuc;
	}
	//-- kdv -->
	function kdv($tutar="", $kdv="", $islem="") {
    $yuzde = ($kdv + 100) / 100; // KDV oranını yüzdelik olarak hesapla
    if ($islem == 0) {  // KDV ekleme
        $kdv = $tutar * $yuzde;  // KDV'yi ekle
    } elseif ($islem == 1) {  // KDV çıkarma
        $kdv = $tutar / $yuzde;  // KDV'yi çıkar
    } elseif ($islem == 2) {  // +KDV farkı hesaplama
        $kdv = ($tutar * $yuzde) - $tutar;  // KDV farkını ekle
    } elseif ($islem == 3) {  // -KDV farkı hesaplama
        $kdv = $tutar - ($tutar / $yuzde);  // KDV farkını çıkar
    }
    return $kdv;  // Sonucu döndür
}
/*
$tutar = 100; $kdv_orani = 18;
$sonuc = kdv($tutar, $kdv_orani, 0);  // KDV'yi ekle
echo $sonuc;  // 118.00
$sonuc = kdv($tutar, $kdv_orani, 1);  // KDV'yi çıkar
echo $sonuc;  // 100.00
$sonuc = kdv($tutar, $kdv_orani, 2);  // +KDV farkını hesapla
echo $sonuc;  // 18.00
$sonuc = kdv($tutar, $kdv_orani, 3);  // -KDV farkını hesapla
echo $sonuc;  // 18.00
*/
function yuzdesi($p1 = "", $p2 = "") {
	if (empty($p1) || empty($p2)) { return 0; }
	$p1 = floatval(str_replace(",", ".", $p1));
	$p2 = floatval(str_replace(",", ".", $p2));
	if ($p2 == 0) { return "Bölme hatası: $p2 sıfır olamaz"; }
	$oran = (($p1 * 100) / $p2) - 100;
    return ceil(abs($oran)); // Yukarı yuvarla
}
function yuzde($sayi="", $yuzde_deger="", $secenek=""){
	$yuzdemiz = ($sayi * $yuzde_deger) / 100;
	$fark = $sayi - $yuzdemiz;
	$topla = $sayi + $yuzdemiz;
	$carp = $sayi * $yuzdemiz;
	$bol = $sayi / $yuzdemiz;
	
	if($secenek == 1){ 
		return ceil($yuzdemiz); 
	}elseif($secenek == 2){ 
		return ceil($fark);
	}elseif($secenek == 3){ 
		return ceil($topla); 
	}elseif($secenek == 4){ 
		return ceil($carp); 
	}elseif($secenek == 5){ 
		return ceil($bol); 
	}else{ 
		return ceil($yuzdemiz); 
	} 
} 
//200'ün %10'u kaçtır. Yazsın. 
//echo yuzde(200,10);
//# Çıktı: 20 
//200'ün %10'unu 200 ile farkı kaçtır bulsun ve yazsın. 
//echo yuzde(200,10,2); 
//# Çıktı: 180 
//200'ün %10'unu 200 ile toplamı kaçtır bulsun ve yazsın. 
//echo yuzde(200,10,3); 
//# Çıktı: 220 
//200'ün %10'unu 200 ile çarpımı kaçtır bulsun ve yazsın. 
//echo yuzde(200,10,4);
//# Çıktı: 4000 
//200'ün %10'unu 200 ile bölümü kaçtır bulsun ve yazsın. 
//echo yuzde(200,10,5); 
//# Çıktı: 10 

/*
function kural($u = "", $kurTipi = "BanknoteSelling"){
	if ($kurTipi == "") $kurTipi = "BanknoteSelling";
	global $b10, $t40, $conn, $usd, $eur, $gbp, $grgold, $btc;
	$old_usd = $usd;
	$old_eur = $eur;
	$old_gbp = $gbp;
	$old_grgold = $grgold;
	$old_btc = $btc;
	$cex = json_decode($t40, true);
	if ($u == 1) {
		mysqli_query($conn, "UPDATE ".$_SESSION['lang']." SET t40='' WHERE ne='ayarlar'");
	}
	if (($b10 == 1 && ($cex["d"] != date("d") && date("H") >= 15 && date("i") > 30)) || $u == 1) {
		// Yeni gram altın kaynağı
		$new_gr_api_url = 'https://api.exchangerate-api.com/v4/latest/USD';
		$new_gr_data = json_decode(file_get_contents($new_gr_api_url), true);
		$grgold = isset($new_gr_data['rates']['TRY']) ? $new_gr_data['rates']['TRY'] : 0;
		// BTC
		$btc = 0;
		$json = json_decode(file_get_contents('https://bitpay.com/api/rates'));
		foreach ($json as $obj) {
			if ($obj->code == 'USD') {
				$btc = $obj->rate * $usd;
				break;
			}
		}
		if (!is_numeric($grgold)) $grgold = 0;
		if (!is_numeric($btc)) $btc = 0;
		// TCMB XML
		$xml = simplexml_load_file('https://www.tcmb.gov.tr/kurlar/today.xml');
		foreach ($xml->Currency as $Currency) {
			if ($Currency['Kod'] == "USD") {
				$usd_S = (string)$Currency->$kurTipi;
			}
			if ($Currency['Kod'] == "EUR") {
				$eur_S = (string)$Currency->$kurTipi;
			}
			if ($Currency['Kod'] == "GBP") {
				$gbp_S = (string)$Currency->$kurTipi;
			}
		}
		$exchanges = array( "d" => date("d"), "m" => date("m"), "y" => date("Y"), "tarih" => date("d.m.Y H:i:s"), "old_usd" => $old_usd, "usd" => trim($usd_S), "old_eur" => $old_eur, "eur" => trim($eur_S), "old_gbp" => $old_gbp, "gbp" => trim($gbp_S), "old_grgold" => $old_grgold, "grgold" => round($grgold * floatval($usd_S), 2), "old_btc" => $old_btc, "btc" => trim($btc) );
		$rex = json_encode($exchanges);
		if (trim($usd_S) != "" || trim($eur_S) != "" || trim($gbp_S) != "") {
			mysqli_query($conn, "UPDATE ".$_SESSION['lang']." SET t40='".addslashes($rex)."' WHERE ne='ayarlar'");
		}
	}
}
*/

function kural($u = "", $kurTipi = "BanknoteSelling"){
	global $b10, $t40, $conn, $usd, $eur, $gbp, $grgold, $btc;

	$old_usd = $usd;
	$old_eur = $eur;
	$old_gbp = $gbp;
	$old_grgold = $grgold;
	$old_btc = $btc;

	$cex = json_decode($t40, true);
	if (($b10 == 1 && ($cex["d"] != date("d") && date("H") >= 15 && date("i") > 30)) || $u == 1) {

		$json = file_get_contents('https://api.exchangerate-api.com/v4/latest/USD');
		$data = json_decode($json, true);

		if (!isset($data["rates"])) return false;

		// USD → TRY temel kur
		$try_S  = floatval($data["rates"]["TRY"] ?? 0);

		// Eğer TRY 0 ise eksik veri var demektir
		if ($try_S <= 0) return false;

		// Çevirim oranları
		$eur_USD = floatval($data["rates"]["EUR"] ?? 0);   // EUR → USD
		$gbp_USD = floatval($data["rates"]["GBP"] ?? 0);   // GBP → USD

		// TRY karşılıkları
		$usd_S  = $try_S;                          // USD zaten TRY bazlı
		$eur_S  = $try_S / $eur_USD;               // EUR → TRY
		$gbp_S  = $try_S / $gbp_USD;               // GBP → TRY

		// BTC
		$btc = 0; $json = json_decode(file_get_contents('https://bitpay.com/api/rates'));
		foreach ($json as $obj) {
			if ($obj->code == 'USD') { $btc = $obj->rate * $usd; break; }
		}
		if (!is_numeric($grgold)) $grgold = 0;
		if (!is_numeric($btc)) $btc = 0;

		$exchanges = [ "d"     => date("d"), "m"     => date("m"), "y"     => date("Y"), "tarih" => date("d.m.Y H:i:s"), "old_usd" => floatval($old_usd), "usd"     => round($usd_S, 4), "old_eur" => floatval($old_eur), "eur"     => round($eur_S, 4), "old_gbp" => floatval($old_gbp), "gbp"     => round($gbp_S, 4), "old_grgold" => floatval($old_grgold), "grgold"     => $grgold, "old_btc" => floatval($old_btc), "btc"     => $btc, ];

		$rex = json_encode($exchanges);
		mysqli_query( $conn, "UPDATE ".$_SESSION['lang']." SET t40='".addslashes($rex)."' WHERE ne='ayarlar'" );
	}
}
// Efektif satış kuruna göre güncelle
//kural(1, 'BanknoteSelling');
// Döviz alış kuruna göre güncelle
//kural(1, 'ForexBuying');
//u değişkeni boş değilse manuel update yapar

//-- Yüzde indirim -->
function iyuzde($tutar2="",$tutar1=""){
	$tyuzde = ($tutar2-$tutar1)/$tutar1*100;
	return $tyuzde;}
//echo number_format(tyuzde($rs["pb2"],$rs["pb1"]),2);
//======================> Para -->

//======================> Genel -->
//-- Location -->
	function loc($id="", $type=""){
		if($type==""){$type="il";} global $weburl; global $path; global $cpath; global $locations;
		if(is_numeric($id)){
			foreach($locations as $array){
				if($array["id"]==$id){
					$location=$array["t1"];
				}
			}
		}else{
			foreach($locations as $array){
				if(strpos($array["t1"], $id) !== FALSE and $array["ne"]==$type){
					$location=$array["id"];
				}
			}
		}
		return $location;
	}
//-- Location -->

//-- Medya #s1 yazdırma-->
	function medya($s1="", $s2="", $ne="", $stn="", $lng="", $url="", $exists=""){
		global $module; global $conn; global $mobile; global $t44; global $weburl; global $cpath; global $cdnurl;
		if($module["media_path"]<>""){
			$url=$module["media_path"]."/";
		}elseif($url<>""){
			$url=$url."/";
		}
		if($module["stamp"]<>""){
			$yok="".$url."deppo/image/".$module["stamp"]."";
		}else{
			$yok="//cdn.".$cdnurl."/images/crm-plus-stamp.png";
		}
		$sne = explode("+", $ne);
		$ss1 = explode("+", $s1);
		if($lng<>""){ $msorgu .=" and t6='".$lng."'";}
		if($s2<>"" or $s2==0){ $msorgu .=" and s2=".$s2."";}
		if($sne[1]<>""){ $msorgu .=" and t3='".$sne[1]."'";}
		if($ss1[0]<>""){ $msorgu .=" and s1=".$ss1[0]."";}
		if($ss1[1]<>""){ $msorgu .=" and s4=".$ss1[1]."";}
		if($ss1[2]<>""){ $msorgu .=" and s3=".$ss1[2]."";}
		if($sne[0]=="kresim"){ $nedir="resim"; }else{ $nedir=$sne[0];}
		$sqlm=mysqli_query($conn, "select id,ne,s1,s2,s3,s4,s13,t1,t3,t4,t6,t7,t2,n1,n2,n3,n4,n6,s19 from medya where ne='".$nedir."' ".$msorgu.""); $rsm=mysqli_fetch_assoc($sqlm);
		if(mysqli_num_rows($sqlm)<>0){
			$uzanti = explode('.',$rsm[$stn]);
			if($mobile==""){
				$msorgu .=" and (t7 IS NULL or t7='' or t7='Desktop' or t7='All')";
			} else {
				$msorgu .=" and (t7 IS NULL or t7='' or t7='Mobile' or t7='All')";
			}
			if($stn=="n1" or $stn=="n2" or $stn=="t1"){
				if($sne[0]=="resim"){
					if($url<>""){
						$filename= "".$url."deppo/image/".$rsm[$stn]."";
						//$imageInfo = @getimagesize($filename);	//yavaşlattığı için kaldırıldı
						//if($imageInfo == ''){
						//	$medya=$yok;
						//} else {
							$mpath="".$url."deppo/image/";
							$medya="".$m."".$rsm[$stn]."";
						//}
					}else{
						if (file_exists("".$cpath."deppo/image/".$rsm[$stn]."")){
							$mpath="".$url."deppo/image/";
							$medya="".$m."".$rsm[$stn]."";
						}else{
							$medya=$yok;
						}
					}
				}elseif($sne[0]=="kresim"){
					if($uzanti[count($uzanti)-1]<>"svg" and $uzanti[count($uzanti)-1]<>"webp"){ $m="k_"; }
					if($url<>""){
						$filename= "".$url."deppo/image/".$m.$rsm[$stn]."";
						//$file_headers = @get_headers($filename);	//yavaşlattığı için kaldırıldı
						//if($file_headers[0] == 'HTTP/1.0 404 Not Found'){
						//	$medya=$yok;
						//} else if ($file_headers[0] == 'HTTP/1.0 302 Found' && $file_headers[7] == 'HTTP/1.0 404 Not Found'){
						//	$medya=$yok;
						//} else {
							$mpath="".$url."deppo/image/";
							$medya="".$m.$rsm[$stn]."";
						//}
					}else{
						if (file_exists("".$cpath."deppo/image/".$m.$rsm[$stn]."")){
							$mpath="".$cpath."deppo/image/";
							$medya="".$m.$rsm[$stn]."";
						}else{
							$medya=$yok;
						}
					}
				}elseif($sne[0]=="video" and $stn=="n1"){
					$medya=$rsm[$stn];
				}elseif($sne[0]=="video" and $stn=="n2"){
					$mpath="".$cpath."deppo/video/";
					$medya="".$rsm[$stn]."";
				}elseif($sne[0]=="dosya"){
					$mpath="".$cpath."deppo/dosya/";
					$medya="".$rsm[$stn]."";
				}
			}else{
				$medya=$rsm[$stn];
			}
		}else{
			$medya=$yok;
		}
		if($exists<>"" and $medya==$yok){$medya="0";}else{$medya=$mpath.$medya;}
		return $medya;
	}
//echo medya("10+xid","1","resim+sayfa","stn","",$weburl);

	function kategori($id = "", $stn = "") {
		global $conn; global $cpath;

    // Çoklu ID varsa {72},{112} gibi → önce süz
		if (strpos($id, "{") !== false && strpos($id, "}") !== false) {
			preg_match_all('/\{(\d+)\}/', $id, $matches);
        $ids = $matches[1]; // sadece sayıları al
    } else {
        $ids = [$id]; // tek ID varsa diziye çevir
    }

    $kategoriler = [];

    foreach ($ids as $single_id) {
        $cat = "#".$single_id."..."; // varsayılan
        $sqlc = mysqli_query($conn, "SELECT Cat_ID, Cat_" . $_SESSION["lang"] . ", image, n1 FROM kategoriler WHERE Cat_ID='" . $single_id . "'"); $rsc = mysqli_fetch_assoc($sqlc); $jslf = json_decode($rsc["n1"], true);
        $sqlsc = mysqli_query($conn, "SELECT t1 FROM " . $_SESSION["lang"] . " WHERE id='" . $single_id . "'"); $rssc = mysqli_fetch_assoc($sqlsc);

        if (mysqli_num_rows($sqlc) > 0) {
        	if ($stn == "") {
        		if (!empty($jslf[$_SESSION["lang"]])) {
        			$cat = $jslf[$_SESSION["lang"]];
        		} else {
        			$cat = $rsc["Cat_" . $_SESSION['lang']];
        		}
        	} elseif ($stn == "image") {
        		if (file_exists("{$cpath}deppo/kategori/" . $rsc[$stn])) {
        			$cat = "{$cpath}deppo/kategori/" . $rsc[$stn];
        		} else {
        			$cat = "{$cpath}deppo/tools/img/yok.png";
        		}
        	} else {
        		$cat = $rsc[$stn];
        	}
        } elseif (mysqli_num_rows($sqlsc) > 0) {
        	$cat = $rssc["t1"];
        }

        $kategoriler[] = $cat;
    }

    return implode(" / ", $kategoriler);
}

function sabit($id = "", $ne = "", $stn = ""){
    global $conn; 
    $stxt = ""; 
    $tsql = "";

    $ids = explode("+", $id);
    //$s13 = "and s13=1";

    if ($ids[0] == "0" && $ids[2] == "") {
        $tsql = " and s2='" . $ids[1] . "'";
    } elseif ($ids[0] == "0" && $ids[1] == "0") {
        $tsql = " and s1='" . $ids[2] . "'";
    } else {
        $tsql = " and id='" . $ids[0] . "'";
    }

    if ($ne == "sayfa" || $ne == "haber" || $ne == "msayfa" || $ne == "kayit") { 
        $nedir = $_SESSION["lang"]; 
    } elseif ($ne == "isayfa" || $ne == "extra") { 
        $nedir = "t1"; 
    } elseif ($ne == "uye") { 
        $nedir = "t5"; 
    } else { 
        $nedir = $_SESSION["lang"]; 
    }

    $sqls = mysqli_query($conn, "SELECT * FROM ".$nedir." WHERE ne='".$ne."' $tsql $s13");
    $rss = mysqli_fetch_assoc($sqls);

    if (mysqli_num_rows($sqls) <> 0) {
        $jsi = json_decode($rss["n17"], true);

        if (substr($stn, 0, 2) == "id") {
            $stxt = $rss[$stn];
        } elseif (substr($stn, 0, 1) <> "i") {
            $stxt = $rss[$stn];
        } else {
            $stxt = $jsi[$stn];
        }
    } else {
        $stxt = "#" . $id . " " . translate("Kayıt Bulunamadı");
    }

    return $stxt;
}

	//echo sabit("10","sayfa","t1");
	//echo sabit("0+s2","sayfa","t1");
	//echo sabit("0+0+s1","sayfa","t1");

function mlinked($id=""){
	global $conn;
	$sql=mysqli_query($conn, "select id,t2,n5,s3 from genel where id=".$id.""); $rs=mysqli_fetch_assoc($sql);
	if ($rs["t2"] == "kayit"){ $q="d"; }elseif ($rs["t2"]  == "sayfa"){ $q="s"; }elseif ($rs["t2"]  == "haber"){ $q="h"; }elseif ($rs["t2"]  == "msayfa"){ $q="m"; }elseif ($rs["t2"]  == "uye"){ $q="u"; }elseif ($rs["t2"]  == "skategori" or $rs["t2"]  == "hkategori" or $rs["t2"]  == "mkategori"){ $q="a"; }elseif ($rs["t2"]  == "ukategori"){ $q="x"; }elseif ($rs["t2"]  == "ualt_kategori"){ $q="y"; }elseif ($rs["t2"]  == "ualt_kategori2"){ $q="z"; }else{ $q=substr($rs["t2"] ,0,1); }
	if($rs["n5"]<>""){
		echo $rs["n5"];
	}else{
		echo linked($q,$rs["s3"]);
	}
}

function linked($ne = "", $id = "", $ver = "", $url = "") {
    global $module, $conn, $weburl, $lveri;
	$veri = !empty($lveri) ? $lveri : null;

    static $cache = [];
    $cacheKey = "link_{$ne}_{$id}_{$ver}_{$url}";

    if (isset($_SESSION["cache"][$cacheKey])) {
		return $_SESSION["cache"][$cacheKey];
    }

    if (empty($module["fseo"]) || $module["fseo"] == "0") {
        $w3 = $url !== "" ? $url . "?" : "?";
    } else {
        $w3 = $url !== "" ? rtrim($url, "/") . "/" : rtrim($weburl, "/") . "/";
    }

    $kategoriTipleri = ["x", "y", "z", "w", "j", "a", "b", "c"];
    $dil = $_SESSION["lang"];
    $tablo = in_array($ne, $kategoriTipleri) ? "kategoriler" : ($ne === "u" ? "t5" : ($ne === "v" ? "medya" : $dil));

    // Eğer dışarıdan veri geldiyse sorgu yapmadan kullan
    if ($veri === null) {
        // Veritabanından çek
        if (in_array($ne, $kategoriTipleri)) {
            $sql = "SELECT Cat_ID, Cat_$dil, n1, n3, n5 FROM kategoriler WHERE Cat_ID = " . intval($id);
        } elseif ($ne === "u") {
            $sql = "SELECT id, t1, n3, n5, n17 FROM t5 WHERE id = " . intval($id);
        } elseif ($ne === "v") {
            $sql = "SELECT t2 FROM medya WHERE id = " . intval($id);
        } else {
            $sql = "SELECT id, t1, n3, n5 FROM $tablo WHERE id = " . intval($id);
        }

        $result = mysqli_query($conn, $sql);
        if (!$result || mysqli_num_rows($result) === 0) {
            $_SESSION["cache"][$cacheKey] = "#$id Kayıt Bulunamadı";
            return $_SESSION["cache"][$cacheKey];
        }

        $veri = mysqli_fetch_assoc($result);
    }

    $cevir = function($text) { return cevir($text); };
    $rlang = function($text) { return rlang($text); };
    $fseo = $module["fseo"] ?? "0";
    $link = "";

    $n1 = isset($veri["n1"]) ? (is_array($veri["n1"]) ? $veri["n1"] : json_decode($veri["n1"], true)) : [];
    $n3 = $veri["n3"] ?? "";
    $n5 = $veri["n5"] ?? "";
    $t1 = $veri["t1"] ?? "";
    $t2 = $veri["t2"] ?? "";
    $n17 = isset($veri["n17"]) ? (is_array($veri["n17"]) ? $veri["n17"] : json_decode($veri["n17"], true)) : [];
    $catDil = $veri["Cat_$dil"] ?? "";

    if ($fseo == "0" || $fseo == "") {
        if (in_array($ne, $kategoriTipleri)) {
            $isim = $n1[$dil] ?? $catDil;
            $link = $n5 ?: ($n3 ? $w3 . $ne . $id . "/" . $cevir($n3) : $w3 . $ne . $id . "/" . $cevir($isim));
        } elseif ($ne == "u") {
            $firma = $n17["ifirma"] ?? "";
            $link = $n5 ?: ($firma ? $w3 . $ne . $id . "/" . $cevir($firma) : $w3 . $ne . $id . "/" . $cevir($t1));
        } elseif ($ne == "v") {
            $link = $w3 . $ne . $id . "/" . $cevir($t2);
        } else {
            $link = $n5 ?: ($n3 ? $w3 . $ne . $id . "/" . $cevir($rlang($n3)) : ($t1 ? $w3 . $ne . $id . "/" . $cevir($rlang($t1)) : $w3 . $ne . $id));
        }
    } elseif ($fseo == "1") {
        if (in_array($ne, $kategoriTipleri)) {
            $isim = $n1[$dil] ?? $catDil;
            $link = $n5 ?: ($isim ? $w3 . $cevir($isim) . "-" . $ne . $id : $w3 . $ne . $id);
        } elseif ($ne == "u") {
            $firma = $n17["ifirma"] ?? "";
            $link = $n3 ? $w3 . $cevir($n3) . "-" . $ne . $id : $w3 . $cevir($firma) . "-" . $ne . $id;
        } elseif ($ne == "v") {
            $link = $w3 . $cevir($t2) . "-" . $ne . $id;
        } else {
            $link = $n5 ?: ($n3 ? $w3 . $cevir($rlang($n3)) . "-" . $ne . $id : $w3 . $cevir($rlang($t1)) . "-" . $ne . $id);
        }
    } elseif ($fseo == "2") {
        if (in_array($ne, $kategoriTipleri)) {
            $isim = $n1[$dil] ?? $catDil;
            $link = $n5 ?: $w3 . $cevir($isim);
        } elseif ($ne == "u") {
            $firma = $n17["ifirma"] ?? "";
            $link = $n3 ? $w3 . $cevir($n3) : $w3 . $cevir($firma);
        } elseif ($ne == "v") {
            $link = $w3 . $cevir($t2);
        } else {
            $link = $n5 ?: ($n3 ? $w3 . $cevir($rlang($n3)) : $w3 . $cevir($rlang($t1)));
        }
    } else {
        $link = $w3 . $ne . $id;
    }

    $_SESSION["cache"][$cacheKey] = $link;
    return $link;
}

	//linked("modul","id","page_versiyon");

	//-- Meta -->
function meta($ne = "", $id = "") {
	global $conn;
	$lang = $_SESSION["lang"] ?? "tr";
	$cacheKey = "meta_{$ne}_{$id}_{$lang}";

	// Önbellekten kontrol et
	if (isset($_SESSION["cache"][$cacheKey])) {
		return $_SESSION["cache"][$cacheKey];
	}

	$meta = "";

	if (in_array($ne, ["x", "y", "z", "a", "b", "c"])) {
		$sql = "SELECT n1, n3, Cat_$lang FROM kategoriler WHERE Cat_ID = " . intval($id);
		$result = mysqli_query($conn, $sql);
		if ($result && mysqli_num_rows($result) > 0) {
			$row = mysqli_fetch_assoc($result);
			$jscl = json_decode($row["n1"], true);
			$mn3 = $row["n3"] ?? "";
			$mt1 = !empty($jscl[$lang]) ? $jscl[$lang] : ($row["Cat_$lang"] ?? "");
		} else {
			// Fallback: lang tablosundan
			$sql = "SELECT n3, t1 FROM $lang WHERE id = " . intval($id);
			$result = mysqli_query($conn, $sql);
			$row = mysqli_fetch_assoc($result);
			$mn3 = $row["n3"] ?? "";
			$mt1 = $row["t1"] ?? "";
		}
		$meta = !empty($mn3) ? $mn3 : $mt1;

	} elseif ($ne === "u") {
		$sql = "SELECT t1, n3, n17 FROM t5 WHERE id = " . intval($id);
		$result = mysqli_query($conn, $sql);
		$row = mysqli_fetch_assoc($result);
		$jsi = json_decode($row["n17"] ?? "", true);
		$meta = !empty($jsi["ifirma"]) ? $jsi["ifirma"] : ($row["t1"] ?? "");

	} elseif ($ne === "t") {
		$sql = "SELECT t1, n3 FROM t1 WHERE id = " . intval($id);
		$result = mysqli_query($conn, $sql);
		$row = mysqli_fetch_assoc($result);
		$meta = !empty($row["n3"]) ? $row["n3"] : ($row["t1"] ?? "");

	} else {
		$sql = "SELECT t1, n3 FROM $lang WHERE id = " . intval($id);
		$result = mysqli_query($conn, $sql);
		$row = mysqli_fetch_assoc($result);
		if (!empty($row["n3"])) {
			$meta = rlang($row["n3"]);
		} else {
			$meta = rlang($row["t1"] ?? "");
		}
	}

	// Önbelleğe yaz
	$_SESSION["cache"][$cacheKey] = $meta;

	return $meta;
}

//-- Reklam -->
function reklam($id="", $s12="0", $stn="", $s19=""){
	global $conn; global $cdnurl; global $module; global $weburl; global $mobile;
	$url = uri("domain") . "/"; $url = ($module["media_path"] == "") ? $url : $module["media_path"]."/";
	if($s19<>""){$qry="and s19='".$s19."'";}
	$sqlr=mysqli_query($conn, "select id,t3,t4,t5,t6,t7,t8,t10,t12,t16,n1,n2,n3,n4,n17,s13 from genel where ne='reklam' and (s1='".$id."' or id='".$id."') and s12=".$s12." and s13=1 $qry"); $rsr=mysqli_fetch_assoc($sqlr);
	if($mobile<>"" and $rsr["t16"]==""){$ad="t6";}elseif($mobile<>"" and $rsr["t16"]<>""){$ad="t16";}elseif($mobile==""){$ad="t6";}
	$jsi = json_decode($rsr["n17"],true);
	if($stn==""){
		if($rsr["n4"]==""){$n4="style=\"max-width:100%;\"";}else{$n4=$rsr["n4"];}
		if($rsr["t7"]<>"1" and $rsr["n2"]<>""){$n2="ad/".$rsr["id"]."";}elseif($rsr["t7"]=="1" and $rsr["n2"]<>""){$n2=$rsr["n2"];}else{$n2="#";}
		if ($rsr["t3"]=="image" and $rsr[$ad]<>""){
			$filename= "".$url."deppo/rek-lam/".$rsr[$ad]."";
			//$imageInfo = @getimagesize($filename);
			//if($imageInfo == ''){
			//	$reklam="<a href=\"".$n2."\" ".$rsr["t10"]." target=\"".$rsr["t8"]."\" id=\"ad".$rsr["id"]."\"><img src=\"".$weburl."/deppo/rek-lam/".$rsr[$ad]."\" ".$n4." /></a>";
			//}else{
				$reklam="<a href=\"".$n2."\" ".$rsr["t10"]." target=\"".$rsr["t8"]."\" id=\"ad".$rsr["id"]."\"><img src=\"".$url."deppo/rek-lam/".$rsr[$ad]."\" ".$n4." /></a>";
			//}
		}elseif ($rsr["t3"]=="video" and $rsr[$ad]<>""){
			$reklam='<video controls> <source src="'.$url.'deppo/rek-lam/'.$rsr[$ad].'" '.$n4.' type="video/mp4"> </video>';
		}elseif ($rsr["t3"]=="text" and $rsr["n1"]<>""){
			$reklam=$rsr["n1"];
		}elseif ($rsr["t3"]=="kod" and $rsr["n3"]<>""){
			$reklam=$rsr["n3"];
		}else{
			if ($rsr["s13"]==1){
				$reklam="<a href=\"#\" ".$rsr["t10"]." target=\"".$rsr["t8"]."\" id=\"ad".$rsr["id"]."\"><img src=\"https://sample.".$cdnurl."/".$rsr["t4"]."x".$rsr["t5"]."\" ".$rsr["n4"]." /></a>";
			}
		}
		if(($rsr["t12"]<>"" and dleft($rsr["t12"])>=0) or $rsr["t12"]==""){
			$reklam=$reklam;
		}else{
			$reklam="<a href=\"#\" ".$rsr["t10"]." target=\"".$rsr["t8"]."\" title=\"#".$id." ".translate("Süresi Doldu")."\" id=\"ad".$rsr["id"]."\"><img src=\"https://sample.".$cdnurl."/".$rsr["t4"]."x".$rsr["t5"]."\" ".$rsr["n4"]." /></a>";
		}
	}else{
		if(substr($stn,0,1)<>"i"){
			$reklam=$rsr[$stn];
		}else{
			$reklam=$jsi[$stn];
		}
	}
	return $reklam;
}
	//echo reklam($id,0);

function ads($id="", $s12="0", $stn="", $s19=""){
	global $conn; global $cdnurl; global $module; global $weburl; global $mobile; $url=uri("domain")."/";
	if($s19<>""){$qry="and s19='".$s19."'";}
	$sqlr=mysqli_query($conn, "select id,t3,t4,t5,t6,t7,t8,t10,t12,t16,n1,n2,n3,n4,n17,s13 from genel where ne='reklam' and (s1='".$id."' or id='".$id."') and s13=1 $qry"); $rsr=mysqli_fetch_assoc($sqlr);
	$sqlic = mysqli_query($conn, "select id from medya where ne='resim' and s1=".$rsr["id"]." and s13=1 order by s3 asc"); $icount = mysqli_num_rows($sqlic);
	if($icount>1){
		echo "<div class=\"owl-carousel owl-theme a_d_s\">";
		$sqli=mysqli_query($conn, "select * from medya where ne='resim' and s1=".$rsr["id"]." and s13=1 order by s3 asc"); while($rsi=mysqli_fetch_assoc($sqli)){
			echo "<div class=\"item\"><img src=\"".$url."deppo/image/".$rsi["t1"]."\"></div>";
		}
		echo "</div>";
	}else{
		echo reklam($id, $s12, $stn, $s19);
	}
}
	//echo ads($id,0);
	//-- JSON dosyası yoksa MySQL’den çevirileri al -->

function initializeTranslations() {
	global $conn, $weburl;
	// 'sdil' ile ilişkili tüm satırları al
	$sql = mysqli_query($conn, "SELECT * FROM genel WHERE ne='sdil'");
	if ($sql && mysqli_num_rows($sql) > 0) {
		$translations = [];
		$counter = 1;  // Benzersiz ID oluşturmak için sayaç başlatıyoruz
		// Her satır için çevirileri oluştur
		while ($row = mysqli_fetch_assoc($sql)) {
			// Her satırda benzersiz bir ID (counter) ekleyerek çeviri bilgilerini oluştur
			$translations[$counter] = [
				"key" => $row['n20'],  // 'n20' key olarak kullanılıyor
				"lang1" => $row['n1'], // 'n1' dil1 çevirisi
				"lang2" => $row['n2'] // 'n2' dil2 çevirisi (isteğe bağlı)
			];
			$counter++;  // Sayaç her seferinde arttırılır
		}
		$translationurl = $weburl . "/deppo/tools/script/translations.php?type=transfer";
		$ch = curl_init($translationurl);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($translations));
		curl_setopt($ch, CURLOPT_HTTPHEADER, [
			'Content-Type: application/json'
		]);
		
		// İsteği gönder
		$response = curl_exec($ch);
		curl_close($ch);
		Print_r($response);
		if (trim($response) === "Çeviri verileri başarıyla güncellendi.") {
			// Tabloyu temizle
			$deleteQuery = mysqli_query($conn, "DELETE FROM genel WHERE ne='sdil'");
			if ($deleteQuery) {
				echo "<br>Tablo temizlendi.";
			} else {
				echo "<br>Silme işlemi başarısız: " . mysqli_error($conn);
			}
		}
	}
}

function translate($metin = "", $lang2 = "") {
    global $firm, $weburl, $kpb, $kargolmt, $_SESSION;

    static $translations = null;
    static $cache = [];

    if ($metin === "") return "";

    // Orijinal key'i sakla (JSON'da + ile kayıtlı olabilir)
    $originalKey = $metin;

    // + temizleme (Sadece görüntüleme ve eşleştirme için)
    if ($metin[0] === "+") {
        $metin = substr($metin, 1);
    }

    $langKey = $_SESSION["lang"] ?? "lang1";

    if (isset($cache[$langKey][$originalKey])) {
        return $cache[$langKey][$originalKey];
    }

    // Değişken Değişimi
    $metin = str_replace(
        ["{ftel}", "{fmail}", "{weburl}", "{firma}", "{fadres}", "{cargo_limit}", "{kpb}"],
        [$firm["ftel"], $firm["fmail"], $weburl, $firm["firma"], $firm["fadres"], $kargolmt, $kpb],
        $metin
    );

    // JSON Yükleme
    if ($translations === null) {
        $filePath = $_SERVER["DOCUMENT_ROOT"]."/deppo/datas/translations.json";
        if (is_file($filePath)) {
            $content = file_get_contents($filePath);
            $translations = json_decode($content, true);
            // JSON bozuksa veya boşsa veriyi koru, sıfırlama!
            if (json_last_error() !== JSON_ERROR_NONE || !is_array($translations)) {
                $translations = []; 
            }
        } else {
            $translations = [];
        }
    }

    // Çeviri Ara
    $found = false;
    $result = $metin;
    foreach ($translations as $row) {
        // Hem +lı hem +sız key kontrolü (Güvenlik için)
        if (($row["key"] ?? "") === $originalKey || ($row["key"] ?? "") === $metin) {
            $result = $row[$langKey] ?? $row["lang1"] ?? $metin;
            $found = true;
            break;
        }
    }

    // Metin yoksa ekle (cURL yerine doğrudan yazmak daha güvenlidir ama mevcut yapını koruyorum)
    if (!$found) {
        // cURL isteğini sadece bir kez atması için static bir kontrol ekleyebilirsin
        $ch = curl_init($weburl."/deppo/tools/script/translations.php?type=add");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query(["key" => $originalKey]), // Orijinal haliyle ekle
            CURLOPT_TIMEOUT => 1 // Sayfayı yavaşlatmaması için timeout
        ]);
        curl_exec($ch);
        curl_close($ch);
    }

    if (!$found && $lang2 !== "") {
        $result = ($langKey === "lang1") ? $metin : $lang2;
    }

    return $cache[$langKey][$originalKey] = $result;
}

function hasTranslation($metin) {
	global $weburl;
	$filePath = $weburl."/deppo/datas/translations.json";
	static $translations = null;
	if ($translations === null){
		$translations = json_decode(file_get_contents($filePath), true);
	}
	foreach ($translations as $translation) {
		if ($translation['key'] === $metin) {
			return true;
		}
	}
	return false;
}

function ctranslate($word = "", $path = "../"){
	global $module, $weburl;
    // Eğer m1_crm modülü etkinse, işlem devam eder
	if ($module["m1_crm"] <> "") {
        // Cache dosyasını belirleyelim
		$cacheFile = $_SERVER['DOCUMENT_ROOT'] . "/deppo/datas/translate_" . $_SESSION["clang"] . ".json";
        // Eğer cache dosyası mevcutsa, cache'yi oku ve dosyayı cache'e al
		static $translationsCache = null;
        // Cache'i kontrol et ve yükle
		if ($translationsCache === null) {
			if (file_exists($cacheFile)) {
                // Dosya mevcutsa, cache'e yükle
				$fgc = file_get_contents($cacheFile);
				$translationsCache = json_decode($fgc, true);
			} else {
                // Eğer dosya yoksa, cache boş olur
				$translationsCache = [];
			}
		}
        // Çeviri kontrolü
		$control = 0;
		foreach ($translationsCache as $result) {
			foreach ($result as $key => $value) {
				if ($key == $word) {
					$word = $value;
					$control = 1;
                    break 2; // Çeviri bulunduğunda döngüyü kır
                }
            }
        }
        // Çeviri bulunamadıysa, yeni çeviriyi ekle
        if ($control <> 1) {
            // Yeni çeviriyi ekle
            $arr_new = [$word => $word]; // Yeni çeviri
            array_push($translationsCache, $arr_new);
            // Cache'i güncelle ve dosyaya yaz
            $data = json_encode($translationsCache, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
            $fp = fopen($cacheFile, 'w');
            fwrite($fp, $data);
            fclose($fp);
        }
    }
    return $word;
}
function order_adress($id = "", $type = "", $stn = "") {
	global $conn;
	$id = intval($id);
	$result = "";
	$stns = explode(",", $stn);
	// Sipariş ve adres verilerini al
	$order = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM eticaret WHERE ne='siparis' AND id=$id"));
	if (!$order) return "";
	$adresID = ($type == "delivery") ? $order["s11"] : $order["s12"];
	$adres = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM t1 WHERE ne='adress' AND id=" . intval($adresID)));
	if ($adres) {
		$jsi = ($adres["n16"] != "") ? json_decode($adres["n16"], true) : $adres;
		extract($jsi); // n1, n2, ..., n15
		if ($stn == "") {
			$result = " <table class=\"$type fs13\"> <tr><td><b>$n2</b></td></tr> <tr><td>$n7</td></tr> <tr><td>$n6</td></tr> <tr><td>" . loc($n5) . " / " . loc($n4) . " - " . loc($n3) . "</td></tr> </table> ";
		} else {
			if (in_array("ad", $stns))      $result .= $n2;
			if (in_array("gsm", $stns))	$result .= $n7;
			if (in_array("adres", $stns))	$result .= $n6;
			if (in_array("sehir", $stns))	$result .= loc($n4);
			if (in_array("ilce", $stns))	$result .= loc($n5);
			if (in_array("firma", $stns))	$result .= $n8;
			if (in_array("vn", $stns))		$result .= $n12;
			if (in_array("vd", $stns))		$result .= $n13;
			if (in_array("fvdvn", $stns) && $n12 != "" && $n13 != "") $result .= "$n12 / $n13";
			if (in_array("adres_full", $stns)) {
				$parcalar = array_filter([ $n6, $n3 ? loc($n3) : "", $n4 ? loc($n4) : "", $n5 ? loc($n5) : "", $n11 ? loc($n11) : "" ]);
				$result .= implode(" / ", $parcalar);
			}
		}
	} else {
		$user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM t5 WHERE id=" . intval($order["s1"])));
		if ($type == "delivery") {
			$result = $order["n3"] != "" ? $order["n3"] : $user["n5"];
		} else {
			$result = $order["n2"] != "" ? $order["n2"] : $user["n5"];
		}
	}
	return $result;
}
//echo order_adress("Sipariş ID","delivery/invoice");

// ✅ Kargo Takip Linki veya Firma Adı Döndüren Fonksiyon
// Parametreler:
// $cargo → Kargo firması adı veya içinde geçen ifade (örnek: "yurtiçi", "aras")
// $code → Kargo takip numarası
// $type → "link" veya "" ise takip linki döner, "firma" ise kargo firması adı döner
function cargotracking($cargo="", $code="", $type=""){
	$cargo_l = strtolower($cargo);
	$tracking = "";
	$firm = "";

	if(strpos($cargo_l,'yurtici') !== FALSE or strpos($cargo_l,'yurtiçi') !== FALSE){
		$firm = "Yurtiçi Kargo";
		$tracking = "https://selfservis.yurticikargo.com/reports/SSWDocumentDetail.aspx?DocId=".$code;
	}
	elseif(strpos($cargo_l,'aras') !== FALSE){
		$firm = "Aras Kargo";
		$tracking = "https://kargotakip.araskargo.com.tr/mainpage.aspx?code=".$code;
	}
	elseif(strpos($cargo_l,'surat') !== FALSE or strpos($cargo_l,'sürat') !== FALSE){
		$firm = "Sürat Kargo";
		$tracking = "http://suratkargo.com.tr/KargoTakip?kargotakipno=".$code;
	}
	elseif(strpos($cargo_l,'dhl') !== FALSE){
		$firm = "DHL Express";
		$tracking = "https://www.dhl.com.tr/tr/express/tracking.html?AWB=".$code."&brand=DHL";
	}
	elseif(strpos($cargo_l,'ptt') !== FALSE){
		$firm = "PTT Kargo";
		$tracking = "https://www.turkiye.gov.tr/ptt-gonderi-takip?barkod=".$code;
	}
	elseif(strpos($cargo_l,'mng') !== FALSE){
		$firm = "MNG Kargo";
		$tracking = "https://service.mngkargo.com.tr/iactive/popup/KargoTakip/link12.asp?k=".$code."&y=".date('Y');
	}

	return ($type=="firma") ? $firm : $tracking;
}

// Örnek Kullanım:
// echo cargotracking("yurtici","54066540654"); // Takip linki döner
// echo cargotracking("yurtici","54066540654","firma"); // "Yurtiçi Kargo" döner


function fav($id="", $op="", $ne=""){
	global $conn;
	$sqlf=mysqli_query($conn, "select id,s13 from genel where ne='".$op."' and t2='".$ne."' and s1=".$id." and s19='".$_SESSION["User_ID"]."'"); $rs=mysqli_fetch_assoc($sqlf);
	if(mysqli_num_rows($sqlf)>0 and $_SESSION["User_ID"]<>""){
		$sts="active";
	}elseif($_SESSION["User_ID"]==""){
		$sts="passive";
	}
	if($ne=="friend" and $rs["s13"]<>1){
		$sts="passive";
	}elseif($ne=="friend" and $rs["s13"]==1){
		$sts="active";
	}
	return $sts;
}

function yuvarla($deger, $katsayi) {
	$return = array('ceil' => 0, 'floor' => 0, 'degerler' => $deger.','.$katsayi, 'fmod' => '', 'error' => '');
	$error = array();
	
	if (!is_numeric($deger)) {
		$error[] = 'İlk değer rakam olmalı.';
	}      
	if (!is_numeric($katsayi)) {
		$error[] = 'Katsayı rakam olmalı';
	}
	if ($deger == 0 AND $katsayi == 0) {
		$error[] = 'Değerler Sıfır';
	}
	elseif ($deger == 0) {
		$error[] = 'Değer Sıfır';
	}
	elseif ($katsayi == 0) {
		$error[] = 'Katsayı Sıfır';
	}
	
	if ($error) {
		$err = '';
		foreach ($error as $ev) {
			$err .= $ev."\n";
		}
		$return['error']= nl2br(trim($err));
		$return['ceil'] = false;
		$return['floor'] = false;
	}
	else {
		$fark = fmod($deger, $katsayi); // ex: fmod(8,3) => 2;
		$return['fmod'] = $fark;
		$return['ceil'] = $fark ? ($deger - $fark)+$katsayi : $deger;
		$return['floor'] = $fark ? $deger - $fark : $deger;
	}
	
	return $return['ceil'];
}

function price($id="",$pb="",$nfn=""){
	global $s11; global $f7; global $kpb; global $eur; global $usd; global $gbp; global $conn; global $module; global $path; global $discount;
	$ids = explode("+",$id);
	if($ids[1]<>""){$id=$ids[0]; $s19=$ids[1];}else{$id=$ids[0];}
	if($s19<>""){$qry="and s19='".$s19."'";}
	$sqlux=mysqli_query($conn, "select id,t1,t2,t5,s4,s5,pb1,pb2,pb3,s9,s10 from ".$_SESSION["lang"]." where ne='kayit' and id=".$id.""); $rsux=mysqli_fetch_assoc($sqlux); $jsi=json_decode($rsux["n17"],true); $ppb=$rsux["t2"]; $tax=$rsux["s4"]; 
	$sqlc=mysqli_query($conn, "select id,t1,t2,t5,pb1,pb2,s9,s10 from t1 where ne='post' and t5=".$rsux["t5"].""); $rsc=mysqli_fetch_assoc($sqlc); 
	if($module["mode_catalogue"]>0 and mysqli_num_rows($sqlc)>0){
		$sqlu=mysqli_query($conn, "select id,t1,t2,t5,s4,s5,pb1,pb2,pb3,s19 from t1 where ne='post' and t5=".$rsux["t5"]." $qry order by pb1 desc"); $rsu=mysqli_fetch_assoc($sqlu); $id=$rsu["id"];
	}else{
		$sqlu=mysqli_query($conn, "select id,t1,t2,t5,s5,pb1,pb2,pb3,s19 from ".$_SESSION["lang"]." where ne='kayit' and id=".$id.""); $rsu=mysqli_fetch_assoc($sqlu); $id=$rsu["id"];
	}
	$sqlcd=mysqli_query($conn, "select t1,t2 from genel where ne='discount' and (s1=".$rsux["s9"]." or s1=".$rsux["s10"]." or s1=".$rsux["id"]." or s1=0) and s2=0"); $rscd=mysqli_fetch_assoc($sqlcd);	
	include("".path."deppo/tools/script/prices.php"); include("prices.php");
	$prc=$module["prc"];
	if(mysqli_num_rows($sqlcd)>0 and dt($rscd["t2"],0)>0){
		$fiyat2 = $fiyat1; $fiyat_2 = $fiyat_1;
		$fiyat1 = $fiyat1 * ((100 - $rscd["t1"]) / 100);
		$fiyat_1 = $fiyat_1 * ((100 - $rscd["t1"]) / 100);
		$fiyat3 = $fiyat3 * ((100 - $rscd["t1"]) / 100);
		$fiyat_3 = $fiyat_3 * ((100 - $rscd["t1"]) / 100);
	}
	if($pb=="" or $pb=="pb1"){
		if($prc==0){
		$sprc=$fiyat1;		//Kdv Hariç
	}else{
			$sprc=$fiyat_1;	//Kdv dahil
		}
	}elseif($pb=="pb2"){
		if($prc==0){
			$sprc=$fiyat2;		//Kdv Hariç
		}else{
			$sprc=$fiyat_2;	//Kdv dahil
		}
	}elseif($pb=="pb3"){
		if($prc==0){
			$sprc=$fiyat3;		//Kdv Hariç
		}else{
			$sprc=$fiyat_3;	//Kdv dahil
		}
	}
	if($nfn=="" and $sprc<>0){
		if($module["round"]<>""){
			$sprc=wprice(yuvarla($sprc,$module["round"]));
		}else{
			$sprc=wprice($sprc);
		}
	}

	// Ürün bazlı kar marjı
	if(isset($jsi["iprofit_margin"]) && $jsi["iprofit_margin"] > 0){
		$sprc = $sprc * (1 + $jsi["iprofit_margin"]/100); // Marj eklenmiş fiyat
	}

	if(($pb==pb2 and $sprc>0) or $pb==pb1){
		return $sprc;
	}
}

//fiyatları döviz ve KDV’ye göre otomatik dönüştüren bir hesaplayıcı.
function xprice($price="", $pb="", $tax=""){
	global $s11; global $f7; global $kpb; global $eur; global $usd; global $gbp; global $module;
	if($module["currency"]=="TRY"){
		if($pb=="TRY"){
			$xprice=$price;
		}elseif($pb=="USD"){
			$xprice=$price*$usd;
		}elseif($pb=="EUR"){
			$xprice=$price*$eur;
		}elseif($pb=="GBP"){
			$xprice=$price*$gbp;
		}
	}elseif($module["currency"]=="USD"){
		if($pb=="TRY"){
			$xprice=$price*$usd;
		}elseif($pb=="USD"){
			$xprice=$price;
		}elseif($pb=="EUR"){
			$xprice=$price*$eur/$usd;
		}elseif($pb=="GBP"){
			$xprice=$price*$gbp/$usd;
		}
	}elseif($module["currency"]=="EUR"){
		if($pb=="TRY"){
			$xprice=$price*$eur;
		}elseif($pb=="USD"){
			$xprice=$price*$usd/$eur;
		}elseif($pb=="EUR"){
			$xprice=$price;
		}elseif($pb=="GBP"){	
			$xprice=$price*$gbp/$eur;		
		}
	}elseif($module["currency"]=="GBP"){
		if($pb=="TRY"){
			$xprice=$price*$gbp;
		}elseif($pb=="USD"){
			$xprice=$price*$usd/$gbp;
		}elseif($pb=="EUR"){
			$xprice=$price*$eur/$gbp;
		}elseif($pb=="GBP"){
			$xprice=$price;
		}
	}
	$fkdv=(1+($tax/100));
	if($s11<>1){
		$xprice=$xprice * $fkdv;
	}
	return $xprice;
}
//xprice(Fiyat,"USD",kdv)

function fmesaj($ne="",$nedir=""){
	global $mail; global $sunucu; global $firma; global $conn;
	$ono=date('dmYHis');
	if($nedir==""){ $nedir="fmesaj"; }else{ $nedir=$nedir;}
	include("deppo/tools/script/mail/design.php");
	$mesaj  = "Web Site : ".$_SERVER['HTTP_HOST']."<br/><br/>";
	$mesaj .="<table style=\"width:99%\">";
	$jset = array();
	foreach ($_POST as $key => $val){
		
		if($val<>"" and $key<>"t1" and $key<>"malici" and $key<>"Konu" and $key<>"bcc" and $key<>"cc" and $key<>"name" and $key<>"first-name" and $key<>"last-name" and $key<>"number" and $key<>"expiry" and $key<>"cvc" and $key<>"vadef" and $key<>"tvadef" and $key<>"banka_id" and $key<>"aurl" and $key<>"burl"){
			$jset = $jset + array(translate("Tarih") => date('d.m.Y H:i:s'));
			$jset = $jset + array(translate("İleti No") => $ono);
			$jset = $jset + array( $key => $val);
			$mesaj .= "
			<tr>
			<td style=\"width:25%\"><b>".$key."</b> : </td>
			<td>".$val."</td>
			</tr>
			";
		}
	}
	$mesaj .= "
	<tr>
	<td style=\"width:25%\"><b>".translate("Tarih")."</b> : </td>
	<td>".$ono."</td>
	</tr>
	";
	$mesaj .="</table>";
	$aform = json_encode($jset, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
	$gonderen	= $_POST["Ad_Soyad"];
	$mgonderen  = $mail;
	$msifre     = tanim('email','n2',0);
	if($_POST["malici"]<>""){
		$malici	= $_POST["malici"];
	}else{
		$malici = tanim('email','n1',0);
		sNotification(translate("Form Mail"), $ne, "Crm");
	}
	$konu		= $_POST["Konu"];
	if($_POST["cc"]<>""){
		$cc			= $_POST["cc"];
	}
	if($_POST["bcc"]<>""){
		$bcc			= $_POST["bcc"];
	}
	$mesaj	= $design_top.$mesaj.$design_bottom;
	emailgonder($malici,$konu,$cc,$mesaj,$ne);
	$fmesaj = $conn->query("insert into genel (ne,t1,t2,t3,ts2,ts3,n1,n2,s19,ts1) values ('".$nedir."', '".$_POST["t1"]."', '".$ne."', '".$ono."', '".$_POST["date"]."', '', '".$mesaj."' , '".addslashes(stripslashes($aform))."', '".$_SESSION["User_ID"]."', now())");
}

function slider($n1=""){
	if (file_exists("deppo/slide/".$n1."")){
		$slideimg="deppo/slide/".$n1."";
	}else{
		$slideimg="//img.wdclouds.com/1920x800";
	}
	return $slideimg;
}

function inc($file=""){
	if($file=="gmap" or $file=="gmaps" or $file=="ymap" or $file=="ymaps" or $file=="comment" or $file=="form"){$fpath="deppo/tools/script/";}
	global $conn; global $sdil; global $id; global $fid; global $sayfa; global $jsl; global $firm; global $firma; global $coordinats; global $logo; global $weburl; global $module;
	//echo "".$fpath."".$file.".php";
	include("".$fpath."".$file.".php");
}

function txttoimg($txt=""){
	global $cdnurl;
	$img="<img src=\"//cdn.".$cdnurl."/tools/email/?txt=".$txt."\" style=\"filter: invert(1);\">";
	return $img;
}

function uri($ne=""){
	$host = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
	$directory = dirname($_SERVER["PHP_SELF"]);
	if($ne=="domain"){				//>https://cloud.crmplus.com.tr
		return trim($host);
	}elseif($ne=="directory"){	//>/crmplus/modules/pages
		return trim($directory);
	}elseif($ne=="get"){			//>islem=dsayfa&ne=sayfa&id=...
		return parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
	}elseif($ne=="full"){				//>https://cloud.crmplus.com.tr/crmplus/modules/pages
		return $host.$directory;
	}
}

function user_agent(){
	$iPod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");
	$iPhone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
	$iPad = strpos($_SERVER['HTTP_USER_AGENT'],"iPad");
	$android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
	file_put_contents('./public/upload/install_log/agent',$_SERVER['HTTP_USER_AGENT']);
	if($iPad||$iPhone||$iPod){
		return 'ios';
	}else if($android){
		return 'android';
	}else{
		return 'desktop';
	}
}
$user_agent=user_agent();

function xreader($file=""){
	require_once "simple_xlsx.php";
	if($xlsx = SimpleXLSX::parse($file)){
		$result=$xlsx->rows();
	} else {
		$result=SimpleXLSX::parseError();
	}
	$data="<table class=\"v3-table xls_data\">";
	foreach($result as $row){
		$data.="<tr>";
		foreach($row as $col){
			$data.="<td>".$col."</td>";
		}
		$data.="</tr>";
	}
	$data.="<table>";
	return $data;
}

function download($file="",$rename=""){
	if($rename==""){ $rename=date("YmdHis");}
	$uzanti = explode('.',$file);
	$download_name="".$rename.".".$uzanti[count($uzanti)-1]."";
	return $download_name;
}

function uzanti($file="",$ne=""){
	$uzanti_ = explode('.',$file); $uzanti=$uzanti_[count($uzanti_)-1]; $adi=$uzanti_[0];
	if($uzanti=="jpg" or $uzanti=="jpeg" or $uzanti=="png" or $uzanti=="gif" or $uzanti=="svg" or $uzanti=="webp"){
		$tip="resim";
		$gorsel=$file;
	}elseif($uzanti=="zip" or $uzanti=="rar"){
		$tip="arsiv";
		$gorsel="assets/img/icons/".$uzanti."_b.png";
	}elseif($uzanti=="docx" or $uzanti=="doc" or $uzanti=="xsl" or $uzanti=="xlsx" or $uzanti=="pdf"){
		$tip="dosya";
		$gorsel="assets/img/icons/".$uzanti."_b.png";
	}elseif($uzanti=="mp4" or $uzanti=="avi"){
		$tip="video";
		$gorsel="assets/img/icons/".$uzanti."_b.png";
	}
	if($ne=="tip"){
		return $tip;
	}elseif($ne=="gorsel"){
		return $gorsel;
	}elseif($ne=="adi"){
		return $adi;
	}elseif($ne=="uzanti"){
		return $uzanti;
	}
}

function towebp($file = "", $dir = "") {
    if (substr($dir, -1) !== "/") $dir .= "/";

    $fullPath = $dir . $file;
    if (!file_exists($fullPath)) {
        error_log("towebp HATA: Dosya bulunamadı: $fullPath");
        return false;
    }

    $mime = mime_content_type($fullPath);
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    $nfile = preg_replace('/\.[^.]+$/', '.webp', $file); // .jpg/.png -> .webp

    // Görseli uygun şekilde oluştur
    if ($mime === 'image/jpeg') {
        $img = @imagecreatefromjpeg($fullPath);
        $preserveAlpha = false;
    } elseif ($mime === 'image/png') {
        $img = @imagecreatefrompng($fullPath);
        $preserveAlpha = true;
    } else {
        error_log("towebp HATA: Desteklenmeyen MIME türü: $mime ($file)");
        return false;
    }

    if (!$img) {
        error_log("towebp HATA: Resim açılamadı: $fullPath");
        return false;
    }

    imagepalettetotruecolor($img);

    if ($preserveAlpha) {
        // PNG: transparanlık korunmalı
        imagealphablending($img, false); // transparanlık için false
        imagesavealpha($img, true);
    } else {
        imagealphablending($img, true);
    }

    $webpPath = $dir . $nfile;

    if (!imagewebp($img, $webpPath, 100)) {
        error_log("towebp HATA: WebP kaydedilemedi: $webpPath");
        imagedestroy($img);
        return false;
    }

    imagedestroy($img);

    // Orijinal dosyayı sil
    if (file_exists($fullPath)) {
        unlink($fullPath);
    }

    return $nfile;
}

function nGetAccessToken() {
    $jsonKey = file_get_contents("".$_SERVER['DOCUMENT_ROOT']."/deppo/notification.json"); // service account dosyası
    $data = json_decode($jsonKey, true);

    $jwtHeader = base64_encode(json_encode(['alg'=>'RS256','typ'=>'JWT']));
    $now = time();
    $jwtClaim = base64_encode(json_encode([
        'iss' => $data['client_email'],
        'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
        'aud' => $data['token_uri'],
        'iat' => $now,
        'exp' => $now + 3600
    ]));

    $signature = '';
    openssl_sign($jwtHeader.".".$jwtClaim, $signature, $data['private_key'], 'sha256');
    $jwt = $jwtHeader.".".$jwtClaim.".".base64_encode($signature);

    // Token iste
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $data['token_uri']);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion' => $jwt
    ]));
    $result = curl_exec($ch);
    curl_close($ch);

    $res = json_decode($result, true);
    return ['access_token' => $res['access_token'] ?? null, 'project_id' => $data['project_id'] ?? null];
}

function nDevice($title="test", $msg="", $deviceToken="", $platform=""){
	global $conn; global $module;
	$auth = nGetAccessToken();
    $accessToken = $auth['access_token'];
    $projectId   = $auth['project_id'];
    if(!$auth){ return false; }

	if(!$accessToken || !$projectId){ 
        echo "Token veya project_id alınamadı."; 
        return false; 
    }

    $url = "https://fcm.googleapis.com/v1/projects/".$projectId."/messages:send";
    $fields = [ "message" => [ "token" => $deviceToken, "notification" => [ "title" => $title, "body"  => $msg ] ] ];
    $headers = [ 'Authorization: Bearer '.$accessToken, 'Content-Type: application/json; UTF-8' ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);
    if(isset($data['error'])){
        echo "FCM Error: ".$data['error']['message'];
        return false;
    }
    return true;
}

function sNotification($title="", $msg="", $platform="", $UserID="", $type=""){
    global $conn; global $module;
    if($UserID<>""){
        $sql=mysqli_query($conn, "select n8 from t5 where id=".$UserID.""); while($rss=mysqli_fetch_assoc($sql)){ $jsa = json_decode($rss["n8"], true);
            $result=nDevice($title, $msg, $jsa["Token"], $platform);
        }
        $sql = $conn->query("insert into genel (ne,t1,n1,s1, ts1) values ('notification', '".$title."', '".$msg."', '".$UserID."', now())");
    }else{
        if($module["bildirim_notification"]=="1" and $module["bildirim_yoneticiler"]=="1"){
            $sql=mysqli_query($conn, "select * from genel where ne='asifre' and n8<>''"); while($rss=mysqli_fetch_assoc($sql)){ $jsa = json_decode($rss["n8"], true);
				$result=nDevice($title, $msg, $jsa["Token"], $platform);
            }
        }
        if($module["bildirim_notification"]=="1" and $module["bildirim_editorler"]=="1"){
            $sql=mysqli_query($conn, "select id,n8,n10 from t5 where n8<>'' and s1=1"); while($rss=mysqli_fetch_assoc($sql)){ $jsy = json_decode($rss["n10"], true); $jsa = json_decode($rss["n8"], true);
                if(($type=="fmesaj" and $jsy["y30_mesaj"]==1) or ($type=="request" and $jsy["y30_request"]==1) or ($type=="siparis" and $jsy["y30_siparis"]==1)){
                	$result=nDevice($title, $msg, $jsa["Token"], $platform);
                }
            }
        }
    }

	if($result == 1){ 
		echo "[".date("Y-m-d H:i:s")."] Gönderildi<br>"; 
	} else { 
		echo "[".date("Y-m-d H:i:s")."] Hata<br>"; 
	}

}
//sNotification("selam", "Merhaba", 'Crm');

// Function to remove folders and files
function rrmdir($dir="") {
	if (is_dir($dir)) {
		$files = scandir($dir);
		foreach ($files as $file)
			if ($file != "." && $file != "..") rrmdir("$dir/$file");
		rmdir($dir);
	}
	else if (file_exists($dir)) unlink($dir);
}

// Function to Copy folders and files
function rcopy($src="", $dst="") {
	if (file_exists ( $dst ))
		rrmdir ( $dst );
	if (is_dir ( $src )) {
		mkdir ( $dst );
		$files = scandir ( $src );
		foreach ( $files as $file )
			if ($file != "." && $file != "..")
				rcopy ( "$src/$file", "$dst/$file" );
		} else if (file_exists ( $src ))
		copy ( $src, $dst );
	}
//rcopy($source , $destination );	
	function qrCode($strText="",$intSize=""){
	//$qrCode = "https://chart.googleapis.com/chart?cht=qr&chs=".$intSize."x".$intSize."&chld=L|1&chl=".$strText."";
		$qrCode = "https://api.qrserver.com/v1/create-qr-code/?size=".$intSize."x".$intSize."&chld=L|1&data=".$strText."";
		return $qrCode;
	}
//echo qrCode("123",150);

function sendLogData() {
    global $pow1, $pow2, $wurl, $cdnurl, $ai, $logColor;  // Dışarıdaki parametrelere erişim sağlıyoruz
    $ljson = json_encode(array( 'Firma' => $pow1, 'Versiyon' => $pow2, 'Domain' => $wurl, 'User' => $_SESSION["user"], 'IP' => $_SERVER['REMOTE_ADDR'], 'Device' => $_SESSION["Device"], 'MacID' => $_SESSION["MacID"], 'DeviceID' => $_SESSION["DeviceID"], 't1' => $_POST["t1"], 'logData' => $ai, 'logColor' => $logColor));
	//Print_r($ljson);
	$url = "https://log." . $cdnurl . "/?log=" . v3e($ljson);  // v3e fonksiyonu ile şifreleme yapılmış JSON verisi
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);  // URL'yi ayarlıyoruz
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // Yanıtı döndürmesini sağlıyoruz
	curl_setopt($ch, CURLOPT_POST, true);  // POST isteği olduğunu belirtiyoruz
	curl_setopt($ch, CURLOPT_POSTFIELDS, $ljson);  // Gönderilecek veriyi ekliyoruz
	$response = curl_exec($ch);
	Print_r($response);
	curl_close($ch);
}

function kontrol(){
	$adres=$_SERVER['SERVER_NAME'];
	global $pow1; global $pow3; global $pow4; global $conn;
	$sqlk=mysqli_query($conn, "select id from genel where ne='tanim' and n1='".base64_encode(str_replace("www.", "", $adres))."' "); $rsk=mysqli_fetch_assoc($sqlk);
	
	// DB hatası, bağlantı yok, sorgu bozuk, geçici sorun
	if ($sqlk === false) {return;}

	if (mysqli_num_rows($sqlk) == 0 && empty($_SESSION["V3Server"])) {
		$kmesaj="
		<div style='width:100%;height:100%;background:rgba(0,0,0,.99);position:fixed;z-index:999999999;top:0;left:0;display:flex;align-items:center;justify-content:center;'>
			<div style='width:360px;background:#1b1b1b;padding:25px;border-radius:14px;text-align:center;color:#fff;box-shadow:0 0 25px rgba(0,0,0,.6);'>
				<img src='https://cdn-icons-png.flaticon.com/512/564/564619.png' style='width:90px;opacity:.95;margin-bottom:15px;'>
				<h2 style='margin:0 0 10px 0;font-size:22px;font-weight:600; color: aquamarine;'>Bir Şeyler Ters Gitti</h2>
				<p style='font-size:15px;margin:0 0 5px 0;opacity:.9;'>Bu bölüm şu anda lisans kontrolü nedeniyle geçici olarak kapalı.</p>
				<p style='font-size:15px;margin:0 0 15px 0;opacity:.9;'>Lütfen daha fazla bilgi için servis sağlayıcınıza başvurun.</p>
				<button onclick='location.reload();' style='background:#ff4747;border:none; padding: 2px 10px;border-radius:8px;color:#fff;font-size:15px;cursor:pointer;'>Tekrar Dene</button>
			</div>
		</div>
		<script> document.body.setAttribute('oncontextmenu','return false'); document.body.setAttribute('onselectstart','return false'); document.body.setAttribute('ondragstart','return false'); </script>			
	";
	}
	echo $kmesaj;
}
//echo kontrol();

function HTTPPOST($url="", $request="", $header = []){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	$result = curl_exec($ch);
	curl_close($ch);
	return $result;
}

function surl($url=""){
	global $cdnurl;
	$json_string = file_get_contents('https://link.'.$cdnurl.'?url='.$url.'');		
	return rlang($json_string);
}
//echo surl("http://test.com");

function go ($url="", $time = 0){
	if ($time) header("Refresh: {$time}; url={$url}");
	else header("Location: {$url}");
}
//   go("siteadi.com", 10);
//   go("siteadi.com");

function location($url="",$target="",$sure="",$preload=""){
	global $weburl;
	echo "<script>var delay = 2; var targetURL = '".$url."'; setTimeout('".$target.".location.replace(targetURL)', (delay * ".$sure."));</script>";
	if ($preload=="1"){
		echo "<div style=\"width:100%; height:100%; padding:20% 45%; position:fixed; margin:0px; left:0px; top:0px; z-index:999999999999; background-image:url('".$weburl."/deppo/tools/img/trns.png')\"><img border=\"0\" src=\"".$weburl."/deppo/tools/img/loading.svg\" style=\"max-height:150px;\"></div>";
	}elseif ($preload=="2"){
		echo "<div style=\"width:100%; height:100%; padding:20% 45%; position:fixed; margin:0px; left:0px; top:0px; z-index:999999999999; background-image:url('".$weburl."/deppo/tools/img/trns.png')\"><img border=\"0\" src=\"".$weburl."/deppo/tools/img/loading.svg\" style=\"max-height:150px;\"></div>";
	}
}
//-- Yönlendirme -->

function saveok(){
	global $weburl;
	//echo "<div style='width:300px; height:300px; padding:10% 46%; position:absolute; margin:0px; left:0px; top:0px; z-index:999999999999;' id='saveok'><img border='0' src='".$weburl."/deppo/tools/img/saved.gif' style=\"max-height:150px;\"></div>";
}	
//echo base64_encode($dizge);
//echo base64_decode($dizge);

function ID2Guid($ID=""){
	$chars = "0123456789abcd";
	$ID=str_pad($ID, 6, '0', STR_PAD_LEFT);
	$guid .= substr(str_shuffle($chars),0,6)."-";
	$guid .= substr(str_shuffle($chars),0,6)."-";
	$guid .= substr(str_shuffle($chars),0,6)."-";
	$guid .= base64_encode($ID);
	return $guid;
}
function Guid2ID($ID=""){
	$guides = explode("-", $ID);
	return ltrim(base64_decode($guides[3]), '0');
}

function Posts(){
	foreach ($_POST as $key => $value){
		${$key} = $value;
		$posts .="<input type=\"hidden\" name=\"".$key."\" value=\"".$value."\">\n";
	}
	return $posts;
}

function Gets(){
	foreach ($_GET as $key => $value){
		${$key} = $value;
		$gets .= $key."=".$value;
	}
	return $gets;
}

function v3e($metin=""){
	$metin = base64_encode($metin);
	return $metin;
}

function v3e2($metin=""){
	$metin = base64_encode($metin);
	$metin = base64_encode($metin);
	return $metin;
}

function V3d($metin=""){
	$metin = base64_decode($metin);
	return $metin;
}

function V3d2($metin=""){
	$metin = base64_decode($metin);
	$metin = base64_decode($metin);
	return $metin;
}

function V3sha($metin=""){
	$metin = hash('sha512', $metin);
	return $metin;
}

function sha($string="",$secret_key="",$status=""){
	$encrypt_method = 'AES-256-CBC'; //sifreleme yontemi
	$secret_iv = '22-=**_'; //gerekli sifreleme baslama vektoru
	$key = hash('sha256', $secret_key); //anahtar hast fonksiyonu ile sha256 algoritmasi ile sifreleniyor
	$iv = substr(hash('sha256', $secret_iv), 0, 16); 
	if($status=="e"){
		$secret = openssl_encrypt($string,$encrypt_method, $key, false, $iv);
	}else{
		$secret = openssl_decrypt($string,$encrypt_method, $key, false, $iv);
	}
	return $secret;
}

//echo sha("veri","key","e/d");
function generatePassword( $length="" ) {
	$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
	return substr(str_shuffle($chars),0,$length);
}

function generateSPassword( $length="" ) {
	$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	return substr(str_shuffle($chars),0,$length);
}

function generatenumber( $length="" ) {
	$chars = "012345678901234567890123456789";
	return substr(str_shuffle($chars),0,$length);
}

function ftelefon($numara = "") {
	if (empty($numara) || strlen($numara) < 10) {
		echo "Geçersiz telefon numarası!";
		return;
	}
	$numara = preg_replace("/\D/", "", $numara); // \D, sayılar dışında her şeyi temizler
	if (strlen($numara) == 10) {
		echo "(" . substr($numara, 0, 3) . ") " . substr($numara, 3, 3) . "-" . substr($numara, 6, 4);
	} else {
		echo "Geçersiz telefon numarası!";
	}
}

function i2a($s1="",$s2=""){
	$i2a=str_pad($s1, $s2, '0', STR_PAD_LEFT);
	return $i2a;
}
//echo i2a(99,8);

function ihb($metin=""){
	$k_uzunluk = mb_strlen($metin, "UTF-8");
	$imetin = str_replace("İ", "I", $metin);
	$ilkKarakter= mb_substr($imetin, 0, 1, "UTF-8");
	$metin = str_replace("I", "ı", $metin);
	$metin = str_replace("İ", "i", $metin);
	$kalan = mb_substr($metin, 1, $k_uzunluk - 1, "UTF-8");
	return mb_strtoupper($ilkKarakter, "UTF-8") . mb_strtolower($kalan,"UTF-8");
}
//echo ihb(metin);

function validate($str = "", $type = "") {
	// Str parametresini güvenli hale getirmek için (isteğe bağlı)
	//$str = test_input($str); 
	$result = "ok"; // Varsayılan olarak başarı durumu
	// Ad doğrulaması
	if ($type == "name") {
		if (!preg_match("/^[a-zA-Z-' ]*$/", $str)) {
	        $result = "Sadece Harf ve Boşluk";  // Yalnızca harf ve boşluk kabul edilir
	    }
	}
	// E-posta doğrulaması
	elseif ($type == "mail") {
		if (!filter_var($str, FILTER_VALIDATE_EMAIL)) {
	        $result = "Hatalı Email";  // Geçersiz e-posta adresi
	    }
	}
	// Telefon numarası doğrulaması
	elseif ($type == "phone") {
	    // Telefon numarasını kontrol etmeden önce düzgün bir şekilde işlediğinden emin olalım
		$telefon = telefon($str);
	    // Telefon numarasının başı 5 ile başlamalı ve uzunluğu 10 olmalı
		if (substr($telefon, 0, 1) != "5" || strlen($telefon) != 10) {
	        $result = "Hatalı Telefon";  // Geçersiz telefon numarası
	    }
	}

	return $result;
}

function nice_number($str="") {
	if($str > 1000){
		$rakam=$str/1000;
		$rakam="".number_format($rakam,2)." K";
	}else{
		$rakam=$str;
	}
	return $rakam;
}

function kisalt($metin, $uzunluk = 100) {
	if (strlen($metin) <= $uzunluk) {
		return $metin;
	}
	
	$kisalt = substr($metin, 0, $uzunluk);
	$kisalt = substr($kisalt, 0, strrpos($kisalt, ' '));
	return $kisalt . '...';
}

function tback($text="") {
	$ubol = explode("/", $_SERVER['QUERY_STRING']);
	$sayfa=$ubol[0];
	$sayfa1=$ubol[1];
	$sayfa2=$ubol[2];
	if($sayfa==""){
		$str="";
	}elseif($sayfa<>"" and $sayfa1==""){
		$str="/".$sayfa."";
	}elseif($sayfa1<>"" and $sayfa2==""){
		$str="/".$sayfa.",".$sayfa1."";
	}elseif($sayfa2<>""){
		$str="/".$sayfa.",".$sayfa1.",".$sayfa2."";
	}
	return $str;
}

function isMobile(){
	return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}

if(isMobile()){ $mobile="1"; }else{$mobile="";}

function filetransfer($nereden="",$nereye=""){
	$ch = curl_init($nereden);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	file_put_contents($nereye,curl_exec($ch));
	if(file_exists($nereye)){
		return true;
	}else{
		return false;
	}
}
//if(filetransfer($nereden,$nereye)){echo "ok";}else{echo "err";}

function getRealIpAddr(){
	if (!empty($_SERVER['HTTP_CLIENT_IP'])){
		$ip=$_SERVER['HTTP_CLIENT_IP'];
	}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
		$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	}else{
		$ip=$_SERVER['REMOTE_ADDR'];
	}
	return $ip;
}
//echo "Gerçek IP: ".getRealIpAddr();

function ilocation($str=""){
	global $module;
	$gjson = file_get_contents("http://ip-api.com/json/".$_SERVER['REMOTE_ADDR']."");
	$json = json_decode($gjson,true);
	if($module["city"]<>"" and $str=="city"){
		$str=$module["city"];
	}else{
		$str=$json[$str];
	}
	/*{ "ip": "31.145.112.18", "city": "Istanbul", "region": "Istanbul", "country": "TR", "loc": "41.0177,28.9744", "postal": "34110", "org": "AS15924 VODAFONE NET ILETISIM HIZMETLERI ANONIM SIRKETI" }*/
	return $str;
}

function stars($s20 = 0, $oran = 100) {
    // Maksimum 5 yıldız olacak şekilde ölçekleme
	$star_count = min(5, ($s20 / $oran) * 5);
    // Tam yıldız ve boş yıldız hesapla
	$stars_full = floor($star_count);
	$stars_half = ($star_count - $stars_full) >= 0.5 ? 1 : 0;
	$stars_empty = 5 - ($stars_full + $stars_half);
    // Yıldızları birleştir
	return str_repeat('<i class="fa fa-star"></i>', $stars_full) . str_repeat('<i class="fa fa-star-half-o"></i>', $stars_half) . str_repeat('<i class="fa fa-star-o"></i>', $stars_empty);
}
// echo stars(431, 500); // 431 hit, 500 izlenme = yaklaşık 4.3 yıldız

function expdf($url="",$pdfname="",$expath=""){
	require("php-pdf-class.php"); 
	$pdf_options = array( "source_type" => 'url', "source" => $url, "action" => 'save', "save_directory" => '../deppo/dosya/', "file_name" => $pdfname);
	phptopdf($pdf_options);
	return $pdfname;
}

function private_str($str = "", $start = 0, $end = 0) {
    $after = mb_substr($str, 0, $start, 'utf8');  // Başlangıç kısmı
    $repeat = str_repeat('*', $end);               // Gizlenecek kısmın yıldızlarla tekrarı
    $before = mb_substr($str, $start + $end);      // Sonraki kısmı
    return $after . $repeat . $before;  // Birleştirip geri döndür
}
//echo private_str($telefon, 3, 5); // Çıktı: 054*****744
//echo private_str($tc, 2, 7); // Çıktı: 45*******45

function tck($tc="") {
    // 11 haneli ve sadece rakamlardan oluşuyor mu kontrol et
	if(strlen($tc) == 11 && is_numeric($tc)) {
		$toplam1 = 0;
		$toplam2 = 0;
        // İlk 9 haneyi al ve iki ayrı toplam oluştur
		for($i = 0; $i < 9; $i++) {
			if ($i % 2 == 0) {
				$toplam1 += $tc[$i];
			} else {
				$toplam2 += $tc[$i];
			}
		}
        // 10. rakamı hesapla
		$onuncu = ($toplam1 * 7 - $toplam2) % 10;
        // 11. rakamı hesapla
		$onbirinci = ($toplam1 + $toplam2 + $onuncu) % 10;
        // Sonuçları kontrol et
		if ($onuncu == $tc[9] && $onbirinci == $tc[10]) {
            return "1";  // Geçerli
        } else {
            return "0";  // Geçersiz
        }
    } else {
        return "0";  // Geçersiz, 11 haneli değil veya sayısal değil
    }
}

function names($name="",$ne=""){
	$names = explode(' ',$name); if(count($names)>2){$name="".$names[0]." ".$names[1].""; $surname="".$names[2]."";}else{$name="".$names[0].""; $surname="".$names[1]."";}
	if($ne=="ad" or $ne=="name"){ $result = $name; }elseif($ne=="sname"){ $result = "<span class=\"v3-circle names u".v3e($name.$surname)."\" title=\"".$name." ".$surname."\">".strtoupper(cevir(mb_substr($name,0,1)).cevir(mb_substr($surname,0,1)))."</span>"; }else{ $result = $surname;}
	return $result;
}

function importSql($filePath){
	global $V3Server; global $V3User; global $V3Pass; global $V3Db;
	$db = new mysqli($V3Server, $V3User, $V3Pass, $V3Db); 
	$templine = '';
	$lines = file($filePath);
	$error = '';
	foreach ($lines as $line){
		if(substr($line, 0, 2) == '--' || $line == ''){ continue; }
		$templine .= $line;
		if (substr(trim($line), -1, 1) == ';'){
			if(!$db->query($templine)){
				$error .= 'Error importing query "<b>' . $templine . '</b>": ' . $db->error . '<br /><br />';
			}
			$templine = '';
		}
	}
	return !empty($error)?$error:true;
}
//======================> sistem -->
?>
