<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Created by DT Team.
 * AppName: NearbyStores
 */

class Modules_manager extends MAIN_Controller {

    public function __construct(){
        parent::__construct();
        /////// register module ///////
        $this->init("modules_manager");
    }

    public function onLoad()
    {
        parent::onLoad(); // TODO: Change the autogenerated stub

        define('MANAGE_MODULES','manage_modules');
        define('MODULES_MANAGER_ACTIONS_ON_ENABLE','onEnable');
        define('MODULES_MANAGER_ACTIONS_ON_DISABLE','onDisable');
        define('MODULES_MANAGER_ACTIONS_ON_INSTALL','onInstall');
        define('MODULES_MANAGER_ACTIONS_ON_UNINSTALL','onUninstall');
        define('MODULES_MANAGER_ACTIONS_ON_UPGRADE','onUpgrade');

        $this->load->model('modules_manager/modules_manager_model');
        $this->load->helper('modules_manager');

        $this->modules_manager_model->updateFields();


    }


    public function onCommitted($isEnabled)
    {
        parent::onCommitted($isEnabled); // TODO: Change the autogenerated stub


        AdminTemplateManager::registerMenuSetting(
            'modules_manager',
            "modules_manager/menu_setting",
            13
        );


        //new upgrade detected
        if(GroupAccess::isGranted('modules_manager') && $this->check_need_upgrade()
            && !ModulesChecker::isEnabled("demo")){

            NotesManager::addNew(
                TM_Note::newInstance("setting",
                    $this->upadateAlert()
                )
            );
        }

    }

    private function check_need_upgrade(){

        $modules = ModuleManager::fetch();

        foreach ($modules as $module){
            if($module["_installed"] == 1 && $module["version_code"] < $module["detail"]['version_code']){
                return TRUE;
            }
        }

        return FALSE;
    }

    private function upadateAlert(){
        return '<div class="callout callout-warning">
            <h4><i class="fa fa-check" aria-hidden="true"></i>&nbsp;Update!</h4>
            <h5>Some modules need to be upgraded</h5>
            <a href="'.admin_url("modules_manager/manage").'">Upgrade now</a>
        </div>';
    }


    public function onEnable()
    {
        GroupAccess::registerActions("modules_manager",array(
            MANAGE_MODULES
        ));
    }

    public function onInstall()
    {
        GroupAccess::registerActions("modules_manager",array(
            MANAGE_MODULES
        ));

        return TRUE;
    }

    public function onUpgrade()
    {
        GroupAccess::registerActions("modules_manager",array(
            MANAGE_MODULES
        ));

        $this->modules_manager_model->updateFields();


        return TRUE;
    }


    public function error404(){



    }






}

/* End of file CmsDB.php */