<?php
// =============================================================
//  POST /api/v1/auth/register_device
//
//  Registers (or re-homes) an FCM device token for push notifications —
//  see scripts/add_mobile_api_tables.sql's device_push_tokens table and
//  services/FirebaseServiceProvider.php (Phase A5). Kept separate from
//  the auth token so logging out on one device doesn't stop pushes to
//  others, and re-registering the same fcm_token under a different
//  account (e.g. shared device, different user logs in) simply re-homes
//  that row instead of erroring.
//
//  Body: { "fcm_token": "...", "platform": "android"|"ios" }
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Api::error(405, 'MethodNotAllowed', 'Use POST');
}

$account = api_authenticate();

$body      = Api::body();
$fcmToken  = trim((string)($body['fcm_token'] ?? ''));
$platform  = strtolower(trim((string)($body['platform'] ?? '')));

if ($fcmToken === '') {
    Api::error(422, 'ValidationError', 'fcm_token is required');
}
if (!in_array($platform, ['android', 'ios'], true)) {
    Api::error(422, 'ValidationError', 'platform must be "android" or "ios"');
}

$table = $account->getTable();
$id    = $account->getId();

$stmt = $conn->prepare("
    INSERT INTO device_push_tokens (account_table, account_id, fcm_token, platform)
    VALUES (?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE account_table = VALUES(account_table), account_id = VALUES(account_id),
                             platform = VALUES(platform), updated_at = NOW()
");
$stmt->bind_param('siss', $table, $id, $fcmToken, $platform);
$stmt->execute();
$stmt->close();

Api::success(['status' => 'registered']);
