<?php
/**
 * PWA API - Get Notifications
 * 
 * GET /api/get-notifications
 * Returns pending notifications for the user
 */

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 {
    $db = new Database();
    $userId = SessionManager::getUserId();

    // Get unread notifications
    $notifications = $db->fetchAll(
        "SELECT id, title, message as body, type, icon, tag, data, created_at
         FROM notifications
         WHERE user_id = ? AND read_at IS NULL
         ORDER BY created_at DESC
         LIMIT 10",
        [$userId]
    );

    // Format notifications
    $formatted = [];
    foreach ($notifications as $notif) {
        $formatted[] = [
            'id' => $notif['id'],
            'title' => $notif['title'] ?? 'Notification',
            'body' => $notif['body'] ?? '',
            'icon' => $notif['icon'] ?? '/invcount/assets/images/icons/icon-192x192.png',
            'badge' => '/invcount/assets/images/icons/badge-72x72.png',
            'tag' => $notif['tag'] ?? 'notification',
            'data' => json_decode($notif['data'] ?? '{}', true),
            'requireInteraction' => $notif['type'] === 'alert',
        ];
    }

    // Return notifications
    header('Content-Type: application/json');
    http_response_code(200);
    echo json_encode($formatted);

    // Mark as read in background
    if (!empty($notifications)) {
        $notifIds = array_column($notifications, 'id');
        $db->execute(
            "UPDATE notifications SET read_at = NOW() WHERE id IN (" . 
            implode(',', array_fill(0, count($notifIds), '?')) . ")",
            $notifIds
        );
    }

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