<?php
/**
 * PWA API - Get VAPID Public Key
 * 
 * GET /api/get-vapid-key
 * Returns the server's VAPID public key for push notifications
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../includes/auth.php';

// Only allow GET requests
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

// Check authentication
if (!SessionManager::isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

try {
    // Get VAPID key from settings or environment
    $settings = new Settings();
    $vapidKey = $settings->get('push_vapid_public_key');
    
    if (empty($vapidKey)) {
        // VAPID key not configured
        // Generate one using web-push library if available
        // For now, return error
        http_response_code(503);
        echo json_encode([
            'error' => 'Push notifications not configured on server',
        ]);
        exit;
    }

    // Return VAPID public key
    header('Content-Type: application/json');
    http_response_code(200);
    echo json_encode([
        'key' => $vapidKey,
    ]);

} catch (Exception $e) {
    error_log('[PWA API] Get VAPID key error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'error' => 'Failed to fetch VAPID key',
        'message' => $e->getMessage(),
    ]);
}
