<?php
header("Content-Type: application/json; charset=UTF-8");

/* ===== KONFIG ===== */
$BOT_TOKEN = "7434118269:AAGM8Jvpn3JoJTL9sD6izPEYho8H6AEji9A";
$CHAT_ID  = "-1002452255334";
$LIMIT_SECONDS = 300; // 5 menit
$SPAM_FILE = __DIR__ . "/spam_log.json";

/* ===== AMBIL DATA ===== */
$data = json_decode(file_get_contents("php://input"), true);
if(!$data || empty($data['name']) || empty($data['answer'])){
  echo json_encode(["ok"=>false,"error"=>"Data tidak lengkap"]);
  exit;
}

$name = trim($data['name']);
$answer = trim($data['answer']);
$ip = $_SERVER['REMOTE_ADDR'];
$now = time();

/* ===== LOAD LOG ===== */
if(!file_exists($SPAM_FILE)){
  file_put_contents($SPAM_FILE, "{}");
}
$log = json_decode(file_get_contents($SPAM_FILE), true);
if(!is_array($log)) $log = [];

/* ===== CEK SPAM ===== */
if(isset($log[$ip])){
  $diff = $now - $log[$ip];
  if($diff < $LIMIT_SECONDS){
    $sisa = ceil(($LIMIT_SECONDS - $diff)/60);
    echo json_encode([
      "ok"=>false,
      "error"=>"Terlalu cepat 😅 tunggu {$sisa} menit lagi"
    ]);
    exit;
  }
}

/* ===== KIRIM TELEGRAM ===== */
$msg =
"📩 *Jawaban Baru*\n\n".
"👤 *Nama:* {$name}\n".
"🌐 *IP:* {$ip}\n".
"✍️ *Jawaban:*\n{$answer}";

$url = "https://api.telegram.org/bot{$BOT_TOKEN}/sendMessage";
$post = [
  "chat_id" => $CHAT_ID,
  "text" => $msg,
  "parse_mode" => "Markdown"
];

$ch = curl_init($url);
curl_setopt_array($ch,[
  CURLOPT_POST=>true,
  CURLOPT_POSTFIELDS=>$post,
  CURLOPT_RETURNTRANSFER=>true,
  CURLOPT_TIMEOUT=>15
]);

$res = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);

if($res === false){
  echo json_encode(["ok"=>false,"error"=>"Koneksi ke Telegram gagal"]);
  exit;
}

$json = json_decode($res,true);
if(!isset($json['ok']) || $json['ok'] !== true){
  echo json_encode(["ok"=>false,"error"=>"Telegram error"]);
  exit;
}

/* ===== SIMPAN WAKTU TERAKHIR ===== */
$log[$ip] = $now;
file_put_contents($SPAM_FILE, json_encode($log, JSON_PRETTY_PRINT));

echo json_encode(["ok"=>true]);