<?php
header("Content-Type: application/json");

require_once '../config/koneksi.php';

/// =========================
/// 🔥 VALIDASI KONEKSI
/// =========================
if (!isset($conn) || $conn->connect_error) {
  http_response_code(500);
  echo json_encode([
    "success" => false,
    "message" => "Koneksi database gagal"
  ]);
  exit;
}

/// =========================
/// 🔥 AMBIL INPUT JSON
/// =========================
$raw = file_get_contents("php://input");
$input = json_decode($raw, true);

if (!$input) {
  http_response_code(400);
  echo json_encode([
    "success" => false,
    "message" => "JSON tidak valid"
  ]);
  exit;
}

/// =========================
/// 🔥 AMBIL DATA
/// =========================
$user_id     = $input['user_id'] ?? null;
$fcm_token   = $input['fcm_token'] ?? null;
$device_name = $input['device_name'] ?? 'unknown';

/// =========================
/// 🔥 VALIDASI
/// =========================
if (!$user_id || !$fcm_token) {
  http_response_code(400);
  echo json_encode([
    "success" => false,
    "message" => "user_id dan fcm_token wajib"
  ]);
  exit;
}

/// =========================
/// 🔥 VALIDASI USER
/// =========================
$checkUser = $conn->prepare("SELECT id FROM users WHERE id = ?");
$checkUser->bind_param("s", $user_id);
$checkUser->execute();
$resUser = $checkUser->get_result();

if ($resUser->num_rows == 0) {
  http_response_code(400);
  echo json_encode([
    "success" => false,
    "message" => "User tidak ditemukan"
  ]);
  exit;
}
$checkUser->close();

$now = date("Y-m-d H:i:s");

/// =========================
/// 🔥 CEK TOKEN SUDAH ADA?
/// =========================
$checkToken = $conn->prepare("
  SELECT id, user_id 
  FROM user_devices 
  WHERE fcm_token = ?
");
$checkToken->bind_param("s", $fcm_token);
$checkToken->execute();
$resToken = $checkToken->get_result();

if ($row = $resToken->fetch_assoc()) {

  /// 🔥 TOKEN SUDAH ADA → UPDATE USER
  $update = $conn->prepare("
    UPDATE user_devices 
    SET user_id = ?, device_name = ?, updated_at = ?
    WHERE id = ?
  ");

  $update->bind_param(
    "ssss",
    $user_id,
    $device_name,
    $now,
    $row['id']
  );

  $update->execute();
  $update->close();

  echo json_encode([
    "success" => true,
    "message" => "Token diperbarui"
  ]);

} else {

  /// 🔥 INSERT BARU
  $id = uniqid("dev_");

  $insert = $conn->prepare("
    INSERT INTO user_devices (
      id, user_id, fcm_token, device_name, created_at, updated_at
    ) VALUES (?, ?, ?, ?, ?, ?)
  ");

  $insert->bind_param(
    "ssssss",
    $id,
    $user_id,
    $fcm_token,
    $device_name,
    $now,
    $now
  );

  if ($insert->execute()) {

    echo json_encode([
      "success" => true,
      "message" => "Token disimpan"
    ]);

  } else {
    http_response_code(500);
    echo json_encode([
      "success" => false,
      "message" => "Gagal simpan token",
      "error" => $insert->error
    ]);
  }

  $insert->close();
}

$conn->close();