<?php
declare(strict_types=1);

namespace App\Modules\Notifications;

use App\Core\Http\Request;
use App\Core\Http\Response;
use App\Core\I18n\Translator;
use App\Core\Security\Csrf;
use App\Core\Support\Flash;
use App\Core\View\Template;
use App\Modules\Auth\AuthService;

final class NotificationController
{
    public function __construct(
        private readonly Template $template,
        private readonly Translator $translator,
        private readonly AuthService $auth,
        private readonly NotificationRepository $repository
    ) {
    }

    public function index(Request $request): Response
    {
        $page = max(1, (int) $request->input('page', 1));
        $result = $this->repository->paginate($page, 30);

        $html = $this->template->render('notifications/index', [
            'title' => $this->translator->get('notifications.title'),
            'activeMenu' => 'notifications',
            'user' => $this->auth->user(),
            'csrfToken' => Csrf::token(),
            'notifications' => $result['items'],
            'pagination' => $result,
            'unreadCount' => $this->repository->unreadCount(),
        ], 'layouts/app');

        return Response::html($html);
    }

    public function markRead(Request $request): Response
    {
        if (!Csrf::validate((string) $request->input('_token', ''))) {
            Flash::push('danger', $this->translator->get('auth.errors.csrf_expired'));
            return Response::redirect('/notifications');
        }

        $id = max(0, (int) $request->input('id', 0));
        if ($id > 0) {
            $this->repository->markRead($id);
        } else {
            $this->repository->markAllRead();
        }

        return Response::redirect('/notifications');
    }
}
