<?php
require_once __DIR__ . '/../server/db.php';

header('Content-Type: application/json; charset=utf-8');

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);

$org_id   = (int)($data['org_id'] ?? 0);
$endpoint = trim($data['endpoint'] ?? '');
$p256dh   = trim($data['p256dh'] ?? '');
$auth     = trim($data['auth'] ?? '');
$ua       = trim($data['user_agent'] ?? '');

if ($org_id <= 0 || $endpoint === '' || $p256dh === '' || $auth === '') {
  http_response_code(400);
  echo json_encode(['error' => 'Missing fields']);
  exit;
}

$stmt = $conn->prepare("SELECT id FROM organizations WHERE id = ? LIMIT 1");
$stmt->bind_param("i", $org_id);
$stmt->execute();
$org = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$org) {
  http_response_code(404);
  echo json_encode(['error' => 'Organization not found']);
  exit;
}

$stmt = $conn->prepare("
  INSERT INTO subscribers (org_id, endpoint, p256dh, auth, user_agent, last_seen_at)
  VALUES (?, ?, ?, ?, ?, NOW())
  ON DUPLICATE KEY UPDATE
    p256dh=VALUES(p256dh),
    auth=VALUES(auth),
    user_agent=VALUES(user_agent),
    last_seen_at=NOW()
");
$stmt->bind_param("issss", $org_id, $endpoint, $p256dh, $auth, $ua);
$stmt->execute();
$stmt->close();

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