<?php
/**
 * POST /api/notifications/register_device.php
 * Body (JSON): { device_token, platform } - platform is 'android' or 'ios'.
 *
 * Called by the Flutter app once it has both a logged-in session (bearer
 * token) and an FCM device token from Firebase. Upserts - if this exact
 * token is already registered (e.g. app reopened, token unchanged), just
 * refreshes last_used_at and reassigns it to the current user, which
 * correctly handles the "different account logged in on the same device"
 * case without leaving a stale row pointed at the previous user.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

only_post_allowed();
$userId = require_login();

$input = get_json_input();
$deviceToken = trim((string) ($input['device_token'] ?? ''));
$platform = $input['platform'] ?? '';

if ($deviceToken === '') {
    send_error('device_token is required.', 422);
}
if (!in_array($platform, ['android', 'ios'], true)) {
    send_error("platform must be 'android' or 'ios'.", 422);
}

$pdo = Database::connect();
$stmt = $pdo->prepare('
    INSERT INTO device_tokens (user_id, token, platform, created_at, last_used_at)
    VALUES (?, ?, ?, NOW(), NOW())
    ON DUPLICATE KEY UPDATE user_id = VALUES(user_id), platform = VALUES(platform), last_used_at = NOW()
');
$stmt->execute([$userId, $deviceToken, $platform]);

send_json(true, 'Device registered for push notifications.');
