<?php
/**
 * GET /api/notifications/list.php
 * Query params: unread_only=1 (optional), page=<int>
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

$userId = require_login();

$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 30;
$offset = ($page - 1) * $perPage;
$unreadOnly = !empty($_GET['unread_only']);

$pdo = Database::connect();

$where = 'WHERE user_id = ?' . ($unreadOnly ? ' AND is_read = 0' : '');
$params = [$userId];

$stmt = $pdo->prepare("SELECT id, type, message, is_read, created_at FROM notifications $where ORDER BY created_at DESC LIMIT $perPage OFFSET $offset");
$stmt->execute($params);
$notifications = $stmt->fetchAll();

$countStmt = $pdo->prepare("SELECT COUNT(*) FROM notifications $where");
$countStmt->execute($params);
$total = (int) $countStmt->fetchColumn();

$stmt = $pdo->prepare('SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0');
$stmt->execute([$userId]);
$unreadCount = (int) $stmt->fetchColumn();

send_json(true, 'OK', [
    'notifications' => $notifications,
    'unread_count' => $unreadCount,
    'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
]);
