<?php

namespace apexl\Io\modules\user\entities\operators;

use apexl\Io\operators\entityDatabaseOperator;

class userNotificationOperator extends entityDatabaseOperator
{
    public function __construct($table, $primaryKey = 'id')
    {
        parent::__construct($table, $primaryKey);
    }

    public function getForUser($userId, $seen=null, $limit=100)
    {
        $this->vault
            ->select($this->dbTable)
            ->fields($this->dbTable.'.*')
            ->where('user_id', $userId);
        if (!is_null($seen)){
            $this->vault->where('seen', $seen);
        }
        return $this->vault->orderBy('created', 'DESC')
            ->execute()
            ->fetchAll();
    }

    public function getCountForUser($userId, $seen=null)
    {
        $this->vault
            ->select($this->dbTable)
            ->fields('COUNT(*) AS cnt')
            ->where('user_id', $userId);
        if (!is_null($seen)){
            $this->vault->where('seen', $seen);
        }
        $result = $this->vault
            ->execute()
            ->fetchAssoc();

        return $result['cnt'];
    }

    public function markAllAsRead($userId)
    {
        $results = $this->vault->update($this->dbTable)->fields(['seen' => 1])->where('user_id', $userId)->execute();
    }
}
