<?php

// Janky error handler page thingy that looks cool
class ErrorHandler 
{
    public array $errors; // Holds error messages

    public function __construct()
    {
        ob_Start(); // If an error were to occur, we clear the outputted data so we only show the error page instead of both.
        set_error_handler([$this, 'error']);
        set_exception_handler([$this, 'exception']);
        $this->errors = [];
    }

    public function error($errno, $errstr, $errfile, $errline): void
    {
        $errstr = htmlspecialchars($errstr);
        $this->errors[] = "<b>Error[$errno]:</b> $errstr in <b>$errfile</b> at line <b>$errline</b>";
        die();
    }

    public function exception($exception): void
    {
        $this->errors[] = "<b>Uncaught Exception:</b> " . $exception;
    }

    public function __destruct()
    {
        if (!$this->errors) {
           return; 
        }
        ob_end_clean(); // Remove current output to be replaced by error page
        http_response_code(500);
        header_remove();

        echo '<style>body { margin: 1rem; background: tomato; font-family: sans; } #error { padding: 1rem; background: white; margin-bottom: 1rem; border: .1rem solid black; } </style>';
        echo '<h1>Error!!1 (✖﹏✖)</h1>';
        echo '<p>Oisann! Dette var ikke ment å skje. Dersom det vedvarer, vennligst kontakt nettadministratoren.</p>';

        foreach ($this->errors as $error) {
           echo "<div id=\"error\">$error</div>";
        }
    }
}