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

$userId = $_SESSION['user_id'];

try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS push_subscriptions (
            id         INT AUTO_INCREMENT PRIMARY KEY,
            user_id    INT NOT NULL,
            endpoint   TEXT,
            p256dh     TEXT,
            auth_key   TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_user (user_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
} catch (PDOException $e) {}

$action   = $_POST['action']   ?? 'subscribe';
$endpoint = $_POST['endpoint'] ?? '';
$p256dh   = $_POST['p256dh']   ?? '';
$authKey  = $_POST['auth']     ?? '';

if ($action === 'subscribe') {
    if (!$endpoint) {
        echo json_encode(['success' => false, 'message' => 'Missing endpoint']);
        exit;
    }

    // Check if this exact endpoint already exists for this user
    $exists = $pdo->prepare("SELECT id FROM push_subscriptions WHERE user_id=? AND endpoint=?");
    $exists->execute([$userId, $endpoint]);

    if ($exists->fetch()) {
        // Update existing
        $pdo->prepare("UPDATE push_subscriptions SET p256dh=?, auth_key=? WHERE user_id=? AND endpoint=?")
            ->execute([$p256dh, $authKey, $userId, $endpoint]);
    } else {
        // Insert new
        $pdo->prepare("INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth_key) VALUES (?,?,?,?)")
            ->execute([$userId, $endpoint, $p256dh, $authKey]);
    }

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

if ($action === 'unsubscribe') {
    if ($endpoint) {
        $pdo->prepare("DELETE FROM push_subscriptions WHERE user_id=? AND endpoint=?")
            ->execute([$userId, $endpoint]);
    }
    echo json_encode(['success' => true, 'message' => 'Unsubscribed']);
    exit;
}

if ($action === 'status') {
    $count = $pdo->prepare("SELECT COUNT(*) FROM push_subscriptions WHERE user_id=?");
    $count->execute([$userId]);
    echo json_encode(['success' => true, 'subscribed' => (int)$count->fetchColumn() > 0]);
    exit;
}

echo json_encode(['success' => false, 'message' => 'Unknown action']);