<?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 = 'approvals';
      $this->shcontrollname = 'approvals';
      $this->smarty->assign('controllname', $this->controllname);
      $this->smarty->assign('shcontrollname', $this->shcontrollname);

//breadcrumbs
      require_once("../../_library/plugins/Breadcrumbs/Breadcrumbs.php");
      require_once("../../_library/plugins/classupload/uploadfunctions.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] = 'approvals'; //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 index() {
      //check login
      autho::checkautho($this->hosturl);
      //check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

      ##############################################################################
      $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('approvals/show.html');
      leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
      footer::footershow($this->smarty, $this->hosturl);
   }

   public function approvalSearch() {
      $date = filter_input(INPUT_POST, "date");
      $this->needApprovals($date);
      $this->needApprovalsPre($date);
      $this->needApprovalsChronic($date);
      $this->smarty->display('approvals/approvals.html');
   }

   function needApprovalsChronic($date) {
//      r::debug(true, 2);
      $visits = R::getAll('SELECT  gynachronic_pres.id as preId , patients.statusno ,  "Chronic" as preSource
             , CONCAT( COALESCE(patients.wifename,""), " -  "
            , COALESCE(patients.husdandname,"")) AS patientName 
               , limits.name as limitUserName      ,   gynachronic_pres.limit_approve  ,   gynachronic_pres.limit_userid  
                , doc.name as docUserName  
                FROM gynachronic_pres
               join patients                                 on patients.id  =  gynachronic_pres.patientid
               left  join awusers    doc                 on doc.user_id  =  gynachronic_pres.user_id  
                 left  join awusers  limits                 on limits.user_id  =  gynachronic_pres.limit_userid 
               where  gynachronic_pres.pres_date = ?  
               and   (   gynachronic_pres.limit_approve = 1   or gynachronic_pres.limit_userid > 0    )
                order by  gynachronic_pres.id desc  ', [$date]);

      $x = 0;
      foreach ($visits as $visit) {
         if ($visits[$x]['limit_approve'] != 1 && $visit['limit_userid'] == 0) {
            unset($visits[$x]);
         }

         $x++;
      }

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

   function needApprovalsPre($date) {
//      r::debug(true, 2);
      $visits = R::getAll('SELECT  recepittmp.id as preId , patients.statusno ,  "TTT" as preSource
             , CONCAT( COALESCE(patients.wifename,""), " -  "
            , COALESCE(patients.husdandname,"")) AS patientName 
               , limits.name as limitUserName      ,   recepittmp.limit_approve  ,   recepittmp.limit_userid  
                , doc.name as docUserName  
                FROM recepittmp
               join patients                                 on patients.id  =  recepittmp.patientid
               left  join awusers    doc                 on doc.user_id  =  recepittmp.doctorid  
                 left  join awusers  limits                 on limits.user_id  =  recepittmp.limit_userid 
               where  recepittmp.receiptdate = ?  
               and   (   recepittmp.limit_approve = 1   or recepittmp.limit_userid > 0    )
                order by  recepittmp.id desc  ', [$date]);

      $x = 0;
      foreach ($visits as $visit) {
         if ($visits[$x]['limit_approve'] != 1 && $visit['limit_userid'] == 0) {
            unset($visits[$x]);
         }

         $x++;
      }

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

   function needApprovals($date) {
      $visits = R::getAll('SELECT  visits.id as visitId , patients.statusno , detections.title as detName
             , CONCAT( COALESCE(patients.wifename,""), " -  "
            , COALESCE(patients.husdandname,"")) AS patientName
               , limits.name as limitUserName    , dept.name as deptUserName
               ,   visits.limit_approve  ,   visits.limit_userid  , 0 as visitDept 
               ,   0  as dept_approve  ,   visits.dept_userid  , visits.restdetectionvalue
                FROM visits
               join patients                            on patients.id  =  visits.patientid
               join detections                        on detections.id  =  visits.detectionid
               left  join awusers  limits          on limits.user_id  =  visits.limit_userid
               left  join awusers  dept           on dept.user_id  =  visits.dept_userid
               where  visits.visitdate = ?   and visits.deleted != 1  
               and   (   visits.limit_approve = 1 or visits.restdetectionvalue > 0
                                or visits.limit_userid > 0  or visits.dept_userid > 0  )
                order by  visits.id desc  ', [$date]);

      $x = 0;
      foreach ($visits as $visit) {
         if ($visit['restdetectionvalue'] > 0 && $visit['dept_userid'] == 0) {
            $visitDept = visitDept($visit['visitId']);
            if ($visitDept > 0) {
               $visits[$x]['dept_approve'] = 1;
               $visits[$x]['visitDept'] = $visitDept;
            }
         }

         if ($visits[$x]['limit_approve'] != 1 && $visits[$x]['dept_approve'] != 1 &&
                 $visit['limit_userid'] == 0 && $visit['dept_userid'] == 0) {
            unset($visits[$x]);
         }

         $x++;
      }

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

   function approveDept() {
      autho::checkautho($this->hosturl);
      $visitId = filter_input(INPUT_POST, "visitId");
      try {
         $visitOld = R::load('visits', $visitId);
         $this->approveIt($visitId, 'dept_approve', 'dept_userid');
         $this->reserveOldVisit($visitOld);
         echo $this->approvedUser($_SESSION['user_id']);
      } catch (Exception $ex) {
         echo -1;
      }
   }

   function approveLimit() {
      autho::checkautho($this->hosturl);
      $visitId = filter_input(INPUT_POST, "visitId");
      try {
         $visitOld = R::load('visits', $visitId);
         $this->approveIt($visitId, 'limit_approve', 'limit_userid');
         $this->reserveOldVisit($visitOld);
         echo $this->approvedUser($_SESSION['user_id']);
      } catch (Exception $ex) {
         echo -1;
      }
   }

   function approveIt($visitId, $approveCol, $userCol) {
      $visit = R::load('visits', $visitId);
      $visit->$approveCol = 0;
      $visit->$userCol = $_SESSION['user_id'];
      r::store($visit);
   }

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

      date_default_timezone_set('Africa/Cairo');

      $visitEdit = R::xdispense('visits_updates');
      $colums = R::getAll('DESCRIBE visits');

      foreach ($colums as $col) {
         $colName = $col['Field'];
         if ($colName != id) {
            $visitEdit->$colName = $oldVisit->$colName;
         }
      }

      $visitEdit->userid_edit = $_SESSION['user_id'];
      $visitEdit->date_edit = date('Y-m-d H:i:s'); //$this->today;
      $visitEdit->patientid_edit = $oldVisit->id;
      R::store($visitEdit);
   }

   function approvedUser($userId) {
      $user = R::getRow('select name from awusers where user_id = ?', [$userId]);
      return $user['name'];
   }

   function approveLimitPre() {
      autho::checkautho($this->hosturl);
      $preId = filter_input(INPUT_POST, "preId");
      $type = filter_input(INPUT_POST, "type");
      try {
         switch ($type) {
            case 1:
               $this->approveItPre($preId, 'recepittmp', 'limit_approve', 'limit_userid');
               break;
            case 2:
               $this->approveItPre($preId, 'gynachronic_pres', 'limit_approve', 'limit_userid');
               break;
            default:
               break;
         }

         echo $this->approvedUser($_SESSION['user_id']);
      } catch (Exception $ex) {
         echo -1;
      }
   }

   function approveItPre($preId, $table, $approveCol, $userCol) {
      $pre = R::load($table, $preId);
      $pre->$approveCol = 0;
      $pre->$userCol = $_SESSION['user_id'];
      r::store($pre);
   }

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

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

      $allowDelBtn = 0;
      $btn20 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 20  ', [$_SESSION['role_id']]);
      if (count($btn20) > 0) {
         $allowDelBtn = $btn20->checkval;
      }
      $this->smarty->assign('allowDelBtn', $allowDelBtn);

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

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

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

      $dateFrom = filter_input(INPUT_POST, 'dateFrom');
      $dateTo = filter_input(INPUT_POST, 'dateTo');
      $patientId = filter_input(INPUT_POST, 'patientId');

      $allowDelBtn = 0;
      $btn20 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 20  ', [$_SESSION['role_id']]);
      if (count($btn20) > 0) {
         $allowDelBtn = $btn20->checkval;
      }
      $this->smarty->assign('allowDelBtn', $allowDelBtn);

      $this->externalSearch($dateFrom, $dateTo, $patientId);
      $this->smarty->display('approvals/external_search.html');
   }

   public function externalSearch($dateFrom, $dateTo, $patientId) {
      //  r::debug(true, 2);
      $sql = 'select external_transfer.id  ,awusers.name as userName , patients.statusno
                                       , external_transfer.transfer_date , external_transfer.discription , external_transfer.img
                                       ,external_transfer.cost   , CONCAT( COALESCE(patients.wifename,""), " -  "
                                      , COALESCE(patients.husdandname,"")) AS patientName
                            from  external_transfer
                            left    join  awusers                    on  external_transfer.user_id =awusers.user_id
                             join    patients                           on   external_transfer.patientid   =  patients.id
                            where external_transfer.deleted != 1  and external_transfer.transfer_date between  ? and ?  ';

      if ($patientId > 0) {
         $sql .= ' and external_transfer.patientid = ' . $patientId;
      }

      $sql .= '  order by external_transfer.transfer_date desc ';

      $external_transfer = R::getAll($sql, [$dateFrom, $dateTo]);
      // r::debug(false);
      $this->smarty->assign('external_transfer', $external_transfer);
   }

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

      $this->smarty->assign('transfer_date', date('Y/m/d', strtotime($this->today)));
      $this->smarty->assign('toDo', 'externalAdd');

      $refer_center = R::findAll('refer_center', 'deleted = 0 order by name');
      $this->smarty->assign('refer_center', $refer_center);

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

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

      $transfer_date = filter_input(INPUT_POST, 'transfer_date');
      $patientId = filter_input(INPUT_POST, 'patientId');
      $cost = filter_input(INPUT_POST, 'cost');
      $discription = filter_input(INPUT_POST, 'discription');
      $receipt_no = filter_input(INPUT_POST, 'receipt_no');
      $refer_center = filter_input(INPUT_POST, 'refer_center');

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

      $external_transfer = R::xdispense('external_transfer');
      $external_transfer->transfer_date = $transfer_date;
      $external_transfer->patientid = $patientId;
      $external_transfer->discription = $discription;
      $external_transfer->receipt_no = $receipt_no;
      $external_transfer->refer_center = $refer_center;
      $external_transfer->cost = $cost;
      $external_transfer->img = uploadupdate("img", '', False, 0, 0, 'transferimg');
      $external_transfer->create_date = date('Y-m-d H:i:s');
      $external_transfer->user_id = $_SESSION['user_id'];

      try {
         R::store($external_transfer);
         header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=external_show');
      } catch (Exception $e) {
         header('Location:' . $this->hosturl . '/error/notadd/' . $this->controllname);
      }
   }

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

      $id = filter_input(INPUT_GET, 'id');
      $external_transfer = R::getRow('SELECT  external_transfer.*  , patients.statusno 
               FROM external_transfer
               join patients                            on patients.id  =  external_transfer.patientid
               where  external_transfer.id = ?   ', [$id]);

      $this->smarty->assign('transfer_date', date('Y/m/d', strtotime($external_transfer['transfer_date'])));
      $this->smarty->assign('toDo', 'externalUpdate');
      $this->smarty->assign('external_transfer', $external_transfer);

      $refer_center = R::findAll('refer_center', 'deleted = 0 order by name');
      $this->smarty->assign('refer_center', $refer_center);

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

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

      $transfer_date = filter_input(INPUT_POST, 'transfer_date');
      $patientId = filter_input(INPUT_POST, 'patientId');
      $cost = filter_input(INPUT_POST, 'cost');
      $discription = filter_input(INPUT_POST, 'discription');
      $receipt_no = filter_input(INPUT_POST, 'receipt_no');
      $refer_center = filter_input(INPUT_POST, 'refer_center');
      $id = filter_input(INPUT_POST, 'id');

      ##################################################
      $img = uploadupdate("img", '', False, 0, 0, 'transferimg');

      $external_transfer = R::load('external_transfer', $id);
      $old = R::load('external_transfer', $id);

      $external_transfer->transfer_date = $transfer_date;
      $external_transfer->patientid = $patientId;
      $external_transfer->discription = $discription;
      $external_transfer->receipt_no = $receipt_no;
      $external_transfer->refer_center = $refer_center;
      $external_transfer->cost = $cost;
      if ($img != "") {
         $external_transfer->img = $img;
      }


      try {
         R::store($external_transfer);
         $this->reserveOldOne($old);
         header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=external_show');
      } catch (Exception $e) {
         header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
      }
   }

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

      date_default_timezone_set('Africa/Cairo');

      $visitEdit = R::xdispense('external_transfer_updates');
      $colums = R::getAll('DESCRIBE external_transfer');

      foreach ($colums as $col) {
         $colName = $col['Field'];
         if ($colName != id) {
            $visitEdit->$colName = $old->$colName;
         }
      }

      $visitEdit->userid_edit = $_SESSION['user_id'];
      $visitEdit->date_edit = date('Y-m-d H:i:s'); //$this->today;
      $visitEdit->id_edit = $old->id;
      R::store($visitEdit);
   }

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

      $id = filter_input(INPUT_POST, 'id');
      $external_transfer = R::getRow('SELECT  external_transfer.*  , patients.statusno
            , refer_center.name as referCenter  , patients.wifename
               FROM external_transfer
               join patients                                        on patients.id  =  external_transfer.patientid
               left join refer_center                            on refer_center.id  =  external_transfer.refer_center
               where  external_transfer.id = ?   ', [$id]);

      $external_transfer['transfer_date'] = date('Y/m/d', strtotime($external_transfer['transfer_date']));
      $this->smarty->assign('external_transfer', $external_transfer);

      $this->smarty->display('approvals/external_print.html');
   }

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

   public function del() {
      autho::checkautho($this->hosturl);

      $id = filter_input(INPUT_POST, 'id');
      $tableName = filter_input(INPUT_POST, 'tableName');
      try {
         R::exec('update  ' . $tableName . ' set deleted = 1 ,  delete_userid = ' . $_SESSION['user_id'] . '    ,
                         delete_date = "' . date('Y-m-d H:i:s') . '" WHERE id = ' . $id);
         echo 1;
      } catch (Exception $e) {
         echo $e;
      }
   }

   ########################### chronic Add drugs prescription ###############################

   function chronicTTT() {

      autho::checkautho($this->hosturl);

      $controller = filter_input(INPUT_POST, "controller");
      $patientId = filter_input(INPUT_POST, "patientId");
      $type = filter_input(INPUT_POST, "type");

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

      if ($type == "add") {
         $presDate = date("Y-m-d");
         $preFor = 0;
         $this->getprescription($patientId, $presDate, $preFor);
      } else if ($type == "edit") {
         $date = filter_input(INPUT_POST, "preDate");
         $presDate = date("Y-m-d", strtotime($date));
         $preFor = filter_input(INPUT_POST, "preFor");
         $this->getprescription($patientId, $presDate, $preFor);
      } else if ($type == "duplicate") {
         $date = filter_input(INPUT_POST, "preDate");
         $presDate = date("Y-m-d", strtotime($date));
         $preFor = filter_input(INPUT_POST, "preFor");
         $this->duplicateChronicPre($patientId, $presDate, $preFor);
      }

//      $this->getprescription($patientId, $presDate, $preFor);
      $this->smarty->assign('presDate', date("Y/m/d"));
      $this->smarty->assign('preController', $controller);
      $this->smarty->assign('preChronicType', $type);

      $this->smarty->display('approvals/chronic.html');
   }

   private function duplicateChronicPre($patientId, $date, $preFor) {

      $PatientPresByDate = R::findall('gynachronicdrugs', 'deleted = ? and patientid = ? and date = ?
                        and forhusband = ?', [0, $patientId, $date, $preFor]);

      foreach ($PatientPresByDate as $preOld) {
         $presDate = date("Y-m-d");

         $PatPres = R::findall('gynachronicdrugs', 'deleted = ? and patientid = ? and date = ? 
            and drugid = ? and drugtype = ? and drugdos = ?  and forhusband = ?'
                         , [0, $patientId, $presDate, $preOld->drugid, $preOld->drugtype, $preOld->drugdos, $preFor]);
         if (!(count($PatPres) > 0 )) {

            $pre = R::xdispense('gynachronicdrugs');
            $pre->patientid = $patientId;
            $pre->date = date("Y-m-d", strtotime($presDate));
            $pre->create_date = date('Y-m-d H:i:s');
            $pre->drugid = $preOld->drugid;
            $pre->drugtype = $preOld->drugtype;
            $pre->quantity = $preOld->quantity;
            $pre->drugdos = $preOld->drugdos;
            $pre->forhusband = $preOld->forhusband;
            $pre->doctorid = $_SESSION['user_id'];
            $pre->deleted = 0;
            $pre->pres_id = $this->getPrestId($patientId, $presDate, $preFor, $_SESSION['user_id']);
            $pre->id = R::store($pre);

            $dd = R::load('drugs', $pre->drugid);
            $pre->drugcat = $dd->drugcat;
         }
      }

      $PatientPresByDate = R::findall('gynachronicdrugs', 'deleted = ? and patientid = ? and date = ?
                        and forhusband = ?', [0, $patientId, $presDate, $preFor]);

      $drugs = R::getAll('SELECT  id , drugname ,minimumbalance  FROM drugs order by drugname asc');
      $allDrugcats = R::getAll('SELECT distinct  drugcat   FROM drugs order by drugcat asc');
      $allDrugTypes = R::getAll('SELECT distinct  drugtype  FROM drugs order by drugtype asc');
      $allDrugDoses = R::getAll('SELECT distinct  drugdos   FROM drugs order by drugdos asc');

      $this->smarty->assign('drugs', $drugs);
      $this->smarty->assign('allDrugcats', $allDrugcats);
      $this->smarty->assign('allDrugTypes', $allDrugTypes);
      $this->smarty->assign('allDrugDoses', $allDrugDoses);
      $this->smarty->assign('PatientChronicByDate', $PatientPresByDate);
      $this->smarty->assign('drugChronicItr', count($PatientPresByDate));
   }

   private function getprescription($patientId, $date, $preFor) {

      $PatientPresByDate = R::findall('gynachronicdrugs', 'deleted = ? and patientid = ? and date = ?
                        and forhusband = ?', [0, $patientId, $date, $preFor]);

      $drugs = R::getAll('SELECT  id , drugname ,minimumbalance  FROM drugs order by drugname asc');
      $allDrugcats = R::getAll('SELECT distinct  drugcat   FROM drugs order by drugcat asc');
      $allDrugTypes = R::getAll('SELECT distinct  drugtype  FROM drugs order by drugtype asc');
      $allDrugDoses = R::getAll('SELECT distinct  drugdos   FROM drugs order by drugdos asc');

      foreach ($PatientPresByDate as $pre) {
         $dd = R::load('drugs', $pre->drugid);
         $pre->drugcat = $dd->drugcat;
      }
      $this->smarty->assign('drugs', $drugs);
      $this->smarty->assign('allDrugcats', $allDrugcats);
      $this->smarty->assign('allDrugTypes', $allDrugTypes);
      $this->smarty->assign('allDrugDoses', $allDrugDoses);
      $this->smarty->assign('PatientChronicByDate', $PatientPresByDate);
      $this->smarty->assign('drugChronicItr', count($PatientPresByDate));
   }

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

      $itr = filter_input(INPUT_POST, "itr");
      $preFor = filter_input(INPUT_POST, "preFor");
      $patientId = filter_input(INPUT_POST, "patientId");
      $presDate = filter_input(INPUT_POST, "presDate");
      $allowAdd = 1;

      $programesetting = R::findOne('programesetting');
      $this->smarty->assign('programSettingData', $programesetting);
      $limitExceded = patientLimitPrescriptions($patientId, $presDate, $programesetting->pres_limit);
      if ($limitExceded > 0) {
         $allowAdd = $this->getPresPrevillage($patientId, $presDate, $preFor, $_SESSION['user_id']);
      }


      if ($allowAdd == 1) {
         $this->chronicRow($itr, $preFor, $patientId, $presDate);
      } else {
         echo $allowAdd;
      }
   }

   function getPresPrevillage($patientId, $presDate, $preFor, $userId) {

      $presByDate = R::findOne('gynachronic_pres', 'patientid = ? and pres_date = ?     and forhusband = ?     
             and  user_id = ?    ', [$patientId, date("Y-m-d", strtotime($presDate)), $preFor, $userId]);

      if (count($presByDate) > 0) {
         if ($presByDate->limit_approve > 0) {
            $res = -2;
         } else {
            $res = 1;
         }
      } else {
         $res = -2;
      }
      return $res;
   }

   function chronicRow($itr, $preFor, $patientId, $presDate) {
      $pre = R::xdispense('gynachronicdrugs');
      $pre->patientid = $patientId;
      $pre->date = date("Y-m-d", strtotime($presDate));
      $pre->create_date = date('Y-m-d H:i:s');
      $pre->drugid = '';
      $pre->drugtype = '';
      $pre->drugdos = '';
      $pre->forhusband = $preFor;
      $pre->doctorid = $_SESSION['user_id'];
      $pre->deleted = 0;
      $pre->pres_id = $this->getPrestId($patientId, $presDate, $preFor, $_SESSION['user_id']);
      $pre->id = R::store($pre);

      $drugs = R::getAll('SELECT  id , drugname , minimumbalance  , 0 as currentbalance  FROM drugs order by drugname asc');
      $allDrugcats = R::getAll('SELECT distinct  drugcat   FROM drugs order by drugcat asc');
      $allDrugTypes = R::getAll('SELECT distinct  drugtype  FROM drugs order by drugtype asc');
      $allDrugDoses = R::getAll('SELECT distinct  drugdos   FROM drugs order by drugdos asc');

      $this->smarty->assign('drugs', $drugs);
      $this->smarty->assign('allDrugcats', $allDrugcats);
      $this->smarty->assign('allDrugTypes', $allDrugTypes);
      $this->smarty->assign('allDrugDoses', $allDrugDoses);
      $this->smarty->assign('itr', $itr);
      $this->smarty->assign('pre', $pre);
      $this->smarty->display('approvals/chronic_row.html');
   }

   function getPrestId($patientId, $presDate, $preFor, $userId) {
      ### get pres_id if exist or insert new one
      $presByDate = R::findOne('gynachronicdrugs', 'patientid = ? and date = ?     and forhusband = ?     
             and  doctorid = ?    ', [$patientId, date("Y-m-d", strtotime($presDate)), $preFor, $userId]);

      if (count($presByDate) > 0) {
         $pres_id = $presByDate->pres_id;
      } else {
         $pres = R::xdispense('gynachronic_pres');
         $pres->patientid = $patientId;
         $pres->pres_date = date("Y-m-d", strtotime($presDate));
         $pres->user_id = $_SESSION['user_id'];
         $pres->forhusband = $preFor;
         $pres->create_date = date('Y-m-d H:i:s');
         $pres_id = R::store($pres);
      }
      return $pres_id;
   }

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

      $preFor = filter_input(INPUT_POST, "preFor");
      $preDate = filter_input(INPUT_POST, "preDate");
      $patientId = filter_input(INPUT_POST, "patientId");

      $this->getprescription($patientId, $preDate, $preFor);
      $this->smarty->assign('presDate', $preDate);

      $this->smarty->display('approvals/chronic_pres.html');
   }

   public function printChronicPres() {       ## show prescriptions of patient
      //check login
      autho::checkautho($this->hosturl);

      $patientId = filter_input(INPUT_POST, "patientId");
      $printDate = filter_input(INPUT_POST, "printDate");
      $date = filter_input(INPUT_POST, "preDate");
      $preFor = filter_input(INPUT_POST, "preFor");

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

      $date = date("Y/m/d", strtotime($date));
      $this->smarty->assign('date', $date);
      if (isset($printDate) && !empty($printDate)) {
         $printDate = date("Y/m/d", strtotime($printDate));
         $this->smarty->assign('printDate', $printDate);
      } else {
         $this->smarty->assign('printDate', $date);
      }



      ## all prescription of certain patient
      $PatientPresByDate = R::findall('gynachronicdrugs', 'deleted = ? and patientid = ? and date = ? 
                and forhusband = ? ', [0, $patientId, $date, $preFor]);
      if ($preFor == 1) {
         $this->smarty->assign('name', $patient->husdandname);
         $this->smarty->assign('title', $husbandtypes->title);
      } elseif ($preFor == 0) {
         $this->smarty->assign('name', $patient->wifename);
         $this->smarty->assign('title', $wifetypes->title);
      }


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

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

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

      $this->smarty->assign('statusNo', $patient->statusno);
      if ($ProgramesettingData->pres_version == 1) {
         $doctors = presDoctors('gynachronicdrugs', $patientId, $date, $preFor);
         $this->smarty->assign('doctorName', $doctors);

         $user = R::findOne('awusers', 'user_id = ?', [$_SESSION['user_id']]);
         $this->smarty->assign('userName', $user->name);

         $this->smarty->assign('presType', 'شهرى  ');
         $this->smarty->assign('presTypeNo', 1);
         $this->smarty->display('gyna/print_full_back.html');
      } else {
         $this->smarty->display('gyna/print.html');
      }
   }

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

      $preFor = filter_input(INPUT_POST, "preFor");
      $patientId = filter_input(INPUT_POST, "patientId");
      $presDate = filter_input(INPUT_POST, "presDate");

      $presId = $this->getPres($patientId, $presDate, $preFor, $_SESSION['user_id']);

      if ($presId > 0) {
         $pres = R::load('gynachronic_pres', $presId);
         $pres->limit_approve = 1;
         $pres->limit_userid = 0;
         r::store($pres);
         echo 1;
      } else {
         echo -1;
      }
   }

   function getPres($patientId, $presDate, $preFor, $userId) {
      ### get pres_id if exist or insert new one
      $pres = R::findOne('gynachronic_pres', 'patientid = ? and pres_date = ?     and forhusband = ?     
             and  user_id = ?    ', [$patientId, date("Y-m-d", strtotime($presDate)), $preFor, $userId]);

      if (count($pres) > 0) {
         $pres_id = $pres->id;
      } else {
         $pres = R::xdispense('gynachronic_pres');
         $pres->patientid = $patientId;
         $pres->pres_date = date("Y-m-d", strtotime($presDate));
         $pres->user_id = $_SESSION['user_id'];
         $pres->forhusband = $preFor;
         $pres->create_date = date('Y-m-d H:i:s');
         $pres_id = R::store($pres);
      }
      return $pres_id;
   }

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

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

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

      $patientId = filter_input(INPUT_POST, "patientId");
      $type = filter_input(INPUT_POST, "type");  ## show or edit
      $preFor = filter_input(INPUT_POST, "preFor");
      ## show all prescription of patient
      if ($type == "show") {
         $dates = R::getAll('SELECT DISTINCT date  FROM gynachronicdrugs WHERE deleted = ? and patientid = ?  order by date desc', [0, $patientId]);
         $countHusband = array();
         $countWife = array();
         $i = 0;
         foreach ($dates as $date) {
            ## all prescription of certain patient


            $PatientPresByDateWife = R::findall('gynachronicdrugs', 'deleted = ? and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date['date'], 0]);
            $PatientPresByDateHusband = R::findall('gynachronicdrugs', 'deleted = ? and patientid = ? and date = ? and forhusband = ?', [0, $patientId, $date['date'], 1]);

            $j = 0;

            foreach ($PatientPresByDateWife as $pres) {
               $dd = R::load('drugs', $pres->drugid);
               if ($j == 0) {
                  $dates[$i]["drugdos"] = "";
                  $dates[$i]["drugdos"] = $dd->drugname;
               } else {
                  $dates[$i]["drugdos"] = $dates[$i]["drugdos"] . ' , ' . $dd->drugname;
               }

               $j++;
            }

            $j = 0;

            foreach ($PatientPresByDateHusband as $pres) {
               $dd = R::load('drugs', $pres->drugid);
               if ($j == 0) {
                  $dates[$i]["drugtype"] = "";
                  $dates[$i]["drugtype"] = $dd->drugname;
               } else {
                  $dates[$i]["drugtype"] = $dates[$i]["drugtype"] . ' , ' . $dd->drugname;
               }

               $j++;
            }

            $dates[$i]['date'] = date("Y/m/d", strtotime($dates[$i]['date']));
            $countHusband[$dates[$i]['date']] = count($PatientPresByDateHusband);
            $countWife[$dates[$i]['date']] = count($PatientPresByDateWife);

            $i++;
         }

         $this->smarty->assign('countHusband', $countHusband);
         $this->smarty->assign('countWife', $countWife);
         $this->smarty->assign('dates', $dates);

         $this->smarty->display('approvals/showPrescriptions.html');
      }
   }

   ########################## chronic  prescription report ################################

   function chronic() {

      autho::checkautho($this->hosturl);

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

   public function chronic_search() {
      $patientId = filter_input(INPUT_POST, 'patientId');
      $this->chronicSearch($patientId);

      $programesetting = R::findOne('programesetting');
      $this->smarty->assign('programesetting', $programesetting);
      $this->smarty->display('approvals/chronic_search.html');
   }

   private function chronicSearch($patientId) {
      $allPres = R::getAll('SELECT  distinct pres_id , date , forhusband , 0 as cashCount
                FROM gynachronicdrugs
                where deleted != 1 and  pres_id > 0  and drugid > 0
                and patientid = ? 
                order by date asc', [$patientId]);

      $i = 0;
      foreach ($allPres as $pres) {
         $cashing = R::getAll('select id , cash_date from   gynachronic_pres_cashing
                where pres_id = ? order by  cash_date desc ', [$pres['pres_id']]);
         $allPres[$i]['lastDate'] = $cashing[0]['cash_date'];
         $allPres[$i]['cashCount'] = count($cashing);
         $i++;
      }

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

   function cashPres() {
      autho::checkautho($this->hosturl);
      $presId = filter_input(INPUT_POST, "presId");
      try {
         $cashing = R::xdispense('gynachronic_pres_cashing');
         $cashing->pres_id = $presId;
         $cashing->cash_date = date("Y-m-d");
         $cashing->create_date = date('Y-m-d H:i:s');
         $cashing->user_id = $_SESSION['user_id'];
         $cashing->id = R::store($cashing);
         $this->cashPresDrugs($cashing->id, $presId);
         echo $cashing->id;
      } catch (Exception $ex) {
         echo -1;
      }
   }

   function cashPresDrugs($cashId, $presId) {
      $presDrugs = R::getAll('SELECT  *
                FROM gynachronicdrugs
                where deleted != 1 and  pres_id  = ?  order by date asc', [$presId]);
//        print_r($presDrugs);

      foreach ($presDrugs as $presDrug) {
         $cashingDrug = R::xdispense('gynachronic_cashing_drugs');
         $cashingDrug->pres_cashing_id = $cashId;
         $cashingDrug->drugid = $presDrug['drugid'];
         $cashingDrug->drugtype = $presDrug['drugtype'];
         $cashingDrug->drugdos = $presDrug['drugdos'];
         $cashingDrug->create_date = date('Y-m-d H:i:s');
         $cashingDrug->id = R::store($cashingDrug);
      }
   }

   public function cashingDetails() {
      $presId = filter_input(INPUT_POST, "presId");
      $cashing = R::getAll('select cashing.id , cashing.cash_date , awusers.name as userName
                        , "" as  cashedDrugs 
                 from   gynachronic_pres_cashing   cashing
                 left  join awusers            on awusers.user_id  =  cashing.user_id
                where pres_id = ? order by  cash_date desc ', [$presId]);

      $i = 0;
      foreach ($cashing as $data) {
         $cashing[$i]['cashedDrugs'] = $this->cashingDrugs($data['id']);
         $i++;
      }

      $this->smarty->assign('cashing', $cashing);
      $this->smarty->display('approvals/chronic_details.html');
   }

   public function cashingDrugs($cashingId) {
      $drugs = '  ';
      $cashingDrugs = R::getAll('SELECT  gynachronic_cashing_drugs.drugtype  , drugs.drugname
                FROM gynachronic_cashing_drugs
                join drugs      on drugs.id  =  gynachronic_cashing_drugs.drugid
                where pres_cashing_id =  ?  ', [$cashingId]);

      foreach ($cashingDrugs as $cashingDrug) {
         $drugs .= ' <span class="btn drugSpan"> ';
         $drugs .= $cashingDrug['drugname'] . '    ' . $cashingDrug['drugtype'];
         $drugs .= ' </span> ';
      }
      //  $drugs .= ' </ul> ';
      return $drugs;
   }

   ##########################################################
// at the end of class call

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