<?php

namespace App\Models;

use CodeIgniter\Model;

class Notification extends Model
{
    protected $table = 'notification';
    protected $primaryKey = 'id';
    protected $allowedFields = ['message', 'is_read', 'forgroup', 'store_id', "link", 'created_at'];

    public function getNotifications()
    {
        $session = session();
        $users = $session->get('user');

        $today = date('Y-m-d');

        return $this->where('store_id', $users['store_id'])
            ->groupStart()
                ->where('forgroup', $users['group_name'])
                ->orWhere('forgroup', strtolower('TOUS'))
            ->groupEnd()
            ->groupStart()
                ->where('is_read', 0) // toutes les notifications non lues
                ->orGroupStart()
                    ->where('is_read', 1) // notifications lues
                    ->where('DATE(created_at)', $today) // mais seulement celles d’aujourd’hui
                ->groupEnd()
            ->groupEnd()
            ->orderBy('created_at', 'DESC')
            ->findAll();
    }

    public function markAsRead(int $id)
    {
        return $this->update($id, ['is_read' => 1]);
    }

    public function insertNotification(array $data)
    {
        return $this->insert($data);
    }
}
