<?php

namespace Mnv\Core\Test;

use Mnv\Core\DB;
use Mnv\Core\Singleton\SingletonTrait;

/**
 * Class Logger
 * @package Mnv\App\Test
 */
class Logger
{
    use SingletonTrait;

	private array $logs = [];

    /**
     * Add msg to log
     *
     * @param string|null $message
     * @param $managerId
     * @param string $type
     * @return $this
     */
    public function log(?string $message, $managerId, string $type = "log"): Logger
    {
        if ($type != "info" && $type != "error") {
            $type = "log";
        }

        $this->logs[] = array("message" => $message, "type" => $type, 'managerId' => $managerId);

        return $this;
    }

	/**
	 * Log error
     *
     * @param string|null $message
     * @param $managerId
     * @param bool $save
     * @return $this
     */
	public function error(?string $message, $managerId, bool $save = true): Logger
    {
		if ($save) {
			$this->log($message, $managerId, "error");
		}

		return $this;
	}

	/**
	 * Log info
     * @param string|null $message
     * @param $managerId
     * @param bool $save
     * @return $this
     */
	public function info(?string $message, $managerId, bool $save = true): Logger
    {
		if ($save) {
			$this->log($message, $managerId, "info");
		}

		return $this;
	}



    /** Сохранить (log) в базу данных */
    public function save(): void
    {
	    if (!empty($this->logs)) {
			$dump = [];

			foreach ($this->logs AS $value) {
                $dump['userId']   = $value["managerId"];
                $dump['message']  = $value["message"];
                $dump['type_log'] = $value["type"];
                $dump['date_log'] = gmdate('Y-m-d H:i:s');
                $dump['user_ip']  = '';
			}

            connect()->table('log')->insert($dump);
		}

	}
}
