<?php

class Framex extends Engine
{
    private $viewsPath;

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

    public function renderTemplate(string $file, array $data = []): void
    {
        $filePath = $this->appPath . "templates/" . $file . ".php";
        if (file_exists($filePath)) {
            if (!empty($data)) {
                extract($data);
            }
            require_once $filePath;
        } else {
            // Handle the error appropriately, e.g., log it or throw an exception
            echo "Template file not found: " . htmlspecialchars($filePath);
        }
    }

    public function init(): void
    {
        $file = $this->viewPath;
        $data = [];

        if (!file_exists($file)) {
            $file = $this->viewsPath . 'templates/404.php';
        }

        if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) === 'md') {
            $markdown = file_get_contents($file);
            $parsedown = new Parsedown();
            $data['view'] = '<article class="prose prose-shell">' . $parsedown->text($markdown) . '</article>';
        } else {
            ob_start();
            require_once $file;
            $data['view'] = ob_get_clean();
        }

        $template = $data['template'] ?? 'main';
        $this->renderTemplate($template, $data);
    }
}
