<?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 = 'antenalvisit';
      $this->shcontrollname = 'Antenal visit';
      $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] = 'antenalvisit'; //controller name or tab name
      $active[1] = 'antenalvisit'; //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);
      });

//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");
      require_once("pres_common.php");
      require_once("branch_common.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']);

// all drugs will show in selectbox in add new drugs
      $patientid = filter_input(INPUT_GET, "patientid");

      if (empty($patientid)) {
         header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
         exit();
      }


      $this->smarty->assign('currentUser', $_SESSION['user_id']);
      $this->smarty->assign('patientid', $patientid);
      $this->smarty->assign('presDate', date("Y/m/d"));

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

      $pObstetric = R::findAll("phobstetric", 'patientid = ? and del = 0 and obstermination in(1,2)', [$patientid]);
      $this->smarty->assign("p", count($pObstetric));

      /* =====================================================phobstetric=========================================================================== */
      //get G,p
      $del = 0;
      $myallobsteric = R::getAll('select id  from phobstetric where del = ?  and patientid = ? ', [$del, $patientid]);

      $allphobstericterminate = R::findall('phobstericterminate', 'del = 0');
      $getAllPatientData = R::getRow("SELECT * FROM patients WHERE id = $patientid");

      #### p count
      $svddata = R::getAll('select id from phobstetric where obstermination =? and del = 0  and patientid = ?  ', [1, $patientid]);
      $p = $getAllPatientData['pno'];
      $pcounter = count($svddata) + $p;

      #### c.s count
      $csdata = R::getAll('select id from phobstetric where obstermination =? and del = 0  and patientid = ?  ', [2, $patientid]);
      $cs = $getAllPatientData['cs'];
      $cscounter = count($csdata) + $cs;

      $new_p = $cscounter + $pcounter;

      $this->smarty->assign('p', $pcounter + $cscounter); //
      ###AB COUNT
      ###AB COUNT
      $Abortiondata = R::getAll('select id from phobstetric where obstermination =? and del = 0  and patientid = ?  ', [4, $patientid]);
      $ab = $getAllPatientData['ab'];
      $abcounter = count($Abortiondata) + $ab;

      ###Ectopic COUNT
      $Ectopicdata = R::getAll('select id from phobstetric where obstermination =? and del = 0  and patientid = ?  ', [3, $patientid]);
      $Ectopic = $getAllPatientData['ectopic'];
      $Ectopiccounter = count($Ectopicdata) + $Ectopic;

      ###Vmole COUNT
      $Vmoledata = R::getAll('select id from phobstetric where obstermination =? and del = 0  and patientid = ?  ', [5, $patientid]);
      $vmodel = $getAllPatientData['vmodel'];
      $vmodelcounter = count($Vmoledata) + $vmodel;

      $obstriccountnew = $new_p + $abcounter + $Ectopiccounter + $vmodelcounter; //+ $cs count($myallobsteric) +



      /* ================================================================================ */
      $mainObj = R::findOne('mainantenental', 'done = 0 AND patientid = ?', [$patientid]); //done = 0 current pregnancy

      if (count($mainObj) < 1) {
         $mainObj = R::dispense('mainantenental');
         $mainObj->patientid = $patientid;
         $mainObj->doctorid = $_SESSION['user_id'];
         //   $mainObj->lmp = ''; //$this->today;
         $mainObj->g = $obstriccountnew + 1; //count($myallobsteric) + 1;
//            $mainObj->eed = ''; //date("Y/m/d", strtotime("+ 7 days", strtotime($mainObj->lmp . ' +9 months ')));
         $mainObj->ivf = date("Y/m/d", strtotime("- 7 days", strtotime($mainObj->lmp . ' +9 months ')));
         $mainObj->notes = '';
         $mainObj->done = 0;
         $mainid = R::store($mainObj);
         $mainObj->id = $mainid;
      } else {
         $mainObj->g = $obstriccountnew + 1; //count($myallobsteric) + 1;
         R::store($mainObj);
      }

      if (!empty($mainObj->lmp) && $mainObj->lmp != "0000-00-00") {
         $mainObj->lmp = date("Y/m/d", strtotime($mainObj->lmp));
      } elseif ($mainObj->lmp == "0000-00-00") {
         $mainObj->lmp = '';
      }

      if (!empty($mainObj->eed) && $mainObj->eed != "0000-00-00") {
         $mainObj->eed = date("Y/m/d", strtotime($mainObj->eed));
      } elseif ($mainObj->eed == "0000-00-00") {
         $mainObj->eed = '';
      }

      if (!empty($mainObj->ivf) && $mainObj->ivf != "0000-00-00") {
         $mainObj->ivf = date("Y/m/d", strtotime($mainObj->ivf));
      } elseif ($mainObj->ivf == "0000-00-00") {
         $mainObj->ivf = '00-00-0000';
      }

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

      $allantenalvisit = R::findall('antenalvisit', 'conditions = 0 AND mainantenentalid = ? ORDER BY antenaldate DESC ', [$mainObj->id]);

      $iDsArray = '';
      $selectArray = '';
      foreach ($allantenalvisit as $myvisit) {
         $date1 = new DateTime($myvisit->antenaldate);
         $date2 = new DateTime($mainObj->lmp);
         $interval = $date1->diff($date2);
         $diff = round(abs(strtotime($myvisit->antenaldate) - strtotime($mainObj->lmp)) / 86400);
         $myvisit->w = intval($diff / 7) . 'W ' . ($diff % 7) . 'D';

         $myvisit->dateFlag = 0;
         $myvisit->antenaldate = date("Y/m/d", strtotime($myvisit->antenaldate));
         if ($myvisit->antenaldate < $mainObj->lmp) {
            $myvisit->dateFlag = 1;
         }
         $iDsArray .= $myvisit->id . ',';
         $selectArray = explode(',', $myvisit->diagnosisid);
         $myvisit->select = $selectArray;

         $compSelectArray = explode(',', $myvisit->complaintid);
         $myvisit->compselect = $compSelectArray;

         $doctordata = R::getRow('SELECT user_name FROM awusers WHERE user_id = ? ', [$myvisit->doctorid]);
         $myvisit->doctorName = $doctordata['user_name'];

         $antUS = R::findOne('mainantenentalus', 'deleted = ? and patientid = ? and mainantenatalid = ?  
                and date = ?    ORDER BY date DESC ', [0, $patientid, $mainObj->id, $myvisit->antenaldate]);
         if (count($antUS) > 0) {
            $netW = intval($diff / 7);
            $myvisit->usText = $this->visitUsText($antUS, $netW);
         }


         $myvisit->tttText = '';
         $wPres = R::findall('mainantenentaldrugs', 'deleted = ? and patientid = ? and date = ?  and drugid	> 0  
                    and mainantenatalid = ? and forhusband = ?  ', [0, $patientid, $myvisit->antenaldate, $mainObj->id, 0]);
         if (count($wPres) > 0) {
            $myvisit->tttText .= ' Wife : ';
            $w = 0;
            foreach ($wPres as $pre) {
               if ($w > 0) {
                  $myvisit->tttText .= ' ,  ';
               }
               $dd = R::load('drugs', $pre->drugid);
               $myvisit->tttText .= $dd->drugname;
               $w++;
            }
         }

         $hPres = R::findall('mainantenentaldrugs', 'deleted = ? and patientid = ? and date = ?   and drugid	> 0  
                    and mainantenatalid = ? and forhusband = ?  ', [0, $patientid, $myvisit->antenaldate, $mainObj->id, 1]);
         if (count($hPres) > 0) {
            if ($myvisit->tttText != '') {
               $myvisit->tttText .= '<br>';
            }
            $myvisit->tttText .= ' Hus : ';
            $w = 0;
            foreach ($hPres as $pre) {
               if ($w > 0) {
                  $myvisit->tttText .= ' ,  ';
               }
               $dd = R::load('drugs', $pre->drugid);
               $myvisit->tttText .= $dd->drugname;
               $w++;
            }
         }
      }
      $iDsArray = rtrim($iDsArray, ',');
      $this->smarty->assign('iDsArray', $iDsArray);
      $this->smarty->assign('allantenalvisit', $allantenalvisit);

      $alldiagnosis = R::findall('diagnosisant', 'conditions = 0 order by name');
      $this->smarty->assign('alldiagnosis', $alldiagnosis);
      $allcomplaint = R::findall('complaintant', 'conditions = 0 order by name');
      $this->smarty->assign('allcomplaint', $allcomplaint);

      $oldantenal = R::count('mainantenental', 'done = 1 AND patientid = ? order by g desc', [$patientid]); //done = 0 current pregnancy
      $this->smarty->assign('pregBefore', $oldantenal);

      //call other class with other content
      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      patientdata::patientdatashow($this->smarty, $this->hosturl);

      //for end perg
      $terminate = R::findall('phobstericterminate', 'del = 0');
      $this->smarty->assign('terminate', $terminate);

      $place = R::findall('phobstericterplace', 'del = 0');
      $this->smarty->assign('place', $place);

      #################################################################### Heba : ## ultra sound data  ##############################################################################
      $allAntUS1 = array();
      $allAntUS2 = array();

      $allAntUS = R::findall('mainantenentalus', 'deleted = ? and patientid = ? and mainantenatalid = ?  ORDER BY date DESC ', [0, $patientid, $mainObj->id]);
      $lastAntUS = R::findOne('mainantenentalus', 'deleted = ? and patientid = ? and mainantenatalid = ?  ORDER BY date DESC ', [0, $patientid, $mainObj->id]);
      foreach ($allAntUS as $us) {
         $us->date = date("Y/m/d", strtotime($us->date));
         $doctordata = R::getRow('SELECT user_name FROM awusers WHERE user_id = ? ', [$us->doctorid]);
         $us->doctorname = $doctordata['user_name'];

         $date1 = new DateTime($us->date);
         $date2 = new DateTime($mainObj->lmp);
         $interval = $date1->diff($date2);
         // $us->w = round($interval->days / 7);
         $us->w = intval($interval->days / 7) . 'W ' . ($interval->days % 7) . 'D';
         $us->netW = intval($interval->days / 7);
         if ($us->netW >= 4 && $us->netW < 14) {
            array_push($allAntUS1, $us);
         } elseif ($us->netW >= 14 && $us->netW <= 40) {
            array_push($allAntUS2, $us);
         }
      }
      $this->smarty->assign('allAntUS', $allAntUS);
      $this->smarty->assign('allAntUS1', $allAntUS1);
      $this->smarty->assign('allAntUS2', $allAntUS2);
      if ($lastAntUS) {
         $this->smarty->assign('lastPlacenta', $lastAntUS->placenta);
      } else {
         $this->smarty->assign('lastPlacenta', '');
      }

      $tables = array("no_soc", "no_fetal", "fetal_pulse", "fet_no", "visibility", "ant_presentation", "ant_liquor");
      foreach ($tables as $table) {
         $records = R::findAll($table, ' deleted != 1 ');
         $this->smarty->assign($table, $records);
      }

      #################################################################### Heba : ## Drugs Data   ##############################################################################
      ## get id and distinct drugname
      $this->getprescription($patientid, date("Y/m/d"), 0, $mainObj->id);
      $this->smarty->assign('presDate', date("Y/m/d"));

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

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

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

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

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

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


      $favorites = R::findall('invests', 'deleted = ? and  favorite= ?', [0, 1]);

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

      $invoffers = R::findall('invoffer', 'active = ? and  del = ? ', [1, 0]);
      foreach ($invoffers as $offer) {
         $invs = R::getRow('SELECT  sum(price) as price   FROM  invofferdetails where invoffer_id = ? and  del = ?  '
                         , [$offer->id, 0]);
         $offer->price = $invs['price'];
      }
      $this->smarty->assign('invoffers', $invoffers);

//Save entering antenatal visit
      $lastVisitData = R::findOne('lastvisit', 'patientid', [$patientid]);

      $lastVisit = R::dispense('lastvisit');
      $lastVisit->patientid = $patientid;
      $lastVisit->control = $this->controllname;
      if ($lastVisitData->patientid == $patientid) {
         $lastVisit->id = $lastVisitData->id;
      }
      R::store($lastVisit);

      $allRayCats1 = R::findall('rayscats', 'deleted = ? and displayorder in (1 , 2) order by displayorder ', [0]);
      foreach ($allRayCats1 as $cat) {
         $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
         $cat->rays = $rays;
      }

      $allRayCats2 = R::findall('rayscats', 'deleted = ? and displayorder = 3 order by displayorder ', [0]);
      foreach ($allRayCats2 as $cat) {
         $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
         $cat->rays = $rays;
      }

      $allRayCats3 = R::findall('rayscats', 'deleted = ? and displayorder in (4 , 5) order by displayorder ', [0]);
      foreach ($allRayCats3 as $cat) {
         $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
         $cat->rays = $rays;
      }

      $allRayCats4 = R::findall('rayscats', 'deleted = ? and displayorder  between 6 and  11 order by displayorder ', [0]);
      foreach ($allRayCats4 as $cat) {
         $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
         $cat->rays = $rays;
      }

      $allRayCats5 = R::findall('rayscats', 'deleted = ? and displayorder > 11 order by displayorder ', [0]);
      foreach ($allRayCats5 as $cat) {
         $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
         $cat->rays = $rays;
      }

      $otherRays = R::findall('rayscats', 'deleted = ? and displayorder = ?  order by displayorder ', [0, 0]);
      foreach ($otherRays as $cat) {
         $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
         $cat->rays = $rays;
      }


      $favoritesRays = R::findall('rays', 'deleted = ? and  favorite= ?', [0, 1]);

      $this->smarty->assign('favoritesRays', $favoritesRays);
      $this->smarty->assign('allRayCats1', $allRayCats1);
      $this->smarty->assign('allRayCats2', $allRayCats2);
      $this->smarty->assign('allRayCats3', $allRayCats3);
      $this->smarty->assign('allRayCats4', $allRayCats4);
      $this->smarty->assign('allRayCats5', $allRayCats5);
      $this->smarty->assign('otherRays', $otherRays);

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

      $presCount = R::count('mainantenentaldrugs', 'deleted = ? and patientid = ? and mainantenatalid = ?
                 and drugid > 0  ', [0, $patientid, $mainObj->id]);
      $this->smarty->assign('presCount', $presCount);

      $raysCount = R::count('mainantenentalrays', 'deleted = ? and patientid = ? and mainantenatalid = ?'
                      , [0, $patientid, $mainObj->id]);
      $this->smarty->assign('raysCount', $raysCount);

      $usCount = R::count('mainantenentalus', 'deleted = ? and patientid = ? and mainantenatalid = ?'
                      , [0, $patientid, $mainObj->id]);
      $this->smarty->assign('usCount', $usCount);

      $investCount = R::count('mainantenentalinvest', 'deleted = ? and patientid = ? and mainantenatalid = ?'
                      , [0, $patientid, $mainObj->id]);
      $this->smarty->assign('investCount', $investCount);

#################################################################
      $this->smarty->display('antenalvisit/add.html');

      leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
      footer::footershow($this->smarty, $this->hosturl);
   }

   function visitUsText($antUS, $netW) {
      $us = '';

      if ($netW >= 4 && $netW < 14) {
         if ($antUS->no_soc > 0) {
            $no_soc = R::load('no_soc', $antUS->no_soc);
            $us .= '<span class=" usSpan fleft"> No. of soc  :  ' . $no_soc->name . ' </span>';
         }

         if ($antUS->no_fetal > 0) {
            $no_fetal = R::load('no_fetal', $antUS->no_fetal);
            $us .= '<span class=" usSpan fleft"> No. of Fetal Pole  :  ' . $no_fetal->name . ' </span>';
         }

         if ($antUS->fetal_pulse > 0) {
            $fetal_pulse = R::load('fetal_pulse', $antUS->fetal_pulse);
            $us .= '<span class=" usSpan fleft"> Fetal Pulsation  :  ' . $fetal_pulse->name . ' </span>';
         }

         if ($antUS->gs != '' && $antUS->gs != null) {
            $us .= '<span class=" usSpan fleft"> GS  :  ' . $antUS->gs . ' </span>';
         }

         if ($antUS->crl != '' && $antUS->crl != null) {
            $us .= '<span class=" usSpan fleft"> CRL  :  ' . $antUS->crl . ' </span>';
         }

         if ($antUS->notes != '' && $antUS->notes != null) {
            $us .= '<span class=" usSpan fleft"> Notes  :  ' . $antUS->notes . ' </span>';
         }
      }


      #############
      elseif ($netW >= 14 && $netW <= 40) {
         if ($antUS->fet_no > 0) {
            $fet_no = R::load('fet_no', $antUS->fet_no);
            $us .= '<span class=" usSpan fleft"> No.  :  ' . $fet_no->name . ' </span>';
         }

         if ($antUS->visibility > 0) {
            $visibility = R::load('visibility', $antUS->visibility);
            $us .= '<span class=" usSpan fleft"> Visibility  :  ' . $visibility->name . ' </span>';
         }

         if ($antUS->ant_presentation > 0) {
            $ant_presentation = R::load('ant_presentation', $antUS->ant_presentation);
            $us .= '<span class=" usSpan fleft"> Presentation  :  ' . $ant_presentation->name . ' </span>';
         }

         if ($antUS->ant_liquor > 0) {
            $ant_liquor = R::load('ant_liquor', $antUS->ant_liquor);
            $us .= '<span class=" usSpan fleft"> Liquor  :  ' . $ant_liquor->name . ' </span>';
         }

         if ($antUS->bpd != '' && $antUS->bpd != null) {
            $us .= '<span class=" usSpan fleft"> BPD  :  ' . $antUS->bpd . ' </span>';
         }

         if ($antUS->fl != '' && $antUS->fl != null) {
            $us .= '<span class=" usSpan fleft"> FL  :  ' . $antUS->fl . ' </span>';
         }

         if ($antUS->ac != '' && $antUS->ac != null) {
            $us .= '<span class=" usSpan fleft"> AC  :  ' . $antUS->ac . ' </span>';
         }

         if ($antUS->efw != '' && $antUS->efw != null) {
            $us .= '<span class=" usSpan fleft"> EFW  :  ' . $antUS->efw . '  gm</span>';
         }

         if ($antUS->notes != '' && $antUS->notes != null) {
            $us .= '<span class=" usSpan fleft"> Notes  :  ' . $antUS->notes . ' </span>';
         }
      }


      return $us;
   }

   private function getprescription($patientId, $date, $preFor, $mainAntenatalId) {
      // r::debug(true, 2);
      $PatientPresByDate = R::findall('mainantenentaldrugs', 'deleted = ? and patientid = ? and date = ?  and mainantenatalid = ? and forhusband = ?  ', [0, $patientId, $date, $mainAntenatalId, $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('PatientPresByDate', $PatientPresByDate);
      $this->smarty->assign('preItr', count($PatientPresByDate));
   }

   public function del() {

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

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

      try {
         $myObject = R::load('antenalvisit', $id);
         $myObject->conditions = 1;
         R::store($myObject);
         echo 1;
         //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname.'.php?ac=index' );
      } catch (Exception $e) {
         //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
      }
   }

   public function archive() {

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

      $patientid = filter_input(INPUT_GET, "patientid");

      if (empty($patientid)) {
         header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
         exit();
      }
      //call other class with other content
      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      patientdata::patientdatashow($this->smarty, $this->hosturl);

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

      $oldantenal = R::findall('mainantenental', 'done = 1 AND patientid = ? order by id asc', [$patientid]); //done = 0 current pregnancy
      $this->smarty->assign('oldantenal', $oldantenal);
      $this->smarty->assign('oldantenalCount', count($oldantenal));

      $this->smarty->display('antenalvisit/archive.html');

      leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
      footer::footershow($this->smarty, $this->hosturl);
   }

   public function pregdetail() {

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

      $patientid = filter_input(INPUT_GET, "patientid");
      $this->smarty->assign('patientid', $patientid);

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

      if (empty($patientid) || empty($id)) {
         header('Location:' . $this->hosturl . '/controllers/index.php?empty=1');
         exit();
      }

      //call other class with other content
      header::headershow($this->smarty, $this->hosturl);
      sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
      patientdata::patientdatashow($this->smarty, $this->hosturl);

      //$this->smarty->assign('patientid', $patientid);

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

      $mainObj = R::findOne('mainantenental', 'patientid = ? and id = ?', [$patientid, $id]); //done = 0 current pregnancy
      $this->smarty->assign('mainObj', $mainObj);
      if (count($mainObj) > 0) {
         #################################################################### Heba : ## ultra sound data  ##############################################################################

         $allAntUS = R::findall('mainantenentalus', 'deleted = ? and patientid = ? and mainantenatalid = ?  ORDER BY date DESC ', [0, $patientid, $mainObj->id]);
         foreach ($allAntUS as $us) {
            $doctordata = R::getRow('SELECT user_name FROM awusers WHERE user_id = ? ', [$us->doctorid]);
            $us->doctorname = $doctordata['user_name'];
         }
         $this->smarty->assign('allAntUS', $allAntUS);

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

         #############################################################################################################################################################
         $allantenalvisit = R::findall('antenalvisit', 'conditions = 0 AND mainantenentalid = ? ORDER BY antenaldate DESC ', [$mainObj->id]);
         $iDsArray = '';
         foreach ($allantenalvisit as $myvisit) {
            $date1 = new DateTime($myvisit->antenaldate);
            $date2 = new DateTime($mainObj->lmp);
            $interval = $date1->diff($date2);
            //echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
            // shows the total amount of days (not divided into years, months and days like above)
            $myvisit->w = round($interval->days / 7);
            $myvisit->dateFlag = 0;
            if ($myvisit->antenaldate < $mainObj->lmp) {
               $myvisit->dateFlag = 1;
            }
            $iDsArray .= $myvisit->id . ',';
            $selectArray = explode(',', $myvisit->diagnosisid);
            $myvisit->select = $selectArray;

            $compSelectArray = explode(',', $myvisit->complaintid);
            $myvisit->compselect = $compSelectArray;
         }

         $iDsArray = rtrim($iDsArray, ',');
         $this->smarty->assign('iDsArray', $iDsArray);

         $alldiagnosis = R::findall('diagnosisant', 'conditions = 0 order by name');
         $this->smarty->assign('alldiagnosis', $alldiagnosis);
         $allcomplaint = R::findall('complaintant', 'conditions = 0 order by name');
         $this->smarty->assign('allcomplaint', $allcomplaint);

         $this->smarty->assign('patientid', $patientid);
         $this->smarty->assign('allantenalvisit', $allantenalvisit);
         $this->smarty->assign('allantenalvisitCount', count($allantenalvisit));
         $this->smarty->display('antenalvisit/pregdetail.html');
      }



      leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
      footer::footershow($this->smarty, $this->hosturl);
   }

   //------------------------------ ajax calls ------------------------------//
   public function newrow() {

      //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_GET, "id");

      $mainObj = R::findOne('mainantenental', 'done = 0 AND patientid = ?', [$patientid]); //done = 0 current pregnancy


      $myObject = R::dispense('antenalvisit');
      $myObject->patientid = $patientid;
      $myObject->doctorid = $_SESSION['user_id'];
      $myObject->antenaldate = $this->today;
      $myObject->complaint = '';
      $myObject->wt = '';
      $myObject->bp = '';
      $myObject->notes = '';
      $myObject->conditions = 0;
      $myObject->diagnosisid = '';
      $myObject->complaintid = '';
      $myObject->mainantenentalid = $mainObj->id;
      //call other class with other content


      try {
         $id = R::store($myObject);
         $myObject->id = $id;

         $date1 = new DateTime($myObject->antenaldate);
         $date2 = new DateTime($mainObj->lmp);
         $interval = $date1->diff($date2);
         //echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
         // shows the total amount of days (not divided into years, months and days like above)
         //   $myObject->w = round($interval->days / 7);
         $diff = round(abs(strtotime($myObject->antenaldate) - strtotime($mainObj->lmp)) / 86400);
         $myObject->w = intval($diff / 7) . 'W ' . ($diff % 7) . 'D';
         $myObject->dateFlag = 0;
         $mainObj->lmp = date("Y/m/d", strtotime($mainObj->lmp));
         if ($myObject->antenaldate < $mainObj->lmp) {
            $myObject->dateFlag = 1;
         }
         $myObject->antenaldate = date("Y/m/d", strtotime($myObject->antenaldate));
         $alldiagnosis = R::findall('diagnosisant', 'conditions = 0 order by name');
         $allcomplaint = R::findall('complaintant', 'conditions = 0 order by name');
         $this->smarty->assign('allcomplaint', $allcomplaint);
         $this->smarty->assign('alldiagnosis', $alldiagnosis);
         $this->smarty->assign('myObject', $myObject);
         $this->smarty->display('antenalvisit/newrow.html');
         //header('Location:' . $this->hosturl . '/' . $this->controllname );
      } catch (Exception $e) {
         //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
      }
   }

   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");
      $vdateFlag = filter_input(INPUT_POST, "vdateFlag");

      if ($colname == "placentaOut") {
         $mainObj = R::load('mainantenental', $id); //done = 0 current pregnancy
         $lastAntUS = R::findOne('mainantenentalus', 'deleted = ? and patientid = ? and mainantenatalid = ? and date = ?', [0, $mainObj->patientid, $id, date('Y/m/d')]);
         if (count($lastAntUS) > 0) {
            $lastAntUS->placenta = $value;
            R::store($lastAntUS);
         } else {
            $newUs = R::dispense('mainantenentalus');
            $newUs->placenta = $value;
            $newUs->patientid = $mainObj->patientid;
            $newUs->doctorid = $_SESSION['user_id'];
            $newUs->date = $this->today;
            $newUs->mainantenatalid = $id;
            $newUs->deleted = 0;
            R::store($newUs);
         }
      } else {
         if ($tablename == 'mainantenentaldrugs') {
            $this->updatedrugs($id, $tablename, $colname, $value);
         } else {

            if ($colname == 'lmp' || $colname == 'eed' || $vdateFlag == true) {
               $value = date("Y/m/d", strtotime($value));
            }

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

            if ($dated == 1) {
               $value = date("Y/m/d", strtotime($value));
            }

            if ($colname == "diagnosisid") {
               $diagnosis = json_decode($value);
               sort($diagnosis);
               $value = "";
               foreach ($diagnosis as $myname) {
                  $value = $value . $myname . ",";
               }

               $value = substr($value, 0, -1);
            }
            if ($colname == "complaintid") {
               $complaint = json_decode($value);
               sort($complaint);
               $value = "";
               foreach ($complaint as $myname) {
                  $value = $value . $myname . ",";
               }

               //print_r($finalname);
               $value = substr($value, 0, -1);
            }

            $gyna_obj = R::load($tablename, $id);
            if (($colname == 'eed' || $colname == 'lmp') && $gyna_obj->$colname == '0000-00-00') {
               $gyna_obj->sysdate = date('Y-m-d');
            }

            $gyna_obj->$colname = $value;

            if ($colname == 'lmp') {
               $gyna_obj->eed = date("Y-m-d", strtotime("+ 7 days", strtotime($gyna_obj->$colname . ' +9 months ')));
               $gyna_obj->ivf = date("Y-m-d", strtotime("- 7 days", strtotime($gyna_obj->$colname . ' +9 months ')));

               $data = date("Y/m/d", strtotime($gyna_obj->eed));
               $data .= ',' . date("Y/m/d", strtotime($gyna_obj->ivf));
               $data .= ',' . date("Y/m/d", strtotime($gyna_obj->lmp));
               echo $data;
            }

            if ($colname == 'eed') {

               $gyna_obj->lmp = date("Y-m-d", strtotime("- 7 days", strtotime($gyna_obj->$colname . ' -9 months ')));
               $gyna_obj->ivf = date("Y-m-d", strtotime("- 7 days", strtotime($gyna_obj->lmp . ' +9 months ')));

               $data = date("Y/m/d", strtotime($gyna_obj->eed));
               $data .= ',' . date("Y/m/d", strtotime($gyna_obj->ivf));
               $data .= ',' . date("Y/m/d", strtotime($gyna_obj->lmp));
               echo $data;
            }
            R::store($gyna_obj);
         }
      }
   }

   private function updatedrugs($id, $tablename, $colname, $value) {
      $obj = R::load($tablename, $id);
      archiveDrugRecord($obj, $tablename);
      if ($colname == 'drugid') {
         $obj->doctorid = $_SESSION['user_id'];
         if ($value != '') {
            $drug = R::load("drugs", $value);
            $obj->drugname = $drug->drugname;
         }
      }

      $obj->$colname = $value;
      try {
         R::store($obj);
      } catch (Exception $e) {
         //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
      }
   }

   public function endpreg() {

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

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

      $mainObj = R::findOne('mainantenental', 'done = 0 AND patientid = ?', [$patientid]); //done = 0 current pregnancy

      if (count($mainObj) > 0) {
         /* $obstrduration = filter_input(INPUT_POST, "obstrduration");
           $obstermination = filter_input(INPUT_POST, "obstermination");
           $obsplace = filter_input(INPUT_POST, "obsplace");
           $obsdate = filter_input(INPUT_POST, "obsdate");
           $obsnote = filter_input(INPUT_POST, "obsnote");


           $myObject = R::dispense('phobstetric');
           $myObject->patientid = $patientid;
           $myObject->sysdate = $this->today;
           $myObject->obstrduration = $obstrduration;
           $myObject->obstermination = $obstermination;

           $myObject->obsplace = $obsplace;
           $myObject->obsdate = $obsdate;
           $myObject->obsnote = $obsnote;

           $myObject->doctorid = $_SESSION['user_id'];
           $myObject->del = 0;
           R::store($myObject); */




         try {



            $mainObj->done = 1;
            R::store($mainObj);
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname.'.php');
         } catch (Exception $e) {
            //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
         }
      } else {
         echo -1;
      }
   }

   public function addtermination() {

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

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

      try {
         $obj = R::dispense('phobstericterminate');
         $obj->name = $name;
         $obj->del = 0;
         $id = R::store($obj);

         echo $id;
      } catch (Exception $e) {
         //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
      }
   }

   public function addplace() {

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

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

      try {
         $obj = R::dispense('phobstericterplace');
         $obj->name = $name;
         $obj->del = 0;
         $id = R::store($obj);

         echo $id;
      } catch (Exception $e) {
         //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
      }
   }

   public function alltermination() {

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

      try {

         $alldata = R::findall('phobstericterminate', 'del = 0');
         $this->smarty->assign('alldata', $alldata);
         $this->smarty->assign('func', 'deltermination');
         $this->smarty->assign('tablename', 'phobstericterminate');
         $this->smarty->assign('colname', 'name');
         $this->smarty->display('antenalvisit/editmodel.html');
         //header('Location:' . $this->hosturl . '/' . $this->controllname );
      } catch (Exception $e) {
         //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
      }
   }

   public function allplace() {

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

      try {

         $alldata = R::findall('phobstericterplace', 'del = 0');
         $this->smarty->assign('alldata', $alldata);
         $this->smarty->assign('func', 'delplace');
         $this->smarty->assign('tablename', 'phobstericterplace');
         $this->smarty->assign('colname', 'name');
         $this->smarty->display('antenalvisit/editmodel.html');
         //header('Location:' . $this->hosturl . '/' . $this->controllname );
      } catch (Exception $e) {
         //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
      }
   }

   public function deltermination() {

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

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

      try {
         $obj = R::load('phobstericterminate', $id);
         $obj->del = 1;
         R::store($obj);

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

   public function delplace() {

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

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

      try {
         $obj = R::load('phobstericterplace', $id);
         $obj->del = 1;
         R::store($obj);

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

   public function loadusrow() {       ## new row at ultrasound  form model
      //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");   ## ussimple or uscomplete or usantenatal
      $itr = filter_input(INPUT_POST, "itr");
      $mainAntenatalId = filter_input(INPUT_POST, "mainAntenatalId");
      $mainObj = R::load('mainantenental', $mainAntenatalId);

      if ($type == "usantenatal") {
         $antUltrasound = R::dispense('mainantenentalus');
         $antUltrasound->patientid = $patientId; //
         $antUltrasound->doctorid = $_SESSION['user_id'];
         $antUltrasound->date = $this->today;
         $antUltrasound->mainantenatalid = $mainAntenatalId;
         $antUltrasound->deleted = 0;
         //call other class with other content
         try {
            $id = R::store($antUltrasound);
            $antUltrasound->id = $id;

            $date1 = new DateTime($antUltrasound->date);
            $date2 = new DateTime($mainObj->lmp);
            $interval = $date1->diff($date2);
            //echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
            // shows the total amount of days (not divided into years, months and days like above)
            //     $antUltrasound->w = round($interval->days / 7);

            $antUltrasound->w = intval($interval->days / 7) . 'W ' . ($interval->days % 7) . 'D';
            $antUltrasound->netW = intval($interval->days / 7);

            if ($antUltrasound->netW >= 4 && $antUltrasound->netW < 14) {
               $tables = array("no_soc", "no_fetal", "fetal_pulse");
               foreach ($tables as $table) {
                  $records = R::findAll($table, ' deleted != 1 ');
                  $this->smarty->assign($table, $records);
               }
               $this->smarty->assign('antType', 1);
            } elseif ($antUltrasound->netW >= 14 && $antUltrasound->netW <= 40) {
               $tables = array("fet_no", "visibility", "ant_presentation", "ant_liquor");
               foreach ($tables as $table) {
                  $records = R::findAll($table, ' deleted != 1 ');
                  $this->smarty->assign($table, $records);
               }
               $this->smarty->assign('antType', 2);
            }





            $antUltrasound->dateFlag = 0;

            $doctordata = R::getRow('SELECT user_name FROM awusers WHERE user_id = ? ', [$antUltrasound->doctorid]);
            $antUltrasound->doctorname = $doctordata['user_name'];

            $antUltrasound->date = date('Y/m/d', strtotime($antUltrasound->date));

            $this->smarty->assign('aUs', $antUltrasound);
            $this->smarty->assign('itr', $itr);
            $this->smarty->assign('type', $type);
            $this->smarty->display('antenalvisit/newrowUS.html');
         } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
         }
      }
   }

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

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

      try {
         $myObject = R::load('mainantenentaldrugs', $id);
         $myObject->deleted = 1;
         R::store($myObject);
         echo 1;
         //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname.'.php?ac=index' );
      } catch (Exception $e) {
         //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
      }
   }

   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");
      $mainAntenatalId = filter_input(INPUT_POST, "mainAntenatalId");
      $archive = filter_input(INPUT_POST, "archive");
      $type = filter_input(INPUT_POST, "type");  ## show or edit
      $preFor = filter_input(INPUT_POST, "preFor");
      $countHusband = '';
      $countWife = '';

      ## show all prescription of patient
      if ($type == "show") {
         $dates = R::getAll('SELECT DISTINCT date  FROM mainantenentaldrugs WHERE deleted = ? and patientid = ? and mainantenatalid = ?  order by date desc', [0, $patientId, $mainAntenatalId]);
         $i = 0;
         foreach ($dates as $date) {
            ## all prescription of certain patient
            $PatientPresByDateWife = R::findall('mainantenentaldrugs', 'deleted = ? and patientid = ? and date = ?  and mainantenatalid = ? and forhusband = ? ', [0, $patientId, $date['date'], $mainAntenatalId, 0]);
            $PatientPresByDateHusband = R::findall('mainantenentaldrugs', 'deleted = ? and patientid = ? and date = ?  and mainantenatalid = ? and forhusband = ? ', [0, $patientId, $date['date'], $mainAntenatalId, 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->assign('archive', $archive);
         $this->smarty->display('antenalvisit/showPrescriptions.html');
      }

      ## show  prescription of patient with determined date to edit it
      else if ($type == "edit") {
         $date = filter_input(INPUT_POST, "preDate");
         $date = date("Y/m/d", strtotime($date));
         $this->getprescription($patientId, $date, $preFor, $mainAntenatalId);
         $this->smarty->assign('type', "drugedit");
         $this->smarty->display('antenalvisit/newrowdrugedit.html');
      }
   }

   public function addinvestigation() {       ## add prescription to 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);

      $invDate = filter_input(INPUT_POST, 'invDate');
      $printDate = filter_input(INPUT_POST, 'printInvDate');

      $forHusband = filter_input(INPUT_POST, 'forHusband');
      if ($forHusband != 1) {
         $forHusband = 0;
      }

      $patientId = filter_input(INPUT_POST, 'patientId');
      $mainAntenatalId = filter_input(INPUT_POST, 'mainId');  ## main Antenatal Id
      $investsList = $_POST['invCheck'];
      $offersList = $_POST['offersCheck'];

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

      $invests = array();

      if (!empty($investsList)) {

         foreach ($investsList as $check) {
            $antInvest = R::dispense('mainantenentalinvest');
            $antInvest->patientid = $patientId;
            $antInvest->mainantenatalid = $mainAntenatalId;
            $antInvest->date = date("Y/m/d", strtotime($invDate));
            $antInvest->investid = $check;
            $antInvest->doctorid = $_SESSION['user_id'];
            $antInvest->deleted = 0;
            $antInvest->forhusband = $forHusband;

            array_push($invests, $antInvest);
         }
      }

      if (!empty($offersList)) {
         foreach ($offersList as $offer_id) {
            $invofferdetails = R::findall('invofferdetails', 'del = ? and invoffer_id = ?  ', [0, $offer_id]);
            foreach ($invofferdetails as $data) {
               $antInvest = R::dispense('mainantenentalinvest');
               $antInvest->patientid = $patientId;
               $antInvest->mainantenatalid = $mainAntenatalId;
               $antInvest->date = date("Y/m/d", strtotime($invDate));
               $antInvest->investid = $data->inv_id;
               $antInvest->doctorid = $_SESSION['user_id'];
               $antInvest->deleted = 0;
               $antInvest->forhusband = $forHusband;
               $antInvest->offer_id = $offer_id;

               array_push($invests, $antInvest);
            }
         }
      }

      if (count($invests) > 0) {
         try {
            R::storeAll($invests);
            foreach ($invests as $invest) {
               $investm = R::load('invests', $invest->investid);
               $invest->name = $investm->name;
            }
            $this->smarty->assign('investigations', $invests);
            if ($forHusband == 1) {
               $this->smarty->assign('name', $patient->husdandname);
               $this->smarty->assign('title', $husbandtypes->title);
            } else {
               $this->smarty->assign('name', $patient->wifename);
               $this->smarty->assign('title', $wifetypes->title);
            }
            $this->smarty->assign('date', date("Y/m/d", strtotime($printDate)));
            $this->smarty->assign('statusNo', $patient->statusno);
            $this->smarty->display('gyna/printinv.html');
         } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
         }
      }
   }

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

      $patientId = filter_input(INPUT_POST, "patientId");
      $mainAntenatalId = filter_input(INPUT_POST, "mainAntenatalId");
      $archive = filter_input(INPUT_POST, "archive");

      ## show all investigations of patient
      $dates = R::getAll('SELECT DISTINCT date  FROM mainantenentalinvest WHERE deleted = ? and patientid = ? and mainantenatalid = ?  order by date desc', [0, $patientId, $mainAntenatalId]);
      $countHusband = array();
      $countWife = array();

      $i = 0;
      foreach ($dates as $date) {
         ## all invs of certain patient
         $PatientInvByDateHusband = R::findall('mainantenentalinvest', 'deleted = ? and patientid = ? and date = ? and mainantenatalid = ? and forhusband = ? ', [0, $patientId, $date['date'], $mainAntenatalId, 1]);
         $PatientInvByDateWife = R::findall('mainantenentalinvest', 'deleted = ? and patientid = ? and date = ? and mainantenatalid = ? and forhusband = ? ', [0, $patientId, $date['date'], $mainAntenatalId, 0]);

         foreach ($PatientInvByDateHusband as $in) {
            $invest = R::load('invests', $in->investid);
            $in->invname = $invest->name;
            $in->invResId = checkInvResult($in->investid, $patientId, $date['date'], 1);
         }

         foreach ($PatientInvByDateWife as $in) {
            $invest = R::load('invests', $in->investid);
            $in->invname = $invest->name;
            $in->invResId = checkInvResult($in->investid, $patientId, $date['date'], 0);
         }


         $dates[$i]['investsh'] = $PatientInvByDateHusband;
         $dates[$i]['investsw'] = $PatientInvByDateWife;
         $dates[$i]['date'] = date("Y/m/d", strtotime($dates[$i]['date']));

         $countHusband[$dates[$i]['date']] = count($PatientInvByDateHusband);
         $countWife[$dates[$i]['date']] = count($PatientInvByDateWife);
         $i++;
      }

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

      $this->smarty->display('antenalvisit/showInvestigation.html');
   }

   public function delantus() {      ## delete row from gynaus table
      //check login
      autho::checkautho($this->hosturl);
      //check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

      $id = filter_input(INPUT_POST, "id");
      $gynaus = R::load('mainantenentalus', $id);
      $gynaus->deleted = 1;

      try {
         R::store($gynaus);
         echo 1;
      } catch (Exception $e) {
         echo 22;
      }
   }

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

      $patientId = filter_input(INPUT_POST, "patientId");
      $date = filter_input(INPUT_POST, "date");
      $printDate = filter_input(INPUT_POST, "printDate");
      $preFor = filter_input(INPUT_POST, "preFor");
      $mainAntenatalId = filter_input(INPUT_POST, 'mainAntenatalId');  ## main Antenatal Id

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

      $date = date("Y/m/d", strtotime($date));

      ## all prescription of certain patient
      $PatientPresByDate = R::findall('mainantenentaldrugs', 'deleted = ? and patientid = ? and date = ? and mainantenatalid = ? and forhusband = ? ', [0, $patientId, $date, $mainAntenatalId, $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);

      if (isset($printDate) && !empty($printDate)) {
         $this->smarty->assign('printDate', $printDate);
      } else {
         $this->smarty->assign('printDate', $date);
      }


      $this->smarty->assign('statusNo', $patient->statusno);
      if ($ProgramesettingData->pres_version == 1) {
         $doctors = presDoctors('mainantenentaldrugs', $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->display('gyna/print_full.html');
      } else {
         $this->smarty->display('gyna/print.html');
      }
   }

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

      $patientId = filter_input(INPUT_POST, "patientId");
      $date = filter_input(INPUT_POST, "date");
      $mainAntenatalId = filter_input(INPUT_POST, 'mainAntenatalId');  ## main Antenatal Id
      $dataFor = filter_input(INPUT_POST, "dataFor");

      $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 ($dataFor == 'wife') {
         $this->smarty->assign('name', $patient->wifename);
         $this->smarty->assign('title', $wifetypes->title);
      } elseif ($dataFor == 'husband') {
         $this->smarty->assign('name', $patient->husdandname);
         $this->smarty->assign('title', $husbandtypes->title);
      }



      ## all prescription of certain patient
      if ($dataFor == 'wife') {
         $PatientInvByDate = R::findall('mainantenentalinvest', 'deleted = ? and patientid = ? and date = ? and mainantenatalid = ? and forhusband = ?', [0, $patientId, $date, $mainAntenatalId, 0]);
      } elseif ($dataFor == 'husband') {
         $PatientInvByDate = R::findall('mainantenentalinvest', 'deleted = ? and patientid = ? and date = ? and mainantenatalid = ? and forhusband = ? ', [0, $patientId, $date, $mainAntenatalId, 1]);
      }

      foreach ($PatientInvByDate as $invest) {
         $investm = R::load('invests', $invest->investid);
         $invest->name = $investm->name;
      }
      $this->smarty->assign('investigations', $PatientInvByDate);

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

      $this->smarty->assign('statusNo', $patient->statusno);
      $this->smarty->display('gyna/printinv.html');
   }

   public function adddiagnosis() {

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

      $name = filter_input(INPUT_POST, "diagnosisName");
      $id = filter_input(INPUT_POST, "id");
      $table = filter_input(INPUT_POST, "table");
      try {
         $diagnosis = R::dispense($table);
         $diagnosis->name = $name;
         $diagnosis->conditions = 0;
         $did = R::store($diagnosis);
         $mygyna = R::findone('antenalvisit', 'id=? ', [$id]);
         if ($table == "diagnosisant") {
            if (empty($mygyna->diagnosisid))
               $mygyna->diagnosisid = $did;
            else
               $mygyna->diagnosisid = $mygyna->diagnosisid . ',' . $did;
         } else {
            if (empty($mygyna->complaintid))
               $mygyna->complaintid = $did;
            else
               $mygyna->complaintid = $mygyna->complaintid . ',' . $did;
         }
         R::store($mygyna);

         echo $did;
      } catch (Exception $e) {
         //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
      }
   }

   public function alldiagnosis() {

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

      $colname = filter_input(INPUT_POST, "colName");
      $table;
      if ($colname == "diagnosisid")
         $table = "diagnosisant";
      else
         $table = "complaintant";
      try {

         $alldiagnosis = R::findall($table, 'conditions = 0 order by name');
         $this->smarty->assign('alldata', $alldiagnosis);
         $this->smarty->assign('table', $table);
         $this->smarty->display('antenalvisit/editmodel.html');
         //header('Location:' . $this->hosturl . '/' . $this->controllname );
      } catch (Exception $e) {
         //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
      }
   }

   public function deldiagnosis() {

      //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");
      try {
         $gyna_obj = R::load($tableName, $id);
         $gyna_obj->conditions = 1;
         R::store($gyna_obj);

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

   public function addNewRow() {

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

      //vars here
      $table = filter_input(INPUT_POST, 'tablename');

      ### insert into table
      $newtable = R::dispense($table);
      $newtable->conditions = 0;

      $insertid = R::store($newtable);

      echo $insertid;
   }

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

      $patientId = filter_input(INPUT_POST, 'patientId');
      $raysList = $_POST['rayCheck'];
      $ProgramesettingData = R::findone('programesetting');
      $this->smarty->assign('ProgramesettingData', $ProgramesettingData);

      $rayDate = filter_input(INPUT_POST, 'rayDate');
      $printDate = filter_input(INPUT_POST, 'printrayDate');

      $forHusband = filter_input(INPUT_POST, 'forHusbandRay');
      if ($forHusband != 1) {
         $forHusband = 0;
      }

      $mainAntenatalId = filter_input(INPUT_POST, 'mainId');  ## main Antenatal Id

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

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

      if (!empty($raysList)) {
         $rays = array();
         foreach ($raysList as $check) {
            $antRays = R::dispense('mainantenentalrays');
            $antRays->patientid = $patientId;
            $antRays->date = date("Y-m-d", strtotime($rayDate));
            $antRays->mainantenatalid = $mainAntenatalId;
            $antRays->rayid = $check;
            $antRays->doctorid = $_SESSION['user_id'];
            $antRays->deleted = 0;
            $antRays->forhusband = $forHusband;

            array_push($rays, $antRays);
         }

         try {
            R::storeAll($rays);
            foreach ($rays as $ray) {
               $raytm = R::load('rays', $ray->rayid);
               $ray->name = $raytm->name;
            }
            $this->smarty->assign('investigations', $rays);
            if ($forHusband == 1) {
               $this->smarty->assign('name', $patient->husdandname);
               $this->smarty->assign('title', $husbandtypes->title);
            } else {
               $this->smarty->assign('name', $patient->wifename);
               $this->smarty->assign('title', $wifetypes->title);
            }
            $this->smarty->assign('statusNo', $patient->statusno);
            $this->smarty->display('gyna/printinv.html');
         } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
         }
      }
   }

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

      $patientId = filter_input(INPUT_POST, "patientId");
      $mainAntenatalId = filter_input(INPUT_POST, "mainAntenatalId");
      $archive = filter_input(INPUT_POST, "archive");

      ## show all investigations of patient
      $dates = R::getAll('SELECT DISTINCT date  FROM mainantenentalrays WHERE deleted = ? and patientid = ? and mainantenatalid = ?   order by date desc ', [0, $patientId, $mainAntenatalId]);
      $countHusband = array();
      $countWife = array();
      $i = 0;
      foreach ($dates as $date) {
         ## all invs of certain patient
         $PatientRayByDateHusband = R::findall('mainantenentalrays', 'deleted = ? and patientid = ? and date = ? and forhusband = ? and mainantenatalid = ?  ', [0, $patientId, $date['date'], 1, $mainAntenatalId]);
         $PatientRayByDateWife = R::findall('mainantenentalrays', 'deleted = ? and patientid = ? and date = ? and forhusband = ? and mainantenatalid = ?  ', [0, $patientId, $date['date'], 0, $mainAntenatalId]);

         foreach ($PatientRayByDateHusband as $in) {
            $ray = R::load('rays', $in->rayid);
            $in->invname = $ray->name;

            if ($in->raysresults_id > 0) {
               $imgs = R::findall('raysresults_img', 'deleted = ? and raysresults_id = ? ', [0, $in->raysresults_id]);
               $in->imgs = $imgs;
            }
         }

         foreach ($PatientRayByDateWife as $in) {
            $ray = R::load('rays', $in->rayid);
            $in->invname = $ray->name;

            if ($in->raysresults_id > 0) {
               $imgs = R::findall('raysresults_img', 'deleted = ? and raysresults_id = ? ', [0, $in->raysresults_id]);
               $in->imgs = $imgs;
            }
         }


         $dates[$i]['raysh'] = $PatientRayByDateHusband;
         $dates[$i]['raysw'] = $PatientRayByDateWife;
         $dates[$i]['date'] = date("Y/m/d", strtotime($dates[$i]['date']));

         $countHusband[$dates[$i]['date']] = count($PatientRayByDateHusband);
         $countWife[$dates[$i]['date']] = count($PatientRayByDateWife);

         $i++;
      }


      $this->smarty->assign('countHusband', $countHusband);
      $this->smarty->assign('countWife', $countWife);
      $this->smarty->assign('dates', $dates);
      $this->smarty->assign('archive', $archive);
      $this->smarty->display('antenalvisit/showRays.html');
   }

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

      $patientId = filter_input(INPUT_POST, "patientId");
      $date = filter_input(INPUT_POST, "date");
      $mainAntenatalId = filter_input(INPUT_POST, 'mainAntenatalId');  ## main Antenatal Id
      $dataFor = filter_input(INPUT_POST, "dataFor");

      $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 ($dataFor == 'wife') {
         $this->smarty->assign('name', $patient->wifename);
         $this->smarty->assign('title', $wifetypes->title);
      } elseif ($dataFor == 'husband') {
         $this->smarty->assign('name', $patient->husdandname);
         $this->smarty->assign('title', $husbandtypes->title);
      }



      ## all prescription of certain patient
      if ($dataFor == 'wife') {
         $PatientRayByDate = R::findall('mainantenentalrays', 'deleted = ? and patientid = ? and date = ? and mainantenatalid = ? and forhusband = ?', [0, $patientId, $date, $mainAntenatalId, 0]);
      } elseif ($dataFor == 'husband') {
         $PatientRayByDate = R::findall('mainantenentalrays', 'deleted = ? and patientid = ? and date = ? and mainantenatalid = ? and forhusband = ? ', [0, $patientId, $date, $mainAntenatalId, 1]);
      }

      foreach ($PatientRayByDate as $invest) {
         $ray = R::load('rays', $invest->rayid);
         $invest->name = $ray->name;
      }
      $this->smarty->assign('investigations', $PatientRayByDate);

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

      $this->smarty->assign('statusNo', $patient->statusno);
      $this->smarty->display('gyna/printinv.html');
   }

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

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

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

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

      $date = filter_input(INPUT_POST, "preDate");
      $date = date("Y-m-d", strtotime($date));
      $this->getDuplicatePre($patientId, $date, $preFor, $mainAntenatalId);
      $this->smarty->assign('type', "drugedit");
      $this->smarty->display('antenalvisit/newrowdrugedit.html');
   }

   private function getDuplicatePre($patientId, $date, $preFor, $mainAntenatalId) {
      $PatientPresByDate = R::findall('mainantenentaldrugs', 'deleted = ? and patientid = ? and date = ?  
                      and mainantenatalid = ? and forhusband = ?  ', [0, $patientId, $date, $mainAntenatalId, $preFor]);

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

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

            $pre = R::xdispense('mainantenentaldrugs');
            $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->drugdos = $preOld->drugdos;
            $pre->quantity = $preOld->quantity;
            $pre->forhusband = $preOld->forhusband;
            $pre->doctorid = $_SESSION['user_id'];
            $pre->mainantenatalid = $mainAntenatalId;
            $pre->deleted = 0;
            $pre->pres_id = $this->getPrestId('mainantenentaldrugs', $patientId, $presDate, $preFor, $_SESSION['user_id']);
            $pre->id = R::store($pre);

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


      $PatientPresByDate = R::findall('mainantenentaldrugs', 'deleted = ? and patientid = ? and date = ?  
                      and mainantenatalid = ? and forhusband = ?  ', [0, $patientId, $date, $mainAntenatalId, $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('PatientPresByDate', $PatientPresByDate);
      $this->smarty->assign('preItr', count($PatientPresByDate));
   }

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

      if (count($presByDate) > 0) {
         $pres_id = $presByDate->recepittmpid;
      } else {
         $recepittmp = R::xdispense('recepittmp');
         $recepittmp->doctorid = $_SESSION['user_id'];
         $recepittmp->doctorname = '';
         $recepittmp->patientid = $patientId;
         $recepittmp->patientname = '';
         $recepittmp->receiptdate = date("Y-m-d", strtotime($presDate));
         $recepittmp->userid = 0;
         $recepittmp->status = 0;
         $recepittmp->type = 0;
         $recepittmp->prescriptiontable = $tablename;
         $recepittmp->forhusband = $preFor;
         $recepittmp->storeid = 0;
         $pres_id = R::store($recepittmp);
      }
      return $pres_id;
   }

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

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