<?php

require_once("Config.php");

class ErrorHandler {
	public static function checkForFatalCrash() {
		$error = error_get_last();
		if ($error) {
			if ($error['type'] == E_ERROR) {
				ErrorHandler::handleException(new ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line']));
			}
		}
	}

	public static function printErrorEntry($type, $message, $file, $line) {
?>
<?php
	}

	public static function getFileLines($file, $start, $end) {
		$f = file_get_contents($file);
		$l = explode("\n", $f);
		if ($start < 0) $start = 0;
		if ($end >= count($l)) $end = count($l) -1;

		$out = [];
		for ($i = $start; $i <= $end; $i++) {
			$out[] = $l[$i];
		}
		return $out;
	}

	public static function handleException($e) {
		header("Content-Type: text/html");
		header("X-Error-Message: " . $e->getMessage());
		header("X-Error-Line: " . $e->getLine());
		header("X-Error-File: " . $e->getFile());
		header("X-Error-Code: " . $e->getCode());
		$trace = $e->getTrace();
		array_shift($trace);

		$i = 0;
		foreach ($trace as $t) {
			$i++;
			header("X-Error-Trace-" . $i . ": " . $t['file'] . "(" . $t['line'] . ")");
		}

		print("<div style='background-color: #ffaaaa;'>");
		print("<h3>" . $e->getMessage() . "</h3>");
		print("At Line " . $e->getLine() . " of " . $e->getFile() . "<br>");

		$line = $e->getLine() - 1;

		$pre = ErrorHandler::getFileLines($e->getFile(), $line - 5, $line - 1);
		$line = ErrorHandler::getFileLines($e->getFile(), $line, $line);
		$post = ErrorHandler::getFileLines($e->getFile(), $line + 1, $line + 5);
		
		print("<pre>");

		foreach ($pre as $l) {
			print($l . "\n");
		}
		print($line[0] . " <---\n");
		foreach ($post as $l) {
			print($l . "\n");
		}

		print("</pre>");
		print("</div>");

		$trace = $e->getTrace();
		array_shift($trace);

		foreach ($trace as $t) {
			if (array_key_exists("class", $t) && array_key_exists("function", $t)) {
				print("<div>");
				print("<h5>From " . $t['class'] . "::" . $t['function'] . "</h5>");
				print("At Line " . $t['line'] . " of " . $t['file'] . "<br>");
				print("</div>");
			}
			
		}

	}

	public static function handleError($num, $str, $file, $line, $context = null) {
		ErrorHandler::handleException(new ErrorException($str, 0, $num, $file, $line));
	}

	public static function hook() {

		if (Config::get("DEBUG")) {
			ini_set("display_errors", "on");
			error_reporting(E_ALL);
		} else {
			ini_set("display_errors", "off");
		}
//		register_shutdown_function("ErrorHandler::checkForFatalCrash");
//		set_error_handler("ErrorHandler::handleError");
//		set_exception_handler("ErrorHandler::handleException");
	}

}
