<?php

namespace Snaju\Inception\Exception\Handlers;

class XmlResponseHandler extends AbstractErrorHandler
{
    
    public int $priority = 300;
    
    public function shouldRender(): bool
    {

        return
            str_contains($this->request->getHeaderLine('Accept'), 'text/xml') ||
            str_contains($this->request->getHeaderLine('Accept'), 'xhtml') ||
            str_contains($this->request->getHeaderLine('Accept'), '*/*');
    }
    
    public function handle(\Exception $exception)
    {
        // TODO: fix how responses are used to enable sending responses with default response handler for exceptions. Right now, everything is based on middleware and exceptions don't follow the same flow... Responses here are send manually for now.
        // TODO: fix how responses are used to enable sending responses with default response handler for exceptions. Right now, everything is based on middleware and exceptions don't follow the same flow... Responses here are send manually for now.
        $this->setExceptionName($exception);
        $responseCode = $exception->getCode() === 0 ? 500 : $exception->getCode();
        $response = '<?xml version="1.0" encoding="utf-8"?>';
        $response .= '<response><error>';
        $response .= "<type>Server Error</type>";

        if (! $this->debugMode) {
            $response .= "<name>{$this->getExceptionName()}</name>";
            $response .= "<message>{$exception->getMessage()}</message>";
        }
            else {
                $response .= "<request_method>{$this->request->getMethod()}</request_method>";
                $response .= "<request_path>{$this->request->getUri()->getPath()}</request_path>";
                $response .= "<exception_name>{$this->getExceptionName()}</exception_name>";
                $response .= "<message>{$exception->getMessage()}</message>";
                $response .= "<file_path>{$exception->getFile()}</file_path>";
                $response .= "<file_line>{$exception->getLine()}</file_line>";
                $response .= "<stack_trace>{$exception->getTraceAsString()}</stack_trace>";
            }

        $response .= '</error></response>';

        http_response_code($responseCode);
        header("Last-Modified: " . gmdate('D,d M YH:i:s') . " GMT");
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: no-cache');
        header('Content-Type: text/xml; charset=utf-8');
        header('Content-Description: PHP Generated Data');
        echo $response;
    }

}