<?php
/**
 * NotificationsController — inbox + AJAX badges/actions for the top-nav bell.
 */
class NotificationsController extends Controller
{
    public function indexAction()
    {
        $n     = new Notifications();
        $items = $n->recentForUser($this->currentUserId(), 100);
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Notifications/index', [
            'page_title' => 'Notifications',
            'items'      => $items,
        ]);
    }

    public function unreadCountAjAction()
    {
        $n = new Notifications();
        $this->jsonResponse(['ok' => true, 'count' => $n->unreadCountForUser($this->currentUserId())]);
    }

    /** Return up to 10 recent items for the top-nav dropdown preview. */
    public function recentAjAction()
    {
        $n     = new Notifications();
        $items = $n->recentForUser($this->currentUserId(), 10);
        $out   = [];
        foreach ($items as $it) {
            $out[] = [
                'id'          => (int)$it['c0d'],
                'kind'        => $it['kind'],
                'subject'     => $it['subject'],
                'body'        => $it['body'],
                'target_url'  => $it['target_url'],
                'created_on'  => $it['created_on'],
                'read'        => !empty($it['read_on']),
            ];
        }
        $this->jsonResponse(['ok' => true, 'items' => $out, 'unread' => $n->unreadCountForUser($this->currentUserId())]);
    }

    public function markReadAjAction()
    {
        (new Notifications())->markRead((int)($_POST['id'] ?? 0), $this->currentUserId());
        $this->jsonResponse(['ok' => true]);
    }

    public function markAllReadAjAction()
    {
        (new Notifications())->markAllRead($this->currentUserId());
        $this->jsonResponse(['ok' => true]);
    }
}
