<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../includes/db.php';
session_start();

$data = json_decode(file_get_contents('php://input'), true);
if (!$data || empty($data['endpoint']) || empty($data['keys']['p256dh']) || empty($data['keys']['auth'])) {
  echo json_encode(['success' => false, 'error' => 'Payload inválido']);
  exit;
}

$usuario_id = $_SESSION['usuario_id'] ?? null;

$stmt = $pdo->prepare("
  INSERT INTO push_subscriptions (usuario_id, endpoint, p256dh, auth, user_agent)
  VALUES (?, ?, ?, ?, ?)
  ON DUPLICATE KEY UPDATE
    usuario_id = VALUES(usuario_id),
    p256dh = VALUES(p256dh),
    auth = VALUES(auth),
    user_agent = VALUES(user_agent)
");
$stmt->execute([
  $usuario_id,
  $data['endpoint'],
  $data['keys']['p256dh'],
  $data['keys']['auth'],
  $_SERVER['HTTP_USER_AGENT'] ?? null
]);

echo json_encode(['success' => true]);
