<?php

namespace Helpers\Log;

use Helpers\Session\ParseBase1;

class LogSysteme
{

    private string $fileName;
    private string $directory;
    private string $date;
    private string $hour;
   
   
    public function __construct(int $contexte = 1)
    {
        $this->date = '*********************   Date: ' . date('d/m/Y') . '  ********************';
        $this->hour = date('H:i:s');

        switch ($contexte) {
            case 1:
                $this->fileName = 'GENERALERRORLOG_OXAPROC.log';
                $this->directory = (new ParseBase1())->getRep()->log;
                break;
            
            case 2:
                $this->fileName = self::getServerName().'.stats_SQLServer.log';
                $this->directory = (new ParseBase1())->getRep()->tmp;
                break;
            
            case 3:
                $this->fileName = self::getServerName().'.req_SQLServer.log';
                $this->directory = (new ParseBase1())->getRep()->tmp;
                break;
            case 4:
                $this->fileName = date('Ymd').'_req_SQLServer.log';
                $this->directory = (new ParseBase1())->getRep()->log;
        }
    }

    public function setContentInLog(string $content) : int
    {
        return (int) file_put_contents(
            $this->directory.$this->fileName,
            $this->date.PHP_EOL.$this->hour. ' : '.$content.PHP_EOL,
            FILE_APPEND
        );
    }

    /**
     * Permet de préfixer error_log avec PHP_DEV_ERROR
     * Important pour les reports Grafana, a utiliser dans Oxaproc
     * pour chaque error_log à implémenter
     * et de mettre autant de string qu'on veut les unes à la suite des autres
     *
     * @param string|\Stringable|string[] $messages
     */
    public static function prefixErrorLog(string|\Stringable|array $messages): bool
    {
        if (is_string($messages) || $messages instanceof \Stringable) {
            return error_log("PHP_DEV_ERROR :\r\n" . $messages);
        }
        return error_log("PHP_DEV_ERROR :\r\n" . implode("\r\n", $messages));
    }

    public static function getServerName(): string
    {
        return 'PHP_'.$_SERVER['COMPUTERNAME'];
    }
}
