<?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 = 'operationreport';
      $this->shcontrollname = 'operationreport';
      $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] = 'operationreport'; //controller name or tab name
      $this->active = $active;

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

      require_once("visits_common.php"); //general functions
      require_once("invsdept_common.php"); //general functions
//here will call all php pages
      require_once("_header.php");
      require_once("_patientdata.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']);

      $patientNo = filter_input(INPUT_GET, 'patientNo');
      $deviceNo = filter_input(INPUT_GET, 'deviceId');

      if ($patientNo > 0) {
         $patientId = getPatientId($patientNo);
      }

      if ($deviceNo > 0) {
         $deviceId = getDeviceId($deviceNo);
      }

      if ($deviceId > 0 && $patientId > 0) {
         saveTrackingRecord($patientId, $deviceId, 0, '', 'operationreport');
      }

      $today = date("Y/m/d");
      $this->smarty->assign('today', date('Y/m/d', strtotime($today)));

      $all_users_th = R::getAll("select * from awusers");
      $this->smarty->assign('all_users_th', $all_users_th);

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

      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      $this->smarty->display('reports/operations.html');
      leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
      footer::footershow($this->smarty, $this->hosturl);
   }

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

      $fdate = filter_input(INPUT_POST, 'fdate');
      $todate = filter_input(INPUT_POST, 'todate');
      $patientId = filter_input(INPUT_POST, 'value');
      $hPatientId = filter_input(INPUT_POST, 'hvalue');
      $includeClinics = filter_input(INPUT_POST, 'includeClinics');
      $fordepartment = filter_input(INPUT_POST, 'fordepartment');

      $fdate = date('Y/m/d', strtotime($fdate));
      $todate = date('Y/m/d', strtotime($todate));

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

      if ($programesetting->past_search != 1) {
         $endDate = date("Y/m/d", strtotime("- 2 days", strtotime(date('Y/m/d'))));
         if ($fdate < $endDate) {
            $fdate = $endDate;
         }
      }

      $ext = '';
      if (!empty($patientId) && $patientId > 0) {
         $ext .= ' and visits.patientid = ' . $patientId;
      } elseif (!empty($hPatientId) && $hPatientId > 0) {
         $ext .= ' and visits.patientid = ' . $hPatientId;
      }

      //here will load the menu show
      $operations_rooms = R::findAll('operations_rooms', ' deleted != 1 ');
      $this->smarty->assign('operations_rooms', $operations_rooms);

      $residence_rooms = R::findAll('residence_rooms', ' deleted != 1 ');
      $this->smarty->assign('residence_rooms', $residence_rooms);

      $allowAttend = 0;
      $allowOp = 0;
      $allowRes = 0;
      $btn16 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 16  ', [$_SESSION['role_id']]);
      if (count($btn16) > 0) {
         $allowAttend = $btn16->checkval;
      }

      $btn17 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 17  ', [$_SESSION['role_id']]);
      if (count($btn17) > 0) {
         $allowOp = $btn17->checkval;
      }

      $btn18 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 18  ', [$_SESSION['role_id']]);
      if (count($btn18) > 0) {
         $allowRes = $btn18->checkval;
      }

      $this->smarty->assign('allowAttend', $allowAttend);
      $this->smarty->assign('allowOp', $allowOp);
      $this->smarty->assign('allowRes', $allowRes);
      $this->smarty->assign('includeClinics', $includeClinics);

      if (!empty($includeClinics) && $includeClinics == 1) {
         $ext .= ' and  visits.for_department not in ( 5 , 12 ) ';
      } else {
         $ext .= ' and  visits.for_department = 13 ';
      }

      $allData = R::getAll('select detections.title as type, visits.patientid, visits.operation_result
                                , visits.id as visit_id, visits.for_department ,  visits.printorder , visits.visitdate
                                , visits.for_husband, visits.for_doctor, visits.operation_time  , visits.place
                                , visits.room_no, visits.enterance, visits.p_exit  ,visits.operation_attend  as attend   
                                , patients.wifename, patients.husdandname, patients.statusno   ,   organizations.organization_name
                                 ,visits.res_room_no  , visits.res_enterance ,visits.res_p_exit 
                                    , visits.recep_enterance ,visits.recep_p_exit  ,  awusers.name as for_doctor_name  
                                    ,  detections.operation_time   ,  detections.residence_time ,    awrole.name AS deptName  
                                     ,visits.rec_card_add  , visits.op_card_add   ,  visits.bed_no, "" as date_diff
                                    
                                from visits    
                                 join   patients       on visits.patientid = patients.id 
                                  join   detections     on visits.detectionid = detections.id  
                                left join   awusers   on awusers.user_id  = visits.for_doctor 
                                      left join   awrole   on awrole.id  = visits.for_department       
                                         left join   organizations   on organizations.id  = visits.organization_id       
                                where visits.deleted = 0     and visitdate >= "' . $fdate . '" and visitdate <= "' . $todate . '" ' . $ext);

      $i = 0;
      foreach ($allData as $value) {
         $diff = '';
         if (is_null($value['recep_enterance']) || $value['recep_enterance'] == '' || is_null($value['res_p_exit']) || $value['res_p_exit'] == '') {
            $diff = '';
         } else {
            $enter = $value['visitdate'] . ' ' . $value['recep_enterance'];
            $enter = new DateTime($enter);
            $exit = new DateTime($value['res_p_exit']);
            $interval = $exit->diff($enter);
            //  $diff = $interval->d . ':' . $interval->h . ':' . $interval->i;

            $t = 0;
            if ($interval->d > 0) {
               $diff .= $interval->d . 'D';
               $t++;
            }

            if ($interval->h > 0) {
               if ($t > 0) {
                  $diff .= ',';
               }
               $diff .= $interval->h . 'H';
               $t++;
            }

            if ($interval->i > 0) {
               if ($t > 0) {
                  $diff .= ',';
               }
               $diff .= $interval->i . 'M';
               $t++;
            }
         }
         $allData[$i]['date_diff'] = $diff;

         $i++;
      }


      $this->smarty->assign('fdate', $fdate);
      $this->smarty->assign('todate', $todate);
      $this->smarty->assign('allData', $allData);
      $this->smarty->display('reports/operationssearch.html');
   }

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

      $fdate = filter_input(INPUT_POST, 'fdate');
      $todate = filter_input(INPUT_POST, 'todate');
      $patientId = filter_input(INPUT_POST, 'value');
      $hPatientId = filter_input(INPUT_POST, 'hvalue');
      $includeClinics = filter_input(INPUT_POST, 'includeClinics');
      $fordepartment = filter_input(INPUT_POST, 'fordepartment');

      $ext = '';
      if (!empty($patientId) && $patientId > 0) {
         $ext .= ' and visits.patientid = ' . $patientId;
      } elseif (!empty($hPatientId) && $hPatientId > 0) {
         $ext .= ' and visits.patientid = ' . $hPatientId;
      }



      $nab_1_users = filter_input(INPUT_POST, 'nab_1_users');
      $this->smarty->assign('nab_1_users', $nab_1_users);
      $nab_2_users = filter_input(INPUT_POST, 'nab_2_users');
      $this->smarty->assign('nab_2_users', $nab_2_users);
      $lab_1_users = filter_input(INPUT_POST, 'lab_1_users');
      $this->smarty->assign('lab_1_users', $lab_1_users);
      $lab_2_users = filter_input(INPUT_POST, 'lab_2_users');
      $this->smarty->assign('lab_2_users', $lab_2_users);
      $sleep_1_users = filter_input(INPUT_POST, 'sleep_1_users');
      $this->smarty->assign('sleep_1_users', $sleep_1_users);
      $sug_1_users = filter_input(INPUT_POST, 'sug_1_users');
      $this->smarty->assign('sug_1_users', $sug_1_users);

      $fdate = date('Y/m/d', strtotime($fdate));
      $todate = date('Y/m/d', strtotime($todate));

      if (!empty($includeClinics) && $includeClinics == 1) {
         $ext .= ' and  visits.for_department not in ( 5 , 12 ) ';
      } else {
         $ext .= ' and  visits.for_department = 13 ';
      }

      $allData = R::getAll('select detections.title as type, visits.patientid, visits.operation_result , visits.place
                                , visits.id as visit_id, visits.for_department ,  visits.printorder , visits.visitdate
                                , visits.for_husband, visits.for_doctor, visits.operation_time ,   organizations.organization_name
                                , operations_rooms.name as room_no, visits.enterance, visits.p_exit  ,visits.operation_attend  as attend   
                                , patients.wifename, patients.husdandname, patients.statusno  ,    awrole.name AS deptName  
                                 ,residence_rooms.name as res_room_no  , visits.res_enterance ,visits.res_p_exit 
                                    , visits.recep_enterance ,visits.recep_p_exit  ,  awusers.name as for_doctor_name 
                                    , CASE    WHEN visits.place = 1  THEN " التحضير "    
                                     WHEN visits.place = 2  THEN " القسطرة "     
                                     WHEN visits.place = 3  THEN " عناية مركزة "     
                                     WHEN visits.place = 4  THEN " خروج "     
                                     ELSE " "    END as place 
                                 
                                from visits    
                                 join   patients       on visits.patientid = patients.id 
                                  join   detections     on visits.detectionid = detections.id  
                                left join   awusers   on awusers.user_id  = visits.for_doctor  
                                 left join   awrole   on awrole.id  = visits.for_department       
                                    left join   organizations   on organizations.id  = visits.organization_id       
                                left join operations_rooms   on operations_rooms.id  = visits.room_no 
                                   left join residence_rooms   on residence_rooms.id  = visits.res_room_no 
                                where visits.deleted = 0  and visitdate >= "' . $fdate . '" and visitdate <= "' . $todate . '"  ' . $ext);

      $all_users_th = R::getAll("select * from awusers");
      $this->smarty->assign('all_users_th', $all_users_th);

      $this->smarty->assign('fdate', $fdate);
      $this->smarty->assign('todate', $todate);
      $this->smarty->assign('includeClinics', $includeClinics);
      $this->smarty->assign('allData', $allData);
      $this->smarty->display('reports/operationsprint.html');
   }

   public function onesetup() {

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

      try {
         //delete all but with only default
         #1 clean roles only managment
         #2 clean menu only default
         #3 clean controls only default
         #4 users clean users
         #delete all menus
         $menus = R::findAll('awmenu', 'id > 15');
         #delete from awrolemenu
         foreach ($menus as $one) {
            //get propes
            $rolemenu = R::findAll('awrolemenu', 'menu_id = ?', [$one->id]);
            R::trashAll($rolemenu);
         }
         R::trashAll($menus);
         #delete controles
         $controlls = R::findAll('awcontroll', 'id > 4 and id < 18');
         foreach ($controlls as $one) {
            //get propes
            $inprop = R::findAll('awcontrollprop', 'awcontroll_id = ?', [$one->id]);
            #delete from awrolecontroleprop
            foreach ($inprop as $one) {
               //get propes
               $roleprop = R::findAll('awrolecontrollprop', 'controllprop_id = ?', [$one->id]);
               R::trashAll($roleprop);
            }
            R::trashAll($inprop);
         }
         R::trashAll($controlls);
         #delete othre roles
         $roles = R::findAll('awrole', 'id > 1');
         R::trashAll($roles);
         #delete other users
         //$users = R::findAll('awusers', 'user_id > 1');
         //R::exec('Delete from awusers where user_id > 1');
         //R::trashAll($users);
         ############################
         //new one
         $menusx = R::findAll('awmenu', ' id = 4 or id = 5 or id = 7 or id = 8 or id = 10 or id = 11 or id = 13 or id = 14 or id = 15 ');
         #delete from awrolemenu
         foreach ($menusx as $one) {
            //get propes
            $rolemenu = R::findAll('awrolemenu', 'menu_id = ?', [$one->id]);
            R::trashAll($rolemenu);
         }
         R::trashAll($menusx);

         print_r('trash all, install is good');
      } catch (Exception $ex) {
         print_r('something go wrong, try again');
      }
   }

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

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

      $names = array('recep_enterance', 'recep_p_exit', 'res_enterance', 'enterance', 'p_exit');

      if (in_array($colname, $names)) {
         if ($value == "") {
            $value = Null;
         } else {
            $value = date('H:i', strtotime($value));
         }
      }

      $name2 = array('res_p_exit');
      if (in_array($colname, $name2)) {
         if ($value == "") {
            $value = Null;
         } else {
            $value = date('Y/m/d H:i', strtotime($value));
         }
      }


      $obj = R::load($tablename, $id);
      $obj->$colname = $value;
      if ($colname === 'res_enterance') {
         if ($value == "" || $value == null) {
            $obj->res_enterance_date = null;
         } else {
            $resEnterDate = date('H:i', strtotime($value));
            $visitDate = date('Y/m/d', strtotime($obj->visitdate));
            $obj->res_enterance_date = date($visitDate . ' ' . $resEnterDate);
         }
      }
      R::store($obj);
   }

   ###################################  Operation reserve report  ####################

   public function reserve() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
//here will load the menu show
//R::debug(true);

      $operation_types = R::findAll('detections', ' del != 1 and for_operation = 1 ');
      $this->smarty->assign('operation_types', $operation_types);

      $operations_rooms = R::findAll('operations_rooms', 'deleted != 1');
      $this->smarty->assign('operations_rooms', $operations_rooms);

      $residence_rooms = R::findAll('residence_rooms', 'deleted != 1');
      $this->smarty->assign('residence_rooms', $residence_rooms);

      $role = R::findOne('awrole', ' id  = 13');
      $doctors = R::getAll('select * from awusers where user_active = 1 and  role_id in ( ? ) ', [$role->related_dr_depts]);
      $this->smarty->assign('doctors', $doctors);

      $today = date('Y-m-d');
      $this->smarty->assign('today', date('Y-m-d', strtotime($today)));

      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      $this->smarty->display('reports/reserves/operations_reserves.html');
      leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
      footer::footershow($this->smarty, $this->hosturl);
   }

   public function reserveSearch() {
//check login
      autho::checkautho($this->hosturl);

      $operation_date = filter_input(INPUT_POST, 'operation_date');
      $doctor_id = filter_input(INPUT_POST, 'doctor_id');
      $operation_type_id = filter_input(INPUT_POST, 'operation_type_id');
      $show_result = filter_input(INPUT_POST, 'show_result');
      $operations_room_ids = $_POST['operations_rooms'];
      if ($_POST['operations_rooms']) {
         $operations_room_id = implode(',', $_POST['operations_rooms']);
      }

      $residence_room_ids = $_POST['residence_rooms'];
      if ($_POST['residence_rooms']) {
         $residence_room_id = implode(',', $_POST['residence_rooms']);
      }


      if ($operation_date) {

         if ($show_result == 1 || $show_result == 2) {
            $query_search = '1 = 1';
            $query_search .= ' AND the_date = "' . $operation_date . '" ';
            if ($doctor_id) {
               $query_search .= ' AND doctor_id = ' . $doctor_id . ' ';
            }

            if ($operations_room_id) {
               if ($operations_room_id != -1) {
                  $query_search .= ' AND operations_rooms_id in  (' . $operations_room_id . ') ';
               }
            }

            if ($residence_room_id) {
               if ($residence_room_id != -1) {
                  $query_search .= ' AND residence_rooms_id in  (' . $residence_room_id . ') ';
               }
            }

            if ($operation_type_id) {
               $query_search .= ' AND operation_types_id = ' . $operation_type_id . ' ';
            }

            // search in operations
            $operations_main = R::find('operations_main', $query_search);
//                R::loadJoined($operations_main, 'residence_rooms');
//                R::loadJoined($operations_main, 'operations_rooms');
//                R::loadJoined($operations_main, 'detections');
            foreach ($operations_main as $item) {

               $op_room = R::load('operations_rooms', $item->operations_rooms_id);
               $item->operations_room_name = $op_room->name;

               $res_room = R::load('residence_rooms', $item->residence_rooms_id);
               $item->residence_room_name = $res_room->name;

               $detection = R::load('detections', $item->operation_types_id);
               $item->operation_type = $detection->title;
//                    R::selectDatabase('obgy');
               $doctor_info = R::getRow('select * from awusers where user_active = 1 and user_id = ?', [$item->doctor_id]);
               $item->doctor_name = $doctor_info['name'];
//                    R::selectDatabase('default');
               // calculate operation hours
               $operation_hours_arr = explode(',', $item->operation_hours);
               $operation_endTime = date("h:i a", strtotime('+30 minutes', strtotime($operation_hours_arr[count($operation_hours_arr) - 1])));
               $item->operation_hours_text = 'من ' . date("h:i a", strtotime($operation_hours_arr[0])) . ' الي ' . $operation_endTime;

               // calculate residence hours
               $residence_hours_arr = explode(',', $item->residence_hours);
               $residence_endTime = date("h:i a", strtotime('+60 minutes', strtotime($residence_hours_arr[count($residence_hours_arr) - 1])));
               $item->residence_hours_text = 'من ' . date("h:i a", strtotime($residence_hours_arr[0])) . ' الي ' . $residence_endTime;
            }
            $this->smarty->assign('operations_main', $operations_main);
         }


         if ($show_result == 1 || $show_result == 3) {

            //day times
            $operation_day_times = [
                '00:00', '00:30', '01:00', '01:30', '02:00', '02:30', '03:00', '03:30', '04:00', '04:30', '05:00', '05:30',
                '06:00', '06:30', '07:00', '07:30', '08:00', '08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30',
                '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00', '17:30',
                '18:00', '18:30', '19:00', '19:30', '20:00', '20:30', '21:00', '21:30', '22:00', '22:30', '23:00', '23:30'];

            // operation report
            $room_query = '1 = 1';
            if ($operations_room_id) {
               if ($operations_room_id != -1) {
                  $room_query .= ' AND id in  (' . $operations_room_id . ') ';
               }
            }

            $searched_operations_rooms = R::findAll('operations_rooms', $room_query);
            foreach ($searched_operations_rooms as $operations_room) {
               $operation_times = [];
               foreach ($operation_day_times as $day_time) {
                  $saved_id = 0;
                  // check if time in room start and end time
                  if (strtotime($day_time) <= strtotime($operations_room->end_time) &&
                          strtotime($day_time) >= strtotime($operations_room->start_time)) {


                     // get reserve info if there
                     $doctor_reserve = R::findOne('doctors_reserves', 'operations_room_id = ? and hour_text = ? and the_date = ?', [$operations_room->id, $day_time, $operation_date]);
                     if ($doctor_reserve) {
                        $color = 'red'; // not active , done
                        $no = 1;
//                                R::selectDatabase('obgy');
                        $doctor_info_in = R::getRow('select * from awusers where user_id = ?', [$doctor_reserve->doctor_id]);
                        $saved_id = $doctor_info_in['name'];
//                                R::selectDatabase('default');
                     } else {
                        $color = 'green';
                        $no = 0; // active
                     }
                  } else {
                     $color = 'grey';
                     $no = 3; // disabled
                  }

                  $sin = [
                      'hour_text' => $day_time,
                      'status' => $no,
                      'color' => $color,
                      'saved_id' => $saved_id
                  ];

                  $operation_times[] = $sin;
               }
               $operations_room->times = $operation_times;
            }
            $this->smarty->assign('searched_operations_rooms', $searched_operations_rooms);
         }

         if ($show_result == 1 || $show_result == 4) {

            //day times
            $residence_day_times = [
                '00:00', '01:00', '02:00', '03:00', '04:00', '05:00',
                '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
                '12:00', '13:00', '14:00', '15:00', '16:00', '17:00',
                '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'];

            // operation report
            $red_room_query = '1 = 1';
            if ($residence_room_id) {
               if ($residence_room_id != -1) {
                  $red_room_query .= ' AND id in  (' . $residence_room_id . ') ';
               }
            }

            $searched_residence_rooms = R::findAll('residence_rooms', $red_room_query);
            foreach ($searched_residence_rooms as $residence_room) {
               $residence_times = [];
               foreach ($residence_day_times as $day_time) {
                  $saved_id = 0;
                  // check if hour is reserve
                  $room_reserve = R::findOne('residence_reserves', 'hour_text = ? and the_date = ? and residence_room_id = ?', [$day_time, $operation_date, $residence_room->id]);
                  if ($room_reserve) {
                     $no = 1;
                     $color = 'red';
//                            R::selectDatabase('obgy');
                     $doctor_info_in = R::getRow('select * from awusers where user_id = ?', [$room_reserve->doctor_id]);
                     $saved_id = $doctor_info_in['name'];
//                            R::selectDatabase('default');
                  } else {
                     $no = 0;
                     $color = 'green';
                  }

                  $sin = [
                      'hour_text' => $day_time,
                      'status' => $no,
                      'color' => $color,
                      'saved_id' => $saved_id
                  ];
                  // check if hour is available
                  $residence_times[] = $sin;
               }
               $residence_room->times = $residence_times;
            }
            $this->smarty->assign('searched_residence_rooms', $searched_residence_rooms);
         }
      }

      $this->smarty->display('reports/reserves/reserve_result.html');
   }

   ###################################  Operation Data report  ######################

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

      $floors = R::getAll('SELECT DISTINCT floor_no FROM operations_rooms 
                WHERE floor_no > 0 ORDER BY floor_no');

      $floors_arr = [];

      foreach ($floors as $floor) {
         $floor = (object) $floor;
         $o_rooms = R::findAll('operations_rooms', 'floor_no = ? and deleted = 0', [$floor->floor_no]);
         $time_now = date('H:i');
         $today = date('Y-m-d');

         foreach ($o_rooms as $o_room) {

            $visit = R::findOne('visits', 'room_no = ?  and  visitdate = ?
                        and (TIME(enterance) <= TIME("' . $time_now . '"))  and 
                            (TIME(p_exit)  >= TIME("' . $time_now . '")) 
                        and deleted = 0 order by id desc'
                            , [$o_room->id, $today]);

            if (count($visit) > 0) {

               $patient = R::getRow('SELECT patients.*  ,  wifetypes.title as wType  ,  husbandtypes.title as hType     
                    FROM patients 
                        left join  wifetypes   on  patients.wiftypeid  =   wifetypes.id   
                          left join  husbandtypes   on  patients.husbandtypeid  =   husbandtypes.id  
                          WHERE patients.id = "' . $visit->patientid . '"   ');

               if ($visit->for_husband == 1) {
                  $patientName = $patient['hType'] . ' / ' . $patient['husdandname'];
               } else if ($visit->for_husband == 2) {
                  $child = R::load('patients_childs', $visit->child);
                  if (is_null($child->child_name) || $child->child_name == '') {
                     if ($child->gender == 1) {
                        $patientName = 'الطفل / ' . $patient['wifename'];
                     } else {
                        $patientName = 'الطفلة / ' . $patient['wifename'];
                     }
                  } else {
                     $patientName = $child->child_name . '  /  ' . $patient['wifename'];
                  }
               } else {
                  $patientName = $patient['wType'] . ' / ' . $patient['wifename'];
               }

               $drName = '';
               if (!empty($visit->for_doctor)) {
                  $doc_info = R::getRow('select * from awusers where user_id = ?', [$visit->for_doctor]);
                  $drName = $doc_info['name'];
               }

               $detection = R::load('detections', $visit->detectionid);

               $o_room->visitId = $visit->id;
               $o_room->patientName = $patientName;
               $o_room->patientId = $patient['id'];
               $o_room->drName = $drName;
               $o_room->detectionName = $detection->title;
               $o_room->visitCount = 1;
            } else {
               $o_room->visitCount = 0;
            }
         }
         $floor->o_rooms = $o_rooms;

         $flor = R::load('floors', $floor->floor_no);
         $floor->floorName = $flor->name;

         $floors_arr[] = $floor;
      }

      $this->refresh(300);
      $this->smarty->assign('floors_arr', $floors_arr);

      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      $this->smarty->display('operation_data/show.html');
      leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
      footer::footershow($this->smarty, $this->hosturl);
   }

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

      $visitId = filter_input(INPUT_GET, 'id');
      $opPatId = filter_input(INPUT_GET, 'patientid');
      $patientNo = filter_input(INPUT_GET, 'patientNo');
      $deviceNo = filter_input(INPUT_GET, 'deviceId');

      if ($patientNo > 0 && !($opPatId > 0 )) {
         $opPatId = getPatientId($patientNo);
      }

      if ($deviceNo > 0) {
         $deviceId = getDeviceId($deviceNo);
      }

      if ($deviceId > 0 && $opPatId > 0) {
         saveTrackingRecord($opPatId, $deviceId, 0, '', 'operation_data');
      }

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

      if ($visitId > 0) {
         $visit = R::load('visits', $visitId);
      } else {
         $this->smarty->assign('opPatId', $opPatId);
         $visit = R::findOne('visits', ' for_department = 13  and deleted = 0 and patientid = ?
                  and detectionid != 999  and detectionid != 9999 and visitdate <=  ?   order by visitdate desc'
                         , [$opPatId, date('Y-m-d')]);
         $visitId = $visit->id;
      }

      if ($visitId > 0 && $deviceId > 0) {
         R::exec('update visits set op_card_add = 1  
                        , enterance =   "' . date("H:i") . '" 
                        where id = ' . $visitId . '  and ( enterance  IS NULL  or enterance = "")');
         $device = R::load('devices', $deviceId);
         if ($device->location == 2 && $device->room_no > 0) {
            R::exec('update visits set room_no  =  ' . $device->room_no . ' 
                        where id = ' . $visitId . '  and ( room_no  IS NULL  or room_no = ""  or not room_no >=  1)');
         }
      }

      $this->smarty->assign('visitDate', $visit->visitdate);

      $labVisit = R::findOne('visits', ' for_department = 12  and deleted = 0 and patientid = ? and for_husband = ? 
                  and detectionid != 999  and detectionid != 9999 and visitdate <= ?   order by visitdate desc'
                      , [$visit->patientid, $visit->for_husband, $visit->visitdate]);

      $this->board_details($visitId);
      $patData = $this->visit_details($visit);

      if (count($labVisit) > 0) {
         $labVisitCount = 1;
         //     $this->lab_details($labVisit->id, $patData);
      } else {
         $labVisitCount = 0;
      }

      $raysVisit = R::findAll('visits', ' for_department = 5  and deleted = 0 and patientid = ? and for_husband = ? 
                  and detectionid != 999  and detectionid != 9999    order by visitdate desc'
                      , [$visit->patientid, $visit->for_husband]);

      if (count($raysVisit) > 0) {
         $raysVisits = loadRays($visit->patientid);
         $this->smarty->assign('raysVisits', $raysVisits);
      }

      $this->picsAndVideos($visit->patientid);

      $this->smarty->assign('labVisit', $labVisit);
      $this->smarty->assign('labVisitId', $labVisit->id);
      $this->smarty->assign('labVisitDate', $labVisit->visitdate);
      $this->smarty->assign('labVisitCount', $labVisitCount);
      $this->smarty->assign('raysVisitCount', count($raysVisit));
      $this->smarty->assign('visitCount', count($visit));

      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      //   patientdata::patientdatashow($this->smarty, $this->hosturl);
      $this->smarty->display('operation_data/details.html');
      leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
      footer::footershow($this->smarty, $this->hosturl);
   }

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

      $board = R::findOne('operation_data', ' visit_id = ?   and deleted = 0 ', [$visitId]);
      if (count($board) < 1 && $visitId > 0) {
         $board = R::xdispense('operation_data');
         $board->visit_id = $visitId;
         $board->deleted = 0;
         $board->id = R::store($board);
      }

      $this->smarty->assign('board', $board);
      $this->smarty->assign('boardCount', count($board));

      $anaesthetists = R::getAll("select* from awusers where role_id = 7");
      $this->smarty->assign('anaesthetists', $anaesthetists);

      $nurses = R::getAll("select* from awusers where role_id = 6");
      $this->smarty->assign('nurses', $nurses);
   }

   public function visit_details($visit) {

      $drName = '';
      if (!empty($visit->for_doctor)) {
         $doc_info = R::getRow('select * from awusers where user_id = ?', [$visit->for_doctor]);
         $drName = $doc_info['name'];
      }

      $patient = R::getRow('SELECT patients.*  ,  wifetypes.title as wType  ,  husbandtypes.title as hType     
                    FROM patients 
                        left join  wifetypes   on  patients.wiftypeid  =   wifetypes.id   
                          left join  husbandtypes   on  patients.husbandtypeid  =   husbandtypes.id  
                          WHERE patients.id = "' . $visit->patientid . '"   ');

      if ($visit->for_husband == 1) {
         $patientName = $patient['hType'] . ' / ' . $patient['husdandname'];
         $date = $patient->husbanddateofbirth;
         $gender = 1;
      } else if ($visit->for_husband == 2) {
         $child = R::load('patients_childs', $visit->child);
         $date = $child->birth_date;

         if ($child->gender == 1) {
            $gender = 1;
         } else {
            $gender = 0;
         }

         if (is_null($child->child_name) || $child->child_name == '') {
            if ($child->gender == 1) {
               $patientName = 'الطفل / ' . $patient['wifename'];
            } else {
               $patientName = 'الطفلة / ' . $patient['wifename'];
            }
         } else {
            $patientName = $child->child_name . '  /  ' . $patient['wifename'];
         }
      } else {
         $patientName = $patient['wType'] . ' / ' . $patient['wifename'];
         $date = $patient->dateofbirth;
         $gender = 0;
      }

      $detection = R::load('detections', $visit->detectionid);

      $this->smarty->assign('detectionName', $detection->title);
      $this->smarty->assign('drName', $drName);
      $this->smarty->assign('patientName', $patientName);
      $this->smarty->assign('visPatientName', $patientName);
      if ($patient['id'] > 0) {
         $this->smarty->assign('opPatId', $patient['id']);
      }


      $result = array(
          "date" => $date,
          "gender" => $gender
      );

      return $result;
   }

   public function pat_details($visitId) {
      $visit = R::load('visits', $visitId);
      $programesetting = R::findOne('programesetting');
      $patient = R::getRow('SELECT husbanddateofbirth , wifename  , dateofbirth
                    FROM patients 
                          WHERE patients.id = "' . $visit->patientid . '"   ');

      if ($programesetting->system_lang == 2) {
         $date = $patient['dateofbirth'];
         $name = $patient['wifename'];
         $gender = $patient['gender'];
      } else {
         if ($visit->for_husband == 1) {
            $date = $patient['husbanddateofbirth'];
            $name = $patient['husdandname'];
            $gender = 1;
         } else if ($visit->for_husband == 2) {
            $child = R::load('patients_childs', $visit->child);
            $gender = $child->gender;
            $date = $child->birth_date;

            if (is_null($child->child_name) || $child->child_name == '') {
               if ($child->gender == 1) {
                  $name = 'الطفل / ' . $patient['wifename'];
               } else {
                  $name = 'الطفلة / ' . $patient['wifename'];
               }
            } else {
               $name = $child->child_name . '  /  ' . $patient['wifename'];
            }
         } else {
            $date = $patient['dateofbirth'];
            $name = $patient['wifename'];
            $gender = 0;
         }
      }

      $result = array(
          "date" => $date,
          "name" => $name,
          "gender" => $gender
      );

      return $result;
   }

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

      $visitId = filter_input(INPUT_POST, 'labVisitId');

      $this->lab_details_ex($visitId);
   }

   public function lab_details_ex($visitId) {

      $patData = $this->pat_details($visitId);

      if ($patData['date'] == '0000-00-00' || is_null($patData['date']) || $patData['date'] == '') {
         $age = 0;
      } else {
## calculate wife age
         $dateWife = new DateTime($patData['date']);
         $today1 = new DateTime(date('Y-m-d'));
         $interval = $today1->diff($dateWife);
      }

      if ($interval->y > 0) {
         $ageAll = $interval->y . ' Years';
         $age = $interval->y;
         $ageUnit = 1;
      } elseif ($interval->m > 0) {
         $ageAll = $interval->m . ' Months';
         $age = $interval->m;
         $ageUnit = 2;
      } elseif ($interval->d > 0) {
         $ageAll = $interval->d . ' Days';
         $age = $interval->d;
         $ageUnit = 3;
      }

      $this->smarty->assign('age', $ageAll);

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

      $invResIds = array();
      $invRes = R::findall('investigationresults', 'deleted = ? and visitid = ? ', [0, $visitId]);
      foreach ($invRes as $data) {
         $invResIds[] = $data->id;
      }

      investsForPrint($invResIds, $patData['gender'], $age, $ageUnit, $this->smarty, 5);
   }

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

      $opPatId = filter_input(INPUT_GET, 'patientid');
      $opPatNo = getPatientNo($opPatId);
      $this->smarty->assign('opPatNo', $opPatNo);

      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      $this->smarty->display('operation_data/showall.html');
      leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
      footer::footershow($this->smarty, $this->hosturl);
   }

   public function operation_search() {
//check login
      //autho::checkautho($this->hosturl);


      $patientId = filter_input(INPUT_POST, 'value');
      $hPatientId = filter_input(INPUT_POST, 'hvalue');

      if (!empty($patientId) && $patientId > 0) {
         $ext .= ' and visits.patientid = ' . $patientId;
      } elseif (!empty($hPatientId) && $hPatientId > 0) {
         $ext .= ' and visits.patientid = ' . $hPatientId;
      }

      $sql = 'select distinct  visits.id  as visitId ,  detections.title as detectionName ,   visits.visitdate
                  ,visits.for_husband , patients.wifename, patients.husdandname , visits.patientid
                ,  operations_rooms.name as roomNo    ,  awusers.name as drName 
                   from visits  
                               join  patients                         on  visits.patientid = patients.id 
                               left join  detections                on  visits.detectionid = detections.id 
                               left join  operations_rooms    on  visits.room_no = operations_rooms.id 
                               left join  awusers                 on  visits.for_doctor = awusers.user_id 
                         where visits.deleted = 0 and  visits.for_department = 13 
                         ' . $ext . '  and visits.detectionid != 999  and visits.detectionid != 9999  order by visits.visitdate desc';

      $allData = R::getAll($sql);
      $this->smarty->assign('allData', $allData);
      $this->smarty->assign('allDataCount', count($allData));
      $this->smarty->display('operation_data/showall_search.html');
   }

   public function sheet_details() {
//check login
      //autho::checkautho($this->hosturl);

      $patientNo = filter_input(INPUT_POST, 'opPatNo');
      $opPatId = filter_input(INPUT_POST, 'opPatId');

      if ($patientNo > 0 && !($opPatId > 0 )) {
         $opPatId = getPatientId($patientNo);
      }

      caseSummary($opPatId, 0, $this->smarty);
   }

   public function rays_details() {
//check login
      //autho::checkautho($this->hosturl);

      $opPatId = filter_input(INPUT_POST, 'opPatId');

      caseSummary($opPatId, 0, $this->smarty);
   }

   // write the function
   public function refresh($time) {
      $current_url = $_SERVER['REQUEST_URI'];
      return header("Refresh: " . $time . "; URL=$current_url");
   }

   public function getrayimg() {

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

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

      $imgs = R::findall('raysresults_img', 'deleted = ? and raysresults_id = ? ', [0, $id]);

      $this->smarty->assign('imgs', $imgs);
      $this->smarty->display('operation_data/scrollimg.html');
   }

   function picsAndVideos($patientId) {
      $pics = R::getAll('select id, sonardate , imagename , notes , originalname from sonar 
                where tempdelete = 0 and type = 0 and patientid = ?  order by sonardate desc', [$patientId]);
      $videos = R::getAll('select id, sonardate , vediourl , originalname from sonar 
                where tempdelete = 0 and type = 1  and patientid = ?  order by sonardate desc', [$patientId]);
      $pdfs = R::getAll('select id, sonardate , vediourl , originalname from sonar 
                where tempdelete = 0 and type = 2  and patientid = ?  order by sonardate desc', [$patientId]);

      $this->smarty->assign('pics', $pics);
      $this->smarty->assign('picsCount', count($pics));
      $this->smarty->assign('videos', $videos);
      $this->smarty->assign('videosCount', count($videos));
      $this->smarty->assign('pdfs', $pdfs);
      $this->smarty->assign('pdfCount', count($pdfs));
   }

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

   public function tab1_content() {
//check login
      //autho::checkautho($this->hosturl);

      $patientNo = filter_input(INPUT_POST, 'opPatNo');
      $opPatId = getPatientId($patientNo);
      $deviceNo = filter_input(INPUT_POST, 'deviceNo');

      if ($deviceNo > 0) {
         $deviceId = getDeviceId($deviceNo);
      }

      if ($deviceId > 0) {
         saveTrackingRecord($opPatId, $deviceId, 0, '', 'operation_data');
      }


      $visit = R::findOne('visits', ' for_department = 13 and deleted = 0 and patientid = ?
        and detectionid != 999 and detectionid != 9999 and visitdate <= ? order by visitdate desc'
                      , [$opPatId, date('Y-m-d')]);

      if (count($visit) > 0) {

         if ($visit->id > 0) {
            R::exec('update visits set op_card_add = 1  
                        , enterance =   "' . date("H:i") . '" 
                        where id = ' . $visit->id . '  and ( enterance  IS NULL  or enterance = "")');
         }

         $labVisit = R::findOne('visits', ' for_department = 12 and deleted = 0 and patientid = ? and for_husband = ? 
        and detectionid != 999 and detectionid != 9999 and visitdate <= ? order by visitdate desc'
                         , [$opPatId, $visit->for_husband, date('Y-m-d')]);

         if (count($labVisit) > 0) {
            $labVisitCount = 1;
            $this->smarty->assign('labVDate', $labVisit->visitdate);
            $this->smarty->display('operation_data/tab1_details.html');
            $this->lab_details_ex($labVisit->id);
            $this->smarty->display('operation_data/div_close.html');
         } else {
            $labVisitCount = 0;
            $this->smarty->display('operation_data/tab11_details.html');
         }
      } else {
         echo -1;
      }
   }

   public function tab2_content() {
//check login
      //     autho::checkautho($this->hosturl);

      $patientNo = filter_input(INPUT_POST, 'opPatNo');
      $opPatId = getPatientId($patientNo);

      $visit = R::findOne('visits', ' for_department = 13 and deleted = 0 and patientid = ?
        and detectionid != 999 and detectionid != 9999 and visitdate <= ? order by visitdate desc'
                      , [$opPatId, date('Y-m-d')]);

      $this->smarty->assign('VisitDateHidden', $visit->visitdate);

      if (count($visit) > 0) {
         $this->board_details($visit->id);
         $patData = $this->visit_details($visit);
         $this->smarty->display('operation_data/tab2_details.html');
      } else {
         echo -1;
      }
   }

   public function tab4_content() {
//check login
      //     autho::checkautho($this->hosturl);

      $patientNo = filter_input(INPUT_POST, 'opPatNo');
      $opPatId = getPatientId($patientNo);

      $raysVisit = R::findAll('visits', ' for_department = 5 and deleted = 0 and patientid = ? and for_husband = ? 
        and detectionid != 999 and detectionid != 9999 order by visitdate desc'
                      , [$opPatId, $visit->for_husband]);

      if (count($raysVisit) > 0) {
         $raysVisits = loadRays($opPatId);
         $this->smarty->assign('raysVisits', $raysVisits);
      }

      $this->smarty->assign('raysVCount', count($raysVisit));
      $this->smarty->display('operation_data/tab4_details.html');
   }

   public function tab5_content() {
//check login
      //     autho::checkautho($this->hosturl);

      $patientNo = filter_input(INPUT_POST, 'opPatNo');
      $opPatId = getPatientId($patientNo);

      $this->picsAndVideos($opPatId);
      $this->smarty->display('operation_data/tab5_details.html');
   }

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

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

      $date = date("Y-m-d");

      $this->casesOpCommon($date);

      $dayName = $this->getDayNameFnAr($date);
      $this->smarty->assign('dayName', $dayName);
      $this->smarty->assign('dayDate', date('Y/m/d', strtotime($date)));
      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      $this->smarty->display('screens/cases_operation.html');
      leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
      footer::footershow($this->smarty, $this->hosturl);
   }

   public function casesOpReload() {
      autho::checkautho($this->hosturl);       ## check login

      $date = date("Y-m-d");

      $this->casesOpCommon($date);
      $this->smarty->display('screens/cases_operation_load.html');
   }

   function casesOpCommon($date) {

      $operations = R::getAll('select    patients.wifename, patients.husdandname, patients.statusno
                                                         , visits.visitdate  , visits.for_husband  , visits.place
                                                          ,   organizations.organization_name  as organizationName
                                                           ,  awusers.name as  doctorName  
                                                           ,detections.title as type 

                                from visits    
                                 join   patients       on visits.patientid = patients.id 
                                 join   detections     on visits.detectionid = detections.id  
                                left join   awusers   on awusers.user_id  = visits.for_doctor 
                                left join   organizations   on organizations.id  = visits.organization_id       
                                where visits.deleted = 0  and  visits.for_department = 13     and visits.visitdate = "' . $date . '"  ');

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

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

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

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

      $date = date("Y-m-d");

      $this->casesClinicCommon($date);

      $dayName = $this->getDayNameFnAr($date);
      $this->smarty->assign('dayName', $dayName);
      $this->smarty->assign('dayDate', date('Y/m/d', strtotime($date)));
      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      $this->smarty->display('screens/cases_clinics.html');
      leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
      footer::footershow($this->smarty, $this->hosturl);
   }

   public function casesClinicReload() {
      autho::checkautho($this->hosturl);       ## check login

      $date = date("Y-m-d");

      $this->casesClinicCommon($date);
      $this->smarty->display('screens/cases_clinics_load.html');
   }

   function casesClinicCommon($date) {

      $patients = R::getAll('select  distinct   patients.id,   patients.wifename, patients.husdandname, patients.statusno

                                from visits    
                                 join   patients       on visits.patientid = patients.id      
                                where visits.deleted = 0  and  visits.for_department  not in ( 5 , 12 , 13)    
                                and  visits.detectionid   in ( 2 , 3 , 7 , 8 , 9 , 11 )    
                                and visits.visitdate = "' . $date . '"  ');

      $i = 0;
      foreach ($patients as $patient) {
         $detects = R::getAll('select    visits.detectionid   , visits.organization_id       
                                         ,   organizations.organization_name  as organizationName 
                                         ,  visits.for_doctor  ,   awusers.name as  doctorName  

                                from visits    
                                 join   patients       on visits.patientid = patients.id 
                                left join   awusers   on awusers.user_id  = visits.for_doctor 
                                left join   organizations   on organizations.id  = visits.organization_id       
                                where visits.deleted = 0  and  visits.for_department  not in ( 5 , 12 , 13)    
                                and  visits.detectionid   in ( 2 , 3 , 7 , 8 , 9 , 11 )    
                                and visits.visitdate = "' . $date . '" and  visits.patientid =   ' . $patient['id']);

         $doctors = '<ul style="margin: 0 ; padding: 0;"> ';
         $organizations = '<ul style="margin: 0 ; padding: 0;"> ';
         $detections = array();
         $doctorsIds = array();
         $organizationsIds = array();

         foreach ($detects as $detect) {
            $value = trim($detect['detectionid']);
            array_push($detections, $value);

            if ($detect['organization_id'] > 0 && !(in_array($detect['organization_id'], $organizationsIds))) {
               array_push($organizationsIds, $detect['organization_id']);
               $value = trim($detect['organizationName']);
               $organizations .= '<li>' . $value . '</li>';
            }


            if ($detect['for_doctor'] > 0 && !(in_array($detect['for_doctor'], $doctorsIds))) {
               array_push($doctorsIds, $detect['for_doctor']);
               $value = trim($detect['doctorName']);
               $doctors .= '<li>' . $value . '</li>';
            }
         }


         $doctors .= ' </ul> ';
         $organizations .= ' </ul> ';

         $patients[$i]['detections'] = $detections;
         $patients[$i]['organizationName'] = $organizations;
         $patients[$i]['doctorName'] = $doctors;

         $i++;
      }

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

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

   function visitsScreenInfo() {
      
   }

   function casesClinicCommon2($date) {

      $clinics = R::getAll('select    patients.wifename, patients.husdandname, patients.statusno
                                                         , visits.visitdate  , visits.for_husband  , visits.detectionid
                                                          ,   organizations.organization_name  as organizationName
                                                           ,  awusers.name as  doctorName    , visits.leave 

                                from visits    
                                 join   patients       on visits.patientid = patients.id 
                                left join   awusers   on awusers.user_id  = visits.for_doctor 
                                left join   organizations   on organizations.id  = visits.organization_id       
                                where visits.deleted = 0  and  visits.for_department  not in ( 5 , 12 , 13)    
                                and  visits.detectionid   in ( 2 , 3 , 7 , 8 , 9 , 11 )    
                                and visits.visitdate = "' . $date . '"  ');

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

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

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

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

      $date = date("Y-m-d");

      $this->casesOpCommon($date);

      $dayName = $this->getDayNameFnAr($date);
      $this->smarty->assign('dayName', $dayName);
      $this->smarty->assign('dayDate', date('Y/m/d', strtotime($date)));
      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      $this->smarty->display('screens/cases_operation.html');
      leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
      footer::footershow($this->smarty, $this->hosturl);
   }

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

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

      $date = date("Y-m-d");

      $this->casesOpCommon($date);

      $dayName = $this->getDayNameFnAr($date);
      $this->smarty->assign('dayName', $dayName);
      $this->smarty->assign('dayDate', date('Y/m/d', strtotime($date)));
      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      $this->smarty->display('screens/cases_operation.html');
      leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
      footer::footershow($this->smarty, $this->hosturl);
   }

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

   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;
   }

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

   public function dateDiff() {

      $enterance = filter_input(INPUT_POST, 'enterance');
      $exit = filter_input(INPUT_POST, 'exit');
      $id = filter_input(INPUT_POST, 'id');
      // print_r($id);
      $visit = R::load('visits', $id);

      $diff = '';
      if (is_null($enterance) || $enterance == '' || is_null($exit) || $exit == '') {
         $diff = '';
      } else {
         $enter = $visit->visitdate . ' ' . $enterance;
         $enter = new DateTime($enter);
         $exit = new DateTime($exit);
         $interval = $exit->diff($enter);

         $t = 0;
         if ($interval->d > 0) {
            $diff .= $interval->d . 'D';
            $t++;
         }

         if ($interval->h > 0) {
            if ($t > 0) {
               $diff .= ',';
            }
            $diff .= $interval->h . 'H';
            $t++;
         }

         if ($interval->i > 0) {
            if ($t > 0) {
               $diff .= ',';
            }
            $diff .= $interval->i . 'M';
            $t++;
         }
      }

      echo $diff;
   }

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

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