<?php

/*
 * awframework from aw.inc present aw controller
 * it will help you develop easy and fast with secure tools
 * you can edit and add what you feel right
 * don't change in strucure of file
 */

require_once("imp/_imp.php");

class Controllers {

    //public vars
    public $smarty;
    public $hosturl;
    public $controllname;
    public $shcontrollname;
    public $active;

    // it will run in everytime with
    // default requried
    public function __construct() {
        require_once("../public/aw_config.php");
        require_once("imp/_autho.php"); //general functions
        $this->smarty = $smarty;
        $this->hosturl = $hosturl;

        //here name of controll to known
        $this->controllname = '_menu';
        $this->shcontrollname = 'Menu control';
        $this->smarty->assign('controllname', $this->controllname);
        $this->smarty->assign('shcontrollname', $this->shcontrollname);

        //breadcrumbs
        require_once("../../_library/plugins/Breadcrumbs/Breadcrumbs.php");
        $acty = filter_input(INPUT_GET, 'ac');
        $bc = new breadcrumbs($hosturl, $this->controllname, $this->shcontrollname, $acty);
        $bc->crumbs();
        $breadcrumbs = $bc->breadcrumbs;
        $smarty->assign('breadcrumbs', $breadcrumbs);

        require_once("../../_library/plugins/classupload/uploadfunctions.php");
        # here show the active page in menu
        // array called active[] with level of active element
        $active[0] = 'managment'; //controller name or tab name
        $active[1] = 'menu'; //controller name
        // do name  // switch($do)
        switch ($acty) {
            case '':$active[2] = 'menuadd';
                break;
            case 'show':$active[2] = 'menushow';
                break;
            default :$active[2] = 'menushow';
                break;
        }
        $this->active = $active;


        //here will call all php pages
        require_once("_header.php");
        require_once("_sidebar.php");
        require_once("_leftsidebar.php");
        require_once("_footer.php");
    }

    //here the frist page and
    //the frist action in this class
    public function index() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        //load all parents here
        $menus = R::findAll('awmenu');
        $this->smarty->assign('menus', $menus);

        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('_menu/add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function addit() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        //vars here
        $label = filter_input(INPUT_POST, 'label');
        $link = filter_input(INPUT_POST, 'link');
        $parent = filter_input(INPUT_POST, 'parent');
        $icon = filter_input(INPUT_POST, 'menuicon');
        $activename = filter_input(INPUT_POST, 'activename');
        $form = filter_input(INPUT_POST, 'form');
        $display = filter_input(INPUT_POST, 'display');
        if ($display == "image") {
            $img = uploadupdate("menuImage", '', False, 0, 0, 'menu');
        }

        $maxOrder = R::getrow('select max(sort) from awmenu where parent = ?', [$parent]);

        //here the add
        $menu = R::dispense('awmenu');
        $menu->label = $label;
        $menu->link = $link;
        $menu->parent = $parent;
        $menu->sort = $maxOrder['max(sort)'] + 1;
        $menu->icon = $icon;
        $menu->activeName = $activename;
        $menu->form = $form;
        $menu->display = $display;
        if ($display == "image") {
            $menu->image = $img;
        }


        try {
            $id = R::store($menu);
            header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
        }
    }

    public function show() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);


        //here will load the menu show
        $dismenu = $this->displaymenush(0, $this->hosturl);

        $this->smarty->assign('dismenu', $dismenu);

        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('_menu/show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    //just use it to draw menu
    public function displaymenush($parent, $hosturl) {

        $menuhtml = "";
        //get the all about this level in menu
        //dd-handle dd3-handle
        $result = R::getAll('SELECT a.*, Deriv1.count FROM `awmenu` a  LEFT OUTER JOIN (SELECT parent, COUNT(*) AS Count FROM `awmenu` GROUP BY parent) Deriv1 ON a.id = Deriv1.parent WHERE a.parent= ? order by sort', [$parent]);

        foreach ($result as $srel) {

            if ($srel['count'] > 0) {
                $menuhtml .= '<li class="dd-item dd3-item" data-id="' . $srel["id"] . '">';
                $menuhtml .= '<div class=""></div><div class="dd3-content">'
                        . '<i class="' . $srel["icon"] . '"></i> '
                        . $srel["label"]
                        . '<a data-id="' . $srel["id"] . '" data-link="_menu" class="btn grey-cascade btn-xs pull-right deletemsg"><i class="fa fa-times"></i> Delete</a>'
                        . '<a href="' . $hosturl . '/controllers/_menu.php?ac=edit&id=' . $srel["id"] . '" class="btn blue-hoki btn-xs pull-right mg-rg"><i class="fa fa-pencil"></i> Edit</a>'
                        . '<a class="btn default btn-xs green tooltips pull-right mg-rg" id="arrang_sub" data-parent="' . $srel["id"] . '" data-original-title="Arrange sub  menus">Arrange</a>'
                        . '</div>';
                $menuhtml .= '<ol class="dd-list">'
                        . $this->displaymenush($srel["id"], $hosturl)
                        . '</ol>'
                        . '</li>';
            } elseif ($srel['count'] == 0) {
                $menuhtml .= '<li class="dd-item dd3-item" data-id="' . $srel["id"] . '">';
                $menuhtml .= '<div class=""></div><div class="dd3-content">'
                        . '<i class="' . $srel["icon"] . '"></i> '
                        . $srel["label"]
                        . '<a data-id="' . $srel["id"] . '" data-link="_menu" class="btn grey-cascade btn-xs pull-right deletemsg"><i class="fa fa-times"></i> Delete</a>'
                        . '<a href="' . $hosturl . '/controllers/_menu.php?ac=edit&id=' . $srel["id"] . '" class="btn blue-hoki btn-xs pull-right mg-rg"><i class="fa fa-pencil"></i> Edit</a>'
                        . '</div>';
                $menuhtml .= '</li>';
            }
        }
        return $menuhtml;
    }

    public function edit() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        //get id for item
        $itemid = filter_input(INPUT_GET, 'id');

        //load all parents here
        $menus = R::findAll('awmenu');
        $this->smarty->assign('menus', $menus);

        //load all parents here
        $menu = R::load('awmenu', $itemid);
        $this->smarty->assign('menu', $menu);


        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('_menu/edit.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function updateit() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        //vars here
        $label = filter_input(INPUT_POST, 'label');
        $link = filter_input(INPUT_POST, 'link');
        $parent = filter_input(INPUT_POST, 'parent');
        $icon = filter_input(INPUT_POST, 'menuicon');
        $activename = filter_input(INPUT_POST, 'activename');
        $form = filter_input(INPUT_POST, 'form');
        $id = filter_input(INPUT_POST, 'id');
        $display = filter_input(INPUT_POST, 'display');
        if ($display == "image") {
            $img = uploadupdate("menuImage", '', False, 0, 0, 'menu');
        }

        echo $img;
        $maxOrder = R::getrow('select max(sort) from awmenu where parent = ?', [$parent]);

        //R::debug( TRUE );
        //load all parents here
        $menu = R::load('awmenu', $id);

        //here the upadte
        $menu->label = $label;
        $menu->link = $link;
        $menu->parent = $parent;
        //$menu->sort = $maxOrder['max(sort)']+1;
        $menu->icon = $icon;
        $menu->activeName = $activename;
        $menu->form = $form;
        $menu->display = $display;
        if ($display == "image" && $img != "") {
            $menu->image = $img;
        }

        try {
            R::store($menu);
            header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/controllers/error.php?ac=notupdate&id=' . $this->controllname);
        }
    }

    public function del() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        //get id for item
        $itemid = filter_input(INPUT_GET, 'id');


        //load all item here
        $menu = R::load('awmenu', $itemid);

        $undermenu = R::count('awmenu', ' parent = ? ', [$itemid]);
        if ($undermenu > 0) {
            //header('Location:' . $this->hosturl . '/controllers/error.php?ac=relate&id=' . $this->controllname);
            //exit();
        }

        //check in role menu
        $rolemenu = R::count('awrolemenu', ' menu_id = ? ', [$itemid]);
        if ($rolemenu > 0) {
            //header('Location:' . $this->hosturl . '/controllers/error.php?ac=relate&id=' . $this->controllname);
            //exit();
            $rolemenuin = R::findAll('awrolemenu', ' menu_id = ? ', [$itemid]);
            R::trashAll($rolemenuin);
        }

        try {

            R::trash($menu);
            header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/controllers/error.php?ac=notdel&id=' . $this->controllname);
        }
    }

    public function arrangemain() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        //here will load the menu show
        $result = R::getAll('SELECT a.*, Deriv1.count FROM `awmenu` a  LEFT OUTER JOIN (SELECT parent, COUNT(*) AS Count FROM `awmenu` GROUP BY parent) Deriv1 ON a.id = Deriv1.parent WHERE a.parent= ? order by sort', [0]);

        $this->smarty->assign('result', $result);
        $this->smarty->display('_menu/arrange.html');
    }

    public function sortable() {
        $sortedData = filter_input(INPUT_POST, 'datasorted');
        $this->updatearrange($sortedData);
    }

    public function updatearrange($data) {
        parse_str($data, $str);
        $datasort = $str['item'];
        for ($i = 0; $i < count($datasort); $i++) {
            $allData = R::findOne('awmenu', 'id = ?', [$datasort[$i]]);
            $allData->sort = $i + 1;
            R::store($allData);
        }
        echo 'Successfully Updated!';
    }

    public function arrangesub() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $parent = filter_input(INPUT_POST, 'parent');
        //here will load the menu show
        $result = R::getAll('SELECT a.*, Deriv1.count FROM `awmenu` a  LEFT OUTER JOIN (SELECT parent, COUNT(*) AS Count FROM `awmenu` GROUP BY parent) Deriv1 ON a.id = Deriv1.parent WHERE a.parent= ? order by sort', [$parent]);

        $this->smarty->assign('result', $result);
        $this->smarty->display('_menu/arrange.html');
    }

    // at the end of class call
    public function __destruct() {
        //colse connection
        R::close();
    }

}
