<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;
use App\Services\NotificationService;

final class NotificationController extends BaseController
{
    public function index(Request $request): Response
    {
        $userId = $this->currentUserId();
        $rows = NotificationService::recentFor($userId, (int) $request->query('limit', 20));
        $unread = NotificationService::unreadCount($userId);

        if ($request->isAjax() || $request->isJson()) {
            return AjaxResponse::success(['rows' => $rows, 'unread_count' => $unread]);
        }

        return $this->view('notifications/index', [
            'title' => 'Notification Center',
            'activeNav' => 'notifications',
            'breadcrumbs' => [['Home', 'dashboard'], ['Notifications', 'notifications']],
            'rows' => $rows,
            'unread' => $unread,
        ]);
    }

    public function unreadCount(Request $request): Response
    {
        return AjaxResponse::success(['unread_count' => NotificationService::unreadCount($this->currentUserId())]);
    }

    public function markRead(Request $request, array $params): Response
    {
        NotificationService::markRead($this->currentUserId(), (int) $params['id']);

        return AjaxResponse::success(null, 'Marked as read.');
    }

    public function markAllRead(Request $request): Response
    {
        NotificationService::markAllRead($this->currentUserId());

        return AjaxResponse::success(null, 'All notifications marked as read.');
    }
}
