<?php
// save_subscription.php
header('Content-Type: application/json');

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

// Получаем тело запроса
$body = file_get_contents('php://input');
$data = json_decode($body, true);

// Валидация входных данных
if (!is_array($data) || empty($data['client_id']) || empty($data['subscription'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Missing client_id or subscription']);
    exit;
}

$clientId = (int)$data['client_id'];
$sub = $data['subscription'];

if (empty($sub['endpoint']) || empty($sub['keys']['p256dh']) || empty($sub['keys']['auth'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Incomplete subscription data']);
    exit;
}

$endpoint = $sub['endpoint'];
$p256dh   = $sub['keys']['p256dh'];
$authKey  = $sub['keys']['auth'];

try {
    // Проверяем, есть ли уже подписка для данного endpoint
    $stmt = $pdo->prepare(
        'SELECT id FROM push_subscriptions WHERE client_id = :client_id AND endpoint = :endpoint LIMIT 1'
    );
    $stmt->execute([':client_id' => $clientId, ':endpoint' => $endpoint]);
    $exists = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($exists) {
        // Обновляем ключи
        $stmt = $pdo->prepare(
            'UPDATE push_subscriptions SET p256dh = :p256dh, auth = :auth, created_at = NOW() WHERE id = :id'
        );
        $stmt->execute([
            ':p256dh' => $p256dh,
            ':auth'   => $authKey,
            ':id'     => $exists['id']
        ]);
    } else {
        // Вставляем новую подписку
        $stmt = $pdo->prepare(
            'INSERT INTO push_subscriptions (client_id, endpoint, p256dh, auth)
             VALUES (:client_id, :endpoint, :p256dh, :auth)'
        );
        $stmt->execute([
            ':client_id' => $clientId,
            ':endpoint'  => $endpoint,
            ':p256dh'    => $p256dh,
            ':auth'      => $authKey
        ]);
    }

    echo json_encode(['success' => true]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
