<?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 = '_member';
      $this->shcontrollname = 'Member 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);

      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] = 'member'; //controller name
      // do name  // switch($do)
      switch ($acty) {
         case '':
            $active[2] = 'memberadd';
            break;
         case 'show':
            $active[2] = 'membershow';
            break;
         default :
            $active[2] = 'membershow';
            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
      $roles = R::findAll('awrole');
      $this->smarty->assign('roles', $roles);

      $programesetting = R::findOne('programesetting');
      $this->smarty->assign('system_type', $programesetting->system_type);
      $this->smarty->assign('erpdb', $programesetting->erpdb);

      $branches = R::findAll('branches');
      $this->smarty->assign('branches', $branches);

      $sub_regions = R::getAll('select sub_regions.* from sub_regions
               join  regions   on regions.id =   sub_regions.region_id
                where regions.deleted != 1  and sub_regions.deleted != 1  ');
      $this->smarty->assign('sub_regions', $sub_regions);

      $drs = R::getAll('select awusers.user_id   , awusers.name   from     awusers     
                          join       awrole                                           on awusers.role_id  = awrole.id
                          where awusers.deleted != 1 and   awrole.visit_show = 1');
      $this->smarty->assign('drs', $drs);

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

   //check useraname
   public function checkusername() {

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

      $username = filter_input(INPUT_POST, 'username');
      $checkedit = filter_input(INPUT_POST, 'editusername');

      if (!$checkedit) {
         //new
         $checkusername = R::getRow('SELECT * FROM awusers WHERE user_name = ? LIMIT 1', [$username]);
         if (count($checkusername) > 0) {
            echo "yes";
         } else {
            echo "no";
         }
      } else {

         //edit
         $checkusername = R::getRow('SELECT * FROM awusers WHERE user_name = ? LIMIT 1', [$username]);
         if (count($checkusername) > 0) {
            if ($checkedit == $checkusername['user_name']) {
               echo "no";
            } else {
               echo "yes";
            }
         } else {
            echo "no";
         }
      }
   }

   //check email
   public function checkemail() {

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

      $email = filter_input(INPUT_POST, 'email');
      $checkedit = filter_input(INPUT_POST, 'checkedit');

      if (!$checkedit) {
         //new
         $checkemail = R::getRow('SELECT * FROM awusers WHERE user_email = ? LIMIT 1', [$email]);

         if (count($checkemail) > 0) {
            echo "yes";
         } else {
            echo "no";
         }
      } else {

         //edit
         $checkemail = R::getRow('SELECT * FROM awusers WHERE user_email = ? LIMIT 1', [$email]);
         if (count($checkemail) > 0) {
            if ($checkedit == $checkemail['user_email']) {
               echo "no";
            } else {
               echo "yes";
            }
         } else {
            echo "no";
         }
      }
   }

   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');
      $email = filter_input(INPUT_POST, 'email');
      $role = filter_input(INPUT_POST, 'role');
      $erpDBSave = (int) filter_input(INPUT_POST, 'erpDBSave');
      $erpdbsavename = filter_input(INPUT_POST, 'erpdbsavename');
      //   $special = filter_input(INPUT_POST, 'special');
//        $position = filter_input(INPUT_POST, 'position');
      $username = filter_input(INPUT_POST, 'username');
      $password = filter_input(INPUT_POST, 'password');

      $license_no = filter_input(INPUT_POST, 'license_no');
      $register_no = filter_input(INPUT_POST, 'register_no');
      $tanks_settings = filter_input(INPUT_POST, 'tanks_settings');
      $whatsapp_no = filter_input(INPUT_POST, 'whatsapp_no');
      $special = (filter_input(INPUT_POST, 'special') > 0) ? filter_input(INPUT_POST, 'special') : NULL;
      $position = (filter_input(INPUT_POST, 'position') > 0) ? filter_input(INPUT_POST, 'position') : NULL;

      $hour_price = (filter_input(INPUT_POST, 'hour_price') > 0) ? filter_input(INPUT_POST, 'hour_price') : 0;
      $visit_percent = (filter_input(INPUT_POST, 'visit_percent') > 0) ? filter_input(INPUT_POST, 'visit_percent') : 0;

      $normal_per = (filter_input(INPUT_POST, 'normal_per') > 0) ? filter_input(INPUT_POST, 'normal_per') : 0;
      $pulse_per = (filter_input(INPUT_POST, 'pulse_per') > 0) ? filter_input(INPUT_POST, 'pulse_per') : 0;
      $session_per = (filter_input(INPUT_POST, 'session_per') > 0) ? filter_input(INPUT_POST, 'session_per') : 0;

      $user_name = trim($username);
      $hash_cost_factor = (defined('HASH_COST_FACTOR') ? HASH_COST_FACTOR : null);
      $user_password_hash = password_hash($password, PASSWORD_DEFAULT, array('cost' => $hash_cost_factor));
      $user_activation_hash = sha1(uniqid(mt_rand(), true));
      $user_email = trim($email);
      $user_registration_ip = $_SERVER['REMOTE_ADDR'];

      $img = uploadupdate("memberImage", '', False, 0, 0, 'mambers');
      $signature = uploadupdate("signatureImage", '', False, 0, 0, 'mambers');

      $branch_id = filter_input(INPUT_POST, 'branch_id', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
      $branch_ids = implode(',', $branch_id);

      if (filter_input(INPUT_POST, 'related_dr_all') == 1) {
         $related_dr = 0;
      } else {
         $related_dr = '';
         $i = 1;
         foreach ($_POST['related_dr'] as $selectedOption) {

            if ($i != 1) {
               $related_dr .= ' , ';
            }
            $related_dr .= $selectedOption;
            $i++;
         }
      }

      if (filter_input(INPUT_POST, 'related_branches_all') == 1) {
         $related_branches = 0;
      } else {
         $related_branches = '';
         $i = 1;
         foreach ($_POST['related_branches'] as $selectedOption) {

            if ($i != 1) {
               $related_branches .= ' , ';
            }
            $related_branches .= $selectedOption;
            $i++;
         }
      }

      $show_all_visits = (filter_input(INPUT_POST, 'show_all_visits') > 0) ? filter_input(INPUT_POST, 'show_all_visits') : 0;
      $financial_user = (filter_input(INPUT_POST, 'financial_user') > 0) ? filter_input(INPUT_POST, 'financial_user') : 0;

      $original_sub_regions = '';
      $i = 1;
      foreach ($_POST['original_sub_regions'] as $selectedOption) {

         if ($i != 1) {
            $original_sub_regions .= ' , ';
         }
         $original_sub_regions .= $selectedOption;
         $i++;
      }

      $alt_sub_regions = '';
      $i = 1;
      foreach ($_POST['alt_sub_regions'] as $selectedOption) {

         if ($i != 1) {
            $alt_sub_regions .= ' , ';
         }
         $alt_sub_regions .= $selectedOption;
         $i++;
      }



      try {
//            //here the add
         $newuser = R::exec('INSERT INTO awusers (user_name, user_password_hash, user_email
                    ,user_active, user_activation_hash, user_registration_ip, user_registration_datetime,role_id,name
                    , specialid ,positionid , hour_price , visit_percent ,  normal_per, pulse_per, session_per,erpsaveid,savename , image, branch_id
                     , related_dr , license_no , register_no , tanks_settings , show_all_visits , related_branches , financial_user 
                     ,  original_sub_regions   , alt_sub_regions  , whatsapp_no , signature  )
                    VALUES(?, ?, ?, ?,?, ?, now(),?,?,? ,? , ?, ?, ?, ?,?,? , ?,? , ?,? , ? , ? , ? , ?  , ?, ?, ?  , ? , ? , ?   )'
                         , [$user_name, $user_password_hash, $user_email, 1, $user_activation_hash
                     , $user_registration_ip, $role, $name, $special, $position, $hour_price, $visit_percent
                     , $normal_per, $pulse_per, $session_per, $erpDBSave, $erpdbsavename, $img, $branch_ids
                     , $related_dr, $license_no, $register_no, $tanks_settings, $show_all_visits, $related_branches
                     , $financial_user, $original_sub_regions, $alt_sub_regions, $whatsapp_no, $signature]);

         $insertedUserId = R::getInsertID();
         $user = R::getRow('select * from awusers where user_id = ?', [$insertedUserId]);
         $this->erpDoctor($user);

         header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
      } catch (Exception $e) {
         //   print_r($e);
         header('Location:' . $this->hosturl . '/controllers/error.php?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
//        $users = R::getAll('SELECT * FROM awusers where  deleted != 1 and  role_id != 99');
      $users = R::getAll('SELECT awusers.* , branches.name as branchName  
                      FROM awusers
                       left join branches    on branches.id =  awusers.branch_id 
                      where  awusers.deleted != 1 and  awusers.role_id != 99');
      $this->smarty->assign('users', $users);

      $roles = R::findAll('awrole');
      $this->smarty->assign('roles', $roles);

      $programesetting = R::findOne('programesetting');
      $this->smarty->assign('erpdb', $programesetting->erpdb);
      $this->smarty->assign('branchesActivate', $programesetting->branches);

      //call other class with other content
      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      $this->smarty->display('_member/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 parents here
      $roles = R::findAll('awrole');
      $this->smarty->assign('roles', $roles);

      $drs = R::getAll('select awusers.user_id   , awusers.name   from     awusers     
                          join       awrole                                           on awusers.role_id  = awrole.id
                          where awusers.deleted != 1 and   awrole.visit_show = 1');
      $this->smarty->assign('drs', $drs);

      $sub_regions = R::getAll('select sub_regions.* from sub_regions
               join  regions   on regions.id =   sub_regions.region_id
                where regions.deleted != 1  and sub_regions.deleted != 1  ');
      $this->smarty->assign('sub_regions', $sub_regions);

      //load all here
      $user = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$itemid]);
      $this->smarty->assign('user', $user);

      $specials = R::findAll('awrolespecialize', 'roleid = ?', [$user['role_id']]);
      $positions = R::findAll('awroleposition', 'roleid = ?', [$user['role_id']]);

      $this->smarty->assign('specials', $specials);
      $this->smarty->assign('positions', $positions);

      $programesetting = R::findOne('programesetting');
      $this->smarty->assign('system_type', $programesetting->system_type);
      $this->smarty->assign('erpdb', $programesetting->erpdb);

      $branches = R::findAll('branches');
      $this->smarty->assign('branches', $branches);

      #########################################
      $related_drs = array();

      if ($user['related_dr'] == 0) {
         $this->smarty->assign('related_dr_all', 1);
      } else {
         $index_roles = explode(',', $user['related_dr']);

         foreach ($index_roles as $value) {
            $value = trim($value);
            array_push($related_drs, $value);
         }
      }
      $this->smarty->assign('related_drs', $related_drs);

      #########################################
      $related_branches = array();

      if ($user['related_branches'] == 0 && $user['related_branches'] != '' && $user['related_branches'] != null) {
         $this->smarty->assign('related_branches_all', 1);
      } else {
         $index_roles = explode(',', $user['related_branches']);

         foreach ($index_roles as $value) {
            $value = trim($value);
            array_push($related_branches, $value);
         }
      }
      $this->smarty->assign('related_branches', $related_branches);

      #########################################
      $original_sub_regions = array();
      $index_roles = explode(',', $user['original_sub_regions']);

      foreach ($index_roles as $value) {
         $value = trim($value);
         array_push($original_sub_regions, $value);
      }

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

      #########################################
      $alt_sub_regions = array();

      $index_roles = explode(',', $user['alt_sub_regions']);

      foreach ($index_roles as $value) {
         $value = trim($value);
         array_push($alt_sub_regions, $value);
      }
      $this->smarty->assign('alt_sub_regions', $alt_sub_regions);

      #########################################
      //call other class with other content
      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      $this->smarty->display('_member/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');
      $email = filter_input(INPUT_POST, 'emaile');
      $role = filter_input(INPUT_POST, 'role');
      $erpDBSave = (int) filter_input(INPUT_POST, 'erpDBSave');
      $erpdbsavename = filter_input(INPUT_POST, 'erpdbsavename');
      $special = filter_input(INPUT_POST, 'special');
      $position = filter_input(INPUT_POST, 'position');
      $username = filter_input(INPUT_POST, 'username');
      $epassword = filter_input(INPUT_POST, 'epassword');
      $oldpassword = filter_input(INPUT_POST, 'oldpassword');
      $license_no = filter_input(INPUT_POST, 'license_no');
      $register_no = filter_input(INPUT_POST, 'register_no');
      $tanks_settings = filter_input(INPUT_POST, 'tanks_settings');
      $whatsapp_no = filter_input(INPUT_POST, 'whatsapp_no');
      $id = filter_input(INPUT_POST, 'id');

      if ($_FILES['memberImage']['size'] == 0) {
         $img = '';
      } else {
         $img = uploadupdate("memberImage", '', False, 0, 0, 'mambers');
      }


      if ($_FILES['signatureImage']['size'] == 0) {
         $signature = '';
      } else {
         $signature = uploadupdate("signatureImage", '', False, 0, 0, 'mambers');
         R::exec('UPDATE awusers SET signature = ?     WHERE user_id = ?', [$signature, $id]);
      }

      //new password or old password
      if (empty($epassword)) {
         $user_password_hash = $oldpassword;
      } else {
         $hash_cost_factor = (defined('HASH_COST_FACTOR') ? HASH_COST_FACTOR : null);
         $user_password_hash = password_hash($epassword, PASSWORD_DEFAULT, array('cost' => $hash_cost_factor));
      }


      $user_name = trim($username);
      $user_activation_hash = sha1(uniqid(mt_rand(), true));
      $user_email = trim($email);
      $user_registration_ip = $_SERVER['REMOTE_ADDR'];

      if (empty($special)) {
         $special = Null;
      }
      if (empty($position)) {
         $position = Null;
      }

      $hour_price = (filter_input(INPUT_POST, 'hour_price') > 0) ? filter_input(INPUT_POST, 'hour_price') : 0;
      $visit_percent = (filter_input(INPUT_POST, 'visit_percent') > 0) ? filter_input(INPUT_POST, 'visit_percent') : 0;
      $normal_per = (filter_input(INPUT_POST, 'normal_per') > 0) ? filter_input(INPUT_POST, 'normal_per') : 0;
      $pulse_per = (filter_input(INPUT_POST, 'pulse_per') > 0) ? filter_input(INPUT_POST, 'pulse_per') : 0;
      $session_per = (filter_input(INPUT_POST, 'session_per') > 0) ? filter_input(INPUT_POST, 'session_per') : 0;

      $branch_id = filter_input(INPUT_POST, 'branch_id', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
      $branch_ids = implode(',', $branch_id);

      if (filter_input(INPUT_POST, 'related_dr_all') == 1) {
         $related_dr = 0;
      } else {
         $i = 1;
         $related_dr = '';
         if ($_POST['related_dr'] && !empty($_POST['related_dr'])) {
            foreach ($_POST['related_dr'] as $selectedOption) {
               if ($i != 1) {
                  $related_dr .= ' , ';
               }
               $related_dr .= $selectedOption;
               $i++;
            }
         }
      }


      if (filter_input(INPUT_POST, 'related_branches_all') == 1) {
         $related_branches = 0;
      } else {
         $i = 1;
         $related_branches = '';
         if ($_POST['related_branches'] && !empty($_POST['related_branches'])) {
            foreach ($_POST['related_branches'] as $selectedOption) {
               if ($i != 1) {
                  $related_branches .= ' , ';
               }
               $related_branches .= $selectedOption;
               $i++;
            }
         }
      }

      $show_all_visits = (filter_input(INPUT_POST, 'show_all_visits') > 0) ? filter_input(INPUT_POST, 'show_all_visits') : 0;
      $financial_user = (filter_input(INPUT_POST, 'financial_user') > 0) ? filter_input(INPUT_POST, 'financial_user') : 0;

      $original_sub_regions = '';
      $i = 1;
      foreach ($_POST['original_sub_regions'] as $selectedOption) {

         if ($i != 1) {
            $original_sub_regions .= ' , ';
         }
         $original_sub_regions .= $selectedOption;
         $i++;
      }

      $alt_sub_regions = '';
      $i = 1;
      foreach ($_POST['alt_sub_regions'] as $selectedOption) {

         if ($i != 1) {
            $alt_sub_regions .= ' , ';
         }
         $alt_sub_regions .= $selectedOption;
         $i++;
      }

      try {
         //here the add
         if ($_FILES['memberImage']['size'] == 0) {
            R::exec('UPDATE awusers SET user_name = ?,user_password_hash = ?, user_email = ?
                    ,role_id = ?,name = ? , specialid = ? ,positionid = ? , hour_price = ? , visit_percent = ? 
                    , normal_per = ? , pulse_per = ? , session_per = ? ,erpsaveid = ?,savename = ?, branch_id = ?
                    , related_dr = ? , license_no = ?  , register_no = ? , tanks_settings = ?  , show_all_visits = ? 
                       , related_branches = ? , financial_user = ?  , original_sub_regions = ? 
                        , alt_sub_regions =   ? , whatsapp_no = ?    WHERE user_id = ?'
                    , [$user_name, $user_password_hash, $user_email, $role, $name, $special, $position
                , $hour_price, $visit_percent, $normal_per, $pulse_per, $session_per, $erpDBSave, $erpdbsavename, $branch_ids
                , $related_dr, $license_no, $register_no, $tanks_settings, $show_all_visits, $related_branches
                , $financial_user, $original_sub_regions, $alt_sub_regions, $whatsapp_no, $id]);
         } else {
            R::exec('UPDATE awusers SET user_name = ?,user_password_hash = ?, user_email = ?
                    ,role_id = ?,name = ? , specialid = ? ,positionid = ? , hour_price = ? , visit_percent = ? 
                    , normal_per = ? , pulse_per = ? , session_per = ? ,erpsaveid = ?,savename = ? , image = ?, branch_id = ?
                    , related_dr = ? , license_no = ?  , register_no = ? , tanks_settings = ? , show_all_visits = ?   
                      , related_branches = ?  , financial_user = ?    , original_sub_regions = ? 
                      , alt_sub_regions =   ?  , whatsapp_no = ?       WHERE user_id = ?'
                    , [$user_name, $user_password_hash, $user_email, $role, $name, $special, $position
                , $hour_price, $visit_percent, $normal_per, $pulse_per, $session_per, $erpDBSave, $erpdbsavename, $img, $branch_ids
                , $related_dr, $license_no, $register_no, $tanks_settings, $show_all_visits, $related_branches
                , $financial_user, $original_sub_regions, $alt_sub_regions, $whatsapp_no, $id]);
         }
         $user = R::getRow('select * from awusers where user_id = ?', [$id]);
         $this->erpDoctor($user);
         header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
      } catch (Exception $e) {
         print_r($e);
         //  header('Location:' . $this->hosturl . '/controllers/error.php?ac=notupdate&id=' . $this->controllname);
      }
   }

   public function updateerpsaveid() {
      //vars here
      $saveid = (int) filter_input(INPUT_POST, 'val');
      $savename = filter_input(INPUT_POST, 'name');
      $memid = (int) filter_input(INPUT_POST, 'memid');

      if ($saveid == 0) {
         $savename = '';
      }
      try {
         //here the add
         $edituser = R::exec('UPDATE awusers SET erpsaveid=?,savename=? WHERE user_id = ?', [$saveid, $savename, $memid]);
//            $user = R::getRow('select * from awusers where user_id = ?', [$id]);
//            $this->erpDoctor($user);

         echo 1;
      } catch (Exception $e) {
         echo 0;
      }
   }

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

      try {
         //      $edituser = R::exec('Delete from awusers where user_id = ?', [$itemid]);
         R::exec('update  awusers set deleted = 1   where user_id = ?', [$itemid]);
         $this->erpDoctorDel($itemid);
         header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
      } catch (Exception $e) {
         header('Location:' . $this->hosturl . '/controllers/error.php?ac=notdel');
      }
   }

   public function getposition() {

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

      //get id for item
      $roleId = filter_input(INPUT_POST, 'roleId');
      $positions = R::findAll('awroleposition', 'roleid = ?', [$roleId]);
      $result = '<option value=""></option>';
      foreach ($positions as $value) {
         $result .= '<option value = ' . $value->id . ' > ' . $value->name . ' </option>';
      }
      echo $result;
   }

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

      //get id for item
      $roleId = filter_input(INPUT_POST, 'roleId');
      $positions = R::findAll('awrolespecialize', 'roleid = ?', [$roleId]);
      $result = '<option value=""></option>';
      foreach ($positions as $value) {
         $result .= '<option value = ' . $value->id . ' > ' . $value->name . ' </option>';
      }
      echo $result;
   }

   ##fatma

   public function addAllDoctorsToERP() {
      $programesetting = R::load('programesetting', 1);
      if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
         try {
            R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
            $lastId = 0;
            $limit = 50;
            R::selectDatabase('default');
            do {
               $rows = 0;
               R::selectDatabase('default');
               $allDoctors = R::getAll("select * from awusers where user_id > $lastId order by user_id asc limit $limit "); //and user_active = 1
               R::selectDatabase('erpDB');
               if (R::testConnection()) {
                  foreach ($allDoctors as $doctor) {
                     $doctorData = R::getRow('select userid from user where conditions=0 and obygyDoctorId = ' . $doctor['user_id']);
                     if (empty($doctorData['userid'])) {
                        //here use NULL for new insert
                        //better to add client using erp files it self so use  curl "it is like post requist but in php"
                        $this->curlAddDoctor($doctor, $programesetting->erpdb);
                     } else {
                        //here use id to update
                        $this->curlupdateDoctor($doctor, $programesetting->erpdb, $doctorData['userid']);
                     }
                     $rows++;
                     $lastId = $doctor['user_id'];
                  }
               } else {
                  throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
               }
            } while ($rows > 0);
            echo 1;
         } catch (Exception $exc) {
            echo -1;
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
         }
         R::selectDatabase('default');
      }
   }

   public function erpDoctor($doctor) {//detections
      $programesetting = R::load('programesetting', 1);
      if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
         try {
            R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
            R::selectDatabase('erpDB');
            if (R::testConnection()) {
               $doctorData = R::getRow('select userid from user where conditions=0 and obygyDoctorId = ' . (int) $doctor['user_id']);
               if (empty($doctor['user_id']) || empty($doctorData['userid'])) {
                  //here use NULL for new insert
                  //better to add client using erp files it self so use  curl "it is like post requist but in php"
                  $this->curlAddDoctor($doctor, $programesetting->erpdb);
               } else {
                  //here use id to update
                  $this->curlupdateDoctor($doctor, $programesetting->erpdb, $doctorData['userid']);
               }
            } else {
               throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
            }
         } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
            echo $exc;
         }
         R::selectDatabase('default');
      }
   }

   public function erpDoctorDel($doctorId) {//detections
      $programesetting = R::load('programesetting', 1);
      if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
         try {
            R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
            R::selectDatabase('erpDB');
            if (R::testConnection()) {
               $doctorData = R::getRow('select userid from user where conditions=0 and obygyDoctorId = ' . $doctorId);
               $this->curlDelDoctor($programesetting->erpdb, $doctorData['userid']);
            } else {
               throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
            }
            R::selectDatabase('default');
         } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
         }
      }
   }

   //better to add client using erp files it self so use  curl "it is like post requist but in php"
   public function curlAddDoctor($doctor, $erpDB) {
      // set post fields
      $post = [
          'curlpost' => 1,
          'sessionlist' => json_encode(array('dbname' => $erpDB, 'userid' => 1, 'usergroupid' => 1, 'saveid' => 1)),
          'username' => $doctor['user_name'],
          'password' => '123',
          'userstoreid' => 0,
          'userstoreidDef' => 1,
          'employeename' => $doctor['name'],
          'usergroupid' => 2,
          'saveid' => 1,
          'currentdate' => date('Y-m-d'),
          'conditions' => 0,
          'awardrate' => 0,
          'branchid' => 0,
          'question' => '',
          'answer' => '',
          'directSaveBills' => 0,
          'searchinonesave' => 1,
          'obygyDoctorId' => $doctor['user_id'],
      ];
      try {
         $ch = curl_init(HOST_URL_ERP . '/controllers/userController.php?do=add');
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

         // execute!
         $response = curl_exec($ch);

         // close the connection, release resources used
         curl_close($ch);
      } catch (Exception $exc) {
         //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
         //echo -1;
      }
      // do anything you want with your response
//        var_dump($response);
   }

   public function curlupdateDoctor($doctor, $erpDB, $doctorId) {
      // set post fields
      $post = [
          'curlpost' => 1,
          'sessionlist' => json_encode(array('dbname' => $erpDB, 'userid' => 1, 'usergroupid' => 1, 'saveid' => 1)),
          'userid' => $doctorId, //id in erp
          'username' => $doctor['user_name'],
          'password' => '123',
          'userstoreid' => 0,
          'userstoreidDef' => 1,
          'employeename' => $doctor['name'],
          'usergroupid' => 2,
          'saveid' => 1,
          'currentdate' => date('Y-m-d'),
          'conditions' => 0,
          'awardrate' => 0,
          'branchid' => 0,
          'question' => '',
          'answer' => '',
          'directSaveBills' => 0,
          'searchinonesave' => 1,
          'obygyDoctorId' => $doctor['user_id'],
      ];
      try {
         $ch = curl_init(HOST_URL_ERP . '/controllers/userController.php?do=update');
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

         // execute!
         $response = curl_exec($ch);

         // close the connection, release resources used
         curl_close($ch);
      } catch (Exception $exc) {
         //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
         //echo -1;
      }

      // do anything you want with your response
//        var_dump($response);
   }

   public function curlDelDoctor($erpDB, $doctorId) {
      // set post fields
      $post = [
          'curlpost' => 1,
          'sessionlist' => json_encode(array('dbname' => $erpDB, 'userid' => 1, 'usergroupid' => 1, 'saveid' => 1)),
      ];
      try {
         $ch = curl_init(HOST_URL_ERP . '/controllers/userController.php?do=delete&conditions=0&userid=' . $doctorId); //do=deleteFinaly&userid=
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

         // execute!
         $response = curl_exec($ch);

         // close the connection, release resources used
         curl_close($ch);
      } catch (Exception $exc) {
         //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
         //echo -1;
      }

      // do anything you want with your response
//        var_dump($response);
   }

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

   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;

      $user = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$itemid]);
      $this->smarty->assign('user', $user);

      //menu display
      $dismenu = $this->displaymenush(0, $this->hosturl, $itemid);
      $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('_member/setting.html');
      leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
      footer::footershow($this->smarty, $this->hosturl);
   }

   public function displaymenush($parent, $hosturl, $userid) {


      $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('awusermenu', 'user_id = ? and menu_id = ?', [$userid, $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="menu_user_item menuroleyes" data-menuid="' . $srel["id"] . '" name="menurolecheck' . $this->menuitr . '" value="1" ';
            if ($srel['rolevalue'] == 1) {
               $menuhtml .= 'checked';
            }
            $menuhtml .= '/> Show </label>'
                    . '<label class="radio-inline nopadding">'
                    . '<input type="radio" class="menu_user_item menuroleno" data-menuid="' . $srel["id"] . '" 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, $userid)
                    . '</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="menu_user_item menuroleyes" data-menuid="' . $srel["id"] . '" name="menurolecheck' . $this->menuitr . '" value="1" ';
            if ($srel['rolevalue'] == 1) {
               $menuhtml .= 'checked';
            }
            $menuhtml .= '/> Show </label>'
                    . '<label class="radio-inline nopadding">'
                    . '<input type="radio" class="menu_user_item menuroleno" data-menuid="' . $srel["id"] . '" name="menurolecheck' . $this->menuitr . '" value="0" ';
            if ($srel['rolevalue'] == 0) {
               $menuhtml .= 'checked';
            }
            $menuhtml .= '/> Hide</label></div>'
                    . '</div>'
                    . '</div>';
            $menuhtml .= '</li>';
         }
      }

      return $menuhtml;
   }

   public function updateMenuUserSetting() {
      $user_id = filter_input(INPUT_POST, 'userid');
      $menu_id = filter_input(INPUT_POST, 'menuid');
      $check_val = filter_input(INPUT_POST, 'menurolecheck');

      if (!$menu_id) {
         return false;
      }

      //R::debug('true');

      $getrolemenu = R::findOne('awusermenu', 'user_id = ? and menu_id = ?', [$user_id, $menu_id]);
      if ($getrolemenu) {
         R::exec('UPDATE awusermenu SET checkval = ' . $check_val . '  WHERE id = ' . $getrolemenu->id);
      } else {
         //insert
         $awrolemenu = R::dispense('awusermenu');
         $awrolemenu->user_id = $user_id;
         $awrolemenu->menu_id = $menu_id;
         $awrolemenu->checkval = $check_val;

         $result = R::store($awrolemenu);
      }


      return $result;
   }

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