<?php

namespace App\Models;

use CodeIgniter\Model;

class NotificationModel extends Model
{
    protected $table         = 'notifications';
    protected $useTimestamps = false;
    protected $allowedFields = ['user_id', 'type', 'payload', 'channel', 'is_read', 'sent_at', 'created_at'];
    protected $casts         = ['payload' => 'json'];

    public function forUser(int $userId, bool $unreadOnly = false, int $page = 1, int $perPage = 20): array
    {
        $builder = $this->where('user_id', $userId);
        if ($unreadOnly) {
            $builder->where('is_read', 0);
        }
        $offset = ($page - 1) * $perPage;
        return $builder->orderBy('created_at', 'DESC')->findAll($perPage, $offset);
    }

    public function markRead(int $notificationId, int $userId): bool
    {
        return (bool) $this->where('id', $notificationId)->where('user_id', $userId)->set(['is_read' => 1])->update();
    }
}
