<?php

namespace Snaju\Inception\Exception\Handlers;

use Snaju\Inception\InceptionCore;
use Snaju\Inception\Route\Loaders\Twig\Template;
use Snaju\Inception\Route\Loaders\Twig\TemplateManager;

class HtmlPageHandler extends AbstractErrorHandler
{
    
    public int $priority = 200;

    public function shouldRender(): bool
    {
        return
            str_contains($this->request->getHeaderLine('Accept'), 'text/html') ||
            str_contains($this->request->getHeaderLine('Accept'), 'xhtml') ||
            str_contains($this->request->getHeaderLine('Accept'), '*/*');
    }

    public function handle($exception)
    {
        $this->setExceptionName($exception);
        $responseCode = $exception->getCode();

        $templateData = [
            'request_method' => $this->request->getMethod(),
            'request_path' => $this->request->getUri()->getPath(),
            'exception_name' => $this->getExceptionName(),
            'exception_message' => $exception->getMessage(),
            'file_path' => $exception->getFile(),
            'file_line' => $exception->getLine(),
            'stack_trace' => $exception->getTraceAsString(),
        ];

        if (! $this->debugMode) {
            $errorTemplateDir = config('app.errorTemplateDirectory');
            $userDefinedTemplate = $errorTemplateDir . '/' . $responseCode;

            // If a template with the appropriate code matches, use it
            if (TemplateManager::exist($userDefinedTemplate)) {
                render($userDefinedTemplate, $templateData, $responseCode);
            }
                else if (TemplateManager::exist($errorTemplateDir . '/error')) {
                    render($errorTemplateDir . '/error', $templateData, $responseCode);
                }
                else {
                    http_response_code($responseCode);
                    TemplateManager::renderDefaultTemplate('/template-default', $templateData);
                }
        }
            else {
                http_response_code($responseCode === 0 ? 500 : $responseCode);
                TemplateManager::renderDefaultTemplate('/template-debug', $templateData);
            }
    }

}