<?php

namespace Hura8;

use Liquid\Liquid;
use Liquid\Template as LiquidTemplate;

class AppAdmin
{

    protected $tpl_path = "template";

    protected $current_route_info = [
        "module" => 'home',
        "view" => 'home',
        "url" => '/admin/product'
    ];

    protected $data = [];


    public function __construct()
    {

    }

    // start the app
    public function start() {
        $this->getRouter();
        $this->getData();
        echo $this->renderModule();
    }


    protected function getRouter() {
        /*$route = [
            "module" => (isset($_REQUEST['module'])) ? $_REQUEST['module'] : 'home',
            "view" => (isset($_REQUEST['view'])) ? $_REQUEST['view'] : 'home',
        ];*/

        $objRouter = new Router();
        $this->current_route_info = $objRouter->getRouting();
    }


    protected function getData() {
        $module_file = $this->getModuleFile();
                
        if(file_exists($module_file)) {
            // print_r($this->current_route_info);
           // die('Page '. $module_file .' not found!');
            $data = include_once $module_file;
        }else{
            $data = ['file data '. $module_file .' not found!'];
        }

        $global_data = [
            "module" => $this->current_route_info['module'],
            "view"  => $this->current_route_info['view'],
            "url"   => $this->current_route_info['url'],
            "main_menu" => include_once ROOT_DIR."/data/menu.php",
        ];

        $this->data = array(
            'global' => $global_data,
            // module-specific data, just print {{ page }} to see all available data for the current page!!!
            'page' => (is_array($data)) ? $data : [],
        );
    }


    protected function getModuleFile() {
        return join(DIRECTORY_SEPARATOR, [
            "data",
            $this->current_route_info["module"],
            str_replace("-", "_", $this->current_route_info["view"]).".php"
        ]) ;
    }


    protected function renderModule() {

        if(!$this->current_route_info['module'] || !$this->current_route_info['view'])  {
            die("Module not exist");
        }

        $template_file_path     = $this->tpl_path ."/". $this->current_route_info['module'];
        $template_file_name     = str_replace("-", '_', $this->current_route_info['view']).".html";
        $template_file_full_path = $template_file_path."/".$template_file_name;

        //check exist
        if(!@file_exists( $template_file_full_path)) {
            // attempt to auto create first
            // todo: this MUST BE TURNED OFF IN PRODUCTION, else many files will be created unintentionally
            $module_file = $this->getModuleFile();
            // only create if module file exist
            if(file_exists($module_file) && !$this->autoCreateTplFile( $template_file_path, $template_file_name )) {
                die("Please manually create template file at: ". $template_file_full_path);
            }
        }

        $theme_file_path  = $this->tpl_path ."/theme.html";
        if( ! @file_exists( $theme_file_path)) {
            die("Theme not exist (please create): " . $theme_file_path);
        }

        $theme_content  = @file_get_contents( $theme_file_path );
        $module_content = @file_get_contents( $template_file_full_path );

        $page_content_to_parse = preg_replace([
            "/{{(\s+)?page_content(\s+)?}}/"
        ], [
            $module_content,
        ] , $theme_content );


        return $this->parse(
            $page_content_to_parse,
            $template_file_path
        );
    }


    protected function autoCreateTplFile($file_path, $file_name) : bool {
        // create dir if not exist
        if(!file_exists($file_path)) {
            if(!mkdir($file_path, 0755, true)) {
                return false;
            }

            if(!file_exists($file_path)) {
                return false;
            }
        }

        //create file
        $file_full_path = $file_path . "/". $file_name;
        @file_put_contents($file_full_path, $file_full_path);

        return file_exists($file_full_path);
    }


    /*
         * 2 ways to render a html template
         * 1. Use $html_to_parse, which requires no dependencies
         *  Example:
         *  Template::parse(null, 'Age =  {{age}}', ['age' => 21], '');
         *
         * 2. Use $template_file_path, which requires dependency $path
         *  Template::parse(Template::$setting_template_path, null, ['age' => 21], 'email/test');
     * */
    protected function parse($html_to_parse = null, $template_file_path = '') {

        if(!$html_to_parse && !$template_file_path) {
            return 'Nothing to parse';
        }

        //output to html
        Liquid::set('INCLUDE_SUFFIX', 'html');
        Liquid::set('INCLUDE_PREFIX', '');
        //Liquid::set('INCLUDE_ALLOW_EXT', true);
        Liquid::set('ESCAPE_BY_DEFAULT', false);

        $enable_cache = false; // default = true, turn this on-off to disable cache while working on local mode
        //$enable_cache = true;

        //catch exception and print friendly notice
        try {

            $objLiquidTemplate = new LiquidTemplate( $this->tpl_path );
            $objLiquidTemplate->registerFilter( AdminTemplateFilter::class );
            if($enable_cache) {
                /*$objLiquidTemplate->setCache(new File([
                    'cache_dir' => self::$cache_dir
                ]));*/
            }

            if($html_to_parse) {
                $objLiquidTemplate->parse($html_to_parse);
            }elseif ($template_file_path) {
                $objLiquidTemplate->parseFile($template_file_path);
            }

            return $objLiquidTemplate->render($this->data);

        } catch (\Exception $e) {
            $result = [];
            do {
                //printf("%s:%d %s (%d) [%s]\n", $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
                //echo $e->getTraceAsString();
                //$code = $e->getTrace()[0]['args'][0];
                //if(is_array($code)) $code = serialize($code);
                $result[] = sprintf(
                    "
Lỗi code trong file template html: <br />
- Chi tiết lỗi: %s<br />
- File template: %s<br />
- Hướng dẫn xử lý: Tách từng phần html để kiểm tra và nhấn F5 mỗi lần. Nếu không xuất hiện thông báo này nghĩa là phần đó không tạo lỗi
",
                    $e->getMessage(),
                    substr($template_file_path, strrpos($template_file_path, DIRECTORY_SEPARATOR) + 1 ),
                    //static::$cache_dir
                );

            } while($e = $e->getPrevious());

            return join(" - ", $result);
        }
    }

}
