<?php

namespace engine\logging;

class DatabaseLogger extends Logger
{
    protected function writer(LogLevel $level,
                              int      $num,
                              string   $message,
                              ?int     $errno = null,
                              ?string  $errfile = null,
                              ?string  $errline = null,
                              ?string  $stacktrace = null): void
    {
        $db = getDB();

        $data = [
            'ts' => time(),
            'num' => $num,
            'time' => exectime(),
            'errno' => $errno ?: 0,
            'file' => $errfile ?: '?',
            'line' => $errline ?: 0,
            'text' => $message,
            'level' => $level->value,
            'stacktrace' => $stacktrace ?: Util::backtraceAsString(2),
            'is_cli' => intval(isCli()),
            'admin_id' => isAdmin() ? \app\Admin::getId() : 0,
        ];

        if (isCli()) {
            $data += [
                'ip' => '',
                'ua' => '',
                'url' => '',
            ];
        } else {
            $data += [
                'ip' => ip2ulong($_SERVER['REMOTE_ADDR']),
                'ua' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                'url' => $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
            ];
        }

        $db->insert('backend_errors', $data);
    }
}
