# Analytics-Framework: Anwendungsbeispiele

## Grundlegende Verwendung

### Events tracken

```php
// Über Dependency Injection
public function __construct(private readonly Analytics $analytics) {}

// Einfaches Event tracken
$this->analytics->track('login_attempt', [
    'success' => true,
    'user_type' => 'admin',
    'method' => 'password'
]);

// Seitenaufruf tracken
$this->analytics->page('/produkte/kategorie/elektronik', [
    'referrer' => 'homepage',
    'search_query' => 'smartphones'
]);

// Benutzer identifizieren
$this->analytics->user($user->getId(), [
    'email' => $user->getEmail(),
    'plan' => $user->getSubscriptionPlan(),
    'registered_since' => $user->getCreatedAt()->format('Y-m-d')
]);
```

### Fehler tracken

```php
try {
    // Fehleranfälliger Code
    $result = $this->riskyOperation();
    return $result;
} catch (\Exception $e) {
    // Fehler tracken
    $this->analytics->error($e);

    // Fehler behandeln
    $this->logger->error($e->getMessage());
    return $this->fallbackOperation();
}
```

### Performance tracken

```php
// Manuelles Performance-Tracking
$startTime = microtime(true);
$startMemory = memory_get_usage();

// Operation durchführen
$result = $this->heavyOperation();

// Performance-Metriken tracken
$this->analytics->performance([
    'operation' => 'heavy_operation',
    'execution_time' => microtime(true) - $startTime,
    'memory_used' => memory_get_usage() - $startMemory,
    'result_size' => is_countable($result) ? count($result) : 0
]);
```

## Erweiterte Anwendungsfälle

### Benutzerdefinierte Middleware

```php
// In einem Service Provider oder Initializer
public function initialize(AnalyticsManager $manager): void
{
    // DSGVO-Middleware zur Anonymisierung personenbezogener Daten
    $manager->addMiddleware(function(array $event) {
        // E-Mail-Adressen anonymisieren
        if (isset($event['properties']['email'])) {
            $parts = explode('@', $event['properties']['email']);
            if (count($parts) === 2) {
                $event['properties']['email'] = substr($parts[0], 0, 1) . 
                    '***@' . $parts[1];
            }
        }

        // Passwörter und Tokens entfernen
        foreach (['password', 'token', 'api_key', 'secret'] as $key) {
            if (isset($event['properties'][$key])) {
                $event['properties'][$key] = '[redacted]';
            }
        }

        return $event;
    });

    // Spam-Filter
    $manager->addMiddleware(function(array $event) {
        // Zu viele Events von einem Benutzer filtern
        static $userCounts = [];
        $userId = $event['user_id'] ?? $event['session_id'] ?? null;

        if ($userId) {
            $userCounts[$userId] = ($userCounts[$userId] ?? 0) + 1;

            // Mehr als 100 Events pro Session ist verdächtig
            if ($userCounts[$userId] > 100) {
                return null; // Event verwerfen
            }
        }

        return $event;
    });
}
```

### Integration mit dem Domain-Layer

```php
// In einem Domain-Service
namespace App\Domain\Shop\Services;

use App\Framework\Analytics\Analytics;

class ProductService
{
    public function __construct(private readonly Analytics $analytics) {}

    public function viewProduct(string $productId, ?string $userId): Product
    {
        $product = $this->productRepository->find($productId);

        if (!$product) {
            throw new ProductNotFoundException($productId);
        }

        // Produktansicht tracken
        $this->analytics->track('product_view', [
            'product_id' => $product->getId(),
            'product_name' => $product->getName(),
            'product_price' => $product->getPrice(),
            'product_category' => $product->getCategory()->getName(),
            'in_stock' => $product->isInStock()
        ], $userId);

        return $product;
    }

    public function addToCart(string $productId, int $quantity, ?string $userId): Cart
    {
        // Implementation...

        // Event tracken
        $this->analytics->track('add_to_cart', [
            'product_id' => $productId,
            'quantity' => $quantity,
            'cart_value' => $cart->getTotalValue()
        ], $userId);

        return $cart;
    }
}
```

### Verwendung im Controller

```php
namespace App\Application\Controllers;

use App\Framework\Analytics\Analytics;
use App\Framework\Http\Request;
use App\Framework\Http\Response;
use App\Framework\Attributes\Route;

class CheckoutController
{
    public function __construct(
        private readonly Analytics $analytics,
        private readonly CheckoutService $checkoutService
    ) {}

    #[Route('/checkout/complete', method: 'POST')]
    public function completeCheckout(Request $request): Response
    {
        $userId = $request->getSession()->get('user_id');
        $cartId = $request->getSession()->get('cart_id');

        try {
            $order = $this->checkoutService->completeCheckout($cartId, $userId);

            // Erfolgreichen Checkout tracken
            $this->analytics->track('checkout_complete', [
                'order_id' => $order->getId(),
                'order_value' => $order->getTotalValue(),
                'items_count' => count($order->getItems()),
                'payment_method' => $order->getPaymentMethod(),
                'shipping_method' => $order->getShippingMethod()
            ], $userId);

            return new Response([
                'success' => true,
                'order_id' => $order->getId()
            ], 200);
        } catch (\Exception $e) {
            // Fehler beim Checkout tracken
            $this->analytics->track('checkout_error', [
                'error' => $e->getMessage(),
                'cart_id' => $cartId
            ], $userId);

            // Auch den Exception-Stack tracken
            $this->analytics->error($e);

            return new Response([
                'success' => false,
                'error' => $e->getMessage()
            ], 400);
        }
    }
}
```

## Analyse der Daten

### Dashboard-Controller

```php
namespace App\Application\Controllers;

use App\Framework\Analytics\AnalyticsDashboard;
use App\Framework\Http\Request;
use App\Framework\Http\Response;
use App\Framework\View\ViewRenderer;
use App\Framework\Attributes\Route;

class AnalyticsDashboardController
{
    public function __construct(
        private readonly AnalyticsDashboard $dashboard,
        private readonly ViewRenderer $viewRenderer
    ) {}

    #[Route('/admin/analytics/conversion')]
    public function conversionReport(Request $request): Response
    {
        $from = $request->getQueryParam('from');
        $to = $request->getQueryParam('to');

        // Benutzerdefinierte Analyse für Conversion-Funnel
        $pageViews = $this->dashboard->getEventCountByType('page_view', $from, $to);
        $productViews = $this->dashboard->getEventCountByType('product_view', $from, $to);
        $addToCarts = $this->dashboard->getEventCountByType('add_to_cart', $from, $to);
        $checkouts = $this->dashboard->getEventCountByType('checkout_complete', $from, $to);

        // Conversion-Raten berechnen
        $data = [
            'total_visitors' => $pageViews,
            'product_view_rate' => $pageViews > 0 ? $productViews / $pageViews : 0,
            'add_to_cart_rate' => $productViews > 0 ? $addToCarts / $productViews : 0,
            'checkout_rate' => $addToCarts > 0 ? $checkouts / $addToCarts : 0,
            'overall_conversion' => $pageViews > 0 ? $checkouts / $pageViews : 0,
            'from_date' => $from,
            'to_date' => $to
        ];

        return $this->viewRenderer->render('admin/analytics/conversion', $data);
    }
}
```
