<?php

namespace Modules\Notifications\Controllers;

use core\Controller;
use core\Auth;
use core\Database;
use core\Security;

class NotificationController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index(): void
    {
        $this->requirePermission('notifications_view');

        $db = Database::getInstance();
        $page = max(1, (int)$this->request->get('page', 1));
        $perPage = PAGINATION_LIMIT;

        $notifications = $db->table('notifications')
            ->where('user_id', Auth::id())
            ->orWhere('user_id', 0)
            ->orderBy('created_at', 'DESC')
            ->paginate($perPage, $page);

        $unreadCount = $db->table('notifications')
            ->where('user_id', Auth::id())
            ->where('is_read', 0)
            ->count();

        $this->view('Notifications/index', [
            'title' => 'Notifications',
            'breadcrumb' => ['Notifications' => url('notifications')],
            'notifications' => $notifications,
            'unreadCount' => $unreadCount,
        ]);
    }

    public function markRead(int $id): void
    {
        $db = Database::getInstance();
        $notification = $db->table('notifications')
            ->where('id', $id)
            ->where('user_id', Auth::id())
            ->first();

        if ($notification) {
            $db->table('notifications')->where('id', $id)->update(['is_read' => 1]);
        }

        $this->json(['success' => true]);
    }

    public function markAllRead(): void
    {
        Database::getInstance()->table('notifications')
            ->where('user_id', Auth::id())
            ->where('is_read', 0)
            ->update(['is_read' => 1]);

        $this->json(['success' => true]);
    }
}
