<?php

/**
 * Set your ini settings here
 */
ini_set('error_reporting', E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', true);
ini_set('date.timezone', 'America/Edmonton');
if (s3MVC_GetCurrentAppEnvironment() !== S3MVC_APP_ENV_DEV) {
    ini_set('error_reporting', E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED & ~E_WARNING);
}
    /**
     * 
     * Handler for Http 500 Server Errors. Returns a response object containing the server error page.
     * 
     * @param \Exception $exception exception that was raised (it contains info about the server error) 
     * @param ServerRequestInterface $req a request object
     * @param ResponseInterface $res a response object
     * 
     * @return ResponseInterface a response object with an http 500 status code, Content-Type 
     *                           of `text/html` and appropriate body (eg the html showing the 
     *                           500 message)
     */
    public function generateServerErrorResponse(\Exception $exception, ServerRequestInterface $req = null, ResponseInterface $res = null)
    {
        is_null($req) && ($req = $this->request);
        is_null($res) && ($res = $this->response);
        $new_response_body = new \Slim\Http\Body(fopen('php://temp', 'r+'));
        $new_response = $res->withBody($new_response_body);
        //generate default 500 page content using the layout and write it into the response body
        $error_str = '';
        $_500_page_content = '';
        $layout_content = 'Something went wrong!';
        $exception_info = $exception->getMessage() . ' on line ' . $exception->getLine() . ' in `' . $exception->getFile() . '`' . '<br><br>' . $exception->getTraceAsString();
        if (s3MVC_GetCurrentAppEnvironment() !== S3MVC_APP_ENV_PRODUCTION) {
            //Append exception message if we are not in production.
            $layout_content .= '<br>' . nl2br($exception_info);
        }
        try {
            //log the server error message
            $this->container->has('logger') && $this->container->get('logger') instanceof \Psr\Log\LoggerInterface && $this->container->get('logger')->error(str_replace('<br>', PHP_EOL, "HTTP 500: {$exception_info}"));
        } catch (\Exception $e) {
            if (s3MVC_GetCurrentAppEnvironment() !== S3MVC_APP_ENV_PRODUCTION) {
                // for non production environments, capture the exception string and display
                // it in the browser
                $error_str .= '<br><br>Error while logging 500 Server Error: ' . $e->getTraceAsString();
            }
        }
        try {
            $layout_data = [];
            $layout_data['content'] = $layout_content . '<br><br>' . $error_str;
            $_500_page_content .= $this->renderLayout($this->layout_template_file_name, $layout_data);
        } catch (\Exception $e) {
            // could not inject the error page info into the layout
            $error_str .= "<br><br>Error while rendering layout `{$this->layout_template_file_name}` 500 Server Error: " . $e->getTraceAsString();
            // inject error page info into a bare bones layout below
            $_500_page_content = <<<EOT
<!doctype html>
<html lang="en">
    <head>
      <meta charset="utf-8">
      <title>Server Error</title>
    </head>

    <body>
        <div>
            <p>{$layout_content}</p>
            <br><br>
            <p>{$error_str}</p>
        </div>
    </body>
</html>
EOT;
        }
        $new_response->getBody()->write($_500_page_content);
        return $new_response->withStatus(500)->withHeader('Content-Type', 'text/html');
    }
});
//Object for rendering view files
$container['new_view_renderer'] = $container->factory(function () {
    //return a new instance on each access to $container['new_view_renderer']
    $ds = DIRECTORY_SEPARATOR;
    $path_2_view_files = S3MVC_APP_ROOT_PATH . $ds . 'src' . $ds . 'views' . "{$ds}base";
    $view_renderer = new \Rotexsoft\FileRenderer\Renderer('', [], [$path_2_view_files]);
    return $view_renderer;
});
////////////////////////////////////////////////////////////////////////////////
// End configuration specific to all environments
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Start Vespula.Auth Authentication setup
////////////////////////////////////////////////////////////////////////////
if (s3MVC_GetCurrentAppEnvironment() === S3MVC_APP_ENV_PRODUCTION) {
    //configuration specific to the production environment
    ////////////////////////////////////////////////////////////////////////////
    // Start Vespula.Auth LDAP Authentication setup
    ////////////////////////////////////////////////////////////////////////////
    $container['vespula_auth'] = function () {
        //Optionally pass a maximum idle time and a time until the session
        //expires (in seconds)
        $expire = 3600;
        $max_idle = 1200;
        $session = new \Vespula\Auth\Session\Session($max_idle, $expire);
        /*
         * `basedn`: The base dn to search through
         * `binddn`: The dn used to bind to
         * `bindpw`: A password used to bind to the server using the binddn
         * `filter`: A filter used to search for the user. Eg. samaccountname=%s