<?php
/**
 * Created by Glee Ltd.
 * User: Hieu
 * Date: 3/6/18
 * Time: 6:55 PM
 * Description:
 */

namespace Hura8\System;


class Plugin
{

    public static function getPagePlugin($module, $page) {
        $allowed_plugins = self::getPlugins();

        if($module == 'global') {
            $page_config = $allowed_plugins['global'];
        }else{
            $page_config = (isset($allowed_plugins[$module]) && isset($allowed_plugins[$module][$page])) ? $allowed_plugins[$module][$page] : [];
        }

        if(!sizeof($page_config)) return [];

        $plugin_mapping_file = ROOT_DIR . "/config/system/plugin_mapping.php";

        if(file_exists($plugin_mapping_file)) {

            $plugin_mapping = include ($plugin_mapping_file);
            $page_plugin_data = [];

            foreach ($page_config as $key => $is_enabled) {
                if($is_enabled && isset($plugin_mapping[$key]) && $plugin_mapping[$key]) {
                    $file = "display_plugin/". $plugin_mapping[$key];
                    if(file_exists($file)) {
                        $page_plugin_data[$key] = include $file;
                    }
                }
            }

            return $page_plugin_data;

        } else {

            die($plugin_mapping_file." not exist");

        }
    }


    protected static function getPlugins() {

        $config_file = ROOT_DIR . "/config/client/config_plugin.php";

        if(file_exists($config_file)) {

            $config_plugins =  include $config_file;
            //global plugin should over-ride local one
            $allowed_plugins = $config_plugins;

            foreach ($config_plugins as $module => $content) {
                if($module == "global") continue; //skip

                foreach ($content as $option => $option_pages) {
                    foreach ($option_pages as $page => $precate) {
                        if($precate && array_key_exists($page, $allowed_plugins['global']) && $allowed_plugins['global'][$page] ) {
                            $allowed_plugins[$module][$option][$page] = false;
                        }
                    }
                }
            }

            return $allowed_plugins;

        } else {

            die($config_file." not exist");

        }
    }

}
