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

try {
    // Database connection using PDO
  require('dbcon.php');
    // Receive input
    $data = json_decode(file_get_contents("php://input"));
    $user_id = $data->user_id ?? null;
    $fcm_token = $data->fcm_token ?? null;

    if (!$user_id || !$fcm_token) {
        echo json_encode(["success" => false, "message" => "Missing required fields"]);
        exit;
    }

    // Check if token exists
    $stmt = $pdo->prepare("SELECT id FROM user_devices WHERE user_id = ? LIMIT 1");
    $stmt->execute([$user_id]);

    if ($stmt->rowCount() > 0) {
        // Update existing
        $update = $pdo->prepare("UPDATE user_devices SET fcm_token = ?, removed = 0 WHERE user_id = ?");
        $update->execute([$fcm_token, $user_id]);

        echo json_encode(["success" => true, "message" => "Token updated"]);
    } else {
        // Insert new
        $insert = $pdo->prepare("INSERT INTO user_devices (user_id, fcm_token) VALUES (?, ?)");
        $insert->execute([$user_id, $fcm_token]);

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

} catch (PDOException $e) {
    echo json_encode(["success" => false, "message" => "DB error: " . $e->getMessage()]);
}
?>
