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

// Security check: Only a logged-in user can save a subscription
if (!isset($_SESSION['user_id'])) { 
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Authentication required.']);
    exit();
}
$user_id = $_SESSION['user_id'];

// Get the subscription data sent from the browser
$data = json_decode(file_get_contents('php://input'), true);
$endpoint = $data['endpoint'] ?? null;
$p256dh = $data['keys']['p256dh'] ?? null;
$auth = $data['keys']['auth'] ?? null;

// Validate that we have all the required parts
if ($endpoint && $p256dh && $auth) {
    // Use INSERT ... ON DUPLICATE KEY UPDATE to prevent multiple entries for the same device (endpoint)
    $stmt = $conn->prepare("
        INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth) 
        VALUES (?, ?, ?, ?) 
        ON DUPLICATE KEY UPDATE user_id = ?, p256dh = ?, auth = ?
    ");
    $stmt->bind_param("isssiss", $user_id, $endpoint, $p256dh, $auth, $user_id, $p256dh, $auth);
    
    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Subscription saved successfully.']);
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Could not save subscription to the database.']);
    }
} else {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid subscription data provided.']);
}
?>
