<?php
// Stores a Web Push subscription for the signed-in user. Always responds JSON.
session_start();
ob_start();
header('Content-Type: application/json');

// Guarantee a JSON response even if a fatal error occurs during include/parse.
register_shutdown_function(function () {
    $e = error_get_last();
    if ($e && in_array($e['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json');
        echo json_encode(['ok' => false, 'error' => 'server_error']);
    }
});

require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/includes/webpush.php';

if (empty($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['ok' => false, 'error' => 'auth']); exit; }

$uid      = (int) $_SESSION['user_id'];
$body     = json_decode(file_get_contents('php://input'), true);
$endpoint = $body['endpoint'] ?? '';
$p256dh   = $body['keys']['p256dh'] ?? '';
$auth     = $body['keys']['auth'] ?? '';
if (!$endpoint || !$p256dh || !$auth) { echo json_encode(['ok' => false, 'error' => 'bad_request']); exit; }

try {
    dabil_push_ensure_table($conn);

    // De-dupe by endpoint, then insert — works whether or not a unique index exists.
    if ($del = $conn->prepare("DELETE FROM push_subscriptions WHERE endpoint=?")) {
        $del->bind_param("s", $endpoint);
        $del->execute();
    }
    $ok = false;
    if ($ins = $conn->prepare("INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth) VALUES (?,?,?,?)")) {
        $ins->bind_param("isss", $uid, $endpoint, $p256dh, $auth);
        $ok = $ins->execute();
    }
    echo json_encode(['ok' => (bool)$ok]);
} catch (\Throwable $e) {
    echo json_encode(['ok' => false, 'error' => 'db_error']);
}
