<?php
/**
 * Notifications List API - Get user notifications
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) session_start();

if (!isset($_SESSION['user_id'])) {
    jsonError('Not authenticated', 401);
}

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

try {
    $total = dbCount('push_notifications', 'user_id = ?', [$userId]);
    $unread = dbCount('push_notifications', 'user_id = ? AND is_read = 0', [$userId]);

    $notifications = dbFetchAll(
        "SELECT id, title, body, data, type, is_read, created_at 
         FROM push_notifications 
         WHERE user_id = ? 
         ORDER BY created_at DESC 
         LIMIT ? OFFSET ?",
        [$userId, $limit, $offset]
    );

    // Parse JSON data field
    foreach ($notifications as &$notif) {
        $notif['data'] = $notif['data'] ? json_decode($notif['data'], true) : null;
        $notif['time_ago'] = timeAgo($notif['created_at']);
    }

    jsonSuccess('Notifications loaded', [
        'notifications' => $notifications,
        'total'         => $total,
        'unread'        => $unread,
        'page'          => $page,
        'pages'         => ceil($total / $limit)
    ]);

} catch (Exception $e) {
    error_log("Notifications List Error: " . $e->getMessage());
    jsonError('Failed to load notifications');
}
