<?php
/**
 * ============================================================================
 * ajax/push-subscription.php
 * Handle push notification subscriptions
 * ============================================================================
 */

define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

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

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

try {
    $userId = getUserId();
    $database = new Database();
    $db = $database->getConnection();
    
    $pushNotification = new \App\PushNotification($db);
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';
    
    switch ($action) {
        case 'subscribe':
            $subscription = $input['subscription'] ?? null;
            
            if (!$subscription || !isset($subscription['endpoint'])) {
                throw new Exception('Invalid subscription data');
            }
            
            $result = $pushNotification->saveSubscription($userId, $subscription);
            echo json_encode($result);
            break;
            
        case 'unsubscribe':
            $endpoint = $input['endpoint'] ?? null;
            
            if (!$endpoint) {
                throw new Exception('Endpoint required');
            }
            
            $result = $pushNotification->removeSubscription($userId, $endpoint);
            echo json_encode($result);
            break;
            
        default:
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    
} catch (Exception $e) {
    error_log('Push subscription error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to process subscription'
    ]);
}
?>