create([ 'user_id' => $userId ?? ($_SESSION['user_id'] ?? null), 'branch_id' => $branchId ?? ($_SESSION['branch_id'] ?? 1), 'action' => $action, 'entity_type' => $entityType, 'entity_id' => $entityId, 'old_values' => $oldValues ? json_encode($oldValues, JSON_UNESCAPED_UNICODE) : null, 'new_values' => $newValues ? json_encode($newValues, JSON_UNESCAPED_UNICODE) : null, 'ip_address' => Security::getClientIp(), 'user_agent' => substr($_SERVER['HTTP_USER_AGENT'] ?? 'CLI/Unknown', 0, 255), 'created_at' => date('Y-m-d H:i:s'), ]); } catch (\Throwable $e) { // ห้ามให้การบันทึก Log ล้มเหลวไปกระทบการทำงานหลักของระบบ แต่บันทึกลง Error Log error_log("AuditLog Record Failed: " . $e->getMessage()); } } /** * Get recent audit trails by branch or user */ public function getRecent(int $branchId = null, int $limit = 100): array { $sql = "SELECT a.*, CONCAT(u.first_name, ' ', u.last_name) AS user_name, u.role FROM `{$this->table}` a LEFT JOIN `users` u ON a.user_id = u.id "; $params = []; if ($branchId !== null) { $sql .= " WHERE a.branch_id = :bid "; $params['bid'] = $branchId; } $sql .= " ORDER BY a.id DESC LIMIT :lim"; $stmt = self::getDB()->prepare($sql); if ($branchId !== null) { $stmt->bindValue(':bid', $branchId, \PDO::PARAM_INT); } $stmt->bindValue(':lim', $limit, \PDO::PARAM_INT); $stmt->execute(); return $stmt->fetchAll(); } }