doctor-appointment-system/restored_ActivityLogModel.php
2026-05-08 12:22:08 +05:30

80 lines
5.1 KiB
PHP
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Models;
use CodeIgniter\Model;
class ActivityLogModel extends Model
{
protected $table = 'activity_logs';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $protectFields = true;
protected $allowedFields = [
'actor_user_id',
'actor_role',
'action',
'description',
'target_type',
'target_id',
'ip_address',
'user_agent',
'created_at',
];
public function log(string $action, string $description, ?string $targetType = null, ?int $targetId = null): void
{
$request = service('request');
$this->insert([
'actor_user_id' => session()->get('id') ? (int) session()->get('id') : null,
'actor_role' => session()->get('role') ?: null,
'action' => $action,
'description' => $description,
'target_type' => $targetType,
'target_id' => $targetId,
'ip_address' => method_exists($request, 'getIPAddress') ? $request->getIPAddress() : null,
'user_agent' => method_exists($request, 'getUserAgent') ? $request->getUserAgent()->getAgentString() : null,
'created_at' => date('Y-m-d H:i:s'),
]);
}
public function getFiltered(array $filters = []): array
{
$builder = $this->db->table('activity_logs al')
->select("al.*, CONCAT(COALESCE(u.first_name, ''), ' ', COALESCE(u.last_name, '')) AS actor_name, u.email AS actor_email")
->join('users u', 'u.id = al.actor_user_id', 'left');
if (! empty($filters['action'])) {
$builder->like('al.action', $filters['action']);
}
if (! empty($filters['role'])) {
$builder->where('al.actor_role', $filters['role']);
}
if (! empty($filters['date_from'])) {
$builder->where('DATE(al.created_at) >=', $filters['date_from']);
}
if (! empty($filters['date_to'])) {
$builder->where('DATE(al.created_at) <=', $filters['date_to']);
}
return $builder
->orderBy('al.created_at', 'DESC')
->get()
->getResultArray();
}
public function getRecent(int $limit = 8): array
{
return $this->db->table('activity_logs')
->orderBy('created_at', 'DESC')
->limit($limit)
->get()
->getResultArray();
}
}