<?php
require __DIR__ . "/db.php";

header("Content-Type: application/json; charset=utf-8");

// preflight gelirse patlamasın (zararsız)
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
  http_response_code(204);
  exit;
}

$SECRET = "887755"; // <-- Form1'de SiteKey ile aynı olacak

try {
  // ---- auth ----
  $auth = $_SERVER["HTTP_X_RW_KEY"] ?? "";
  if (!hash_equals($SECRET, $auth)) {
    http_response_code(401);
    echo json_encode(["ok"=>false, "err"=>"unauthorized"], JSON_UNESCAPED_UNICODE);
    exit;
  }

  $raw = file_get_contents("php://input");
  if ($raw === false || trim($raw) === "") {
    http_response_code(400);
    echo json_encode(["ok"=>false, "err"=>"empty_body"], JSON_UNESCAPED_UNICODE);
    exit;
  }

  $data = json_decode($raw, true);
  if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(["ok"=>false, "err"=>"bad_json"], JSON_UNESCAPED_UNICODE);
    exit;
  }

  $pc      = trim((string)($data["pc"] ?? "unknown"));
  $ev_type = trim((string)($data["type"] ?? "unknown"));
  $ev_code = trim((string)($data["code"] ?? "unknown"));

  $val_int = $data["val_int"] ?? null;
  $val_int = (is_numeric($val_int) ? (int)$val_int : null);

  $val_text = $data["val_text"] ?? null;
  $val_text = ($val_text === null ? null : trim((string)$val_text));
  if ($val_text === "") $val_text = null;

  $payload = $data["payload"] ?? null;
  $payload_json = ($payload !== null ? json_encode($payload, JSON_UNESCAPED_UNICODE) : null);

  $ip = $_SERVER["REMOTE_ADDR"] ?? null;

  // val_int NULL gelirse bind_param i patlamasın diye 0 gönderip NULLIF ile NULL yapıyoruz.
  $val_int_safe = ($val_int === null ? 0 : $val_int);

  $stmt = $conn->prepare("
    INSERT INTO rw_events (pc, ev_type, ev_code, val_int, val_text, payload_json, ip)
    VALUES (?, ?, ?, NULLIF(?, 0), ?, ?, ?)
  ");

  $stmt->bind_param("sssisss", $pc, $ev_type, $ev_code, $val_int_safe, $val_text, $payload_json, $ip);
  $stmt->execute();

  echo json_encode(["ok"=>true, "id"=>$conn->insert_id], JSON_UNESCAPED_UNICODE);
}
catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(["ok"=>false, "err"=>"server_error", "msg"=>$e->getMessage()], JSON_UNESCAPED_UNICODE);
}
