<?php
ini_set('display_errors', '0');
error_reporting(0);

header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Methods: POST, OPTIONS");

$path = "../../../../";
require_once($path . "config/sql.php");
require_once($path . "deppo/tools/script/cevir.php");
require_once($path . "config/map.php");
require_once($path . "deppo/tools/script/fonksiyon".$ver.".php");

// --- Helper: s19 format ---
function format_s19($userid) {
    return '{'.intval($userid).'}';
}

// --- Giriş değerleri ---
$module = $_POST["module"] ?? $_GET["module"] ?? "";
$userid = $_POST["userid"] ?? $_GET["userid"] ?? "";
$user   = $_POST["user"] ?? $_GET["user"] ?? "";
$pass   = $_POST["pass"] ?? $_GET["pass"] ?? "";

// --- Kimlik doğrulama ---
if ($module === "blog") {
    $AuthUser = tanim("ws","n1",0);
    $AuthPass = tanim("ws","n2",0);

    if (!($user && $pass && $user === $AuthUser && $pass === $AuthPass)) {
        echo json_encode(["status"=>"error","message"=>"Blog Auth Err"]); exit();
    }

} else {
    if (!($user && $pass && 
          $user === md5("user_" . $userid) && 
          $pass === md5("pass_" . $userid))) {

        echo json_encode(["status"=>"error","message"=>"Api User Err"]); exit();
    }
}

$testMode = isset($_GET["test"]) && $_GET["test"] == "1";

// --- JSON input ---
$input = file_get_contents("php://input");
$data = json_decode($input,true);
if (!$data) {
    echo json_encode(["status"=>"error","message"=>"Invalid or empty JSON data"]); exit();
}

// --- Log ---
$logFile = __DIR__."/../../logs/api_".date("Ymd").".log";
@file_put_contents($logFile, date("Y-m-d H:i:s")." | $module | ".json_encode($data,JSON_UNESCAPED_UNICODE).PHP_EOL, FILE_APPEND);

// -----------------------------------------------------------------------------
// PRODUCT MODULE
// -----------------------------------------------------------------------------
if($module==="product") {
    $title    = trim($data["title"] ?? "");
    $barcode  = trim($data["barcode"] ?? "");
    $price    = floatval($data["price"] ?? 0);
    $price2   = floatval($data["price2"] ?? 0);
    $stock    = intval($data["stock"] ?? 0);
    $s19      = format_s19($userid);

    if($title=="" && $barcode=="") {
        echo json_encode(["status"=>"error","message"=>"Missing fields: title or barcode"]); exit();
    }

    if($testMode){
        echo json_encode([ "status"=>"success", "mode"=>"test", "message"=>"Product simulation", "data"=>compact("title","barcode","price","price2","stock","s19") ], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE); exit();
    }

    // Ürün var mı? (barcode veya stok kodu)
    $stmt = $conn->prepare("SELECT id FROM t1 WHERE s19=? AND (t5=? OR t4=?) LIMIT 1");
    $stmt->bind_param("sss",$s19,$barcode,$barcode);
    $stmt->execute();
    $res = $stmt->get_result();
    $existing = $res->fetch_assoc();
    $stmt->close();

    if($existing){
        // UPDATE
        $stmt = $conn->prepare("UPDATE t1 SET t1=?, pb1=?, pb2=?, s5=? WHERE id=?");
        $stmt->bind_param("sddii",$title,$price,$price2,$stock,$existing["id"]);
        $stmt->execute();
        $stmt->close();

        echo json_encode(["status"=>"success","id"=>$existing["id"],"message"=>"Product updated"], JSON_UNESCAPED_UNICODE);
        exit();
    } else {
        // INSERT
        $stmt = $conn->prepare("INSERT INTO t1 (t1,t5,pb1,pb2,s5,s19,ne,ts1) VALUES (?,?,?,?,?,?, 'post', NOW())");
        $stmt->bind_param("ssddis",$title,$barcode,$price,$price2,$stock,$s19);
        $stmt->execute();
        $newId = $stmt->insert_id;
        $stmt->close();

        echo json_encode(["status"=>"success","id"=>$newId,"message"=>"Product added"], JSON_UNESCAPED_UNICODE);
        exit();
    }
}

// -----------------------------------------------------------------------------
// BLOG MODULE
// -----------------------------------------------------------------------------
if($module==="blog") {
    $title  = trim($data["title"] ?? "");
    $desc   = trim($data["desc"] ?? "");
    $detail = trim($data["detail"] ?? "");
    $cat    = trim($data["cat"] ?? "");
    $img    = trim($data["img"] ?? ""); // base64 veya temp path

    if($title=="") {
        echo json_encode(["status"=>"error","message"=>"Missing fields: title"]); exit();
    }

    if($testMode){
        echo json_encode([ "status"=>"success", "mode"=>"test", "message"=>"Blog simulation", "data"=>compact("title","desc","detail","cat","img") ], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE); exit();
    }

    // Blog var mı? (title kontrol)
	$stmt = $conn->prepare("SELECT id FROM lang1 WHERE t1=? LIMIT 1");
	$stmt->bind_param("s", $title);
	$stmt->execute();
	$res = $stmt->get_result();
	$existing = $res->fetch_assoc();
	$stmt->close();

	if($existing){
		// UPDATE
		$stmt = $conn->prepare("UPDATE lang1 SET t1=?, n2=?, n1=?, s2=?, ne='haber' WHERE id=?");
		$stmt->bind_param("ssssi", $title, $desc, $detail, $cat, $existing["id"]);
		$stmt->execute();
		$blogId = $existing["id"];
		$stmt->close();
		$msg = "Blog updated";
	} else {
		// INSERT
		$stmt = $conn->prepare("INSERT INTO lang1 (t1, n2, n1, s2, s13, ne, ts1) VALUES (?,?,?,?, 1, 'haber', NOW())");
		$stmt->bind_param("ssss", $title, $desc, $detail, $cat);
		$stmt->execute();
		$blogId = $stmt->insert_id;
		$stmt->close();
		$msg = "Blog added";

		// -----------------------------
		// Resim yükleme (img parametresi varsa)
		// -----------------------------
		if($img != ""){
			$imgDir = __DIR__ . "/../../../image/"; // deppo/image/
			if(!is_dir($imgDir)) mkdir($imgDir, 0755, true);

			$ext = pathinfo($img, PATHINFO_EXTENSION);
			if($ext=="") $ext = "jpg"; // uzantı yoksa default
			$filename = "blog_" . $blogId . "_" . time() . "." . $ext;
			$filePath = $imgDir . $filename;

			// Ana resim kaydı
			if(filter_var($img, FILTER_VALIDATE_URL)){
				$imgContent = file_get_contents($img);
				if($imgContent) file_put_contents($filePath, $imgContent);
			} elseif(file_exists($img)){
				copy($img, $filePath);
			}

			// Küçük resim kaydı
			$kFilename = "k_" . $filename;
			$kFilePath = $imgDir . $kFilename;
			copy($filePath, $kFilePath); // orijinal dosyayı k_ ile kopyala

			// Medya tablosuna kaydet (ana resim)
			$yeni = $filename;
			$s2 = $cat;
			$t1_post = $title;
			$conn->query("INSERT INTO medya (ne,s1,s2,s3,s4,t1,t3,t6,t2) VALUES ( 'resim', '".$blogId."', '1', '0', '0', '".addslashes($yeni)."', 'haber', '".$_SESSION["lang"]."', '".addslashes($t1_post)."' )");
		}
	}

    echo json_encode(["status"=>"success","id"=>$blogId,"message"=>$msg], JSON_UNESCAPED_UNICODE);
    exit();
}

// -----------------------------------------------------------------------------
// USER MODULE
// -----------------------------------------------------------------------------
if($module==="user"){
    $name    = trim($data["name"] ?? "");
    $email   = trim($data["email"] ?? "");
    $phone   = trim($data["phone"] ?? "");
    $address = trim($data["address"] ?? "");
    $s19     = format_s19($userid);
    $email_b64 = base64_encode($email);

    if($name=="" && $email==""){
        echo json_encode(["status"=>"error","message"=>"Missing fields: name or email"]);
        exit();
    }

    if($testMode){
        echo json_encode([
            "status"=>"success",
            "mode"=>"test",
            "message"=>"User simulation",
            "data"=>compact("name","email","phone","address","s19")
        ], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
        exit();
    }

    // Kullanıcı var mı? (email veya telefon)
    $stmt = $conn->prepare("SELECT id FROM t5 WHERE s19=? AND (t2=? OR t4=?) LIMIT 1");
    $stmt->bind_param("sss",$s19,$email_b64,$phone);
    $stmt->execute();
    $res = $stmt->get_result();
    $existingUser = $res->fetch_assoc();
    $stmt->close();

    if($existingUser){
        // UPDATE
        $stmt = $conn->prepare("UPDATE t5 SET t1=?, t2=?, t4=?, n6=? WHERE id=?");
        $stmt->bind_param("ssssi",$name,$email_b64,$phone,$address,$existingUser["id"]);
        $stmt->execute();
        $stmt->close();

        echo json_encode(["status"=>"success","id"=>$existingUser["id"],"message"=>"User updated"], JSON_UNESCAPED_UNICODE);
        exit();
    } else {
        // INSERT
        $stmt = $conn->prepare("INSERT INTO t5 (t1,t2,t4,n6,s19,created_at) VALUES (?,?,?,?,?,NOW())");
        $stmt->bind_param("ssssi",$name,$email_b64,$phone,$address,$s19);
        $stmt->execute();
        $newId = $stmt->insert_id;
        $stmt->close();

        echo json_encode(["status"=>"success","id"=>$newId,"message"=>"User added"], JSON_UNESCAPED_UNICODE);
        exit();
    }
}

echo json_encode(["status"=>"error","message"=>"Invalid module"],JSON_UNESCAPED_UNICODE);
exit();
?>