<?php
namespace App\Controllers;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\App;
use Slim\Psr7\Stream;
use Slim\Views\Twig;

class BaseController{
    public $request,$response,$args,$app;
    public string $layoutPath;
    public array $defaultLayouts = ['error.xml'];
    public bool $enableAuth = false;
    public function __construct(Request $request,Response $response,$args,App $app,bool $enableAuth = false){
        $this->request = $request;
        $this->response = $response;
        $this->args = $args;
        $this->app = $app;
        $this->enableAuth = $enableAuth;
    }

    public function checkAuth(Request $request){
        if ($request->hasHeader('Authorization')) {
            if ($request->getHeaderLine('Authorization') == "Basic ".base64_encode(USERNAME . ':' . PASSWORD)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     * @throws \Twig\Error\LoaderError
     */
    public function renderLayout($layout, $data = []): Response{
        if(!in_array($layout,$this->defaultLayouts)){
            $layout = $this->layoutPath.DIRECTORY_SEPARATOR.$layout;
        }

        return Twig::fromRequest($this->request)->render($this->response,$layout,$data)->withAddedHeader('Content-type','application/xml');
    }

    /**
     * @throws \Twig\Error\SyntaxError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\LoaderError
     */
    public function renderLayoutRow($layout, $data = []): string{
        if(!in_array($layout,$this->defaultLayouts)){
            $layout = $this->layoutPath.DIRECTORY_SEPARATOR.$layout;
        }

        return Twig::fromRequest($this->request)->fetch($layout,$data);
    }

    public function renderJson($data) : Response{
        $this->response->getBody()->write(json_encode($data));
        return $this->response->withAddedHeader('Content-Type','application/json');
    }

    public function getUnitIdByListId($listID){
        return $listID;
        $id = $this->listingModel->getVBUnitIdByListId($listID);
        if(!empty($id)){
            return $id[0]['id'];
        }
        else{
            return false;
        }
    }

}