<?php
/**
 * PWA API - Save Push Subscription
 * 
 * POST /api/save-push-subscription
 * Saves user's push notification subscription for sending notifications
 */

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

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    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 JSON payload
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['subscription']) || !is_array($input['subscription'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid subscription data']);
        exit;
    }

    $subscription = $input['subscription'];
    
    // Validate subscription structure
    if (empty($subscription['endpoint'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid subscription: missing endpoint']);
        exit;
    }

    $db = new Database();
    $userId = SessionManager::getUserId();
    
    // Save or update subscription in database
    $result = $db->execute(
        "INSERT INTO push_subscriptions (user_id, endpoint, auth, p256dh, created_at)
         VALUES (?, ?, ?, ?, NOW())
         ON DUPLICATE KEY UPDATE
         endpoint = VALUES(endpoint),
         auth = VALUES(auth),
         p256dh = VALUES(p256dh),
         updated_at = NOW()",
        [
            $userId,
            $subscription['endpoint'],
            $subscription['keys']['auth'] ?? null,
            $subscription['keys']['p256dh'] ?? null,
        ]
    );

    if ($result) {
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'message' => 'Subscription saved successfully',
        ]);
    } else {
        throw new Exception('Failed to save subscription');
    }

} catch (Exception $e) {
    error_log('[PWA API] Save subscription error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Failed to save subscription',
        'message' => $e->getMessage(),
    ]);
}
