<?php

require_once("imp/_imp.php");

class Controllers {

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

// 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 = 'labdevices';
      $this->shcontrollname = 'labdevices';
      $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, '', '', $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] = 'programesetting'; //controller name or tab name
      $active[1] = 'labdevices'; //controller name
// do name  // switch($do)
      switch ($acty) {
         case '':$active[2] = 'show';
            break;
         case 'show':$active[2] = 'show';
            break;
         default :$active[2] = 'show';
            break;
      }
      $this->active = $active;

      R::ext('xdispense', function ($type) {
         return R::getRedBean()->dispense($type);
      });

      require_once("branch_common.php");
      require_once("visits_common.php"); //general functions
//here will call all php pages
      require_once("_header.php");
      require_once("_sidebar.php");
      require_once("_leftsidebar.php");
      require_once("_footer.php");

//find loading time
      $this->time = microtime(true);
      $this->today = date('Y-m-d');
   }

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

#################################################################### Heba : ## get all investigation category ##############################################################################
      $devices = R::findall('lab_devices', 'deleted != 1 and completed = 1 ');
      $this->smarty->assign('devices', $devices);
################################################################################################################################################################################
//call other class with other content
      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      $this->smarty->display('labdevices/show.html');
      leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
      footer::footershow($this->smarty, $this->hosturl);
   }

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

      $device = R::findOne('lab_devices', 'completed = 0 and deleted = 0 ');
      if (count($device) <= 0) {
         $device = R::xdispense('lab_devices');
         $device->completed = 0;
         $device->user_id = $_SESSION['user_id'];
         $deviceId = R::store($device);
      } else {
         $deviceId = $device->id;
      }


      $this->loadInvests();
      $this->loadDevice($deviceId);

      $this->smarty->assign('is_add', 1);
      $this->smarty->assign('tableName', 'lab_devices');
      $this->smarty->assign('show', 'show');
################################################################################################################################################################################
//call other class with other content
      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      $this->smarty->display('labdevices/device.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']);

      $deviceId = filter_input(INPUT_GET, "id");

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

   public function update() {

//check login
      autho::checkautho($this->hosturl);

      $id = filter_input(INPUT_POST, "id");
      $tablename = filter_input(INPUT_POST, "tableName");
      $colname = filter_input(INPUT_POST, "colName");
      $value = filter_input(INPUT_POST, "value");

      try {
         $obj = R::load($tablename, $id);
         $obj->$colname = $value;
         R::store($obj);

//header('Location:' . $this->hosturl . '/controllers/' . $this->controllname.'.php?ac=index' );
      } catch (Exception $e) {
         header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
      }
   }

   public function del() {

//check login
      autho::checkautho($this->hosturl);

      $id = filter_input(INPUT_POST, "id");
      $tableName = filter_input(INPUT_POST, "tableName");

      try {
         $table_obj = R::load($tableName, $id);
         $table_obj->deleted = 1;
         $table_obj->delete_userid = $_SESSION['user_id'];
         $table_obj->delete_date = date('Y-m-d H:i:s');
         R::store($table_obj);

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

   public function loadInvests() {

      ################ Heba : ## Investigation data  #######################################

      $allInvCats1 = R::findall('investcats', 'deleted = ? and displayorder in (1 , 2) order by displayorder ', [0]);
      foreach ($allInvCats1 as $cat) {
         $invests = R::findall('invests', 'investcatid = ? and deleted = ?', [$cat->id, 0]);
         $cat->invests = $invests;
      }

      $allInvCats2 = R::findall('investcats', 'deleted = ? and displayorder = 3 order by displayorder ', [0]);
      foreach ($allInvCats2 as $cat) {
         $invests = R::findall('invests', 'investcatid = ? and deleted = ?', [$cat->id, 0]);
         $cat->invests = $invests;
      }

      $allInvCats3 = R::findall('investcats', 'deleted = ? and displayorder in (4 , 5) order by displayorder ', [0]);
      foreach ($allInvCats3 as $cat) {
         $invests = R::findall('invests', 'investcatid = ? and deleted = ?', [$cat->id, 0]);
         $cat->invests = $invests;
      }

      $allInvCats4 = R::findall('investcats', 'deleted = ? and displayorder  between 6 and  11 order by displayorder ', [0]);
      foreach ($allInvCats4 as $cat) {
         $invests = R::findall('invests', 'investcatid = ? and deleted = ?', [$cat->id, 0]);
         $cat->invests = $invests;
      }

      $allInvCats5 = R::findall('investcats', 'deleted = ? and displayorder > 11 order by displayorder ', [0]);
      foreach ($allInvCats5 as $cat) {
         $invests = R::findall('invests', 'investcatid = ? and deleted = ?', [$cat->id, 0]);
         $cat->invests = $invests;
      }

      $others = R::findall('investcats', 'deleted = ? and displayorder = ?  order by displayorder ', [0, 0]);
      foreach ($others as $cat) {
         $invests = R::findall('invests', 'investcatid = ? and deleted = ?', [$cat->id, 0]);
         $cat->invests = $invests;
      }


      $this->smarty->assign('group1', $allInvCats1);
      $this->smarty->assign('group2', $allInvCats2);
      $this->smarty->assign('group3', $allInvCats3);
      $this->smarty->assign('group4', $allInvCats4);
      $this->smarty->assign('group5', $allInvCats5);
      $this->smarty->assign('others', $others);
   }

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

      $id = filter_input(INPUT_GET, 'id');
      $tableName = filter_input(INPUT_GET, 'tname');
      $show = filter_input(INPUT_GET, 'show');
      $patientid = filter_input(INPUT_GET, "patientid");
      try {

         R::exec('update  ' . $tableName . ' set completed = 1  WHERE id = ' . $id);

         if (!empty($patientid)) {
            header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=' . $show . '&patientid=' . $patientid);
         } else {
            header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=' . $show);
         }
      } catch (Exception $e) {
         print_r($e);
         //    header('Location:' . $this->hosturl . '/error/notadd/' . $this->controllname);
      }
   }

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

   public function loadDevice($deviceId) {
      $device = R::load('lab_devices', $deviceId);
      $this->smarty->assign('device', $device);
      $deviceInvests = $this->loadDeviceInvests($deviceId);
      $this->smarty->assign('deviceInvests', $deviceInvests);
   }

   public function loadDeviceInvests($deviceId) {
//        r::debug(true, 2);
      $invRanges = R::getAll('  select lab_devices_ranges.*  , investcats.name as catName 
             , invests.name as invName
                      from    lab_devices_ranges   
                      join  invests                                  on lab_devices_ranges.investid = invests.id
                      join  investcats                              on  invests.investcatid  = investcats.id  
                      where  lab_devices_ranges.device_id = ?   and lab_devices_ranges.deleted = 0   ', [$deviceId]);
//        r::debug(false);
      return $invRanges;
   }

   public function saveDeviceInvests() {
      $deviceId = filter_input(INPUT_POST, "deviceId");
      $investsList = $_POST['invCheck'];
      if (!empty($investsList)) {
         foreach ($investsList as $investId) {
            $deviceInvest = r::findAll('lab_devices_ranges', ' device_id = ? and investid = ?  and deleted = 0 '
                            , [$deviceId, $investId]);
            if (count($deviceInvest) <= 0) {
               $invest = R::load('invests', $investId);
               $this->saveRanges($investId, $deviceId, $invest->special_inv_type);
            }
         }
      }

      $deviceInvests = $this->loadDeviceInvests($deviceId);
      $this->smarty->assign('deviceInvests', $deviceInvests);
      $this->smarty->display('labdevices/chooseninv.html');
   }

   public function saveRanges($investId, $deviceId, $special_inv_type) {
      $invRanges = r::findAll('inv_ranges', 'investid = ?  and deleted = 0 and active = 1   ', [$investId]);
      foreach ($invRanges as $invRange) {
         $range = R::xdispense('lab_devices_ranges');
         $range->device_id = $deviceId;
         $range->investid = $investId;
         $range->special_inv_type = $special_inv_type;
         $range->invest_child = $invRange->invest_child;
         $range->range_txt = $invRange->range_txt;
         $range->agefrom = $invRange->agefrom;
         $range->ageto = $invRange->ageto;
         $range->age_units = $invRange->age_units;
         $range->gender = $invRange->gender;
         $range->range_low = $invRange->range_low;
         $range->range_high = $invRange->range_high;
         $range->invest_units = $invRange->invest_units;
         $range->deleted = 0;
         R::store($range);
      }
   }

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

   private function getDayNameFnAr($date) {
      $timestamp = strtotime($date);

      $day = date('w', $timestamp);

      switch ($day) {
         case 0:
            $name = 'الأحد  ';
            break;
         case 1:
            $name = ' الإثنين';
            break;
         case 2:
            $name = ' الثلاثاء';
            break;
         case 3:
            $name = 'الأربعاء ';
            break;
         case 4:
            $name = 'الخميس  ';
            break;
         case 5:
            $name = 'الجمعة ';
            break;
         case 6:
            $name = 'السبت ';
            break;
      }

      return $name;
   }

// at the end of class call
   public function __destruct() {
//echo "Time Elapsed: ".(microtime(true) - $this->time)."s";
//close connection
      R::close();
   }
}
