<?php
require 'config.php';
session_start();

// Enable error reporting
error_log("=== Push Subscription Debug ===");
error_log("User ID: " . ($_SESSION['user_id'] ?? 'NOT SET'));

$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);

error_log("Received data: " . print_r($decoded, true));

if (isset($decoded['endpoint'])) {
    if (!isset($_SESSION['user_id'])) {
        error_log("ERROR: No user_id in session");
        echo json_encode(['success' => false, 'error' => 'Not logged in']);
        exit;
    }
    
    $user_id = $_SESSION['user_id'];
    $endpoint = $decoded['endpoint'];
    $p256dh = $decoded['keys']['p256dh'] ?? '';
    $auth = $decoded['keys']['auth'] ?? '';

    $stmt = $pdo->prepare("INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth) 
                           VALUES (?, ?, ?, ?) 
                           ON DUPLICATE KEY UPDATE p256dh=?, auth=?, user_id=?");
    
    $stmt->execute([$user_id, $endpoint, $p256dh, $auth, $p256dh, $auth, $user_id]);
    
    error_log("SUCCESS: Subscription saved for user " . $user_id);
    echo json_encode(['success' => true]);
} else {
    error_log("ERROR: No endpoint in request");
    echo json_encode(['success' => false, 'error' => 'No endpoint']);
}
?>