false,'error'=>'method_not_allowed'], 405); } $input = read_json_body(); // Format attendu: { endpoint, keys:{p256dh,auth}, userAgent?, deviceLabel? } $endpoint = trim((string)($input['endpoint'] ?? '')); $keys = $input['keys'] ?? []; $p256dh = trim((string)($keys['p256dh'] ?? '')); $auth = trim((string)($keys['auth'] ?? '')); if ($endpoint === '' || $p256dh === '' || $auth === '') { json_response(['ok'=>false,'error'=>'bad_params'], 400); } $compteId = (int)($_SESSION['compte_id'] ?? 0); $role = strtolower((string)($_SESSION['role'] ?? '')); $referenceId = $_SESSION['reference_id'] ?? null; $userAgent = trim((string)($input['userAgent'] ?? ($_SERVER['HTTP_USER_AGENT'] ?? ''))); $deviceLabel = trim((string)($input['deviceLabel'] ?? '')); try { // Upsert par endpoint (UNIQUE endpoint(255)) $sql = " INSERT INTO push_subscriptions (compte_id, role, reference_id, endpoint, p256dh, auth, user_agent, device_label, is_active, last_seen_at) VALUES (:compte_id, :role, :reference_id, :endpoint, :p256dh, :auth, :ua, :label, 1, NOW()) ON DUPLICATE KEY UPDATE compte_id = VALUES(compte_id), role = VALUES(role), reference_id = VALUES(reference_id), p256dh = VALUES(p256dh), auth = VALUES(auth), user_agent = VALUES(user_agent), device_label = VALUES(device_label), is_active = 1, last_seen_at = NOW() "; $stmt = $pdo->prepare($sql); $stmt->execute([ ':compte_id' => $compteId, ':role' => $role, ':reference_id' => $referenceId !== null ? (int)$referenceId : null, ':endpoint' => $endpoint, ':p256dh' => $p256dh, ':auth' => $auth, ':ua' => $userAgent !== '' ? $userAgent : null, ':label' => $deviceLabel !== '' ? $deviceLabel : null, ]); json_response(['ok'=>true]); } catch (Throwable $e) { error_log('push subscribe error: '.$e->getMessage()); json_response(['ok'=>false,'error'=>'server_error'], 500); }