<?php

/**
 * Tentative de créer un système de template.
 */
class View
{
    /**
     * S'occupe d'ouvrir la template.
     * @param string $viewName
     * @param array $args
     * @return string
     */
    public static function load(string $viewName, array $args = []): string
    {
        $viewPathParts = explode(".", $viewName);
        $viewPath = "";
        foreach ($viewPathParts as $pathPart){
            $viewPath .= "/" . $pathPart;
        }
        $viewPath = "resources/views" . $viewPath . ".php";
        if(file_exists($viewPath)){
            echo self::render(self::parse($viewPath), $args);
            return "";
        }else{
            return "La vue " . $viewName . " est introuvable.";
        }
    }

    /**
     * S'occuper de remplir la template
     * @param string $viewPath
     * @param array $args
     * @return string
     */
    public static function parse(string $viewPath): string
    {
        $viewContent = file_get_contents($viewPath);
        // On va rechercher toutes les concaténations {{ $var }}
        $viewContent = preg_replace("/\{\{(.*?)\}\}/", "<?=$1?>", $viewContent);


        // On va rechercher tous les @foreach($var1 as $var2) @endforeach
        $viewContent = preg_replace("/@foreach[ ]{0,1}\((.*?) as (.*?)\)/",
            "<?php foreach($1 as $2) { ?>", $viewContent);
        $viewContent = preg_replace("/@endforeach/", "<?php } ?>", $viewContent);

        return $viewContent;
    }

    public static function render(string $viewCode, array $args = []): string
    {
        extract($args);
        // On ouvre le buffer pour enregistrer le résultat de l'echo.
        ob_start();
        eval("?>" . $viewCode . "<?php");
        return ob_get_clean();
    }
}