<?php 

namespace NeurogenesisTheme\Traits;

trait HasTemplate {
    //main template folder, used to separate admin and frontend in different folders
    public static $folder = 'views';

    // the main layout
    public static $__layout = '_layout';    

    public static $__sections = [];

    /**
     * template - load a HTML template
     *
     * @param  mixed $template
     * @param  mixed $args
     * @param  bool  $echo When true, outputs the template and returns null.
     * @return string|null Buffered HTML when $echo is false; null when echoed.
     */
    public static function template($template, $args = [], $echo = true): ?string
    {
        // echo neurogenesis_theme_plugin_path( self::$folder . '/' . $template . '.php');
        extract($args);
        ob_start();
        require NEUROGENESIS_THEME_THEME_PATH . '/'.self::$folder.'/' . $template . '.php';
        $str = ob_get_clean();

        if (
            !$echo
        ) {
            return $str;
        }

        echo $str;

        return null;
    }

    public static function show404($message = null)
    {
        self::template('_not_found', ['message' => $message]);
    }

    public static function make_section($template, $args = [])
    {
        self::$__sections[$template] = self::template($template, $args, false);
    }

    public static function section($template)
    {
        if(isset(self::$__sections[$template])) {
            echo self::$__sections[$template];
        }
    }

    public static function layout($layout = false, $args = [], $echo = true): ?string
    {
        if($layout) {            
            return self::template($layout, $args, $echo);
        }

        return self::template(self::$__layout, $args, $echo);
    }
}