<?php
// api/push-subscribe.php — Save or remove Web Push subscriptions
require_once __DIR__ . '/../includes/config.php';
requireLogin();

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

$userId = $_SESSION['user_id'];

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

$input  = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? ($_POST['action'] ?? 'subscribe');

if ($action === 'subscribe') {
    $endpoint = $input['endpoint'] ?? '';
    $p256dh   = $input['p256dh']   ?? '';
    $authKey  = $input['auth']     ?? '';

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

    // Upsert — avoid duplicates
    $exists = $pdo->prepare("SELECT id FROM push_subscriptions WHERE user_id=? AND endpoint=?");
    $exists->execute([$userId, $endpoint]);

    if ($exists->fetch()) {
        // Update keys in case they changed
        $pdo->prepare("UPDATE push_subscriptions SET p256dh=?, auth_key=? WHERE user_id=? AND endpoint=?")
            ->execute([$p256dh, $authKey, $userId, $endpoint]);
    } else {
        $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') {
    $endpoint = $input['endpoint'] ?? '';
    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']);
