doctor-appointment-system/app/Models/ActivityLogModel.php
2026-04-14 18:42:34 +05:30

80 lines
2.5 KiB
PHP

<?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();
}
}