<?php
/**
 * ErrorHandler is tracking and login erros
 */
class ErrorHandler{
	private $handler;

	function __construct(){
		register_shutdown_function(function(){
            self::check_for_fatal();
        });
		$this->handler = set_error_handler(function($errno, $errstr, $errfile, $errline){
            self::myHandler($errno, $errstr, $errfile, $errline);
        });
		error_reporting( E_ALL );
		ini_set('display_errors', 1);
	}

    /**
     * Custom error handler
     * @param  INT $errno   error code
     * @param  String $errstr  the error message
     * @param  String $errfile the file that triggered the error
     * @param  INT $errline line of code where error was triggered
     * @return Boolean
     */
	private static function myHandler($errno, $errstr, $errfile, $errline){
		if (!(error_reporting() & $errno)) {
	        return;
	    }

		header('Status: 500 Internal Server Error');
        header('HTTP/1.0 500 Internal Server Error');

	    switch ($errno) {
    	    case E_USER_ERROR:
				$err_mes = '<div class="alert alert-danger col-md-12">';
				$err_mes .= '<span class="glyphicon glyphicon-exclamation-sign"></span>';
    	        $err_mes .= "<b>My ERROR</b> [$errno] $errstr<br />". PHP_EOL;
    	        $err_mes .= "  Fatal error on line $errline in file $errfile";
    	        $err_mes .= ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />". PHP_EOL;
    	        $err_mes .= "Aborting...<br />" . PHP_EOL;
				$err_mes .= '</div>';
                self::addLog($err_mes);
    	        exit(1);
    	        break;

    	    case E_USER_WARNING:
				$err_mes = '<div class="alert alert-warning col-md-12">';
    	        $err_mes = "<b>My WARNING</b> [$errno] $errstr<br />". PHP_EOL;
				$err_mes .= '</div>';
                self::addLog($err_mes);
    	        break;

    	    case E_USER_NOTICE:
				$err_mes = '<div class="alert alert-info col-md-12">';
    	        $err_mes = "<b>My NOTICE</b> [$errno] $errstr<br />". PHP_EOL;
				$err_mes .= '</div>';
                self::addLog($err_mes);
    	        break;

    	    default:
				$err_mes = '<div class="alert alert-danger col-md-12">';
				$err_mes .= '<span class="glyphicon glyphicon-exclamation-sign"></span>';
				$err_mes .= "<b>My ERROR</b> [$errno] $errstr<br />". PHP_EOL;
				$err_mes .= "  Fatal error on line $errline in file $errfile";
    	        $err_mes .= ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />". PHP_EOL;
				$err_mes .= "Aborting...<br />" . PHP_EOL;
				$err_mes .= '</div>';
				self::addLog($err_mes);
				exit(1);
				break;
	    }

	    return true;
	}

    /**
     * Subscribe fatal php errors
     */
	private static function check_for_fatal(){
	    $error = error_get_last();
	    if ( $error["type"] == E_ERROR )
	        self::myHandler( $error["type"], $error["message"], $error["file"], $error["line"] );
	}

    /**
     * Adds the error message to a log file using the date of trigger
     * @param String $err_mes the errror message to be added to the log
     */
	public static function addLog($err_mes){
        if(APPLICATION_MODE !== 'PROD'){
			header('Content-Type: text/html; charset=utf-8');
            echo $err_mes;
        }else{
			$errorDate = date('Y/m/d H:i:s');
			$today = getdate();
	        $logDir = PATH_LOGS.$today['year'].'/'.$today['month'].'/'.$today['mday'].'/';
	        if (!file_exists($logDir)) {
	            mkdir($logDir, 0777, true);
	        }
	        $logFile = $logDir.$today['hours'].'_'.$today['minutes'].'.log';
	        $fileHandler = fopen($logFile, "a");

	        fwrite($fileHandler, $errorDate . PHP_EOL);
	        fwrite($fileHandler, $err_mes . PHP_EOL . PHP_EOL);
	        fclose($fileHandler);

			$friendlyErrorMessage = '<div class="alert alert-danger">';
			$friendlyErrorMessage .= '<span class="glyphicon glyphicon-exclamation-sign"></span>';
			$friendlyErrorMessage .= ' There seems to be a problem with the page.';
			$friendlyErrorMessage .= ' An error message has been sent to the support team.';
			$friendlyErrorMessage .= ' In case the error persists please contact the support!';
			$friendlyErrorMessage .= '</div>';
			echo $friendlyErrorMessage;
		}
	}
}
