<?php
require_once("demosettings.php");

require_once 'vendor/autoload.php'; 

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\RotatingFileHandler;
/*
 *Monolog supports the logging levels:
 *DEBUG (100): Detailed debug information.
 *INFO (200): Interesting events. Examples: User logs in, SQL logs.
 *NOTICE (250): Normal but significant events.
 *WARNING (300): Exceptional occurrences that are not errors. Examples: Use of deprecated APIs,
 *poor use of an API, undesirable things that are not necessarily wrong.
 *ERROR (400): Runtime errors that do not require immediate action but should typically be logged and monitored.
 *CRITICAL (500): Critical conditions. Example: Application component unavailable, unexpected exception.
 *ALERT (550): Action must be taken immediately. Example: Entire website down, database unavailable, etc.
 *This should trigger the SMS alerts and wake you up.
 *EMERGENCY (600): Emergency: system is unusable.
 */

function getLogLevel()
{
    global $logLevel;
    if(!empty($logLevel) && !is_int($logLevel)){
        $logLevel = constant($logLevel); 
    }

    switch ($logLevel) {
        case IVLOG_PERFORMACE : 
            return Logger::INFO;
        case IVLOG_TRACE : 
            return Logger::DEBUG;
        case IVLOG_INFO : 
            return Logger::INFO;
        case IVLOG_WARN : 
            return Logger::WARNING;
        case IVLOG_ERROR : 
            return Logger::ERROR;
        default: 
            return Logger::DEBUG;
    }
}

function write_to_log($option, $str, $array = []) {
    global $trace_log_file;
    global $keepLogFileDays;

    $traceLog = new Logger('TRACE');
    $traceLog->pushHandler( new RotatingFileHandler($trace_log_file,$keepLogFileDays, getLogLevel(),false,0777));
    //$traceLog->pushHandler(new StreamHandler($trace_log_file, getLogLevel()));
    switch ($option) {

        case "AUDIT":
            $traceLog->addInfo($str);
            break;
        case "TRACE":
            $traceLog->addDebug($str);
            break;
        case "PERMORMENCE":
            $traceLog->addInfo($str, $array);
            break;
        case "INFO" :
            $traceLog->addInfo($str);
            break;
        case "WARNING" :
            $traceLog->addWarning($str);
            break;
        case "ERROR" :
            $traceLog->addError($str);
            break;
        default:
            $traceLog->addInfo($str);
            break;
    }
}

function write_to_log_depercated2 ($option, $str,$array=[]){
 	global $info_log_file;
	global $warrning_log_file;
	global $error_log_file;
	global $trace_log_file;
	global $perfomence_log_file;
        global $audit_log_file;
	global $logLevel;
 
        $traceLog = new Logger('TRACE');
        $traceLog->pushHandler(new StreamHandler($trace_log_file, Logger::DEBUG));
        
        $errorLog = new Logger('ERROR');
        $errorLog->pushHandler(new StreamHandler($error_log_file, Logger::ERROR));
        
        $preformanceLog = new Logger('PERMORMENCE');
        $preformanceLog->pushHandler(new StreamHandler($perfomence_log_file, Logger::INFO));
        
        $infoLog = new Logger('INFO');
        $infoLog->pushHandler(new StreamHandler($info_log_file, Logger::INFO));
        
        $warrningLog = new Logger('WARRNING');
        $warrningLog->pushHandler(new StreamHandler($warrning_log_file, Logger::WARNING));
        
        $auditLog = new Logger('AUDIT');
        $auditLog->pushHandler(new StreamHandler($audit_log_file, Logger::INFO));

	switch ($option){

                case "AUDIT":
                    if ($logLevel > IVLOG_TRACE) return;
                        $auditLog->addInfo($str);
                        break;
		case "TRACE":
			if ($logLevel > IVLOG_TRACE) return;
                        $traceLog->addInfo($str);
			break;
		case "PERMORMENCE":
			if ($logLevel > IVLOG_PERFORMACE) return;
                        $preformanceLog->addInfo($str,$array);
			break;
		case "INFO" : 
			if ($logLevel > IVLOG_INFO) return;
                        $infoLog->addInfo($str);
			break;		
		case "WARRNING" : 
		case "WARNING" : 
			if ($logLevel > IVLOG_WARN) return;
                        $warrningLog->addWarning($str);
			break;
		case "ERROR" : 
                        $errorLog->addError($str);
			break;	
		default:			
			if ($logLevel > IVLOG_TRACE) return;
                        $traceLog->addInfo($str);
			break;
	}	   
}

function write_to_log_depercated($option, $str) // option - INFO, WARRNING, ERROR,TRACE
{ 
	global $info_log_file;
	global $warrning_log_file;
	global $error_log_file;
	global $trace_log_file;
	global $perfomence_log_file;
	global $TEMP_FOLDER;
	global $logLevel;
	
	$date = date("Y-m-d H:i:s");
	$msec = explode(" ", microtime());
	$msec = substr($msec[0], 2); //skip "0."
	
	$logFileName;
	switch ($option){

		case "TRACE":
			if ($logLevel > IVLOG_TRACE) return;
			$logFileName = $trace_log_file;
			break;
		case "PERMORMENCE":
			if ($logLevel > IVLOG_PERFORMACE) return;
			$logFileName = $perfomence_log_file;
			break;
		case "INFO" : 
			if ($logLevel > IVLOG_INFO) return;
			$logFileName = $info_log_file;
			break;		
		case "WARRNING" : 
		case "WARNING" : 
			if ($logLevel > IVLOG_WARN) return;
			$logFileName = $warrning_log_file;
			break;
		case "ERROR" : 
			$logFileName = $error_log_file;
			break;	
		default:			
			if ($logLevel > IVLOG_TRACE) return;
			$logFileName = $trace_log_file;
			break;
	}
	if (!is_dir($TEMP_FOLDER))
		mkdir_full($TEMP_FOLDER, 0777, true);
	
	$handle = fopen($logFileName,"a");
	
	//Lock File, error if unable to lock
	if(flock($handle, LOCK_EX)) {
		fseek($handle, 0, SEEK_END);
		//if log file larger than 30MB - truncate
		if (ftell($handle) > 1600000)
		{
			rewind($handle);           //Set write pointer to beginning of file
			ftruncate($handle, 0);    //Truncate the file to 0
		}
		fwrite($handle, $date . ":" . $msec . "- " . $str . PHP_EOL);
		flock($handle, LOCK_UN);    //Unlock File
	} else {
		echo "Could not Lock log file " . $logFileName . " for writing message:" . $str . PHP_EOL;
	}
	
	//Close Stream
	fclose($handle);
	
	
}

function myErrorHandler($errno, $errstr, $errfile, $errline)
{
	write_to_log($errno == E_NOTICE? "TRACE": "ERROR", "UNEXPECTED ERROR: no: $errno, str: $errstr, file: $errfile, line: $errline");
	return false;
}
set_error_handler("myErrorHandler");

function exception_handler($exception) {
	write_to_log("ERROR", "Uncaught exception: " . $exception->getMessage());
}
set_exception_handler('exception_handler');

if (!empty($initializationErrors)) {
    write_to_log("ERROR", $initializationErrors);
}
