<?php
/**
 * In-App Notifications
 * GET /v1/notifications
 * Returns user's notifications
 */

use App\Core\Database;
use App\Middleware\AuthMiddleware;

$decoded = AuthMiddleware::check();
$db = Database::getInstance();

$userId = $decoded['user_id'];
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = min(50, max(10, (int)($_GET['limit'] ?? 20)));
$offset = ($page - 1) * $limit;

// Get total + unread count
$countStmt = $db->prepare("SELECT COUNT(*) as total, SUM(CASE WHEN is_read = 0 THEN 1 ELSE 0 END) as unread FROM notifications WHERE user_id = ?");
$countStmt->execute([$userId]);
$counts = $countStmt->fetch();

// Fetch notifications
$stmt = $db->prepare("
    SELECT * FROM notifications 
    WHERE user_id = ? 
    ORDER BY created_at DESC 
    LIMIT ? OFFSET ?
");
$stmt->execute([$userId, $limit, $offset]);
$notifications = $stmt->fetchAll();

json_success([
    'notifications' => $notifications,
    'unread_count' => (int)($counts['unread'] ?? 0),
    'pagination' => [
        'page' => $page,
        'total' => (int)($counts['total'] ?? 0),
        'pages' => ceil(($counts['total'] ?? 0) / $limit),
    ],
]);
