<?php
$max_upload = ini_get('upload_max_filesize');
$max_post = ini_get('post_max_size');
$arrContextOptions = array("ssl"=>array("verify_peer"=>false,"verify_peer_name"=>false));

//-- Updater: Versiyon yükseltme ve dosya çıkarma işlemleri (PHP 8.x uyumlu)
function updater($ver,$path,$folders){
	global $conn,$cdnurl,$lx,$power,$opow1,$opow3,$opow4,$opow5,$pow1,$pow3,$pow4,$pow5,$mmail,$weburl,$cc,$arrContextOptions,$i4;

	$filename=date("YmdHis");
	$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);

	$localZip=$path."deppo/$filename.zip";
	$sourceURL="$i4/$filename.zip";
	if(!filetransfer($sourceURL,$localZip)){echo "Dosya Hata";return false;}

	$zip=new ZipArchive();
	if($zip->open($localZip)!==true){echo "Zip Hata";return false;}

	// 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 ve güvenli biçimde işle
	$zip->extractTo($path);
	for($i=0;$i<$zip->numFiles;$i++){
		$stat=$zip->statIndex($i);
		if(!isset($stat['name']) || substr($stat['name'],-4)!==".php") continue;
		$fileParts=explode("/",$stat['name']);
		$file=end($fileParts);
		$subPath=str_replace($file,"",$stat['name']);
		$original=$path.$subPath.$file;
		$temp=$path.$subPath.'_'.uniqid().'_'.$file;

		if(file_exists($original)){
			$content=@file_get_contents($original,false,stream_context_create($arrContextOptions));
			if($content!==false){
				// BOM temizle
				if(substr($content,0,3)==="\xEF\xBB\xBF") $content=substr($content,3);
				// Satır sonlarını normalize et
				$content=preg_replace("/(\r\n|\r|\n)/","\n",$content);
				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","");

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

	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>CrmPlus+ Güncellendi<br>$ver</div>";

	return true;
}

//-- Filters: Session tabanlı filtreleme ve sıralama
function filters($filters=""){
	global $s16,$sayfa,$sayfa1;
	$filter=explode(':',$filters);
	if($_SESSION['filters']=="" || $filter[0]=="reset"){$_SESSION['filters']=[]; unset($_SESSION['filters_qry'],$_SESSION['filters_keys']);}
	foreach($_SESSION['filters'] as $fkey=>$fvalue){if($filter[0]=="add" && $fkey==$filter[1]) unset($_SESSION['filters'][$filter[1]]);}
	if($filter[0]=="del") unset($_SESSION['filters'][$filter[1]]);
	if($filter[0]=="add"){
		if($filter[1]!="columns" && $filter[1]!="sort" && $filter[1]!="items"){
			$filter_keys=explode(":",v3d($filter[1]));
			$_SESSION['filters'][$filter_keys[0]]=$filter[1];
		}else $_SESSION['filters']=$_SESSION['filters']+[$filter[1]=>$filter[2]];
	}
	//-- Order
	switch($_SESSION['filters']['sort']??""){
		case "ida": $_SESSION['order']="order by id asc"; break;
		case "idd": $_SESSION['order']="order by id desc"; break;
		case "t1a": $_SESSION['order']="order by t1 asc"; break;
		case "t1d": $_SESSION['order']="order by t1 desc"; break;
		case "pb1a": $_SESSION['order']="order by pb1 asc"; break;
		case "pb1d": $_SESSION['order']="order by pb1 desc"; break;
		case "bec": $_SESSION['order']="order by s14 desc"; break;
		case "bez": $_SESSION['order']="order by s14 asc"; break;
		default: $_SESSION['order']="order by id desc"; break;
	}
	//-- Price & POST filters
	if(!empty($_POST)){
		foreach($_SESSION as $k=>$v){if(strpos($k,"filter_post_")===0) unset($_SESSION[$k]);}
		unset($_SESSION['post_keys']);
		foreach($_POST as $pkey=>$pval){
			if(!in_array($pkey,["min_price","max_price"])) $_SESSION["filter_post_".$pkey]=$pval;
			if($pval!==""){
				if($pkey=="x") $_SESSION['filter_post_keys'].="and s9='".$pval."' ";
				elseif($pkey=="y") $_SESSION['filter_post_keys'].="and s10='".$pval."' ";
				elseif($pkey=="z") $_SESSION['filter_post_keys'].="and s11='".$pval."' ";
				elseif(in_array($pkey,["il","ilce","semt"])) $_SESSION['filter_post_keys'].="and n16 like '%".$pval."%' ";
			}
		}
		$_SESSION['filter_post_min_price']=max(0,$_POST['min_price']??0);
		$_SESSION['filter_post_max_price']=max(0,$_POST['max_price']??9999999999999);
		if($_SESSION['filter_post_min_price']>0 || $_SESSION['filter_post_max_price']>0)
			$_SESSION['filter_post_keys'].="and pb1 >= '".$_SESSION['filter_post_min_price']."' and pb1 <= '".$_SESSION['filter_post_max_price']."' ";
	}
	//-- Items per page
	$_SESSION['lsay']=$_SESSION['filters']['items']??$s16;
	$_SESSION['filter_keys']=""; $_SESSION['filters_qry']="";
	foreach($_SESSION['filters'] as $fkey=>$fval){
		if(!in_array($fkey,["columns","sort","items"])){
			$filter_keys=explode(":",v3d($fval));
			$_SESSION['filters_qry'].="and (t1 LIKE '%".$filter_keys[3]."%' or n2 LIKE '%".$filter_keys[3]."%' or n4 LIKE '%".$filter_keys[3]."%' or n17 LIKE '%".$filter_keys[3]."%') ";
			$_SESSION['filter_keys'].="<a href=\"?$sayfa/$sayfa1/del:$fkey:$fval\" class=\"filters v3-btn-success\"><i class=\"fa fa-remove\"></i><span class=\"filter-content\"><span>".$filter_keys[1].":".$filter_keys[2]."</span></span></a>";
		}
	}
	if(!empty($_SESSION['filters'])) $_SESSION['filter_keys'].="<a href=\"?$sayfa/$sayfa1/reset\" title=\"Reset Filter\" class=\"reset-filters v3-btn-danger\"><i class=\"fa fa-remove\"></i> ".translate("Filtreleri Temizle")."</a>";
}

//===================> Satır klonlama
function clonerow($table,$source_id){global $conn;
	$stmt=$conn->prepare("SELECT * FROM `$table` WHERE `id`=?");
	if(!$stmt) return "Hata: ".$conn->error;
	$stmt->bind_param("i",$source_id);$stmt->execute();$row=$stmt->get_result()->fetch_assoc();
	if(!$row) return "Klonlanacak satır bulunamadı.";
	unset($row['id']); if(isset($row['t1'])) $row['t1'].=' {cloned}';
	$cols=array_keys($row);$placeholders=array_fill(0,count($row),'?');
	$insert=$conn->prepare("INSERT INTO `$table` (".implode(", ",$cols).") VALUES (".implode(", ",$placeholders).")");
	if(!$insert) return "Hata: ".$conn->error;
	$types='';foreach($row as $v) $types.=is_int($v)?'i':'s';
	$insert->bind_param($types,...array_values($row));
	return $insert->execute()? $conn->insert_id : "Hata: ".$insert->error;
}

//===================> Kullanıcı bilgisi alma
function GetUser($id="",$stn=""){
	$users=json_decode(GetArr("","users",""),true);$out="";
	if($id!=""){$ids=multivalues($id);if(in_array("0",$ids))$out.='<span class="btn btn-warning btn-sm" style="padding:2px;margin:0 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:0 2px;font-size:11px;'>{$u[$stn]}</span>";}else $out="...";
	return $out!=""?$out:"...";
}

//===================> JSON çıktısı alma
function GetJson($ne="",$stn="",$qry=""){global $weburl,$conn,$module;
	if($qry<>"") $qry="and ".$qry;
	if(in_array($ne,["sayfa","haber","msayfa"])){$tbl=$_SESSION["lang"];$s="s2";$id="id";}
	elseif($ne=="kayit"){$tbl=$_SESSION["lang"];$s="s9";$id="id";}
	elseif($ne=="kategori"){$tbl="kategori";$id="Cat_ID";$s="";}
	elseif(in_array($ne,["isayfa","extra"])){$tbl="t1";$s="s2";$id="id";}
	elseif($ne=="uye"){$tbl=$_SESSION["lang"];$s="s2";$id="id";}
	else{$tbl=$_SESSION["lang"];$s="s2";$id="id";}
	$cstn=$stn;$stn=str_replace(["resim","video","kategori"],"",$stn);
	$iarr=[];$cstns=explode(",",$cstn);
	$sql=mysqli_query($conn,"SELECT $stn FROM $tbl WHERE ne='$ne' $qry");
	while($rss=mysqli_fetch_assoc($sql)){
		$row_array=[];$stns=explode(",",$stn);foreach($stns as $k)$row_array[$k]=$rss[$k];
		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]);
		$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;

//===================> Veritabanından array veya JSON döndürür
function GetArr($ne="",$type="",$qry="",$order="",$path=""){global $weburl,$conn,$module,$cdnurl;
	$arr=[];$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"){$sql=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($rs=mysqli_fetch_assoc($sql)){$j=json_decode($rs["n1"],true);$arr[]=['id'=>$rs["Cat_ID"],'ne'=>$rs["ne"],'t1'=>$rs["t1"],'c1'=>$rs["c1"],'s1'=>$rs["s1"],'c2'=>$rs["c2"],'s2'=>$rs["s2"],'s3'=>$rs["s3"],'s4'=>$rs["s4"],'s5'=>$rs["s5"],'item'=>$j[$lang]!=""?$j[$lang]:$rs["Cat_$lang"]];}}
	elseif($type=="xmodules"){$sqlxm=mysqli_query($conn,"SELECT id,ne,n1,n2,n4,t1 FROM genel WHERE ne='xmodules' $order");while($r=mysqli_fetch_assoc($sqlxm)){$arr[]=['id'=>$r["id"],'ne'=>$r["ne"],'type'=>"xmodule",'n2'=>$r["n2"],'n4'=>$r["n4"],'item'=>$r["n1"]];
		$sqlx=mysqli_query($conn,"SELECT Cat_ID,Cat_$lang,t1,n1 FROM kategoriler WHERE (ne='".$r["n4"]."kategori' OR t1='".$r["n2"]."') $order");while($rx=mysqli_fetch_assoc($sqlx)){$j=json_decode($rx["n1"],true);$arr[]=['id'=>$rx["Cat_ID"],'ne'=>$rx["ne"],'type'=>"category",'t1'=>$rx["t1"],'item'=>$j[$lang]!=""?$j[$lang]:$rx["Cat_$lang"]];}
		$sqls=mysqli_query($conn,"SELECT id,ne,t1 FROM $lang WHERE ne='".$r["n2"]."' AND s5=1 $order");while($rs=mysqli_fetch_assoc($sqls)){$arr[]=['id'=>$rs["id"],'ne'=>$rs["ne"],'type'=>"page",'item'=>$rs["t1"]];}}}
	elseif($type=="slide"){$sql=mysqli_query($conn,"SELECT id,t1,t6,n1,n3 FROM medya WHERE ne='slide' $qry $order");while($r=mysqli_fetch_assoc($sql)){$arr[]=['id'=>$r["id"],'t1'=>$r["t1"],'t6'=>$r["t6"],'n1'=>$r["n1"],'n3'=>$r["n3"],'item'=>$r["t1"]];}}
	elseif($type=="users"){$sql=mysqli_query($conn,"SELECT id,t1,s9 FROM t5 WHERE ne<>'' $qry $order");while($r=mysqli_fetch_assoc($sql)){$j=json_decode($r["n17"],true);$arr[]=['id'=>$r["id"],'t1'=>$r["t1"],'item'=>$r["t1"],'json'=>$j];}}
	elseif($type=="media"){$t1="//cdn.$cdnurl/images/crm-plus-stamp.png";$sql=mysqli_query($conn,"SELECT id,t1,t2,t3,t4,t5,n1,n3 FROM medya WHERE ne='$ne' $qry $order");while($r=mysqli_fetch_assoc($sql)){$filepath=$path."deppo/image/".$r["t1"];if(file_exists($filepath))$t1=$weburl."/deppo/image/".$r["t1"];$arr[]=['id'=>$r["id"],'t1'=>$t1,'t2'=>$r["t2"],'t3'=>$r["t3"],'t4'=>$r["t4"],'t5'=>$r["t5"],'n1'=>$r["n1"],'n3'=>$r["n3"],'item'=>$r["t1"]];}}
	elseif($type=="ads"){$sql=mysqli_query($conn,"SELECT id,t1 FROM genel WHERE ne='$ne' $qry $order");while($r=mysqli_fetch_assoc($sql)){$arr[]=['id'=>$r["id"],'item'=>$r["t1"]];}}
	else{$sql=mysqli_query($conn,"SELECT id,ne,t1,t2,pb1,s5,s9,s10,ts1,n17 FROM $lang WHERE ne='$ne' AND s13=1 $qry $order");while($r=mysqli_fetch_assoc($sql)){$j=json_decode($r["n17"],true);$arr[]=['id'=>$r["id"],'ne'=>$r["ne"],'t1'=>$r["t1"],'t2'=>$r["t2"],'pb1'=>$r["pb1"],'s5'=>$r["s5"],'s9'=>$r["s9"],'s10'=>$r["s10"],'ts1'=>$r["ts1"],'item'=>$r["t1"],'json'=>$j];}}
	return json_encode($arr);
}

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

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

//===================> Kullanıcı bilgisi kaydı (infos.json)
function getinfo(){
	global $weburl,$conn,$module;
	$userId=$_SESSION["User_ID"];
	$path=$_SERVER['DOCUMENT_ROOT']."/deppo/datas";
	$json="$path/infos.json";
	if(!file_exists($path))mkdir($path,0755,true);
	if(!file_exists($json))file_put_contents($json,"[]");
	$datas=json_decode(file_get_contents($json),true);
	$pcontrol=0;$jset=[];
	foreach($datas as $key=>$value){
		if($value['UserIp']==$_SERVER['REMOTE_ADDR'] && $value['Url']==$_SERVER['REQUEST_URI']){
			$jset[]=$value;$pcontrol=1;
		}else $jset[]=$value;
	}
	if($pcontrol==0)$jset[]= ['id'=>date("YmdHis"),'UserId'=>$userId,'UserIp'=>$_SERVER['REMOTE_ADDR'],'Url'=>$_SERVER['REQUEST_URI'],'Date'=>date('Y-m-d H:i:s')];
	file_put_contents($json,json_encode($jset,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_NUMERIC_CHECK));
}

//===================> {id} formatındaki çoklu değerleri arraye çevirir
function multivalues($id){preg_match_all('/\{(\d+)\}/',$id,$m);return $m[1];}

//===================> Sepet işlemleri
function basket($id,$qty){
	global $conn,$weburl;
	if($id=="0" && $qty=="0"){$_SESSION["jbasket"]="";return;}
	$sql=mysqli_query($conn,"SELECT * FROM ".$_SESSION['lang']." WHERE ne='kayit' AND id=".$id);$rs=mysqli_fetch_assoc($sql);
	$datas=$_SESSION["jbasket"]==""?[]:json_decode($_SESSION["jbasket"],true);
	$jset=[];$ichck=0;
	foreach($datas as $val){
		if($val['id']==$id){$val['Qty']=$qty;$jset[]=$val;$ichck=1;}
		else $jset[]=$val;
	}
	if($ichck==0 && $qty>0)$jset[]= ['id'=>$id,'ProductCode'=>$rs["t4"],'Product'=>$rs["t1"],'Qty'=>$qty,'ProductImg'=>medya($rs["id"],1,"resim","t1",$weburl),'Date'=>date('Y-m-d H:i:s')];
	$_SESSION["jbasket"]=json_encode($jset,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_NUMERIC_CHECK);
}

//===================> Genel veri kaydı (data.json)
function setdata($process="",$eventId="",$gname="",$gvalue="",$path=""){
	global $weburl,$conn,$module;
	$eventIds=explode(",",$eventId);
	if(isset($eventIds[1]) && $eventIds[1]<>""){$eventId=$eventIds[1];$eventgId=$eventIds[0];}else{$eventId=$eventIds[0];$eventgId="0";}
	$userId=$_SESSION["User_ID"];
	$path=$_SERVER['DOCUMENT_ROOT']."/deppo/datas";$json="$path/data.json";
	if(!file_exists($path))mkdir($path,0755,true);
	if(!file_exists($json))file_put_contents($json,"[]");
	$datas=json_decode(file_get_contents($json),true);
	$jset=[];$pcontrol=0;
	foreach($datas as $value){
		if($value['UserId']==$userId && $value['Process']==$process && $value['EventId']==$eventId){$jset[]=$value;$pcontrol=1;}
		else $jset[]=$value;
	}
	if($pcontrol==0)$jset[]= ['id'=>date("YmdHis"),'UserId'=>$userId,'Process'=>$process,'EventId'=>$eventId,'Name'=>$gname,'Value'=>$gvalue,'Date'=>date('Y-m-d H:i:s')];
	file_put_contents($json,json_encode($jset,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_NUMERIC_CHECK));
}

//===================> Kullanıcıya ait verileri al
function getdata(){
	global $weburl,$jsf; $weburl=uri("domain"); $jsf=$jsf==""?"data":$jsf;
	$json=$_SERVER['DOCUMENT_ROOT']."/deppo/datas/$jsf.json";
	if(!file_exists($json))file_put_contents($json,"[]");
	$datas=json_decode(file_get_contents($json),true);
	$jset=[];
	foreach($datas as $key=>$value){
		if($value['UserId']==($_SESSION["User_ID"]??0) || $_SESSION["user_id"]==0)$jset[$key]=$value;
	}
	return $jset;
}

//===================> Belirli veriyi sil
function deldata($id=""){
	$json=$_SERVER['DOCUMENT_ROOT']."/deppo/datas/data.json";
	if(!file_exists($json))return;
	$datas=json_decode(file_get_contents($json),true);
	$jset=[];
	foreach($datas as $key=>$value){if($value['id']<>$id)$jset[$key]=$value;}
	file_put_contents($json,json_encode($jset,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_NUMERIC_CHECK));
}

//===================> Kredi kartı numarası maskesi
function ccMasking($number=''){return substr($number,0,4)." ".substr($number,4,4)." ".substr($number,8,4)." ".substr($number,12,4);}

//===================> Array veya JSON içinde değeri güncelle
function uparr($arr,$ukey="",$uval=""){
	$type=is_array($arr)?'array':'json';
	if($type=='json')$arr=json_decode($arr,true);
	foreach($arr as $key=>$value)$arr[$key]=($key==$ukey)?$uval:$value;
	if(isset($ukey))$arr[$ukey]=$uval;
	return $type=='json'?json_encode($arr,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_NUMERIC_CHECK):$arr;
}

//===================> Kart oluştur
function setcard($path="",$userId=""){
	global $weburl,$conn; $userId=$userId==""?$_SESSION["User_ID"]:$userId;
	$user=mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM t5 WHERE id='$userId'"));
	$dir=$_SERVER['DOCUMENT_ROOT']."/deppo/card"; if(!file_exists($dir))mkdir($dir,0755,true);
	$json="$dir/cards.json"; if(!file_exists($json))file_put_contents($json,"[]");
	$cards=json_decode(file_get_contents($json),true); $control=0;
	foreach($cards as $key=>$value)if($value['UserId']==$userId)$control=1;
	if($control<>1 && $userId<>""){
		$cards[]= ['UserId'=>$userId,'Number'=>generatenumber(16),'Name'=>$user["t1"],'Date'=>date('Y-m-d')];
		file_put_contents($json,json_encode($cards,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_NUMERIC_CHECK));
	}
}

//===================> Kart bilgisi al ve maskeler
function getcard($data="Number",$userId=""){
	global $weburl; $userId=$userId==""?$_SESSION["User_ID"]:$userId;
	$json=$_SERVER['DOCUMENT_ROOT']."/deppo/card/cards.json";
	if(!file_exists($json))return "";
	$cards=json_decode(file_get_contents($json),true);
	foreach($cards as $value)if($value['UserId']==$userId)return ccMasking($value[$data]??"");
	return "";
}

//===================> Puan ekle
function setpoint($process="",$eventId="",$userId="",$url=""){
	global $conn,$module; $userId=$userId==""?$_SESSION["User_ID"]:$userId;
	$url = $url==""?$_SERVER['DOCUMENT_ROOT']:$url;
	setcard($url,$userId);

	$processes = explode(",",$process); $process = $processes[1]??$process; $point = $processes[0]??0;
	$eventIds = explode(",",$eventId); $eventId = $eventIds[1]??$eventId; $eventgId = $eventIds[0]??0;
	$userIds = explode(",",$userId); $usergId = $userIds[0]??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);

	$point_type = ($process<>"events")?$rsp["s2"]:$jsei["ievent_point_type"];
	if($point==""){$point = ($process<>"events")?$rsp["t1"]:$jsei["ievent_point"]; $process = ($process<>"events")?$rsp["n1"]:$rse["t1"]; }

	$dir="$url/deppo/card"; if(!file_exists($dir))mkdir($dir,0755,true);
	$json="$dir/points.json"; if(!file_exists($json))file_put_contents($json,"[]");
	$points = json_decode(file_get_contents($json),true); $jset=[]; $total_point=0; $pcontrol=0;

	foreach($points as $key=>$value){
		if(mysqli_num_rows($sqlp)>0 && $point_type==0 && $value['UserId']==$userId && $value['EventId']==$eventId) $pcontrol=1;
		if(mysqli_num_rows($sqlp)>0 && $point_type==1 && $value['UserId']==$userId && $value['EventId']==$eventId && $value['Date']==date('Y-m-d')) $pcontrol=1;
		$jset[$key]=$value;
		if($value['UserId']==$userId && $value['Date']==date('Y-m-d') && ($value['Desc']==$process || substr($value['Desc'],0,11)=='Etkinlik_ID')) $total_point+=$value['Point'];
	}

	$pass=($module["point_limit"]=="" || $module["point_limit"]>=($total_point+$point)) && ($rsp["t3"]=="" || $rsp["t3"]>=($total_point+$point));

	if($pass<>1){
		echo "<script>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>";
	}

	if($pcontrol<>1){
		$jset[]= [
			'Id'=>date("ymdhis"), 'EventgId'=>$eventgId, 'EventId'=>$eventId, 'UsergId'=>$usergId,
			'UserId'=>$userId, 'Point'=>$point, 'Desc'=>$process, 'Date'=>date('Y-m-d')
		];
		file_put_contents($json,json_encode($jset,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_NUMERIC_CHECK));
	}
}

//===================> Puan sil
function delpoint($id="",$url=""){
	$url=$url==""?$_SERVER['DOCUMENT_ROOT']:$url;
	$json="$url/deppo/card/points.json"; if(!file_exists($json))return;
	$points=json_decode(file_get_contents($json),true); $jset=[];
	foreach($points as $key=>$value)if($value['Id']<>$id)$jset[$key]=$value;
	file_put_contents($json,json_encode($jset,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_NUMERIC_CHECK));
}

//===================> Puan bilgisi
function getpoint($userId="",$type="",$url=""){
	global $weburl; $userId=$userId==""?$_SESSION["User_ID"]:$userId;
	$url=$url==""?$weburl:$url; $json="$url/deppo/card/points.json"; if(!file_exists($json))return 0;
	$points=json_decode(file_get_contents($json),true); $jset=[]; $point=0;
	foreach($points as $key=>$value){
		if($userId==0 || $value['UserId']==$userId){$point+=$value['Point']; $jset[$key]=$value;}
	}
	return $type==""?$point:json_encode($jset,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_NUMERIC_CHECK);
}

//===================> Para puan ekle
function parapuan($ne="",$ID=""){
	global $conn; $ID=$ID==""?$_SESSION["User_ID"]:$ID;
	$sqlp=mysqli_query($conn,"SELECT t1 FROM genel WHERE ne='point' AND t2='$ne'"); if(mysqli_num_rows($sqlp)==0)return;
	$point=mysqli_fetch_assoc($sqlp);
	$sqlu=mysqli_query($conn,"SELECT s11 FROM t5 WHERE id='$ID'"); $user=mysqli_fetch_assoc($sqlu);
	$upuan=$user["s11"]+$point["t1"];
	mysqli_query($conn,"UPDATE t5 SET s11='$upuan' WHERE id='$ID'");
}

//===================> Hediye çeki oluştur
function hediyeceki($ne="",$ID=""){
	global $conn,$module; $ID=$ID==""?$_SESSION["User_ID"]:$ID;
	$s2 = ($ne=="tavsiye")?"3":(($ne=="kayit")?"2":(($ne=="siparis")?"4":"0")); if($module["hediye_ceki"]!=1) return;
	$sqld=mysqli_query($conn,"SELECT t2,pb1,pb2,s1,s2,s3,ts2 FROM genel WHERE ne='i-kod' AND s2=$s2");
	if(mysqli_num_rows($sqld)==0) return;
	$dcode=mysqli_fetch_assoc($sqld);
	$sqlco=mysqli_query($conn,"SELECT id FROM eticaret WHERE ne='siparis' AND t6='".$dcode["t1"]."' AND s1='".$_SESSION["s19"]."'");
	$sqlcc=mysqli_query($conn,"SELECT id FROM genel WHERE ne='i-kod' AND s2=4 AND s19='$ID'");
	if((mysqli_num_rows($sqlco)==0 && $s2==4 && mysqli_num_rows($sqlcc)==0) || $s2<>4){
		mysqli_query($conn,"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;
    // Cache sistemi: Önceden yapılmış çağrıları sakla
		static $cache = [];
    // Cache'den kontrol et
		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
    $n4 = "";
    if (in_array($t2, ["analytics", "dogrula", "sms", "email", "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;
}

// publish_date: Gün bazlı sonraki yayın tarihini hesaplar
function publish_date($date){$d=date("l",strtotime($date));$map=["Monday"=>'thursday this week',"Tuesday"=>'friday this week',"Wednesday"=>'saturday this week',"Thursday"=>'monday next week',"Friday"=>'tuesday next week',"Saturday"=>'wednesday next week',"Sunday"=>'wednesday next week'];return date("Y-m-d",strtotime($map[$d]??'now',strtotime($date)));}

// publish_date_viewer: Yayın tarihi veya eklenme tarihini döner (class+formatlı)
function publish_date_viewer($ts1,$ts3){$t=date("Y-m-d");if(!empty($ts3)&&$ts3!="0000-00-00 00:00:00"){$d=date("Y-m-d",strtotime($ts3));$pdc=($d<=$t?"bg-success":"bg-warning");$pdate=dtarih($ts3,"gg ka yy");}else{$pdc="bg-info";$pdate=dtarih($ts1,"gg ka yy");}return["class"=>$pdc,"formattedDate"=>$pdate];}

// csablon: {degisken} biçimli post veya session yer tutucularını değiştirir
function csablon($m){foreach($_POST as $k=>$v)$m=str_replace("{".$k."}",$v,$m);foreach($_SESSION as $k=>$v)$m=str_replace("{".$k."}",$v,$m);return $m;}

// sablon: genel tablosundan şablon yapısını getirip csablon ile işler
function sablon($id){global $conn;$r=mysqli_query($conn,"select * from genel where id='$id'");if($r&&mysqli_num_rows($r)>0){$x=mysqli_fetch_assoc($r);$m=$x["n7"].$x["n1"].$x["n6"];}return csablon($m??'');}

// emailgonder: belirlenen alıcıya mail gönderir (unsubscribe kontrolü içerir)
function emailgonder($malici="",$konu="",$cc="",$mesaj="",$ne="noreply"){global $conn,$mgonderen,$path,$firma,$sunucu,$mail,$msifre,$c4,$cpath;$r=mysqli_query($conn,"select id from genel where ne='unsubscribe' and t1='$malici'");if(mysqli_num_rows($r)==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);$mesaj=str_replace("{malici}",base64_encode($malici),$mesaj);include("mail/index.php");}else echo"Unsubscribed";}

// isJson: String JSON mu kontrol eder
function isJson($s){json_decode($s);return json_last_error()===JSON_ERROR_NONE;}

// string_to_float: Türkçe sayı formatını float’a çevirir
function string_to_float($s){return(float)str_replace(",",".",$s);}

// smsgonder: SMS servislerine göre mesaj yollar (unsubscribe kontrolü dahil)
function smsgonder($smstxt="",$gsm=""){global $conn;$r=mysqli_query($conn,"select id from genel where ne='unsubscribe' and t1='$gsm'");if(mysqli_num_rows($r)==0){$p=tanim("sms","n6",0);if($p=="netgsm"){$sd=str_replace(['.',' ',':'],'',date('d.m.Y H:i'));$ed=str_replace(['.',' ',':'],'',date('d.m.Y H:i',strtotime('+1 day')));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=$sd&stopdate=$ed");}
elseif($p=="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($p=="iletimerkezi"){$send=function($u,$x){$ch=curl_init();curl_setopt_array($ch,[CURLOPT_URL=>$u,CURLOPT_POST=>1,CURLOPT_POSTFIELDS=>$x,CURLOPT_SSL_VERIFYHOST=>1,CURLOPT_SSL_VERIFYPEER=>0,CURLOPT_RETURNTRANSFER=>1,CURLOPT_HTTPHEADER=>['Content-Type: text/xml'],CURLOPT_TIMEOUT=>120]);return curl_exec($ch);};$xml="<request><authentication><key>".tanim("sms","n1",0)."</key><hash>".tanim("sms","n2",0)."</hash></authentication><order><sender>".tanim("sms","n3",0)."</sender><sendDateTime></sendDateTime><message><text><![CDATA[$smstxt]]></text><receipents><number>".telefon($gsm)."</number></receipents></message></order></request>";$send('http://api.iletimerkezi.com/v1/send-sms',$xml);}
elseif($p=="asist"){$k=explode(',',tanim("sms","n5",0));$params=['Username'=>tanim("sms","n1",0),'Password'=>tanim("sms","n2",0),'UserCode'=>$k[0],'AccountId'=>$k[1],'Originator'=>tanim("sms","n3",0),'SendDate'=>'','ValidityPeriod'=>60,'MessageText'=>$smstxt,'IsCheckBlackList'=>'1','ReceiverList'=>[$gsm]];$wsdl='https://webservice.asistiletisim.com.tr/SmsProxy.asmx?WSDL';$xml='<SendSms/>';$SendSms=new SimpleXMLElement($xml);foreach($params as$K=>$V){if($K=='ReceiverList'){$RL=$SendSms->addChild('ReceiverList');foreach($V as$G)$RL->addChild('Receiver',$G);}else$SendSms->addChild($K,$V);}try{$soap=new SoapClient($wsdl,['trace'=>1,'exceptions'=>1]);$soap->sendSms(['requestXml'=>str_replace('<?xml version="1.0"?>','',trim($SendSms->asXML()))]);}catch(Exception$e){}}
elseif($p=="verimor"){$msg=["username"=>tanim("sms","n1",0),"password"=>tanim("sms","n2",0),"source_addr"=>tanim("sms","n3",0),"custom_id"=>"1424441160.9331344","messages"=>[["msg"=>$smstxt,"dest"=>"90".$gsm]]];$ch=curl_init('http://sms.verimor.com.tr/v2/send.json');curl_setopt_array($ch,[CURLOPT_POST=>1,CURLOPT_RETURNTRANSFER=>1,CURLOPT_HTTPHEADER=>['Content-Type: application/json'],CURLOPT_POSTFIELDS=>json_encode($msg)]);$res=curl_exec($ch);if(curl_getinfo($ch,CURLINFO_HTTP_CODE)!=200)echo$res;}}}

// SMS Bakiye sorgulama
function smsbakiye(){
	$suser=tanim("sms","n1",0);$spass=tanim("sms","n2",0);
	switch(tanim("sms","n6",0)){
		case "netgsm":
			return HTTPPOST("https://api.netgsm.com.tr/get_kredi.asp?usercode=$suser&password=$spass");
		case "verimor":
			$url="http://sms.verimor.com.tr/v2/balance?username=$suser&password=".urlencode($spass);
			$ch=curl_init($url);curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
			$res=curl_exec($ch);$code=curl_getinfo($ch,CURLINFO_HTTP_CODE);
			if($code!=200)return false;return $res;
		case "smsvitrini":
			require_once "smsvitrini_class.php";
			try{$cred=new CredentialsHash('8450b5a166e4a75b103f7c49b3a5ac256bd8a5eb');$api=new MesajPaneliApi($cred);return $api->baslikliKrediSorgula();}
			catch(Exception $e){return $e->getMessage();}
		case "iletimerkezi":
			$api_key=$suser;$api_hash=$spass;
			$xml="<request><authentication><key>$api_key</key><hash>$api_hash</hash></authentication></request>";
			$ch=curl_init("https://api.iletimerkezi.com/v1/get-balance");
			curl_setopt_array($ch,[CURLOPT_POST=>1,CURLOPT_POSTFIELDS=>$xml,CURLOPT_SSL_VERIFYPEER=>0,CURLOPT_RETURNTRANSFER=>1,CURLOPT_HTTPHEADER=>['Content-Type:text/xml']]);
			$res=curl_exec($ch);$xml=new SimpleXMLElement($res);return (string)$xml->balance->sms;
	}
	return 0;
}

// JSON'dan CSV oluşturur
function jsonToCSV($jsonFile,$csvFile){
	if(!($json=file_get_contents($jsonFile)))die('JSON okunamadı.');
	$data=json_decode($json,true);$fp=fopen($csvFile,'w');
	$header=false;foreach($data as $row){if(!$header){$header=array_keys($row);fputcsv($fp,$header);$header=array_flip($header);}fputcsv($fp,array_merge($header,$row));}
	fclose($fp);
}

// Tarih sabitleri
$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"));
$gunler=['Pazartesi','Salı','Çarşamba','Perşembe','Cuma','Cumartesi','Pazar'];
$aylar=['Ocak','Şubat','Mart','Nisan','Mayıs','Haziran','Temmuz','Ağustos','Eylül','Ekim','Kasım','Aralık'];
$kgunler=['Pt','Sa','Ça','Pe','Cu','Ct','Pz'];$kaylar=['Ock','Şub','Mar','Nis','May','Haz','Tem','Ağu','Eyl','Eki','Kas','Ara'];

// Haftasonu kontrolü
function isWeekend($d=""){return in_array(date('w',strtotime($d)),[0,6]);}

// Yıl içi gün farkı (tekrar döngülü)
function dt($t="",$loop=""){[$y,$m,$d]=explode('-',$t);$x=strtotime(date("Y")."-$m-$d 00:00:00");$y2=strtotime(date("Y-m-d 00:00:00"));$gun=($x-$y2)/(60*60*24);if($loop==""&&$gun<0)$gun+=365;if($gun<0)$gun="...";return $gun;}

// İki tarih farkı (gün sayısı veya detaylı)
function tfark2($t1="",$t2="",$type=""){if($type=="number")return (strtotime(substr($t2,0,10))-strtotime(substr($t1,0,10)))/(60*60*24);
$d1=new DateTime($t1);$d2=new DateTime($t2);$d=$d2->diff($d1);return ($d->y?"$d->y Yıl, ":"").($d->m?"$d->m Ay, ":"")."$d->d Gün";}

// Tarihe gün ekle
function vade($t="",$f=""){ $dt=new DateTime(substr($t,0,10));$dt->modify("+$f day");return $dt->format('Y-m-d');}

// Belirtilen tarihe kalan saniye farkı
function dleft($t=""){if($t=="")return 0;[$y,$m,$d]=explode('-',$t);return strtotime(date("Y")."-$m-$d 00:00:00")-strtotime(date("Y-m-d 00:00:00"));}

// Belirtilen tarih ile bugünün farkı (gün)
function daynow($z="",$max=""){[$y,$m,$d]=explode('-',$z);$x=strtotime("$y-$m-$d 00:00:00");if($max!="")$x=strtotime("$max day",$x);return ($x-strtotime(date('Y-m-d 00:00:00')))/(60*60*24);}

// Tarih farkı (d.m.Y)
function daydmy($z="",$max=""){[$y,$m,$d]=explode('-',$z);$x=strtotime("$y-$m-$d 00:00:00");if($max!="")$x=strtotime("$max day",$x);return ($x-strtotime(date('Y-m-d 00:00:00')))/(60*60*24);}

// Zamanı "önce" formatında gösterir
function timeAgo($z=""){ $z=strtotime($z);$f=time()-$z;
$s=$f;$m=round($f/60);$h=round($f/3600);$g=round($f/86400);$w=round($f/604800);$a=round($f/2419200);$y=round($f/29030400);
if($s<60)return $s==0?"az önce":"$s sn önce";if($m<60)return "$m dk önce";if($h<24)return "$h saat önce";if($g<7)return "$g gün önce";
if($w<4)return "$w hafta önce";if($a<12)return "$a ay önce";return "$y yıl önce";}

//-- Ay ve Gün Dönüştürme Yardımcıları -->
//function kisaay($a){$ay=["","Ock","Şub","Mar","Nis","May","Haz","Tem","Ağu","Eyl","Eki","Kas","Ara"];return $ay[(int)$a];}
//function uzunay($a){$ay=["","Ocak","Şubat","Mart","Nisan","Mayıs","Haziran","Temmuz","Ağustos","Eylül","Ekim","Kasım","Aralık"];return $ay[(int)$a];}
//function kisagun($g){$gun=["Mon"=>"Pt","Tue"=>"Sa","Wed"=>"Ça","Thu"=>"Pe","Fri"=>"Cu","Sat"=>"Ct","Sun"=>"Pz"];return $gun[$g]??"";}
//function uzungun($g){$gun=["Monday"=>"Pazartesi","Tuesday"=>"Salı","Wednesday"=>"Çarşamba","Thursday"=>"Perşembe","Friday"=>"Cuma","Saturday"=>"Cumartesi","Sunday"=>"Pazar"];return $gun[$g]??"";}

//-- Tarih Kısa -->
function dts($tarih=""){
	if(!$tarih || !strtotime($tarih)) return "";
	$bol = explode('-', substr($tarih,0,10));
	return sprintf("%02d %s %s", $bol[2], uzunay($bol[1]), $bol[0]);
}

//-- Tarih Düzenle -->
function dtarih($tarih="", $format="gg.ka.yy time"){
	if(!$tarih || !strtotime($tarih)) return "";
	$format=str_replace("+"," ",$format);
	$dt=strtotime($tarih);
	$gg=date("d",$dt);
	$aa=date("m",$dt);
	$yyyy=date("Y",$dt);
	$yy=substr($yyyy,2,2);
	$time=date("H:i",$dt);
	$kg= kisagun(date('D',$dt));
	$ug= uzungun(date('l',$dt)); $format=str_replace( ["gg","aa","ka","ua","yyyy","yy","time","kg","ug"], [$gg,$aa,kisaay($aa),uzunay($aa),$yyyy,$yy,$time,$kg,$ug], $format );
	return trim($format);
}
// echo dtarih(date('Y-m-d H:i:s'), 'gg ua yyyy time - ug');

//-- Para Yazı ile -->
function yaziile($sayi="", $kurusbasamak=2, $parabirimi="TL", $parakurus="KR", $karakter="") {
	$b1=["","bir","iki","üç","dört","beş","altı","yedi","sekiz","dokuz"];
	$b2=["","on","yirmi","otuz","kırk","elli","altmış","yetmiş","seksen","doksan"];
	$b3=["","yüz","bin","milyon","milyar","trilyon","katrilyon"];
	$sayi=str_replace(",",".",$sayi);
	$parca=explode(".",$sayi);
	$tam=$parca[0]; $kurus=$parca[1]??"";
	$sonuc=""; $uzun=strlen($tam);
	$grup=0;
	while($uzun>0){
		$uc=substr($tam,max(0,$uzun-3),3);
		$uzun-=3; $yaz="";
		$bir=substr($uc,-1);
		$on=substr($uc,-2,1);
		$yuz=substr($uc,-3,1);
		if($yuz>0){$yaz.=($yuz==1?"":$b1[$yuz]).$b3[1];}
		if($on>0){$yaz.=$b2[$on];}
		if($bir>0){$yaz.=$b1[$bir];}
		if($uc>0){$yaz.=$b3[$grup+2];}
		$sonuc=$yaz.$sonuc; $grup++;
	}
	if($kurus!=""){
		$kurus=substr(str_pad($kurus,2,"0"),0,$kurusbasamak);
		$kurusyazi="";
		if($kurus>0){
			$kurusyazi.=$b2[substr($kurus,0,1)];
			$kurusyazi.=$b1[substr($kurus,1,1)];
			$kurusyazi.=" ".$parakurus;
		}
	}
	return trim("$karakter$sonuc $parabirimi $kurusyazi$karakter");
}
// echo yaziile(1234.56,2,"TL","KR","«»");

//======================> KDV HESAPLAMA <======================//
function kdv($tutar=0, $kdv=18, $islem=0){
	if(!is_numeric($tutar) || !is_numeric($kdv)) return 0;
	$yuzde=($kdv+100)/100;
	switch($islem){
		case 0: return round($tutar*$yuzde,2); // KDV ekle
		case 1: return round($tutar/$yuzde,2); // KDV çıkar
		case 2: return round(($tutar*$yuzde)-$tutar,2); // +KDV farkı
		case 3: return round($tutar-($tutar/$yuzde),2); // -KDV farkı
		default: return $tutar;
	}
}

//======================> YÜZDE HESAPLARI <======================//
function yuzdesi($p1=0,$p2=0){
	if($p1==0 || $p2==0) return 0;
	$p1=floatval(str_replace(",","." ,$p1));
	$p2=floatval(str_replace(",","." ,$p2));
	if($p2==0) return 0;
	$oran=(($p1*100)/$p2)-100;
	return ceil(abs($oran));
}

function yuzde($sayi=0,$yuzde_deger=0,$secenek=1){
	if(!is_numeric($sayi)||!is_numeric($yuzde_deger))return 0;
	$yuzdemiz=($sayi*$yuzde_deger)/100;
	switch($secenek){ case 1:return ceil($yuzdemiz); case 2:return ceil($sayi-$yuzdemiz); case 3:return ceil($sayi+$yuzdemiz); case 4:return ceil($sayi*$yuzdemiz); case 5:return ceil(($yuzdemiz>0)?$sayi/$yuzdemiz:0); default:return ceil($yuzdemiz); }
}

//======================> DÖVİZ & KUR GÜNCELLEME <======================//
function kural($u=0,$kurTipi="BanknoteSelling"){
	global $b10,$t40,$conn,$usd,$eur,$gbp,$grgold,$btc;
	$kurTipi=$kurTipi?:'BanknoteSelling';
	$old_usd=$usd??0;$old_eur=$eur??0;$old_gbp=$gbp??0;$old_grgold=$grgold??0;$old_btc=$btc??0;
	$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){
		// Gram Altın
		try{
			$new_gr_data=@json_decode(file_get_contents('https://api.exchangerate-api.com/v4/latest/USD'),true);
			$grgold=$new_gr_data['rates']['TRY']??0;
		}catch(Exception $e){$grgold=0;}

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

		// TCMB XML
		try{
			$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;
			}
		}catch(Exception $e){
			$usd_S=$eur_S=$gbp_S=0;
		}

		$exchanges=[
			"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)
		];
		if($usd_S!=""||$eur_S!=""||$gbp_S!=""){
			mysqli_query($conn,"UPDATE ".$_SESSION['lang']." SET t40='".addslashes(json_encode($exchanges))."' WHERE ne='ayarlar'");
		}
	}
}

//======================> YÜZDE İNDİRİM <======================//
function iyuzde($tutar2=0,$tutar1=0){
	if($tutar1==0)return 0;
	return round((($tutar2-$tutar1)/$tutar1)*100,2);
}

//======================> LOKASYON BULMA <======================//
function loc($id="",$type="il"){
	global $locations;
	if(!isset($locations)||!is_array($locations))return "";
	$location="";
	if(is_numeric($id)){
		foreach($locations as $a){if($a["id"]==$id){$location=$a["t1"];break;}}
	}else{
		foreach($locations as $a){if(stripos($a["t1"],$id)!==false && $a["ne"]==$type){$location=$a["id"];break;}}
	}
	return $location;
}

//======================> MEDYA <======================//
function medya($s1="", $s2="", $ne="", $stn="", $lng="", $url="", $exists=""){
	global $module,$conn,$mobile,$t44,$weburl,$cpath,$cdnurl;
	$msorgu="";$m="";$mpath="";$medya="";$yok="";
	if(!isset($module))$module=[];
	$url=($module["media_path"]??$url).(($module["media_path"]??$url)?"\/":"");
	$yok=($module["stamp"]??"")? "{$url}deppo/image/{$module["stamp"]}" : "//cdn.{$cdnurl}/images/crm-plus-stamp.png";

	$sne=explode("+",$ne);
	$ss1=explode("+",$s1);
	if($lng!="")$msorgu.=" and t6='{$lng}'";
	if($s2!=""||$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]}";
	$nedir=($sne[0]=="kresim")?"resim":$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}");
	if($sqlm && mysqli_num_rows($sqlm)>0){
		$rsm=mysqli_fetch_assoc($sqlm);
		$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')";

		switch($sne[0]){
			case "resim":
				$dosya=$rsm[$stn]??"";
				$mpath="{$url}deppo/image/";
				$medya=(file_exists("{$cpath}deppo/image/{$dosya}")||$url!="")?$dosya:$yok;
			break;
			case "kresim":
				if(!in_array(end($uzanti),["svg","webp"]))$m="k_";
				$dosya=$m.($rsm[$stn]??"");
				$mpath="{$url}deppo/image/";
				$medya=(file_exists("{$cpath}deppo/image/{$dosya}")||$url!="")?$dosya:$yok;
			break;
			case "video":
				if($stn=="n1"){$mpath="";$medya=$rsm[$stn];}
				elseif($stn=="n2"){$mpath="{$cpath}deppo/video/";$medya=$rsm[$stn];}
			break;
			case "dosya":
				$mpath="{$cpath}deppo/dosya/";
				$medya=$rsm[$stn]??"";
			break;
			default:
				$medya=$rsm[$stn]??$yok;
			break;
		}
	}else $medya=$yok;
	if($exists!="" && $medya==$yok)return "0";
	return $mpath.$medya;
}

//======================> KATEGORİ <======================//
function kategori($id="",$stn=""){
	global $conn,$cpath;
	if(!$id)return "";
	if(preg_match_all('/\{(\d+)\}/',$id,$m))$ids=$m[1];else$ids=[$id];
	$out=[];
	foreach($ids as $sid){
		$sqlc=mysqli_query($conn,"SELECT Cat_ID,Cat_{$_SESSION["lang"]} as cat,image,n1 FROM kategoriler WHERE Cat_ID='{$sid}'");
		if($sqlc && mysqli_num_rows($sqlc)>0){
			$rsc=mysqli_fetch_assoc($sqlc);$jslf=json_decode($rsc["n1"],true);
			if($stn=="")$cat=$jslf[$_SESSION["lang"]]??$rsc["cat"];
			elseif($stn=="image"){
				$path="{$cpath}deppo/kategori/".$rsc["image"];
				$cat=file_exists($path)?$path:"{$cpath}deppo/tools/img/yok.png";
			}else $cat=$rsc[$stn]??"";
		}else{
			$sqlsc=mysqli_query($conn,"SELECT t1 FROM {$_SESSION["lang"]} WHERE id='{$sid}'");
			$rssc=mysqli_fetch_assoc($sqlsc);
			$cat=$rssc["t1"]??"#{$sid}";
		}
		$out[]=$cat;
	}
	return implode(" / ",$out);
}

//======================> SABİT <======================//
function sabit($id="",$ne="",$stn=""){
	global $conn;
	if(!$id||!$ne)return "";
	$ids=explode("+",$id);$tsql="";
	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(in_array($ne,["sayfa","haber","msayfa","kayit"]))$nedir=$_SESSION["lang"];
	elseif(in_array($ne,["isayfa","extra"]))$nedir="t1";
	elseif($ne=="uye")$nedir="t5";
	else $nedir=$_SESSION["lang"];

	$sqls=mysqli_query($conn,"SELECT * FROM {$nedir} WHERE ne='{$ne}' {$tsql}");
	if($sqls && mysqli_num_rows($sqls)>0){
		$rss=mysqli_fetch_assoc($sqls);$jsi=json_decode($rss["n17"],true);
		if(substr($stn,0,2)=="id" || substr($stn,0,1)!="i")$stxt=$rss[$stn]??"";
		else $stxt=$jsi[$stn]??"";
	}else $stxt="#{$id} Kayıt Bulunamadı";
	return $stxt;
}

//--- Mlinked ve Linked Fonksiyonları ---//
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) return "#$id kayıt yok";
	$q=match($rs["t2"]){
		"kayit"=>"d","sayfa"=>"s","haber"=>"h","msayfa"=>"m","uye"=>"u",
		"skategori","hkategori","mkategori"=>"a",
		"ukategori"=>"x","ualt_kategori"=>"y","ualt_kategori2"=>"z",
		default=>substr($rs["t2"],0,1)
	};
	echo $rs["n5"]<>"" ? $rs["n5"] : linked($q,$rs["s3"]);
}

function linked($ne="",$id="",$ver="",$url=""){
	global $module,$conn,$weburl,$lveri;
	static $cache=[];
	$key="link_{$ne}_{$id}_{$ver}_{$url}";
	if(isset($_SESSION["cache"][$key])) return $_SESSION["cache"][$key];

	$fseo=$module["fseo"]??"0";
	$w3=($fseo=="0")?($url? "$url?" : "?"):(($url?rtrim($url,"/"):rtrim($weburl,"/"))."/");
	$dil=$_SESSION["lang"]??"tr";
	$katTip=["x","y","z","w","j","a","b","c"];
	$veri=!empty($lveri)?$lveri:null;

	if($veri===null){
		if(in_array($ne,$katTip))
			$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 id,t2 from medya where id=".intval($id);
		else
			$sql="select id,t1,n3,n5 from $dil where id=".intval($id);
		$q=mysqli_query($conn,$sql);
		if(!$q||!mysqli_num_rows($q)){$_SESSION["cache"][$key]="#$id Bulunamadı";return $_SESSION["cache"][$key];}
		$veri=mysqli_fetch_assoc($q);
	}

	$cevir=fn($t)=>cevir($t);
	$rlang=fn($t)=>rlang($t);

	$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"]??"";
	$firma=$n17["ifirma"]??"";
	$isim=$n1[$dil]??$catDil;
	$link="";

	switch($fseo){
		case "0": // klasik
			if(in_array($ne,$katTip))
				$link=$n5?:($n3?$w3.$ne.$id."/".$cevir($n3):$w3.$ne.$id."/".$cevir($isim));
			elseif($ne=="u")
				$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));
		break;
		case "1": // seo-id
			if(in_array($ne,$katTip))
				$link=$n5?:($isim?$w3.$cevir($isim)."-".$ne.$id:$w3.$ne.$id);
			elseif($ne=="u")
				$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);
		break;
		case "2": // tam seo
			if(in_array($ne,$katTip))
				$link=$n5?:$w3.$cevir($isim);
			elseif($ne=="u")
				$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)));
		break;
		default:
			$link=$w3.$ne.$id;
	}
	$_SESSION["cache"][$key]=$link;
	return $link;
}
// örnek: echo linked("s",12);  echo linked("x",7);  echo linked("u",5);

//--- Meta Fonksiyonu ---//
// Verilen içerik tipine (sayfa, kategori, kullanıcı vs.) göre meta bilgisini döndürür ve cache’ler
function meta($ne = "", $id = "") {
    global $conn;
    $lang = $_SESSION["lang"] ?? "tr";
    $cacheKey = "meta_{$ne}_{$id}_{$lang}";
    if (isset($_SESSION["cache"][$cacheKey])) return $_SESSION["cache"][$cacheKey];

    $meta = "";
    if (in_array($ne, ["x", "y", "z", "a", "b", "c"])) { // Kategori meta
        $sql = "SELECT n1, n3, Cat_$lang FROM kategoriler WHERE Cat_ID=" . intval($id);
        $row = mysqli_fetch_assoc(mysqli_query($conn, $sql) ?: []);
        $jscl = json_decode($row["n1"] ?? "", true);
        $meta = $row["n3"] ?? $jscl[$lang] ?? $row["Cat_$lang"] ?? "";
    } elseif ($ne === "u") { // Kullanıcı/firma meta
        $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT t1,n3,n17 FROM t5 WHERE id=" . intval($id)) ?: []);
        $jsi = json_decode($row["n17"] ?? "", true);
        $meta = $jsi["ifirma"] ?? $row["t1"] ?? "";
    } elseif ($ne === "t") { // Özel tip t1 tablosu
        $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT t1,n3 FROM t1 WHERE id=" . intval($id)) ?: []);
        $meta = $row["n3"] ?? $row["t1"] ?? "";
    } else { // Genel içerik
        $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT t1,n3 FROM $lang WHERE id=" . intval($id)) ?: []);
        $meta = !empty($row["n3"]) ? rlang($row["n3"]) : rlang($row["t1"] ?? "");
    }

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

//--- Reklam Fonksiyonu ---//
// Verilen reklam ID’sine göre reklam içeriğini döndürür (image, video, text veya kod)
function reklam($id = "", $s12 = "0", $stn = "", $s19 = "") {
    global $conn, $cdnurl, $module, $mobile;
    $url = ($module["media_path"] ?? uri("domain") . "/") . "/";
    $qry = $s19 != "" ? " AND s19='$s19'" : "";
    $r = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM genel WHERE ne='reklam' AND (s1='$id' OR id='$id') AND s12=$s12 AND s13=1 $qry") ?: []);
    if (!$r) return "";

    $ad = ($mobile != "" && $r["t16"] != "") ? "t16" : "t6";
    $jsi = json_decode($r["n17"] ?? "", true);

    if ($stn == "") {
        $n4 = $r["n4"] ?: 'style="max-width:100%;"';
        $n2 = ($r["t7"] != "1" && $r["n2"] != "") ? "ad/{$r['id']}" : ($r["n2"] ?: "#");

        if ($r["t3"] == "image" && $r[$ad] != "") {
            $reklam = "<a href=\"$n2\" {$r['t10']} target=\"{$r['t8']}\" id=\"ad{$r['id']}\"><img src=\"{$url}deppo/rek-lam/{$r[$ad]}\" $n4 /></a>";
        } elseif ($r["t3"] == "video" && $r[$ad] != "") {
            $reklam = "<video controls><source src=\"{$url}deppo/rek-lam/{$r[$ad]}\" $n4 type=\"video/mp4\"></video>";
        } elseif ($r["t3"] == "text" && $r["n1"] != "") {
            $reklam = $r["n1"];
        } elseif ($r["t3"] == "kod" && $r["n3"] != "") {
            $reklam = $r["n3"];
        } else {
            $reklam = "<a href=\"#\" {$r['t10']} target=\"{$r['t8']}\" id=\"ad{$r['id']}\"><img src=\"https://sample.$cdnurl/{$r['t4']}x{$r['t5']}\" $n4 /></a>";
        }
    } else {
        $reklam = substr($stn, 0, 1) != "i" ? $r[$stn] : $jsi[$stn] ?? "";
    }

    return $reklam;
}

//--- Ads Fonksiyonu ---//
// Çoklu medya içeren reklamları Owl Carousel ile gösterir, tekse direkt reklam fonksiyonunu çağırır
function ads($id = "", $s12 = "0", $stn = "", $s19 = "") {
    global $conn, $module;
    $url = uri("domain") . "/";
    $qry = $s19 != "" ? " AND s19='$s19'" : "";
    $r = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM genel WHERE ne='reklam' AND (s1='$id' OR id='$id') AND s13=1 $qry") ?: []);
    if (!$r) return;

    $icount = mysqli_num_rows(mysqli_query($conn, "SELECT id FROM medya WHERE ne='resim' AND s1={$r['id']} AND s13=1"));
    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={$r['id']} AND s13=1 ORDER BY s3 ASC");
        while ($m = mysqli_fetch_assoc($sqli)) {
            echo "<div class=\"item\"><img src=\"{$url}deppo/image/{$m['t1']}\"></div>";
        }
        echo '</div>';
    } else {
        echo reklam($id, $s12, $stn, $s19);
    }
}

//--- Translations verilerini MySQL'den alır ve JSON üzerinden API'ye gönderir ---//
function initializeTranslations() {
    global $conn, $weburl;
    $sql = mysqli_query($conn, "SELECT * FROM genel WHERE ne='sdil'");
    if (!$sql || mysqli_num_rows($sql) == 0) return;

    $translations = [];
    $counter = 1;
    while ($row = mysqli_fetch_assoc($sql)) {
        $translations[$counter++] = [
            "key" => $row['n20'],
            "lang1" => $row['n1'],
            "lang2" => $row['n2']
        ];
    }

    $translationurl = $weburl . "/deppo/tools/script/translations.php?type=transfer";
    $ch = curl_init($translationurl);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($translations),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json']
    ]);

    $response = curl_exec($ch);
    curl_close($ch);
    print_r($response);

    if (trim($response) === "Çeviri verileri başarıyla güncellendi.") {
        mysqli_query($conn, "DELETE FROM genel WHERE ne='sdil'");
    }
}

//--- Metni çevirir, cache kullanır, gerekirse yeni çeviri ekler ---//
function translate($metin = "", $lang2 = "") {
    global $firm, $weburl, $kpb, $kargolmt, $_SESSION;
    static $translations = null, $cache = [];
    $filePath = $weburl."/deppo/datas/translations.json";
    $add = false;

    if ($metin[0] === "+") { $metin = substr($metin, 1); $add = true; }

    $metin = str_replace(
        ["{ftel}", "{fmail}", "{weburl}", "{firma}", "{fadres}", "{cargo_limit}", "{kpb}"],
        [$firm["ftel"], $firm["fmail"], $weburl, $firm["firma"], $firm["fadres"], $kargolmt, $kpb],
        $metin
    );

    if (isset($cache[$metin])) return $cache[$metin];
    if ($translations === null) $translations = json_decode(file_get_contents($filePath), true);
    $langKey = $_SESSION["lang"] ?? "lang1";

    foreach ($translations as $t) {
        if ($t['key'] === $metin) return $cache[$metin] = $t[$langKey] ?? $t["lang1"];
    }

    if ($add) {
        $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(['metin' => $metin]),
            CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded']
        ]);
        curl_exec($ch);
        curl_close($ch);
    }

    if (!empty($lang2)) return $cache[$metin] = ($_SESSION["lang"] == "lang1") ? $metin : $lang2;
    return $cache[$metin] = $metin;
}

//--- Verilen metin translations.json içinde var mı kontrol eder ---//
function hasTranslation($metin) {
    global $weburl;
    static $translations = null;
    if ($translations === null) $translations = json_decode(file_get_contents($weburl."/deppo/datas/translations.json"), true);
    foreach ($translations as $t) if ($t['key'] === $metin) return true;
    return false;
}

//--- CRM modülü etkinse cache üzerinden çeviri sağlar, yoksa ekler ---//
function ctranslate($word = "", $path = "../") {
    global $module;
    if ($module["m1_crm"] == "") return $word;

    $cacheFile = $_SERVER['DOCUMENT_ROOT'] . "/deppo/datas/translate_" . $_SESSION["clang"] . ".json";
    static $translationsCache = null;
    if ($translationsCache === null) {
        $translationsCache = file_exists($cacheFile) ? json_decode(file_get_contents($cacheFile), true) : [];
    }

    foreach ($translationsCache as $t) {
        if (isset($t[$word])) return $t[$word];
    }

    $translationsCache[] = [$word => $word];
    file_put_contents($cacheFile, json_encode($translationsCache, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_NUMERIC_CHECK));
    return $word;
}

//--- Siparişin teslimat/fatura adresini tablo veya kısaltmalarla döndürür ---//
function order_adress($id = "", $type = "", $stn = "") {
    global $conn;
    $id = intval($id);
    $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)));
    $result = "";

    if ($adres) {
        $jsi = $adres["n16"] != "" ? json_decode($adres["n16"], true) : $adres;
        extract($jsi);
        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 {
            foreach (explode(",", $stn) as $s) {
                if ($s == "ad") $result .= $n2;
                if ($s == "gsm") $result .= $n7;
                if ($s == "adres") $result .= $n6;
                if ($s == "sehir") $result .= loc($n4);
                if ($s == "ilce") $result .= loc($n5);
                if ($s == "firma") $result .= $n8;
                if ($s == "vn") $result .= $n12;
                if ($s == "vd") $result .= $n13;
                if ($s == "fvdvn" && $n12 != "" && $n13 != "") $result .= "$n12 / $n13";
                if ($s == "adres_full") {
                    $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"])));
        $result = ($type == "delivery") ? ($order["n3"] ?: $user["n5"]) : ($order["n2"] ?: $user["n5"]);
    }

    return $result;
}

//--- Kargo firmasına göre takip linki üretir ---//
function cargotracking($cargo = "", $code = "") {
    $cargo = strtolower($cargo);
    if (strpos($cargo,'yurtici') !== false || strpos($cargo,'yurtiçi') !== false)
        return "https://selfservis.yurticikargo.com/reports/SSWDocumentDetail.aspx?DocId=$code";
    if (strpos($cargo,'aras') !== false)
        return "https://kargotakip.araskargo.com.tr/mainpage.aspx?code=$code";
    if (strpos($cargo,'surat') !== false || strpos($cargo,'sürat') !== false)
        return "http://suratkargo.com.tr/KargoTakip?kargotakipno=$code";
    if (strpos($cargo,'dhl') !== false)
        return "https://www.dhl.com.tr/tr/express/tracking.html?AWB=$code&brand=DHL";
    if (strpos($cargo,'ptt') !== false)
        return "https://www.turkiye.gov.tr/ptt-gonderi-takip?barkod=$code";
    if (strpos($cargo,'mng') !== false)
        return "https://service.mngkargo.com.tr/iactive/popup/KargoTakip/link12.asp?k=$code&y=".date('Y');
    return "";
}

//--- Favori veya arkadaş durumunu döndürür ---//
function fav($id = "", $op = "", $ne = "") {
    global $conn;
    $rs = mysqli_fetch_assoc(mysqli_query($conn, "SELECT id,s13 FROM genel WHERE ne='$op' AND t2='$ne' AND s1=$id AND s19='{$_SESSION["User_ID"]}'"));
    if (mysqli_num_rows(mysqli_query($conn, "SELECT id FROM genel WHERE ne='$op' AND t2='$ne' AND s1=$id AND s19='{$_SESSION["User_ID"]}'")) > 0 && $_SESSION["User_ID"] != "") {
        $sts = "active";
    } else $sts = "passive";

    if ($ne == "friend") $sts = ($rs["s13"] == 1) ? "active" : "passive";
    return $sts;
}

//--- Verilen değeri katsayıya göre yukarı/aşağı yuvarlar ---//
function yuvarla($deger, $katsayi) {
    if (!is_numeric($deger) || !is_numeric($katsayi) || $deger == 0 || $katsayi == 0) return false;
    $fark = fmod($deger, $katsayi);
    return $fark ? ($deger - $fark) + $katsayi : $deger;
}

//--- Fiyat hesaplama (KDV ve indirim dahil) ---//
function price($id = "", $pb = "", $nfn = "") {
    global $conn, $module;
    global $s11, $kpb, $eur, $usd, $gbp, $discount;

    $ids = explode("+", $id);
    $id = $ids[0];
    $s19 = $ids[1] ?? "";
    $qry = $s19 ? "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);

    $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"]);
    if ($module["mode_catalogue"] > 0 && mysqli_num_rows($sqlc) > 0) {
        $sqlu = mysqli_query($conn, "SELECT * FROM t1 WHERE ne='post' AND t5=".$rsux["t5"]." $qry ORDER BY pb1 DESC");
    } else {
        $sqlu = mysqli_query($conn, "SELECT * 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"];

    // İndirim uygulanır
    if (mysqli_num_rows($sqlcd) > 0 && dt($rscd["t2"],0) > 0) {
        foreach (["1","2","3"] as $i) {
            ${"fiyat$i"} *= (100 - $rscd["t1"])/100;
            ${"fiyat_$i"} *= (100 - $rscd["t1"])/100;
        }
    }

    // Seçilen fiyat bandı
    $pb = $pb ?: "pb1";
    $sprc = ($prc == 0) ? ${"fiyat" . substr($pb, 2)} : ${"fiyat_" . substr($pb, 2)};

    // Yuvarlama ve format
    if ($nfn == "" && $sprc != 0) {
        $sprc = $module["round"] ? wprice(yuvarla($sprc, $module["round"])) : wprice($sprc);
    }

    if (($pb == "pb2" && $sprc > 0) || $pb == "pb1") return $sprc;
}

//--- Fiyatı farklı para birimine çevirir ve KDV uygular ---//
function xprice($price = "", $pb = "", $tax = 0) {
    global $module, $s11, $eur, $usd, $gbp;
    $rates = ["TRY" => 1, "USD" => $usd, "EUR" => $eur, "GBP" => $gbp];
    $from = $pb ?: "TRY";
    $to = $module["currency"] ?? "TRY";
    $xprice = $price * ($rates[$to] / $rates[$from]);
    if ($s11 != 1) $xprice *= (1 + $tax/100);
    return $xprice;
}

//--- Form mesajını mail ve DB kaydıyla gönderir ---//
function fmesaj($ne = "", $nedir = "") {
    global $mail, $conn;
    $ono = date('dmYHis');
    $nedir = $nedir ?: "fmesaj";

    include("deppo/tools/script/mail/design.php");

    $mesaj  = "Web Site : ".$_SERVER['HTTP_HOST']."<br/><br/><table style=\"width:99%\">";
    $jset = ["Tarih" => date('d.m.Y H:i:s'), "İleti No" => $ono];

    foreach ($_POST as $k => $v) {
        if ($v != "" && !in_array($k, ["t1","malici","Konu","bcc","cc","name","first-name","last-name","number","expiry","cvc","vadef","tvadef","banka_id","aurl","burl"])) {
            $jset[$k] = $v;
            $mesaj .= "<tr><td style='width:25%'><b>$k</b> :</td><td>$v</td></tr>";
        }
    }
    $mesaj .= "</table>";
    $mesaj = $design_top.$mesaj.$design_bottom;

    $malici = $_POST["malici"] ?: tanim('email','n1',0);
    emailgonder($malici, $_POST["Konu"], $_POST["cc"] ?? "", $mesaj, $ne);

    $aform = json_encode($jset, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_NUMERIC_CHECK);
    $conn->query("INSERT INTO genel (ne,t1,t2,t3,ts2,ts3,n1,n2,s19,ts1) VALUES ('$nedir','{$_POST['t1']}','$ne','$ono','{$_POST['date']}','','".addslashes($mesaj)."','$aform','{$_SESSION['User_ID']}',NOW())");
}

//--- Slider resmi döndürür ---//
function slider($n1 = "") { return file_exists("deppo/slide/$n1") ? "deppo/slide/$n1" : "//sample.crmplus.com.tr/1920x800"; }

//--- Dosya include işlemi ---//
function inc($file = "") { $fpath = in_array($file, ["gmap","gmaps","ymap","ymaps","comment","form"]) ? "deppo/tools/script/" : ""; include($fpath.$file.".php"); }

//--- Metni görsel olarak çevirir ---//
function txttoimg($txt = "") { global $cdnurl; return "<img src='//cdn.$cdnurl/tools/email/?txt=$txt' style='filter: invert(1);'>";}

//--- URL bilgisi döndürür ---//
function uri($ne = "") {
    $host = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://".$_SERVER['HTTP_HOST'];
    $directory = rtrim(dirname($_SERVER["PHP_SELF"]), '/\\');

    return match($ne) {
        "domain"    => $host,
        "directory" => $directory,
        "get"       => parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY),
        "full"      => $host.$directory,
        default     => "",
    };
}

//--- Kullanıcı cihaz tipi ---//
function user_agent() {
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    file_put_contents('./public/upload/install_log/agent', $ua);
    return match(true) {
        str_contains($ua,"iPod") || str_contains($ua,"iPhone") || str_contains($ua,"iPad") => 'ios',
        str_contains($ua,"Android") => 'android',
        default => 'desktop',
    };
}
$user_agent = user_agent();

//--- XLSX dosyasını tabloya çevirir ---//
function xreader($file = "") {
    require_once "simple_xlsx.php";
    if ($xlsx = SimpleXLSX::parse($file)) {
        $rows = $xlsx->rows();
    } else {
        return SimpleXLSX::parseError();
    }

    $html = '<table class="v3-table xls_data">';
    foreach($rows as $row) {
        $html .= '<tr>';
        foreach($row as $col) $html .= '<td>'.$col.'</td>';
        $html .= '</tr>';
    }
    $html .= '</table>';
    return $html;
}


//--- Dosya indirilecek isim
function download($file = "", $rename = "") { $rename = $rename ?: date("YmdHis"); $ext = pathinfo($file, PATHINFO_EXTENSION); return "$rename.$ext"; }

// ================================
//--- Dosya uzantısı ve tür bilgisi
// ================================
function uzanti($file = "", $ne = "") {
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    $name = pathinfo($file, PATHINFO_FILENAME);

    $resim = ['jpg','jpeg','png','gif','svg','webp'];
    $arsiv = ['zip','rar'];
    $dokuman = ['doc','docx','xsl','xlsx','pdf'];
    $video = ['mp4','avi'];

    $tip = match(true) {
        in_array($ext, $resim) => 'resim',
        in_array($ext, $arsiv) => 'arsiv',
        in_array($ext, $dokuman) => 'dosya',
        in_array($ext, $video) => 'video',
        default => 'bilinmiyor'
    };

    $gorsel = match($tip) {
        'resim' => $file,
        'arsiv', 'dosya', 'video' => "assets/img/icons/{$ext}_b.png",
        default => ''
    };

    return match($ne) {
        'tip' => $tip,
        'gorsel' => $gorsel,
        'adi' => $name,
        'uzanti' => $ext,
        default => ''
    };
}

// ================================
//--- Görseli WebP'ye çevirir
// ================================
function towebp($file = "", $dir = "") {
    if ($dir && 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);

    $img = match($mime) {
        'image/jpeg' => @imagecreatefromjpeg($fullPath),
        'image/png' => @imagecreatefrompng($fullPath),
        default => false
    };

    if (!$img) {
        error_log("towebp HATA: Desteklenmeyen veya açılamayan dosya: $file");
        return false;
    }

    imagepalettetotruecolor($img);

    if ($mime === 'image/png') {
        imagealphablending($img, false);
        imagesavealpha($img, true);
    }

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

    imagedestroy($img);
    unlink($fullPath);

    return $nfile;
}
 
// ================================
// FCM / Bildirim Fonksiyonları
// ================================
function nGetAccessToken() {
    $jsonKey = file_get_contents($_SERVER['DOCUMENT_ROOT']."/deppo/notification.json");
    $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
    ]));
    openssl_sign($jwtHeader.".".$jwtClaim,$signature,$data['private_key'],'sha256');
    $jwt = $jwtHeader.".".$jwtClaim.".".base64_encode($signature);

    $ch = curl_init();
    curl_setopt_array($ch,[
        CURLOPT_URL=>$data['token_uri'],
        CURLOPT_POST=>true,
        CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_HTTPHEADER=>['Content-Type: application/x-www-form-urlencoded'],
        CURLOPT_POSTFIELDS=>http_build_query(['grant_type'=>'urn:ietf:params:oauth:grant-type:jwt-bearer','assertion'=>$jwt])
    ]);
    $res = json_decode(curl_exec($ch),true);
    curl_close($ch);
    return ['access_token'=>$res['access_token']??null,'project_id'=>$data['project_id']??null];
}

function nDevice($title="test",$msg="",$deviceToken="",$platform=""){
    global $conn,$module;
    $auth=nGetAccessToken();
    if(!$auth['access_token'] || !$auth['project_id']) { echo "Token veya project_id alınamadı."; return false; }

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

    $ch=curl_init();
    curl_setopt_array($ch,[CURLOPT_URL=>$url,CURLOPT_POST=>true,CURLOPT_HTTPHEADER=>$headers,CURLOPT_RETURNTRANSFER=>true,CURLOPT_POSTFIELDS=>json_encode($fields)]);
    $data=json_decode(curl_exec($ch),true);
    curl_close($ch);

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

function sNotification($title="",$msg="",$platform="",$UserID="",$type=""){
    global $conn,$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);
        }
        $conn->query("insert into genel (ne,t1,n1,s1,ts1) values ('notification','".$title."','".$msg."','".$UserID."',now())");
    } else {
        if($module["bildirim_notification"]=="1" && $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" && $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" && $jsy["y30_mesaj"]==1) || ($type=="request" && $jsy["y30_request"]==1) || ($type=="siparis" && $jsy["y30_siparis"]==1)){
                    $result=nDevice($title,$msg,$jsa["Token"],$platform);
                }
            }
        }
    }
    echo "[".date("Y-m-d H:i:s")."] ".($result==1?"Gönderildi":"Hata")."<br>";
}

// ================================
// Dosya & Klasör Fonksiyonları
// ================================
function rrmdir($dir){ if(is_dir($dir)){ foreach(scandir($dir) as $f) if($f!="." && $f!="..") rrmdir("$dir/$f"); rmdir($dir); } elseif(file_exists($dir)) unlink($dir); }
function rcopy($src,$dst){ rrmdir($dst); if(is_dir($src)){ mkdir($dst); foreach(scandir($src) as $f) if($f!="." && $f!="..") rcopy("$src/$f","$dst/$f"); } elseif(file_exists($src)) copy($src,$dst); }
function qrCode($strText,$intSize=150){ return "https://api.qrserver.com/v1/create-qr-code/?size={$intSize}x{$intSize}&chld=L|1&data=".$strText; }

// ================================
// Log & Kontrol Fonksiyonları
// ================================
function sendLogData(){ global $pow1,$pow2,$wurl,$cdnurl,$ai,$logColor;
    $ljson=json_encode(['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]);
    $url="https://log.".$cdnurl."/?log=".v3e($ljson);
    $ch=curl_init(); curl_setopt_array($ch,[CURLOPT_URL=>$url,CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>$ljson]); print_r(curl_exec($ch)); curl_close($ch);
}

function kontrol(){
	global $conn,$pow1; $adres=$_SERVER['SERVER_NAME']; $kmesaj=""; 
	$sqlk=mysqli_query($conn,"select id from genel where ne='tanim' and n1='".base64_encode(str_replace("www.","",$adres))."'");
	if(mysqli_num_rows($sqlk)==0 && $_SESSION["V3Server"]==""){
		if(mysqli_num_rows($sqlk)==0 and $_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;
}

// ================================
// HTTP & Yönlendirme Fonksiyonları
// ================================
function HTTPPOST($url,$request,$header=[]){ $ch=curl_init(); curl_setopt_array($ch,[CURLOPT_URL=>$url,CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>$request,CURLOPT_TIMEOUT=>30,CURLOPT_HTTPHEADER=>$header]); $res=curl_exec($ch); curl_close($ch); return $res; }
function surl($url){ global $cdnurl; return rlang(file_get_contents('https://link.'.$cdnurl.'?url='.$url)); }
function go($url,$time=0){ if($time) header("Refresh: {$time}; url={$url}"); else header("Location: {$url}"); }
function location($url,$target="self",$sure=2,$preload=""){ global $weburl; echo "<script>setTimeout(()=>{{$target}.location.replace('{$url}')}, ".($sure*1000).");</script>";
    if(in_array($preload,[1,2])) echo "<div style='width:100%;height:100%;padding:20% 45%;position:fixed;z-index:999999999999;background-image:url(".$weburl."/deppo/tools/img/trns.png)'><img src='".$weburl."/deppo/tools/img/loading.svg' style='max-height:150px;'></div>";
}

// ================================
// Diğer Yardımcı Fonksiyonlar
// ================================
function saveok(){ global $weburl; /* Görsel animasyon gösterebilirsin */ }
function ID2Guid($ID=""){ $chars="0123456789abcd"; $ID=str_pad($ID,6,'0',STR_PAD_LEFT); return substr(str_shuffle($chars),0,6)."-".substr(str_shuffle($chars),0,6)."-".substr(str_shuffle($chars),0,6)."-".base64_encode($ID); }
function Guid2ID($ID=""){ $guides=explode("-",$ID); return ltrim(base64_decode($guides[3]),'0'); }

// ================================
// POST / GET Fonksiyonları
// ================================
function Posts(){ $posts=""; foreach($_POST as $k=>$v){ ${$k}=$v; $posts.="<input type='hidden' name='$k' value='$v'>\n"; } return $posts; }
function Gets(){ $gets=""; foreach($_GET as $k=>$v){ ${$k}=$v; $gets.="$k=$v"; } return $gets; }

// ================================
// Şifreleme / Kodlama Fonksiyonları
// ================================
function v3e($m=""){ return base64_encode($m); }
function v3e2($m=""){ return base64_encode(base64_encode($m)); }
function V3d($m=""){ return base64_decode($m); }
function V3d2($m=""){ return base64_decode(base64_decode($m)); }
function V3sha($m=""){ return hash('sha512',$m); }

function sha($string="",$key="",$status=""){
    $method='AES-256-CBC'; $iv=substr(hash('sha256','22-=**_'),0,16);
    $key=hash('sha256',$key);
    return $status=="e"?openssl_encrypt($string,$method,$key,false,$iv):openssl_decrypt($string,$method,$key,false,$iv);
}

// ================================
// Şifre / Rastgele Fonksiyonlar
// ================================
function generatePassword($len=""){ return substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"),0,$len); }
function generateSPassword($len=""){ return substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"),0,$len); }
function generatenumber($len=""){ return substr(str_shuffle("012345678901234567890123456789"),0,$len); }

// ================================
// Telefon / Adres Fonksiyonları
// ================================
function ftelefon($num=""){ $num=preg_replace("/\D/","",$num); echo (strlen($num)==10?"(".substr($num,0,3).") ".substr($num,3,3)."-".substr($num,6,4):"Geçersiz telefon numarası!"); }
function i2a($s1="",$s2=""){ return str_pad($s1,$s2,'0',STR_PAD_LEFT); }
function ihb($metin=""){ $l=mb_strlen($metin,"UTF-8"); $m=str_replace("İ","I",$metin); $ilk=mb_substr($m,0,1,"UTF-8"); $metin=str_replace(["I","İ"],["ı","i"],$metin); return mb_strtoupper($ilk,"UTF-8").mb_strtolower(mb_substr($metin,1,$l-1,"UTF-8"),"UTF-8"); }
function validate($str="",$type=""){
    $res="ok";
    if($type=="name" && !preg_match("/^[a-zA-Z-' ]*$/",$str)) $res="Sadece Harf ve Boşluk";
    elseif($type=="mail" && !filter_var($str,FILTER_VALIDATE_EMAIL)) $res="Hatalı Email";
    elseif($type=="phone"){ $telefon=preg_replace("/\D/","",$str); if(substr($telefon,0,1)!="5" || strlen($telefon)!=10) $res="Hatalı Telefon"; }
    return $res;
}

// ================================
// Sayı / Metin Fonksiyonları
// ================================
function nice_number($n=""){ return ($n>1000?number_format($n/1000,2)." K":$n); }
function kisalt($m,$l=100){ if(strlen($m)<=$l) return $m; $s=substr($m,0,$l); return substr($s,0,strrpos($s,' '))."..."; }
function tback($text=""){ $q=explode("/",$_SERVER['QUERY_STRING']); return "/".implode(",",$q); }
function stars($s20=0,$oran=100){ $sc=min(5,($s20/$oran)*5); $f=floor($sc); $h=($sc-$f>=0.5?1:0); return str_repeat('<i class="fa fa-star"></i>',$f).str_repeat('<i class="fa fa-star-half-o"></i>',$h).str_repeat('<i class="fa fa-star-o"></i>',5-$f-$h); }

// ================================
// Cihaz / Mobil / IP Fonksiyonları
// ================================
function isMobile(){ return preg_match("/(android|iphone|tablet|mobi)/i",$_SERVER["HTTP_USER_AGENT"]); }
$mobile=isMobile()?"1":"";
function getRealIpAddr(){ return $_SERVER['HTTP_CLIENT_IP']?:($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['REMOTE_ADDR']); }
function ilocation($str=""){ $json=json_decode(file_get_contents("http://ip-api.com/json/".$_SERVER['REMOTE_ADDR']),true); global $module; return ($module["city"]<>"" && $str=="city")?$module["city"]:$json[$str]; }

// ================================
// Dosya / PDF / Transfer Fonksiyonları
// ================================
function filetransfer($from="",$to=""){ $ch=curl_init($from); curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_SSL_VERIFYPEER=>false]); file_put_contents($to,curl_exec($ch)); return file_exists($to); }
function expdf($url="",$pdfname="",$expath=""){ require("php-pdf-class.php"); phptopdf(["source_type"=>"url","source"=>$url,"action"=>"save","save_directory"=>"../deppo/dosya/","file_name"=>$pdfname]); return $pdfname; }
function private_str($str="",$start=0,$end=0){ return mb_substr($str,0,$start,'utf8').str_repeat('*',$end).mb_substr($str,$start+$end); }

// ================================
// TC Kimlik / İsim Fonksiyonları
// ================================
function tck($tc=""){ if(strlen($tc)==11 && is_numeric($tc)){ $t1=0;$t2=0; for($i=0;$i<9;$i++) $i%2==0?$t1+=$tc[$i]:$t2+=$tc[$i]; $t10=($t1*7-$t2)%10; $t11=($t1+$t2+$t10)%10; return ($t10==$tc[9] && $t11==$tc[10])?"1":"0"; }else{return "0";} }
function names($name="",$ne=""){ $n=explode(' ',$name); $ad=count($n)>2?$n[0]." ".$n[1]:$n[0]; $soy=count($n)>2?$n[2]:$n[1]; if(in_array($ne,["ad","name"])) return $ad; elseif($ne=="sname") return "<span class='v3-circle names u".v3e($ad.$soy)."' title='$ad $soy'>".strtoupper(mb_substr($ad,0,1).mb_substr($soy,0,1))."</span>"; else return $soy; }

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