<?php

if (!function_exists('log_activity')) {
    /**
     * Catat log aktivitas ke database
     *
     * @param string $action      Aksi yang dilakukan (CREATE, UPDATE, DELETE, IMPORT, EXPORT, dsb)
     * @param string $target      Nama modul atau tabel target (siswa, guru, dsb)
     * @param int|null $recordId  ID record yang dipengaruhi
     * @param string $description Keterangan log secara detail
     */
    function log_activity(string $action, string $target, ?int $recordId = null, string $description = '')
    {
        try {
            $logModel = new \App\Models\ActivityLogModel();
            $request  = \Config\Services::request();
            
            $userId    = session()->get('user_id');
            $ipAddress = method_exists($request, 'getIPAddress') ? $request->getIPAddress() : '0.0.0.0';
            
            // Dapatkan user agent string secara aman
            $userAgent = '';
            if (method_exists($request, 'getUserAgent')) {
                $agentObj  = $request->getUserAgent();
                $userAgent = $agentObj ? (string) $agentObj : '';
            } else {
                $userAgent = 'CLI Command';
            }

            $logModel->insert([
                'user_id'     => $userId ? (int) $userId : null,
                'action'      => strtoupper($action),
                'target'      => $target,
                'record_id'   => $recordId,
                'description' => $description,
                'ip_address'  => $ipAddress,
                'user_agent'  => $userAgent,
            ]);
        } catch (\Exception $e) {
            // Jangan biarkan kegagalan pencatatan log menghentikan alur aplikasi utama
            log_message('error', 'Gagal mencatat log aktivitas: ' . $e->getMessage());
        }
    }
}
