<?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;
    //menu itr for input
    public $menuitr;

    // 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 = '_role';
        $this->shcontrollname = 'Roles panel';
        $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);

        # 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] = 'role'; //controller name
        // do name  // switch($do)
        switch ($acty) {
            case '':$active[2] = 'roleadd';
                break;
            case 'show':$active[2] = 'roleshow';
                break;
            default :$active[2] = 'roleshow';
                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']);


        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('_role/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
        $name = filter_input(INPUT_POST, 'name');


        //here the add
        $role = R::dispense('awrole');
        $role->name = $name;

        try {
            $id = R::store($role);
            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
        $roles = R::findAll('awrole', 'order by id desc');
        $this->smarty->assign('roles', $roles);

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

    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 here
        $role = R::load('awrole', $itemid);
        $this->smarty->assign('role', $role);


        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('_role/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
        $name = filter_input(INPUT_POST, 'name');
        $id = filter_input(INPUT_POST, 'id');


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

        //here the upadte
        $role->name = $name;


        try {
            R::store($role);
            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');

        $roleusers = R::getRow('select * from awusers where role_id = ?', [$itemid]);
        if ($roleusers > 0) {
            header('Location:' . $this->hosturl . '/controllers/error.php?ac=relate&id=' . $this->controllname);
            exit();
        }


        //load all item here
        $role = R::load('awrole', $itemid);

        try {

            R::trash($role);
            R::exec('delete from awrolemenu where role_id = ?', [$itemid]);
            R::exec('delete from awrolecontrollprop where role_id = ?', [$itemid]);

            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 setting() {

        //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');

        $this->menuitr = 0;

        //send role
        $role = R::load('awrole', $itemid);
        $this->smarty->assign('role', $role);

        //menu display
        $dismenu = $this->displaymenush(0, $this->hosturl, $itemid);
        $this->smarty->assign('dismenu', $dismenu);

        //controlls
        $controlls = R::findAll('awcontroll');
        foreach ($controlls as $single) {
            $awcontroll = R::findAll('awcontrollprop', 'awcontroll_id = ?', [$single->id]);
            $single->props = $awcontroll;
            foreach ($awcontroll as $sin) {
                $getroleprop = R::findOne('awrolecontrollprop', 'role_id = ? and controllprop_id = ?', [$itemid, $sin->id]);
                $countrslt = count($getroleprop);
                if ($countrslt > 0) {
                    $sin->rolevalue = $getroleprop->checkval;
                } else {
                    $sin->rolevalue = $sin->checkval;
                }
            }
        }
        $this->smarty->assign('controlls', $controlls);


        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);

        ##############################  index.html buttons show    ####################################
        $drawBtn = $this->displaybtns($itemid);
        $this->smarty->assign('drawBtn', $drawBtn);

        $this->smarty->display('_role/setting.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

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


        $menuhtml = "";
        //get the all about this level in menu
        $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= ?', [$parent]);

        foreach ($result as $srel) {

            //check the value of group
            $getrolemenu = R::findOne('awrolemenu', 'role_id = ? and menu_id = ?', [$roleid, $srel['id']]);
            $countrslt = count($getrolemenu);
            if ($countrslt > 0) {
                $srel['rolevalue'] = $getrolemenu['checkval'];
            } else {
                $srel['rolevalue'] = 0;
            }

            //main itr for input
            $this->menuitr++;

            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"]
                        . '<input type="hidden" name="menuid' . $this->menuitr . '" value="' . $srel["id"] . '"/>'
                        . '<div  class="col-md-3 pull-right forroleradio">'
                        . '<div class="radio-list"><label class="radio-inline nopadding">'
                        . '<input type="radio" class="menuroleyes" name="menurolecheck' . $this->menuitr . '" value="1" ';
                if ($srel['rolevalue'] == 1) {
                    $menuhtml .= 'checked';
                }
                $menuhtml .= '/> Show </label>'
                        . '<label class="radio-inline nopadding">'
                        . '<input type="radio" class="menuroleno" name="menurolecheck' . $this->menuitr . '" value="0" ';
                if ($srel['rolevalue'] == 0) {
                    $menuhtml .= 'checked';
                }
                $menuhtml .= '/> Hide</label></div>'
                        . '</div>'
                        . '</div>';
                $menuhtml .= '<ol class="dd-list">'
                        . $this->displaymenush($srel["id"], $hosturl, $roleid)
                        . '</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> '
                        . '<input type="hidden" name="menuid' . $this->menuitr . '" value="' . $srel["id"] . '"/>'
                        . $srel["label"]
                        . '<div  class="col-md-3 pull-right forroleradio">'
                        . '<div class="radio-list"><label class="radio-inline nopadding">'
                        . '<input type="radio" class="menuroleyes" name="menurolecheck' . $this->menuitr . '" value="1" ';
                if ($srel['rolevalue'] == 1) {
                    $menuhtml .= 'checked';
                }
                $menuhtml .= '/> Show </label>'
                        . '<label class="radio-inline nopadding">'
                        . '<input type="radio" class="menuroleno" name="menurolecheck' . $this->menuitr . '" value="0" ';
                if ($srel['rolevalue'] == 0) {
                    $menuhtml .= 'checked';
                }
                $menuhtml .= '/> Hide</label></div>'
                        . '</div>'
                        . '</div>';
                $menuhtml .= '</li>';
            }
        }

        return $menuhtml;
    }

    public function insetting() {

        //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_POST, 'roleid');
        $itrmenu = count(R::findAll('awmenu'));
        $itrcontroll = filter_input(INPUT_POST, 'itrcontroll');
        $itrcontrollprop = filter_input(INPUT_POST, 'itrcontrollprop1');

        try {

            //insert the role menu
            for ($i = 1; $i <= $itrmenu; $i++) {
                $menuid = filter_input(INPUT_POST, 'menuid' . $i);
                $checkval = filter_input(INPUT_POST, 'menurolecheck' . $i);

                if (!$menuid) {
                    continue;
                }


                //check if this item already in awrolemenu
                $getrolemenu = R::findOne('awrolemenu', 'role_id = ? and menu_id = ?', [$itemid, $menuid]);
                $countrslt = count($getrolemenu);
                if ($countrslt > 0) {
                    //update
                    $awrolemenu = R::load('awrolemenu', $getrolemenu->id);
                    $awrolemenu->role = R::load('awrole', $itemid);
                    $awrolemenu->menu = R::load('awmenu', $menuid);
                    $awrolemenu->checkval = $checkval;

                    R::store($awrolemenu);
                } else {
                    //insert
                    $awrolemenu = R::dispense('awrolemenu');
                    $awrolemenu->role = R::load('awrole', $itemid);
                    $awrolemenu->menu = R::load('awmenu', $menuid);
                    $awrolemenu->checkval = $checkval;

                    R::store($awrolemenu);
                }
            }

            //insert controll prop
            for ($i = 1; $i <= $itrcontroll; $i++) {
                $itrcontrollprop = filter_input(INPUT_POST, 'itrcontrollprop' . $i);

                //insert every prop
                for ($ix = 0; $ix <= $itrcontrollprop; $ix++) {
                    $controllpropid = filter_input(INPUT_POST, 'controllpropid' . $i . $ix);
                    $checkval = filter_input(INPUT_POST, 'proprolecheck' . $i . $ix);

                    if (!$controllpropid) {
                        continue;
                    }

                    $getroleprop = R::findOne('awrolecontrollprop', 'role_id = ? and controllprop_id = ?', [$itemid, $controllpropid]);
                    $countrslt = count($getroleprop);
                    if ($countrslt > 0) {
                        //update
                        $awrolecontrollprop = R::load('awrolecontrollprop', $getroleprop->id);
                        $awrolecontrollprop->role = R::load('awrole', $itemid);
                        $awrolecontrollprop->controllprop = R::load('awcontrollprop', $controllpropid);
                        $awrolecontrollprop->checkval = $checkval;

                        R::store($awrolecontrollprop);
                    } else {
                        //insert
                        $awrolecontrollprop = R::dispense('awrolecontrollprop');
                        $awrolecontrollprop->role = R::load('awrole', $itemid);
                        $awrolecontrollprop->controllprop = R::load('awcontrollprop', $controllpropid);
                        $awrolecontrollprop->checkval = $checkval;

                        R::store($awrolecontrollprop);
                    }
                }
            }

            for ($i = 1; $i <= 4; $i++) {
                $this->updateBtnSetting($itemid, $i);
            }
            header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/controllers/error?ac=insetting&id=' . $this->controllname);
        }
    }

    public function displaybtns($roleid) {
        $drawBtn = '';
        ## add patient btn 

        $btn1 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 1  ', [$roleid]);
        if (count($btn1) < 1) {
            $btn1 = R::dispense('awrolebtn');
            $btn1->role_id = $roleid;
            $btn1->btn_id = 1;
            $btn1->checkval = 0;
            $btn1->id = R::store($btn1);
        }
        $drawBtn .= $this->drawbtnunit($btn1, 'زر إضافة مريضة  ');
###################################################################################
        ## add visit btn 

        $btn2 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 2  ', [$roleid]);
        if (count($btn2) < 1) {
            $btn2 = R::dispense('awrolebtn');
            $btn2->role_id = $roleid;
            $btn2->btn_id = 2;
            $btn2->checkval = 0;
            $btn2->id = R::store($btn2);
        }
        $drawBtn .= $this->drawbtnunit($btn2, 'زر إضافة زيارة ');

###################################################################################
        ## edit  visit btn 

        $btn3 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 3  ', [$roleid]);
        if (count($btn3) < 1) {
            $btn3 = R::dispense('awrolebtn');
            $btn3->role_id = $roleid;
            $btn3->btn_id = 3;
            $btn3->checkval = 0;
            $btn3->id = R::store($btn3);
        }
        $drawBtn .= $this->drawbtnunit($btn3, 'زر تعديل  زيارة ');

        ###################################################################################
        ## edit  visit btn 

        $btn4 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 4  ', [$roleid]);
        if (count($btn4) < 1) {
            $btn4 = R::dispense('awrolebtn');
            $btn4->role_id = $roleid;
            $btn4->btn_id = 4;
            $btn4->checkval = 0;
            $btn4->id = R::store($btn4);
        }
        $drawBtn .= $this->drawbtnunit($btn4, 'زر حذف  زيارة ');

        ###################################################################################

        return $drawBtn;
    }

    public function drawbtnunit($btn, $btnName) {
        $menuhtml = '';

        $menuhtml .= '<li class="dd-item dd3-item" data-id="' . $btn->id . '">';
        $menuhtml .= '<div class=""></div><div class="dd3-content">'
                . $btnName
                . '<div  class="col-md-3 pull-right forroleradio">'
                . '<div class="radio-list"><label class="radio-inline nopadding">'
                . '<input type="radio" class="btn_role_item"  data-btnid="' . $btn->btn_id . '" name="btncheck' . $btn->btn_id . '" value="1" ';
        if ($btn->checkval == 1) {
            $menuhtml .= 'checked';
        }
        $menuhtml .= '/> Show </label>'
                . '<label class="radio-inline nopadding">'
                . '<input type="radio" class="btn_role_item" data-btnid="' . $btn->btn_id . '"  name="btncheck' . $btn->btn_id . '" value="0" ';
        if ($btn->checkval == 0) {
            $menuhtml .= 'checked';
        }
        $menuhtml .= '/> Hide</label></div>'
                . '</div>'
                . '</div>';
        $menuhtml .= '</li>';

        return $menuhtml;
    }

    public function updateBtnSetting($role_id, $btn_id) {

        $check_val = filter_input(INPUT_POST, 'btncheck' . $btn_id);

        if (!$btn_id) {
            return false;
        }

        $btn = R::findOne('awrolebtn', ' role_id = ? and btn_id = ?   ', [$role_id, $btn_id]);
        $btn->checkval = $check_val;
        R::store($btn);
    }

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

}
