<?php
namespace App\Modules\Notifications\Controllers;

use Core\Controller;
use Core\Auth;
use App\Modules\Notifications\Models\NotificationModel;

class NotificationController extends Controller {

    private NotificationModel $model;

    public function __construct() {
        parent::__construct();
        $this->requireAuth();
        $this->model = new NotificationModel();
    }

    public function index() {
        $userId     = Auth::id();
        $unreadOnly = isset($_GET['filter']) && $_GET['filter'] === 'unread';
        $page       = max(1, (int) ($this->getGet('page', 1)));
        $perPage    = 20;
        $offset     = ($page - 1) * $perPage;

        $notifications = $this->model->getForUser($userId, $unreadOnly, $perPage, $offset);
        $unreadCount   = $this->model->getUnreadCount($userId);

        $this->render('notifications/index', [
            'pageTitle'     => 'Notifications',
            'notifications' => $notifications,
            'unreadCount'   => $unreadCount,
            'unreadOnly'    => $unreadOnly,
            'page'          => $page,
            'breadcrumb'    => [['label' => 'Notifications']],
        ]);
    }

    public function delete(int $id) {
        $this->model->delete($id, Auth::id());
        $this->redirect(APP_URL . '/notifications');
    }

    public function markAsRead(int $id) {
        $this->model->markAsRead($id, Auth::id());
        if ($this->getGet('redirect')) {
            $this->redirect(APP_URL . '/notifications');
        }
        $this->json(['success' => true]);
    }

    public function markAllAsRead() {
        $this->model->markAllAsRead(Auth::id());
        $this->setFlash('success', 'All notifications marked as read.');
        $this->redirect(APP_URL . '/notifications');
    }

    public function unreadCount() {
        $count = $this->model->getUnreadCount(Auth::id());
        $this->json(['count' => $count]);
    }
}
