<?php

class RenderClass
{
    private string $html;
    private array $argument;

    public function render(string $file, array $arguments)
    {
        $path = G5_PATH.$file;

        if(!file_exists($path)) {
            throw new Exception("$file Not Found!");
        }

        return $this
            ->validateArguments($arguments)
            ->parseNormalVar($path)
            ->parseIfClause()
            ->parseForClause()
            ->parseForeachClause()
            ->execute();
    }

    protected function validateArguments(array $arguments, bool $isRecursive = false)
    {
        foreach ($arguments as $key => $argument) {
            switch (gettype($argument)) {
                case "boolean" : $arguments[$key] = $argument ? "true" : "false"; break;
                case "string" : $arguments[$key] = htmlspecialchars($argument); break;
                case "array" : $arguments[$key] = $this->validateArguments($argument, true); break;
            }
        }

        if($isRecursive) {
            return $arguments;
        }

        $this->argument = $arguments;
        return $this;
    }

    protected function parseNormalVar(string $path)
    {
        extract($this->argument);

        ob_start();
        include $path;
        $this->html = ob_get_clean();
        return $this;
    }

    protected function parseIfClause()
    {
        $patterns = [
            '/@if\((.*?)\)/' => '<?php if ($1) { ?>',
            '/@elseif\((.*?)\)/' => '<?php } elseif ($1) { ?>',
            '/@else/' => '<?php } else { ?>',
            '/@endif/' => '<?php } ?>',
            '/\{\{\s*(\$\w+)\s*\}\}/' => '<?php echo htmlentities($1); ?>'
        ];

        foreach ($patterns as $pattern => $replacement) {
            $this->html = preg_replace($pattern, $replacement, $this->html);
        }

        return $this;
    }

    protected function parseForClause()
    {
        $patterns = [
            '/@for\((.*?)\)/' => '<?php for ($1) { ?>',
            '/@endfor/' => '<?php } ?>',
            '/\{\{\s*(\$\w+)\s*\}\}/' => '<?php echo htmlentities($1); ?>'
        ];

        foreach ($patterns as $pattern => $replacement) {
            $this->html = preg_replace($pattern, $replacement, $this->html);
        }

        return $this;
    }

    protected function parseForeachClause()
    {
        $patterns = [
            '/@foreach\((.*?)\)/' => '<?php foreach ($1) { ?>',
            '/@endforeach/' => '<?php } ?>',
            '/\{\{\s*(\$\w+)\s*\}\}/' => '<?php echo htmlentities($1); ?>'
        ];

        foreach ($patterns as $pattern => $replacement) {
            $this->html = preg_replace($pattern, $replacement, $this->html);
        }

        return $this;
    }

    protected function execute()
    {
        ob_start();
        eval("?> {$this->html} <?php");
        return ob_get_clean();
    }
}