<?php
session_start();
require_once '../config/database.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['endpoint']) || !isset($data['keys']['p256dh']) || !isset($data['keys']['auth'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid subscription data']);
    exit();
}

$user_id = $_SESSION['user_id'];
$endpoint = $data['endpoint'];
$p256dh = $data['keys']['p256dh'];
$auth = $data['keys']['auth'];
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

$conn = getDBConnection();

// Check if subscription already exists
$check_query = "SELECT id FROM push_subscriptions WHERE user_id = ? AND endpoint = ?";
$stmt = $conn->prepare($check_query);
$stmt->bind_param("is", $user_id, $endpoint);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    // Update existing subscription
    $stmt->close();
    $update_query = "UPDATE push_subscriptions SET p256dh_key = ?, auth_key = ?, user_agent = ?, last_used = CURRENT_TIMESTAMP WHERE user_id = ? AND endpoint = ?";
    $stmt = $conn->prepare($update_query);
    $stmt->bind_param("sssis", $p256dh, $auth, $user_agent, $user_id, $endpoint);
    $stmt->execute();
} else {
    // Insert new subscription
    $stmt->close();
    $insert_query = "INSERT INTO push_subscriptions (user_id, endpoint, p256dh_key, auth_key, user_agent) VALUES (?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($insert_query);
    $stmt->bind_param("issss", $user_id, $endpoint, $p256dh, $auth, $user_agent);
    $stmt->execute();
}

$stmt->close();
$conn->close();

echo json_encode(['success' => true, 'message' => 'Subscription saved successfully']);
?>
