<?php

namespace App\Models;

use CodeIgniter\Model;

class NotificationsModel extends Model
{
    protected $table = 'notifications';
    protected $primaryKey = 'id';

    protected $allowedFields = ['message', 'receiver_id', 'status', 'notification_type', 'created_by', 'updated_by', 'updated_at'];

    protected $returnType     = 'array';
    protected $useTimestamps  = true;
    protected $useSoftDeletes = true;

    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    public function getAll()
    {
        $builder = $this->db->table('notifications as n');
        $builder->where('deleted_at', null);
        return $result = $builder->get()->getResult();
    }

    public function getAlertsByUserId($user)
    {
        $builder = $this->db->table('notifications as n');
        $builder->where('deleted_at', null);
        $builder->where('n.receiver_id', $user);
        $builder->orderBy('n.id', 'DESC');
        $result = $builder->get()->getResult();
        return $result;
    }

    public function getAlertsTypeByUserId($user, $type)
    {
        $builder = $this->db->table('notifications as n');
        $builder->where('n.deleted_at', null);
        $builder->where('n.receiver_id', $user);
        $builder->where('n.notification_type', $type);
        $builder->where('n.receiver_type', 'admin');
        $builder->orderBy('n.id', 'DESC');
        $result = $builder->get()->getResult();
        return $result;
    }
    
    public function getTotalUserAlerts($user)
    {
        $builder = $this->db->table('notifications as n');
        $builder->where('n.receiver_id', $user);
        $builder->where('n.status', '1');
        $result = $builder->countAllResults();
        return $result;
    }
}