<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

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

$requestMethod = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));

if ($requestMethod !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'message' => 'Method not allowed.']);
    exit;
}

if (!web_push_enabled()) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'message' => 'Web push is not enabled.']);
    exit;
}

$payload = json_decode((string) file_get_contents('php://input'), true);
if (!is_array($payload)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'message' => 'Invalid JSON payload.']);
    exit;
}

$action = trim((string) ($payload['action'] ?? 'subscribe'));

try {
    if ($action === 'unsubscribe') {
        web_push_deactivate_subscription((string) ($payload['endpoint'] ?? ''));
        echo json_encode(['ok' => true, 'message' => 'Subscription removed.']);
        exit;
    }

    $subscription = (array) ($payload['subscription'] ?? []);
    $visitorToken = function_exists('public_tracking_visitor_token')
        ? public_tracking_visitor_token()
        : trim((string) ($_COOKIE['jlfc_vid'] ?? ''));

    if ($visitorToken === '') {
        $visitorToken = sha1(uniqid('jlfc-visitor', true));
    }

    web_push_upsert_subscription(
        $subscription,
        isset($_SESSION['user_id']) ? (int) $_SESSION['user_id'] : null,
        hash('sha256', $visitorToken),
        substr(trim((string) ($_SERVER['HTTP_USER_AGENT'] ?? '')), 0, 255)
    );

    echo json_encode(['ok' => true, 'message' => 'Subscription saved.']);
} catch (InvalidArgumentException $exception) {
    http_response_code(422);
    echo json_encode(['ok' => false, 'message' => $exception->getMessage()]);
} catch (Throwable) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'message' => 'Unable to save push subscription.']);
}
