<?php

class Notification extends BaseModel
{
    public function forCurrentUser(int $limit = 100): array
    {
        $user = Auth::user();
        if (!$user) return [];
        $stmt = $this->db->prepare('SELECT * FROM notifications WHERE user_id = ? OR role_target = ? ORDER BY read_at IS NULL DESC, id DESC LIMIT ' . max(1, min(250, $limit)));
        $stmt->execute([(int) $user['id'], $user['role']]);
        return $stmt->fetchAll();
    }

    public function markRead(int $id): void
    {
        $user = Auth::user();
        if (!$user) return;
        $stmt = $this->db->prepare('UPDATE notifications SET read_at = COALESCE(read_at, NOW()) WHERE id = ? AND (user_id = ? OR role_target = ?)');
        $stmt->execute([$id, (int) $user['id'], $user['role']]);
    }

    public function markAllRead(): void
    {
        $user = Auth::user();
        if (!$user) return;
        $stmt = $this->db->prepare('UPDATE notifications SET read_at = COALESCE(read_at, NOW()) WHERE user_id = ? OR role_target = ?');
        $stmt->execute([(int) $user['id'], $user['role']]);
    }
}
