<?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 = 'archive';
      $this->shcontrollname = 'archive';
      $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] = 'archive'; //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']);

      #################################################################### 
      $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, '', 'archive');
         archiveRecord($patientId, $deviceId, 0, '', 'archive');
      }

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

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

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

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

      $date = filter_input(INPUT_POST, 'date');
      $wId = filter_input(INPUT_POST, 'wId');
      $hId = filter_input(INPUT_POST, 'hId');
      $dateType = filter_input(INPUT_POST, 'dateType');

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

      if ($wId > 0 || $hId > 0) {
         if ($hId > 0) {
            $patientId = $hId;
         } else {
            $patientId = $wId;
         }
         $this->archiveSearch($dateType, $patientId);

         $sql = 'select  patients.id as  patient_id  , patients.wifename 
                                        , patients.husdandname      , patients.statusno
                                       from    patients
                         where patients.id =  ' . $patientId . '    ';

         $patient = R::getRow($sql);
         $this->smarty->assign('patient', $patient);

         $this->smarty->display('archive/archive_Patient.html');
      } else {
         $this->archiveSearch($dateType, 0, $date);
         $this->smarty->display('archive/archive_search.html');
      }
   }

   function archiveSearch($dateType, $patientId, $date = '') {

      $ext = ' ';
      if ($patientId > 0) {
         $ext = ' and  archive_tracking.patient_id = ' . $patientId;
      } else {
         switch ($dateType) {
            case 1:
               $ext = ' and  archive_tracking.in_date = "' . $date . '" ';
               break;
            case 2:
               $ext = ' and  archive_tracking.out_date = "' . $date . '" ';
               break;
            default:
               $ext = ' and (  archive_tracking.out_date = "' . $date . '" ||  archive_tracking.in_date = "' . $date . '"   ) ';
               break;
         }
      }

      $sql = 'select   archive_tracking.id   , patients.wifename  , archive_tracking.out_date
                                        , patients.husdandname      , patients.statusno  , archive_tracking.in_date
                                        ,  TIME_FORMAT(archive_tracking.out_time, "%h:%i %p") as  out_time
                                        ,  TIME_FORMAT(archive_tracking.in_time, "%h:%i %p") as  in_time 
                                       ,  out_l.name  as outLocation    ,  in_l.name  as inLocation 
                                        , archive_tracking.receiver  , archive_tracking.notes
                   from    archive_tracking
                               join  patients                               on  patients.id = archive_tracking.patient_id    
                             left  join  devices out_d                          on  out_d.id = archive_tracking.out_device_id 
                             left  join  devices in_d                          on  in_d.id = archive_tracking.in_device_id 
                              left   join  floors   out_l                       on  out_l.id = out_d.floor_no 
                             left  join  floors    in_l                      on  in_l.id = in_d.floor_no 
                         where archive_tracking.deleted = 0        ' . $ext . '        order by patients.statusno ';

      $archive_tracking = R::getAll($sql);

      $this->smarty->assign('archive_tracking', $archive_tracking);
   }

   public function archive_search_exit() {
      //check login
      autho::checkautho($this->hosturl);
      //check authoize
      //   autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
##############################################################################
      $this->archiveSearchExit();
      $this->smarty->display('archive/archive_search.html');
   }

   function archiveSearchExit() {

      $sql = 'select   archive_tracking.id   , patients.wifename  , archive_tracking.out_date
                                        , patients.husdandname      , patients.statusno  , archive_tracking.in_date
                                        ,  TIME_FORMAT(archive_tracking.out_time, "%h:%i %p") as  out_time
                                        ,  TIME_FORMAT(archive_tracking.in_time, "%h:%i %p") as  in_time 
                                       ,  out_l.name  as outLocation    ,  in_l.name  as inLocation 
                                        , archive_tracking.receiver  , archive_tracking.notes
                   from    archive_tracking
                               join  patients                               on  patients.id = archive_tracking.patient_id    
                             left  join  devices out_d                          on  out_d.id = archive_tracking.out_device_id 
                             left  join  devices in_d                          on  in_d.id = archive_tracking.in_device_id 
                              left   join  floors   out_l                       on  out_l.id = out_d.floor_no 
                             left  join  floors    in_l                      on  in_l.id = in_d.floor_no 
                         where archive_tracking.deleted = 0  
                         and  ( archive_tracking.in_time = ""  || archive_tracking.in_time IS  NULL  ) 
                         and   archive_tracking.out_time != ""  and  archive_tracking.out_time IS NOT   NULL  
                         order by patients.statusno ';

      $archive_tracking = R::getAll($sql);

      $this->smarty->assign('archive_tracking', $archive_tracking);
   }

   public function update() {
      $id = filter_input(INPUT_POST, "id");
      $value = filter_input(INPUT_POST, "value");
      $tableName = filter_input(INPUT_POST, "tableName");
      $colName = filter_input(INPUT_POST, "colName");

      //here the update
      $mydata = R::load($tableName, $id);

      $mydata->$colName = $value;
      R::store($mydata);
   }

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

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

      #################################################################### 
      $doctors = R::getAll('select awusers.* from awusers
               join  awrole   on awrole.id =   awusers.role_id
                  where awrole.is_doctor =  1 and deleted != 1  ');
      $this->smarty->assign('doctors', $doctors);

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

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

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

   public function presSearch() {
      $findate = filter_input(INPUT_POST, 'findate');
      $todate = filter_input(INPUT_POST, 'todate');
      $doctorId = (filter_input(INPUT_POST, 'doctorId') > 0) ? filter_input(INPUT_POST, 'doctorId') : 0;
      $wId = filter_input(INPUT_POST, 'wId');
      $hId = filter_input(INPUT_POST, 'hId');
      $patientId = 0;
      if ($wId > 0 || $hId > 0) {
         if ($hId > 0) {
            $patientId = $hId;
         } else {
            $patientId = $wId;
         }
      }
      $ext = $this->presSearchEx($doctorId, $patientId);

      if ($patientId > 0) {
         $pres = patientPrescriptionsAll($ext);
      } else {
         $pres = patientPrescriptions($findate, $todate, $ext);
      }

      $this->smarty->assign('pres', $pres);
      $this->smarty->display('archive/pres_result.html');
   }

   function presSearchEx($doctorId, $patientId) {
      $ext = '';
      if (!empty($doctorId) && $doctorId > 0) {
         $ext .= ' and doctorid = ' . $doctorId;
      }

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

      return $ext;
   }

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

      $presId = (filter_input(INPUT_POST, 'presId') > 0) ? filter_input(INPUT_POST, 'presId') : 0;
      $presType = filter_input(INPUT_POST, 'presType');

      if ($presId > 0) {
         switch ($presType) {
            case 1:
               $tableName = 'gynadrugs';
               $colName = 'recepittmpid';
               $presTmp = R::load('recepittmp', $presId);
               $this->smarty->assign('presType', 'دورى ');
               break;

            case 2:
               $tableName = 'mainantenentaldrugs';
               $colName = 'recepittmpid';
               $presTmp = R::load('recepittmp', $presId);
               $this->smarty->assign('presType', 'دورى ');
               break;

            case 3:
               $tableName = 'gynachronicdrugs';
               $colName = 'pres_id';
               $presTmp = R::load('gynachronic_pres', $presId);
               $presTmp->receiptdate = $presTmp->pres_date;
               $this->smarty->assign('presType', 'شهرى ');
               $this->smarty->assign('presTypeNo', 1);
               break;
         }
         $this->printPresDrugs($presId, $tableName, $colName, $presTmp, $presType);
      } else {
         echo -1;
      }
   }

   function printPresDrugs($presId, $tableName, $colName, $presTmp, $presType) {
      $presDrugs = R::findall($tableName, 'deleted = ? and  ' . $colName . '     = ?  ', [0, $presId]);

      foreach ($presDrugs as $pre) {
         $dd = R::load('drugs', $pre->drugid);
         $pre->drugname = $dd->drugname;
      }

      $patient = R::load('patients', $presTmp->patientid);
      $wifetypes = R::load('wifetypes', $patient->wiftypeid);
      $husbandtypes = R::load('husbandtypes', $patient->husbandtypeid);

      if ($presTmp->forhusband == 1) {
         $this->smarty->assign('name', $patient->husdandname);
         $this->smarty->assign('title', $husbandtypes->title);
      } elseif ($presTmp->forhusband == 0) {
         $this->smarty->assign('name', $patient->wifename);
         $this->smarty->assign('title', $wifetypes->title);
      }

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

      $this->smarty->assign('statusNo', $patient->statusno);

      $lastPrintedDate = $this->lastPrintedDate($presId, $tableName, $presType, $presTmp->receiptdate);
      $this->savePrintedData($presId, $tableName, $presType);

      $this->smarty->assign('drugs', $presDrugs);

      $this->smarty->assign('date', $lastPrintedDate);
      $this->smarty->assign('printDate', date("Y/m/d"));

      if ($ProgramesettingData->pres_version == 1) {
         $doctors = presDoctors($tableName, $presTmp->patientid, $presTmp->receiptdate, $presTmp->forhusband);
         $this->smarty->assign('doctorName', $doctors);
         $user = R::findOne('awusers', 'user_id = ?', [$_SESSION['user_id']]);
         $this->smarty->assign('userName', $user->name);
         $this->smarty->display('gyna/print_full.html');
      } else {
         $this->smarty->display('gyna/print.html');
      }
   }

   function savePrintedData($presId, $tableName, $presType) {
      $pres_printed = R::xdispense('pres_printed');
      $pres_printed->pres_id = $presId;
      $pres_printed->create_date = date('Y-m-d H:i:s'); //$this->today;
      $pres_printed->pres_table = $tableName;
      $pres_printed->pres_type = $presType;
      $pres_printed->user_id = $_SESSION['user_id'];
      R::store($pres_printed);
   }

   function lastPrintedDate($presId, $tableName, $presType, $presDate) {
      $pres_printed = R::findOne('pres_printed', '  pres_id = ? and  pres_table = ?   
              and  pres_type = ? order by create_date desc   ', [$presId, $tableName, $presType]);
      if (count($pres_printed) > 0) {
         $lastPrintedDate = $pres_printed->create_date;
      } else {
         $lastPrintedDate = $presDate;
      }
      $lastPrintedDate = date("Y/m/d", strtotime($lastPrintedDate));
      return $lastPrintedDate;
   }

//    public function new_requests() {
//        $date = date("Y-m-d");
//        $newRequests = $this->newRequests($date);
//        echo $newRequests;
//    }
//
//    public function newRequests($date) {
//        $newRequests = ' ';
//        $sql = 'select   archive_tracking.id   , patients.wifename  , archive_tracking.out_date
//                                        , patients.husdandname      , patients.statusno  , archive_tracking.in_date
//
//                                       ,  out_l.name  as outLocation    ,  in_l.name  as inLocation 
//                                        , archive_tracking.receiver  , archive_tracking.notes
//                   from    archive_tracking
//                               join  patients                               on  patients.id = archive_tracking.patient_id    
//                             left  join  devices out_d                          on  out_d.id = archive_tracking.out_device_id 
//                             left  join  devices in_d                          on  in_d.id = archive_tracking.in_device_id 
//                              left   join  floors   out_l                       on  out_l.id = out_d.floor_no 
//                             left  join  floors    in_l                      on  in_l.id = in_d.floor_no 
//                         where archive_tracking.deleted = 0   
//                         and (  archive_tracking.out_date = "' . $date . '" ||  archive_tracking.in_date = "' . $date . '"   )       '
//                . 'order by patients.statusno ';
//
//
//
//        $archive_tracking = R::getAll($sql);
//
//        return $newRequests;
//    }
   ######################### temporary cases report ##############################
   #######################################################
   #######################################################
// at the end of class call
   public function __destruct() {
      //echo "Time Elapsed: ".(microtime(true) - $this->time)."s";
//close connection
      R::close();
   }
}
