<?php

class Engine
{
    protected $appPath;
    protected $templatesPath;
    public $viewPath;

    public function __construct($appPath = APP, $templatesPath = TEMPLATES)
    {
        $this->appPath = rtrim($appPath, '/') . '/';
        $this->templatesPath = rtrim($templatesPath, '/') . '/';

        $this->viewPath = $this->determineViewPath($this->_urlParams());
    }

    protected function determineViewPath($urlParams): string
    {
        $path1 = $this->appPath . "app/views" . $urlParams . '.php';
        $path2 = $this->appPath . "app/views" . $urlParams . '/index.php';
        $path3 = $this->appPath . "app/views" . $urlParams . '.md';
        $path4 = $this->appPath . "app/views" . $urlParams . '/index.md';
        $path404 = $this->templatesPath . 'error404.php';

        if (file_exists($path1)) {
            return $path1;
        } elseif (file_exists($path2)) {
            return $path2;
        } elseif (file_exists($path3)) {
            return $path3;
        } elseif (file_exists($path4)) {
            return $path4;
        } else {
            return $path404;
        }
    }

    private function _urlParams(): string
    {
        $serverURL = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
        // Normalize URL by removing trailing slashes
        return rtrim($serverURL, "/");
    }
}
