<?php
namespace Core;

use App\Config;

class Error
{
	public static function errorHandler($level, $message, $file, $line)
	{
		if(error_reporting() !== 0)
		{
			throw new \ErrorException($message, 0, $level, $file, $line);
		}
	}

	public static function exceptionHandler($e)
	{
		/* Trigger error */
		if (Config::LOG_ERRORS) {
            $code = $e->getCode();
            $code = ($code == 404 || $code == 500 || $code == 498) ? $code : 500;
            http_response_code($code);

            $file = $e->getFile();
            $line = $e->getLine();

			$logfile = dirname(__DIR__) . '/.logs/' . date('Y-m-d') . '.log';
			ini_set('error_log', $logfile);

            $date = new \DateTime();
            $date->setTimeZone(new \DateTimeZone('Asia/Jakarta'));
            $now = $date->format("d/M/Y:H:i:s O");

            $message = '';
            $message .= self::getIpAddress();
            $message .= ' ';
            $message .= $_SERVER['REMOTE_PORT'];
            $message .= ' ';
            $message .= $_SERVER['SERVER_PORT'];
            $message .= ' ';
            $message .= (Session::exists('userid')) ? Session::get('userid') : 'anonymous';
            $message .= ' ';
            $message .= "[" . $now . "]";
            $message .= ' "';
            $message .= $_SERVER['REQUEST_METHOD'];
            $message .= ' ';
            $message .= $_SERVER['REQUEST_URI'];
            $message .= ' ';
            $message .= $_SERVER['SERVER_PROTOCOL'];
            $message .= '" ';
            $message .= $e->getCode();
            $message .= ' ';
            $message .= $file;
            $message .= ' ';
            $message .= $line;
            $message .= "\n";

			error_log($message, 3, $logfile);
			View::render("Errors/$code.html", [
				'code' => $e->getCode()
				]);
		} else {
			$title = "Fatal Error";
			$class = "Caught exception: " . get_class($e) . "(" . $e->getCode() . ")";
			$message = "Message: " . $e->getMessage();
			$trace_title = "Stack trace:";
			$trace_content = $e->getTraceAsString();
			$file = "Thrown in " . $e->getFile() . "(" . $e->getLine() . ")";

			View::render("Errors/errorHandler.html", [
				'title' => $title,
				'class' => $class,
				'message' => $message,
				'trace_title' => $trace_title,
				'trace_content' => $trace_content,
				'file' => $file
				]);
		}
	}

    public static function getIpAddress() {
        foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'] as $key){
            if (array_key_exists($key, $_SERVER) === true){
                foreach (explode(',', $_SERVER[$key]) as $ip){
                    return $ip;
                }
            }
        }
    }
}
