<?php

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

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

$user = requireAuth();

$fcm_token = $_POST['fcm_token'] ?? '';

if (!$fcm_token) {
    echo json_encode([
        "success" => false,
        "message" => "Token kosong"
    ]);
    exit;
}

// 🔥 AMANKAN INPUT
$fcm_token = mysqli_real_escape_string($conn, $fcm_token);
$user_id   = mysqli_real_escape_string($conn, $user['user_id']);

// 🔥 INSERT ATAU UPDATE (ANTI DUPLIKAT)
mysqli_query($conn, "
INSERT INTO user_devices (user_id, fcm_token, device_name, created_at)
VALUES (
    '$user_id',
    '$fcm_token',
    'android',
    NOW()
)
ON DUPLICATE KEY UPDATE
    user_id = '$user_id',
    device_name = 'android'
");

// 🔥 OPTIONAL: BERSIHKAN TOKEN USER LAIN (JIKA PINDAH DEVICE)
mysqli_query($conn, "
DELETE FROM user_devices 
WHERE user_id = '$user_id' 
AND fcm_token != '$fcm_token'
");

echo json_encode([
    "success" => true,
    "message" => "FCM saved (no duplicate)"
]);