<?php

require_once("imp/_imp.php");

class Controllers {

//public vars
   public $smarty;
   public $hosturl;
   public $controllname;
   public $shcontrollname;
   public $active;
   public $patientid;

// 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 = 'patients';
      $this->shcontrollname = 'Patients';
      $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] = 'patients'; //controller name or tab name
      $active[1] = 'patients'; //controller name
      //
      R::ext('xdispense', function ($type) {
         return R::getRedBean()->dispense($type);
      });
// 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;
      //here will call all php pages
      require_once("_header.php");
      require_once("_patientdata.php");
      require_once("_sidebar.php");
      require_once("_leftsidebar.php");
      require_once("_footer.php");
   }

   //here the frist page and
   //the frist action in this class
   public function index() {
      //check login
      autho::checkautho($this->hosturl);
      //check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

      $searchValue = filter_input(INPUT_GET, "searchValue");
      $isInt = filter_input(INPUT_GET, "intIs");

      $this->smarty->assign('nationalIdMatch', 0);
      $savedBefore = R::findOne('patients', 'done = ? and userid = ?', [0, $_SESSION['user_id']]);

      $treeId = 0;
      $statusNo = 0;

      ## PATIENT EXIST 
      if (count($savedBefore) > 0) {
         $patient = R::load('patients', $savedBefore->id);
         $statusNo = $patient->statusno;
      }

      ## NEW  PATIENT  
      else {
         $patient = R::dispense('patients');
         $patient->userid = $_SESSION['user_id'];

         $statusNo = $this->getstatusno();
         $patient->statusno = $statusNo;

         $patient->vmodel = "";
         $patient->ectopic = "";
         $patient->ab = "";
         $patient->pno = "";

         $patient->id = R::store($patient);
      }

########################### common data  ###################################

      if (!empty($searchValue) && !empty($isInt)) {
         if ($isInt == 1) {
            $patient->wifenationalid = $searchValue;
            $match = $this->checknationalid($searchValue);
            if ($match == 2) {
               $this->smarty->assign('nationalIdMatch', $match);
            } else {
               $this->smarty->assign('nationalIdMatch', 1);
               $birthDate = $match;
               $patient->dateofbirth = $birthDate;
            }
         } else {
            $patient->wifename = $searchValue;
         }
         R::store($patient);
      }

      if (!empty($_SESSION['user_id'])) {
         $this->erpClient($patient);
         $_SESSION["uploadDirectory"] = "../../../../../../../../../upload/patientfiles/$patient->id";
         $this->smarty->assign('lastpatient', $patient);
         $treeId = $this->erpGetClientTreeId($patient->id);
      }

      $datasetting = R::findOne('programesetting', 'WHERE id = 1');
      $this->smarty->assign('stausnoauto', $datasetting->patientnoaut);

      $today = new DateTime(date('d-m-Y'));
      $today1 = new DateTime(date('Y-m-d'));

      $dateHusband = new DateTime($patient->husbanddateofbirth);
      $dateWife = new DateTime($patient->dateofbirth);

      if ($patient->dateofbirth == '0000-00-00' || is_null($patient->dateofbirth)) {
         $wAge = 0;
         $patient->dateofbirth = '00-00-0000';
      } else {
         ## calculate wife age
         $interva2 = $today1->diff($dateWife);
         $wAge = $interva2->y . 'Y , ' . $interva2->m . 'M , ' . $interva2->d . 'D  ';
         $patient->dateofbirth = date('d-m-Y ', strtotime($patient->dateofbirth));
      }
      $this->smarty->assign('wAge', $wAge);

      if ($patient->husbanddateofbirth == '0000-00-00' || is_null($patient->husbanddateofbirth)) {
         $hAge = 0;
         $patient->husbanddateofbirth = '00-00-0000';
      } else {
         ## calculate husband age
         $interval = $today1->diff($dateHusband);
         $hAge = $interval->y . 'Y , ' . $interval->m . 'M , ' . $interval->d . 'D  ';
         $patient->husbanddateofbirth = date('d-m-Y ', strtotime($patient->husbanddateofbirth));
      }
      $this->smarty->assign('hAge', $hAge);

      if ($patient->mirragefromdate == '0000-00-00' || is_null($patient->mirragefromdate)) {
         $patient->mirragefromy = 0;
         $patient->mirragefromm = 0;
      } else {
         ## calculate
         //$dateM = date('d-m-Y ', strtotime($patient->mirragefromdate));
         $dateM = new DateTime($patient->mirragefromdate);
         $interval = $today1->diff($dateM);
         $patient->mirragefromy = $interval->y;
         $patient->mirragefromm = $interval->m;
      }


      $this->relateddata();
      //Html files
      $this->smarty->assign('treeId', $treeId);

      $visit_periods = R::findAll('visit_periods', 'deleted = 0');
      $this->smarty->assign('visit_periods', $visit_periods);

      $branches = R::findAll('branches');
      $this->smarty->assign('branches', $branches);

      $hasBranch = 0;
      if ($_SESSION['user_id'] > 0 && $programesetting->branches == 1) {
         $user = R::findOne('awusers', 'user_id = ?', [$_SESSION['user_id']]);
         if ($user->branch_id > 0) {
            $hasBranch = $user->branch_id;
         }
      }
      $this->smarty->assign('hasBranch', $hasBranch);

      $allWifeJobs = R::findAll('wifejobs', 'order by title');
      $this->smarty->assign('allWifeJobs', $allWifeJobs);

      $allDetections = R::findAll('detections', 'del = 0 order by title');
      $this->smarty->assign('allDetections', $allDetections);

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

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

      $doctors = R::getAll('SELECT * FROM awusers WHERE role_id = ?  ', [4]);
      $this->smarty->assign('doctors', $doctors);

      $previous_marriages = R::findAll('previous_marriage', 'deleted != 1  and patientid = ? ', [$patient->id]);
      $this->smarty->assign('previous_marriages', $previous_marriages);

      $hus_previous_marriages = R::findAll('hus_previous_marriage', 'deleted != 1  and patientid = ? ', [$patient->id]);
      $this->smarty->assign('hus_previous_marriages', $hus_previous_marriages);

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

   function getstatusno() {
      $statusno = 1;
      // $last_code = R::getRow('select max(statusno) as code from patients');
      $last_code = R::getRow('select max(cast(statusno as UNSIGNED)) as code from patients');
      if (count($last_code) > 0) {
         $statusno = $last_code['code'] + 1;
      }
      return $statusno;
   }

   private function checknationalid($nationalId) {
      $patt = '/(2|3)[0-9][1-9][0-1][1-9][0-3][1-9](01|02|03|04|11|12|13|14|15|16|17|18|19|21|22|23|24|25|26|27|28|29|31|32|33|34|35|88)\d\d\d\d\d/i';
      $match = preg_match($patt, $nationalId);
      if ($match == 1) {
         $dArray = str_split($nationalId);

         if ($dArray[0] == 2) {
            $year = 1900 + ($dArray[1] * 10) + $dArray[2];
         } else if ($dArray[0] == 3) {
            $year = 2000 + (($dArray[1]) * 10 ) + $dArray[2];
         }
         $month = ($dArray[3] * 10) + $dArray[4];
         $day = ($dArray[5] * 10) + $dArray[6];

         return $year . '-' . $month . '-' . $day;
      } else {
         return 2;
      }
   }

   private function getage($birthYear) {
      return date_diff(date_create($birthYear), date_create('today'))->y;
   }

   public function patientfiles() {
      $id = filter_input(INPUT_POST, 'id');
      $dir = '../../upload/patientfiles/' . $id;
      // Open a directory, and read its contents
      if ($dir) {

         if ($dh = opendir($dir))
            echo '<div class = "row">
                      <div class="col-md-12">
                      <table class="table table-bordered table-striped table-hover" style="direction:ltr !important; float:right; ">
                      <thead>
                    <tr>
                    <th style="text-align:center;">File</th>
                    <th style="text-align:center;">File name</th>
                    <th style="text-align:center;">Download</th>
                    </tr>
                   </thead>
                   <tbody>';

         while (($file = readdir($dh)) !== false) {
            if ($file != "." && $file != ".." && $file != "thumbnail") {
               $file;
               // 1. The "explode/end" approach
               @$ext = end(explode('.', $file));
               // 2. The "strrchr" approach
               $ext = substr(strrchr($file, '.'), 1);
               // 3. The "strrpos" approach
               $ext = substr($file, strrpos($file, '.') + 1);
               // 4. The "preg_replace" approach
               $ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $file);
               // 5. The "never use this" approach
               @$exts = split("[/\\.]", $file);
               $n = count($exts) - 1;
               $ext = $exts[$n];
               $this->smarty->assign('ptid', $id);
               $this->smarty->assign('patientfiles', $file);
               $this->smarty->assign('fileext', $ext);
               $this->smarty->display('patients/files.html');
            }
         }
         echo ' </tbody>
        </table>
    </div>
</div>';
         closedir($dh);
      }
   }

   public function download() {
      $folderN = filter_input(INPUT_GET, 'id');
      $fname = filter_input(INPUT_GET, 'filename');
      $file = "../../upload/patientfiles/$folderN/$fname";
      header('Content-Type: application/force-download');
      header('Content-Disposition: attachment; filename="' . basename($file) . '"');
      header('Content-Length: ' . filesize($file));
      readfile($file);
   }

   public function clean($string) {
      return $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   }

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

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

      $go = '';
      $allres;

      $resultSearchWifeName = (!filter_input(INPUT_POST, "search")) ? "" : filter_input(INPUT_POST, "search");
      //$resultSearchWifeName = $this->clean($resultSearchWifeNameNotClean);

      $detectionSearch = (!filter_input(INPUT_POST, "detectionSearch")) ? "" : filter_input(INPUT_POST, "detectionSearch");

      $resultSearchHusband = (!filter_input(INPUT_POST, 'husbandname')) ? "" : filter_input(INPUT_POST, 'husbandname');
      //$resultSearchHusband = $this->clean($resultSearchHusbandNotClean);

      $resultSearchHusbandJob = (!filter_input(INPUT_POST, 'jobtitle')) ? "" : filter_input(INPUT_POST, 'jobtitle');
      $resultSearchWifeJob = (!filter_input(INPUT_POST, 'jobtitleًW')) ? "" : filter_input(INPUT_POST, 'jobtitleًW');
      //$resultSearchHusbandJob = $this->clean($resultSearchHusbandJobNotClean);

      $resultSearchAddress = (!filter_input(INPUT_POST, 'address')) ? "" : filter_input(INPUT_POST, 'address');
      //$resultSearchAddress = $this->clean($resultSearchAddressNotClean);

      $resultSearchAge = (!filter_input(INPUT_POST, 'age')) ? "" : filter_input(INPUT_POST, 'age');
      //$resultSearchAge = $this->clean($resultSearchAgeNotClean);

      $resultSearchPhone = (!filter_input(INPUT_POST, 'phone')) ? "" : filter_input(INPUT_POST, 'phone');
      //$resultSearchPhone = $this->clean($resultSearchPhoneNotClean);

      $resultSearchMobile = (!filter_input(INPUT_POST, 'mobile')) ? "" : filter_input(INPUT_POST, 'mobile');
      //$resultSearchMobile = $this->clean($resultSearchMobileNotClean);

      $resultSearchNationalId = (!filter_input(INPUT_POST, 'nationalid')) ? "" : filter_input(INPUT_POST, 'nationalid');
      //$resultSearchNationalId = $this->clean($resultSearchNationalIdNotClean);

      $q1 = '';
      $q2 = '';
      $q3 = '';
      $q4 = '';
      $q5 = '';
      $q6 = '';
      $q7 = '';
      $q8 = '';
      $qW = '';

      if ($detectionSearch == "" || !$detectionSearch) {     ## search in all patients
         $this->smarty->assign('withDept', 0);
         ## wife name or id entered
         if (!empty($resultSearchWifeName)) {
            //     $q1 = " AND (wifename  LIKE '%$resultSearchWifeName%'  OR statusno  LIKE '%$resultSearchWifeName%' OR wifenationalid  LIKE '%$resultSearchWifeName%')";
            $q1 = " AND (wifename  LIKE '%$resultSearchWifeName%'  OR statusno  LIKE '%$resultSearchWifeName%' )";
            $q2 = " OR (husdandname LIKE '%$resultSearchWifeName%') ";
         }

         ## husband name entered
         if (!empty($resultSearchHusband)) {
            $q2 = " AND husdandname LIKE '%$resultSearchHusband%'";
         }

         ## husband job  entered
         if (!empty($resultSearchHusbandJob)) {
            $q3 = " AND husbandjobs.title LIKE '%$resultSearchHusbandJob%' ";
         }

         if (!empty($resultSearchWifeJob)) {
            $qW = " AND wifejobs.title LIKE '%$resultSearchWifeJob%' ";
         }

         ## address  entered
         if (!empty($resultSearchAddress)) {
            $q4 = " AND address LIKE '%$resultSearchAddress%' ";
         }
         ## telephone entered
         if (!empty($resultSearchPhone)) {
            $q5 = " AND phone LIKE '%$resultSearchPhone%' ";
         }

         ## mobile  entered
         if (!empty($resultSearchMobile)) {
            $q6 = " AND mobile LIKE '%$resultSearchMobile%' ";
         }

         ## age  entered
         if (!empty($resultSearchAge)) {
            $q7 = " AND wifeage LIKE '%$resultSearchAge%' ";
         }

         ## national id entered
         if (!empty($resultSearchNationalId)) {
            $q8 = " AND wifenationalid LIKE '%$resultSearchNationalId%'";
         }


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

         if (empty($resultSearchHusbandJob)) {
            $query = "SELECT patients.*    ,  wifejobs.title as wJob
                                      FROM `patients`
                                        left join wifejobs  on wifejobs.id = patients.wifejob
                                        WHERE
                                        patients.done = 1
                                        AND patients.deleted = 0
                                        $q1  $q2  $q3  $q4 $q5 $q6 $q7 $q8 $qW
                                        limit 0,40 ";
         } else {
            $query = "SELECT patients.* , husbandjobs.title     ,  wifejobs.title as wJob
                      FROM `patients` INNER JOIN husbandjobs ON  patients.husbandjob  = husbandjobs.id
                                       left join wifejobs  on wifejobs.id = patients.wifejob     
                                        WHERE
                                        patients.done = 1
                                        AND patients.deleted = 0
                                        $q1  $q2  $q3  $q4 $q5 $q6 $q7 $q8 $qW
                                        limit 0,40 ";
         }

         //print_r($query);

         $queryString = R::getAll($query);
         $arrLinkType = array();
         foreach ($queryString as $pat) {
            /* $antenatalData = R::findOne('antenalvisit', 'patientid = ? and conditions = 0 order by id desc limit 1', [$pat['id']]);
              $gynaData = R::findOne('gyna', 'patientid = ? and conditions = 0 order by id desc limit 1', [$pat['id']]);

              if (!empty($antenatalData) || !empty($gynaData)) {
              if ($gynaData['gynadate'] < $antenatalData['antenaldate'])
              $go = "antenatal";
              else
              $go = "gyna";
              }
              else
              {
              $go = '';
              } */
            $lastVisitData = R::findOne('lastvisit', 'patientid = ? order by id desc', [$pat['id']]);
            if (!empty($lastVisitData))
               $go = $lastVisitData->control;
            else
               $go = '';
            $arrLinkType[$pat['id']] = $go;
         }

         if (count($queryString) < 1) {
            $allNumbers = 1;
            $pieces = str_split($resultSearchWifeName);
            foreach ($pieces as $value) {
               if (ctype_digit($value) != 1) {
                  $allNumbers = 2;
                  break;
               }
            }

            $this->smarty->assign('intIs', $allNumbers);
            $this->smarty->assign('searchValue', $resultSearchWifeName);
         }
      } else {
         ## search in  patients in specific department   ## only hospital option
         $this->smarty->assign('withDept', 1);
         $query = "SELECT   patients.* , visits.visitdate  FROM patients
                                join  visits                on      patients.id = visits.patientid
                                where visits.detectionid = $detectionSearch
                                and  visits.deleted = 0
                                ";
         //limit 0,50 ";


         $pResult = R::getAll($query);
         $queryString = array();
         foreach ($pResult as $pat) {
            $endDates = R::getAll('select enddate from endvisitreports where patientid = ?  and enddate >= ?', [$pat['id'], $pat['visitdate']]);
            if (count($endDates) < 1) {
               array_push($queryString, $pat);
            }
         }
      }



      //$this->smarty->assign('go', $go);
      $this->smarty->assign('arrLinkType', $arrLinkType);
      $this->smarty->assign('patientResult', $queryString);
      $loginPosition = R::getRow('select role_id from awusers where user_id = ?', [$_SESSION['user_id']]);
      $this->smarty->assign('loginPosition', $loginPosition['role_id']);
      $this->smarty->display('searchresult.html');
   }

   public function addfinish() {
      $submitted = filter_input(INPUT_POST, 'submit');
      $id = filter_input(INPUT_POST, 'ptntid');
      $addVisit = filter_input(INPUT_POST, 'addV');

      if (!empty($submitted)) {
         $submitchange = R::load('patients', $id);

         if ($submitchange->done != 1) {
            $submitchange->done = 1;

            if (is_null($submitchange->pno) || !($submitchange->pno > 0 )) {
               $submitchange->pno = "";
            }

            if (is_null($submitchange->ab) || !($submitchange->ab > 0 )) {
               $submitchange->ab = "";
            }

            if (is_null($submitchange->vmodel) || !($submitchange->vmodel > 0 )) {
               $submitchange->vmodel = "";
            }

            if (is_null($submitchange->ectopic) || !($submitchange->ectopic > 0 )) {
               $submitchange->ectopic = "";
            }


            R::store($submitchange);

            #################################################################
            $statusno = filter_input(INPUT_POST, 'statusno');
            $wifename = filter_input(INPUT_POST, 'wifename');
            $doctorid = filter_input(INPUT_POST, 'doctorid');
            $wifetype = (filter_input(INPUT_POST, 'wiftypeid') > 0) ? filter_input(INPUT_POST, 'wiftypeid') : NULL;
            $dateofbirth = filter_input(INPUT_POST, 'dateofbirth');
            $wifeage = filter_input(INPUT_POST, 'wifeage');
            $education = filter_input(INPUT_POST, 'education');
            $wifejob = filter_input(INPUT_POST, 'wifejob');
            $wifestatus = filter_input(INPUT_POST, 'wifestatus');

            $mirragefromY = (filter_input(INPUT_POST, 'mirragefromy') > 0) ? filter_input(INPUT_POST, 'mirragefromy') : 0;
            $mirragefromM = (filter_input(INPUT_POST, 'mirragefromm') > 0) ? filter_input(INPUT_POST, 'mirragefromm') : 0;

            $boyson = filter_input(INPUT_POST, 'boyson');
            $girlson = filter_input(INPUT_POST, 'girlson');
            $address = filter_input(INPUT_POST, 'address');
            $phone = filter_input(INPUT_POST, 'phone');
            $mobile = filter_input(INPUT_POST, 'mobile');
            $wifenationalid = filter_input(INPUT_POST, 'wifenationalid');
            $wifebl = filter_input(INPUT_POST, 'wifebl');
            $importantnote = filter_input(INPUT_POST, 'importantnote');
            $risk = filter_input(INPUT_POST, 'risk');
            $risktype = (filter_input(INPUT_POST, 'risktype') > 0) ? filter_input(INPUT_POST, 'risktype') : NULL;

//            $risktype = filter_input(INPUT_POST, 'risktype');
            $spacialnotes = filter_input(INPUT_POST, 'spacialnotes');

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

            if ($dateofbirth == '00-00-0000') {
               $dateofbirth = NULL;
            } else {
               $dateofbirth = date('Y-m-d', strtotime($dateofbirth));
            }

            if ($husbanddateofbirth == '00-00-0000') {
               $husbanddateofbirth = NULL;
            } else {
               $husbanddateofbirth = date('Y-m-d', strtotime($husbanddateofbirth));
            }

            $months = $mirragefromM + (12 * $mirragefromY);

            $allDate = date("Y-m-d", strtotime(date('Y-m-d') . "-" . $months . " month"));

            $mirragefrom = $mirragefromY . '.' . $mirragefromM;

// prepar Husband data to update
            $husbandtypeid = filter_input(INPUT_POST, 'husbandtypeid');
            $husdandname = filter_input(INPUT_POST, 'husdandname');

            $husbandage = filter_input(INPUT_POST, 'husbandage');
            $husbandeducation = filter_input(INPUT_POST, 'husbandeducation');
            $husbandjob = filter_input(INPUT_POST, 'husbandjob');
            $husbandnationalid = filter_input(INPUT_POST, 'husbandnationalid');
            $husbandbl = filter_input(INPUT_POST, 'husbandbl');

            if ($wifebl == "") {
               $wifebl = NULL;
            }

            if ($boyson == "") {
               $boyson = NULL;
            }

            if ($girlson == "") {
               $girlson = NULL;
            }

            if ($wifestatus == "") {
               $wifestatus = NULL;
            }

            if ($husbandtypeid == "") {
               $husbandtypeid = NULL;
            }


            $submitchange->statusno = $statusno;
            $submitchange->wifename = $wifename;
            $submitchange->wiftypeid = $wifetype;
            $submitchange->dateofbirth = $dateofbirth;
            $submitchange->wifeage = $wifeage;
            $submitchange->wifeeducation = $education;
            $submitchange->wifejob = $wifejob;
            $submitchange->statuesid = $wifestatus;
            $submitchange->mirragefrom = $mirragefrom;
            $submitchange->mirragefromdate = $allDate;
            $submitchange->boyson = $boyson;
            $submitchange->girlson = $girlson;
            $submitchange->address = $address;
            $submitchange->phone = $phone;
            $submitchange->mobile = $mobile;
            $submitchange->wifenationalid = $wifenationalid;
            $submitchange->wifebl = $wifebl;
            $submitchange->importantnote = $importantnote;
            $submitchange->risk = $risk;
            $submitchange->risktype = $risktype;
            $submitchange->spacialnotes = $spacialnotes;
            $submitchange->doctorid = $doctorid;

// Husband data that will insert
            $submitchange->husbandtypeid = $husbandtypeid;
            $submitchange->husdandname = $husdandname;
            $submitchange->husbanddateofbirth = $husbanddateofbirth;
            $submitchange->husbandage = $husbandage;
            $submitchange->husbandeducation = $husbandeducation;
            $submitchange->husbandjob = $husbandjob;
            $submitchange->husbandnationalid = $husbandnationalid;
            $submitchange->husbandbl = $husbandbl;

            if (is_null($submitchange->pno) || !($submitchange->pno > 0 )) {
               $submitchange->pno = "";
            }

            if (is_null($submitchange->ab) || !($submitchange->ab > 0 )) {
               $submitchange->ab = "";
            }

            if (is_null($submitchange->vmodel) || !($submitchange->vmodel > 0 )) {
               $submitchange->vmodel = "";
            }

            if (is_null($submitchange->ectopic) || !($submitchange->ectopic > 0 )) {
               $submitchange->ectopic = "";
            }

            $submitchange->createdate = date('Y-m-d H:i:s');
            #################################################################

            date_default_timezone_set('Africa/Cairo');
            $submitchange->entrydate = date('Y-m-d H:i:s', time());
            //$submitchange->entrydate = date("F j, Y, g:i a");
            ##save patient login data
            $password = filter_input(INPUT_POST, 'password');
            if (empty($password) || $password == '') {
               $password = '123';
            }
            $hash_cost_factor = (defined('HASH_COST_FACTOR') ? HASH_COST_FACTOR : null);
            $user_password_hash = password_hash($password, PASSWORD_DEFAULT, array('cost' => $hash_cost_factor));
            $submitchange->patient_password_hash = $user_password_hash;

            R::begin();
            try {

               R::store($submitchange);

               session_start();

               if ($addVisit == 1) {


                  $visitDate = filter_input(INPUT_POST, 'visitdate');
                  $detectionID = filter_input(INPUT_POST, 'detectionid');
                  $detectionValue_cash = filter_input(INPUT_POST, 'detectionvalue_cash');
                  $detectionValue_visa = filter_input(INPUT_POST, 'detectionvalue_visa');
                  $totaldetectionvalue = filter_input(INPUT_POST, 'totaldetectionvalue');
                  $restdetectionvalue = filter_input(INPUT_POST, 'restdetectionvalue');
                  $discount = filter_input(INPUT_POST, 'discount');
                  $visit_period = filter_input(INPUT_POST, 'visit_period');
                  $urgent = (int) filter_input(INPUT_POST, 'urgent');
                  $payVisit = filter_input(INPUT_POST, 'payVisit');
                  $patientID = $id;

                  $new_date = date('Y-m-d', strtotime($visitDate));
                  $branchId = filter_input(INPUT_POST, "branchId");

                  $newOrder = 1;
                  $data = R::getRow("SELECT MAX(enterordered) as last_order   FROM visits ");
                  if ($data['last_order'] >= 1) {
                     $newOrder = $data['last_order'] + 1;
                  }

                  if ($payVisit != 1) {
                     $payVisit = 0;
                  }


                  $insertDataVisits = R::dispense('visits');
                  $insertDataVisits->patientid = $patientID;
                  $insertDataVisits->visitdate = $new_date;
                  $insertDataVisits->detectionid = $detectionID;
                  $insertDataVisits->detectionvalue_cash = $detectionValue_cash;
                  $insertDataVisits->detectionvalue_visa = $detectionValue_visa;
                  $insertDataVisits->totaldetectionvalue = $totaldetectionvalue;
                  $insertDataVisits->discount = $discount;
                  $insertDataVisits->restdetectionvalue = $restdetectionvalue;
                  $insertDataVisits->visit_period = $visit_period;
                  $insertDataVisits->urgent = $urgent;
                  $insertDataVisits->mobileappvisit = 0;
                  $insertDataVisits->enterordered = $newOrder;
                  $insertDataVisits->visitorder = 0;
                  $insertDataVisits->visit_order = $this->getVisitOrder($new_date);
                  $insertDataVisits->payedflag = 1;
                  $insertDataVisits->createdate = date('Y-m-d h:i:s');
                  $insertDataVisits->user_id = $_SESSION['user_id'];

                  $userBranch = 0;
                  if ($_SESSION['user_id'] > 0) {
                     $user = R::findOne('awusers', 'user_id = ?', [$_SESSION['user_id']]);
                     if ($user->branch_id > 0) {
                        $userBranch = $user->branch_id;
                     }
                  }


                  if ($userBranch == 0 && $branchId > 0) {
                     $userBranch = $branchId;
                  }

                  $insertDataVisits->branch_id = $userBranch;

                  $duplicated = R::find('visits', 'patientid = ? AND  visitdate = ? and deleted = ? ', [$patientID, $new_date, 0]);
                  if (count($duplicated) == 0) {
                     $insertDataVisits->id = R::store($insertDataVisits);
                  }


                  ##stop making bill untill patient pay in visits
                  #            
                  if ($insertDataVisits->payedflag == 1) {
//                        $this->erpSellbill($insertDataVisits);
                  }
               }


               ## login position

               $loginPosition = R::getRow('select role_id from awusers where user_id = ?', [$_SESSION['user_id']]);

               if ($submitchange->done != 1) {
                  header('Location:' . $this->hosturl . '/controllers/patients.php');
               } else {
                  if ($loginPosition['role_id'] != 3) {
                     header('Location:' . $this->hosturl . '/controllers/patienthistory.php?patientid=' . $id);
                  } else {
                     header('Location:' . $this->hosturl . '/controllers/index.php?ac=index');
                  }
               }
            } catch (Exception $e) {
               R::rollback();

               // print_r($e);
               header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
            }
         } else {
            header('Location:' . $this->hosturl . '/controllers/error.php?ac=notadd&id=' . $this->controllname);
         }
      } else {
         header('Location:' . $this->hosturl . '/controllers/error.php?ac=notadd&id=' . $this->controllname);
      }
   }

   function getVisitOrder($visitDate) {
      $data = R::getRow('SELECT MAX(visit_order) as last_order
                 FROM visits  where visitdate = ? ', [$visitDate]);
      $last_order = $data['last_order'];
      $visit_order = $last_order + 1;
      return $visit_order;
   }

   ## add new patient from api 

   public function addFromApi() {
      date_default_timezone_set('Africa/Cairo');
      $wifename = filter_input(INPUT_POST, 'name');
      $dateofbirth = filter_input(INPUT_POST, 'dob');
      $phone_qid = filter_input(INPUT_POST, 'phone_qid');
      $phone = filter_input(INPUT_POST, 'phone');
      //  $email = filter_input(INPUT_POST, 'email');
      $password = filter_input(INPUT_POST, 'password');
      if (empty($password) || $password == '') {
         $password = '123';
      }

      try {
         $patient = R::dispense('patients');
         $patient->statusno = $this->getstatusno();
         $patient->wifename = $wifename;
         $patient->dateofbirth = $dateofbirth;
         $patient->phone = $phone;
         $patient->createdate = date('Y-m-d H:i:s');
         $patient->entrydate = date('Y-m-d H:i:s', time());
         $hash_cost_factor = (defined('HASH_COST_FACTOR') ? HASH_COST_FACTOR : null);
         $user_password_hash = password_hash($password, PASSWORD_DEFAULT, array('cost' => $hash_cost_factor));
         $patient->patient_password_hash = $user_password_hash;
         $patient->vmodel = "";
         $patient->ectopic = "";
         $patient->ab = "";
         $patient->pno = "";
         $patient->insert_from = 2;
         $patient->phone_qid = $phone_qid;
         $patient->new_version = 1;
         $patient->done = 1;
         $patient->id = R::store($patient);
         echo $patient->id;
      } catch (Exception $ex) {
         echo -1;
      }
   }

   private function relateddata() {
      //check login
      //autho::checkautho($this->hosturl);
      //check authoize
      // autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $allTypes = R::findAll('wifetypes', 'order by title');
      $education = R::findAll('education', 'order by title');
      $wifejobs = R::findAll('wifejobs', 'order by title');
      $wifestatus = R::findAll('wifestatus', 'order by title');
      $wifebl = R::findAll('bloodtypes', 'order by title');
      $husbandtypes = R::findAll('husbandtypes', 'order by title');
      $husbandjobs = R::findAll('husbandjobs', 'order by title');
      //Send Data to add.html to use it in insert new patient
      $this->smarty->assign('allTypes', $allTypes);
      $this->smarty->assign('education', $education);
      $this->smarty->assign('wifejobs', $wifejobs);
      $this->smarty->assign('wifestatus', $wifestatus);
      $this->smarty->assign('wifebl', $wifebl);
      $this->smarty->assign('husbandtypes', $husbandtypes);
      $this->smarty->assign('husbandjobs', $husbandjobs);
   }

   public function add() {
      //check login
      autho::checkautho($this->hosturl);
      //check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      //prepar wife data insert
      $statusno = filter_input(INPUT_POST, 'statusno');
      $wifename = filter_input(INPUT_POST, 'wifename');
      $wifetype = filter_input(INPUT_POST, 'wifetype');
      $dateofbirth = filter_input(INPUT_POST, 'dateofbirth');
      $wifeage = filter_input(INPUT_POST, 'wifeage');
      $education = filter_input(INPUT_POST, 'education');
      $wifejob = filter_input(INPUT_POST, 'wifejob');
      $wifestatus = filter_input(INPUT_POST, 'wifestatus');
      $mirragefrom = filter_input(INPUT_POST, 'mirragefrom');
      $boyson = filter_input(INPUT_POST, 'boyson');
      $girlson = filter_input(INPUT_POST, 'girlson');
      $address = filter_input(INPUT_POST, 'address');
      $phone = filter_input(INPUT_POST, 'phone');
      $mobile = filter_input(INPUT_POST, 'mobile');
      $wifenationalid = filter_input(INPUT_POST, 'wifenationalid');
      $wifebl = filter_input(INPUT_POST, 'wifebl');
      $importantnote = filter_input(INPUT_POST, 'importantnote');
      $risk = filter_input(INPUT_POST, 'risk');

      $risktype = filter_input(INPUT_POST, 'risktype');
//        $refering = filter_input(INPUT_POST, 'refering');

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

      $husbandtypeid = filter_input(INPUT_POST, 'husbandtypeid');
      $husdandname = filter_input(INPUT_POST, 'husdandname');
      $husbanddateofbirth = filter_input(INPUT_POST, 'husbanddateofbirth');
      $husbandage = filter_input(INPUT_POST, 'husbandage');
      $husbandeducation = filter_input(INPUT_POST, 'husbandeducation');
      $husbandjob = filter_input(INPUT_POST, 'husbandjob');
      $husbandnationalid = filter_input(INPUT_POST, 'husbandnationalid');
      $husbandbl = filter_input(INPUT_POST, 'husbandbl');

// wife data that will insert
      $inserPatientData = R::dispense('patients');
      $inserPatientData->statusno = $statusno;
      $inserPatientData->wifename = $wifename;
      $inserPatientData->wiftypeid = $wifetype;
      $inserPatientData->dateofbirth = $dateofbirth;
      $inserPatientData->wifeage = $wifeage;
      $inserPatientData->wifeeducation = $education;
      $inserPatientData->wifejob = $wifejob;
      $inserPatientData->statuesid = $wifestatus;
      $inserPatientData->mirragefrom = $mirragefrom;
      $inserPatientData->boyson = $boyson;
      $inserPatientData->girlson = $girlson;
      $inserPatientData->address = $address;
      $inserPatientData->phone = $phone;
      $inserPatientData->mobile = $mobile;
      $inserPatientData->wifenationalid = $wifenationalid;
      $inserPatientData->wifebl = $wifebl;
      $inserPatientData->importantnote = $importantnote;
      $inserPatientData->risk = $risk;
      $inserPatientData->spacialnotes = $spacialnotes;

// Husband data that will insert
      $inserPatientData->husbandtypeid = $husbandtypeid;
      $inserPatientData->husdandname = $husdandname;
      $inserPatientData->husbanddateofbirth = $husbanddateofbirth;
      $inserPatientData->husbandage = $husbandage;
      $inserPatientData->husbandeducation = $husbandeducation;
      $inserPatientData->husbandjob = $husbandjob;
      $inserPatientData->husbandnationalid = $husbandnationalid;
      $inserPatientData->husbandbl = $husbandbl;

      R::begin();
      try {

         $inserted = R::store($inserPatientData);
         ##fatma
         //insert it in erp client
         $inserPatientData->id = $inserted;
         $this->erpClient($inserPatientData);
         if ($inserted) {
            
         }
         header('Location:' . $this->hosturl . '/controllers/index.php?ac=index');
      } catch (Exception $e) {
         R::rollback();
         header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
      }
   }

   public function updateajax() {
      $id = filter_input(INPUT_POST, 'id');
      $colname = filter_input(INPUT_POST, 'colname');
      $valuenew = filter_input(INPUT_POST, 'valuenew');

      $dataupdated = R::load('patients', $id);

      if ($colname == 'dateofbirth' || $colname == 'husbanddateofbirth') {
         $dataupdated->$colname = date('Y-m-d', strtotime($valuenew));
      } elseif ($colname == "mirragefrom") {
         $dataupdated->$colname = $valuenew;
         $months = 12 * $valuenew;

         $dataupdated->mirragefromdate = date("Y-m-d", strtotime(date('Y-m-d') . "-" . $months . " month"));
      } else {
         $dataupdated->$colname = $valuenew;
         ##fatma
         //insert it in erp client
         $this->erpClient($dataupdated);
      }

      $idd = R::store($dataupdated);
      echo $months;
   }

   public function updateajaxtwice() {
      $id = filter_input(INPUT_POST, 'id');
      $wifename = filter_input(INPUT_POST, 'wifename');

      $dataupdated = R::load('patients', $id);
      $dataupdated->wifename = $wifename;

      $dataupdated->statusno = $id;
      ##fatma
      //insert it in erp client
      $this->erpClient($dataupdated);

      echo R::store($dataupdated);
   }

   public function checkingwifename() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $wifename = filter_input(INPUT_POST, 'wifename');
      $patientId = filter_input(INPUT_POST, 'patientId');

      $data = R::findAll('patients', 'wifename = ? and id != ? ', [$wifename, $patientId]);
      $found;
      if (count($data) == 0) {
         $found = 0;
      } else {
         $found = 1;
      }
      echo $found;
   }

   function saveage() {
      $id = filter_input(INPUT_POST, 'ptid');
      $value = filter_input(INPUT_POST, 'value');
      $ptdate = filter_input(INPUT_POST, 'patientdate');
      $dataptidsaveage = R::load('patients', $id);
      $dataptidsaveage->wifeage = $value;
      $dataptidsaveage->dateofbirth = date('Y-m-d', strtotime($ptdate));
      echo R::store($dataptidsaveage);
   }

   function saveagehus() {
      $id = filter_input(INPUT_POST, 'ptid');
      $value = filter_input(INPUT_POST, 'value');
      $ptdate = filter_input(INPUT_POST, 'patientdate');

      $dataptidsaveage = R::load('patients', $id);

      $dataptidsaveage->husbandage = $value;
      $dataptidsaveage->husbanddateofbirth = date('Y-m-d', strtotime($ptdate));
      echo R::store($dataptidsaveage);
   }

   public function checkingwifestatusno() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $wifestatusno = filter_input(INPUT_POST, 'wifestatusno');
      $patientId = filter_input(INPUT_POST, 'patientId');
      $data = R::findAll('patients', 'statusno = ? and id != ? ', [$wifestatusno, $patientId]);
      $found;
      if (count($data) == 0) {
         $found = 0;
      } else {
         $found = 1;
      }
      echo $found;
   }

   public function checkingnationalwifename() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $wifenationalid = filter_input(INPUT_POST, 'wifenationalid');
      $patientId = filter_input(INPUT_POST, 'patientId');

      $data = R::findAll('patients', 'wifenationalid = ? and id != ? ', [$wifenationalid, $patientId]);
      $found;
      if (count($data) == 0) {
         $found = 0;
      } else {
         $found = 1;
      }
      echo $found;
   }

   public function checkingnationalhusband() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $husbandnationalid = filter_input(INPUT_POST, 'husbandnationalid');
      $patientId = filter_input(INPUT_POST, 'patientId');

      $data = R::findAll('patients', 'husbandnationalid = ? and id != ? ', [$husbandnationalid, $patientId]);
      $found;
      if (count($data) == 0) {
         $found = 0;
      } else {
         $found = 1;
      }
      echo $found;
   }

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

      try {
         $diff = date_diff(date_create($patientdate), date_create('today'));
         echo $diff->y . 'Y , ' . $diff->m . 'M , ' . $diff->d . 'D  ';
      } catch (Exception $ex) {
         echo -1;
      }
   }

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

      $allPatientData = R::findAll('patients', 'deleted = ? and done = ?', [0, 1]);
      $this->smarty->assign('allPatientData', $allPatientData);

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

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

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

      $this->relateddata();

      $id = filter_input(INPUT_GET, 'id');
      $_SESSION["uploadDirectory"] = "../../../../../../../../../upload/patientfiles/$id";
      $getOnePatient = R::findOne('patients', 'id = ?', [$id]);

      $previous_marriages = R::findAll('previous_marriage', 'deleted != 1  and patientid = ? ', [$id]);
      $this->smarty->assign('previous_marriages', $previous_marriages);

      $hus_previous_marriages = R::findAll('hus_previous_marriage', 'deleted != 1  and patientid = ? ', [$id]);
      $this->smarty->assign('hus_previous_marriages', $hus_previous_marriages);

      $today = new DateTime(date('d-m-Y'));

      if ($getOnePatient->dateofbirth == '0000-00-00' || is_null($getOnePatient->dateofbirth)) {
         $datewifebirth = '00-00-0000';
         $wAge = 0;
      } else {
         $datewifebirth = date('d-m-Y ', strtotime($getOnePatient->dateofbirth));
         $dateWife = new DateTime($datewifebirth);

         ## calculate wife age
         $interva2 = $today->diff($dateWife);
         $wAge = $interva2->y . 'Y , ' . $interva2->m . 'M , ' . $interva2->d . 'D  ';
      }
      $this->smarty->assign('wAge', $wAge);

      if ($getOnePatient->husbanddateofbirth == '0000-00-00' || is_null($getOnePatient->husbanddateofbirth)) {
         $datehusbirth = '00-00-0000';
         $hAge = 0;
      } else {
         $datehusbirth = date('d-m-Y ', strtotime($getOnePatient->husbanddateofbirth));
         $dateHusband = new DateTime($datehusbirth);
         ## calculate husband age

         $interval = $today->diff($dateHusband);
         $hAge = $interval->y . 'Y , ' . $interval->m . 'M , ' . $interval->d . 'D  ';
      }
      $this->smarty->assign('hAge', $hAge);

      if ($getOnePatient->entrydate == '0000-00-00 00:00:00' || empty($getOnePatient->entrydate)) {
         $getOnePatient->entrydate = '00-00-0000 00:00:00';
         $addDate = '00-00-0000';
         $addTime = '00:00:00';
      } else {
         $getOnePatient->entrydate = date('d-m-Y H:i:s', strtotime($getOnePatient->entrydate));
         $addDate = date('d-m-Y', strtotime($getOnePatient->entrydate));
         $addTime = date('H:i:s', strtotime($getOnePatient->entrydate));
      }

      $this->smarty->assign('addDate', $addDate);
      $this->smarty->assign('addTime', $addTime);

      if ($getOnePatient->mirragefromdate == '0000-00-00' || empty($getOnePatient->mirragefromdate)) {
         $this->smarty->assign("mirragefromy", 0);
         $this->smarty->assign("mirragefromm", 0);
      } else {
         ## calculate
         $today = new DateTime(date('Y-m-d'));
         $dateM = new DateTime($getOnePatient->mirragefromdate);
         $interval = $today->diff($dateM);
         $this->smarty->assign("mirragefromy", $interval->y);
         $this->smarty->assign("mirragefromm", $interval->m);
      }


      $this->smarty->assign('getOnePatient', $getOnePatient);
      $this->smarty->assign('datewifebirth', $datewifebirth);
      $this->smarty->assign('datehusbirth', $datehusbirth);

      $treeId = $this->erpGetClientTreeId($getOnePatient->id);
      $this->smarty->assign('treeId', $treeId);

      $doctors = R::getAll('SELECT * FROM awusers WHERE role_id = ?  ', [4]);
      $this->smarty->assign('doctors', $doctors);

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

   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, 'patientid');
//prepar wife data to update
      $statusno = filter_input(INPUT_POST, 'statusno');
      $wifename = filter_input(INPUT_POST, 'wifename');
      $doctorid = filter_input(INPUT_POST, 'doctorid');
      $wifetype = (filter_input(INPUT_POST, 'wifetype') > 0) ? filter_input(INPUT_POST, 'wifetype') : NULL;
      $dateofbirth = filter_input(INPUT_POST, 'dateofbirth');
      $wifeage = filter_input(INPUT_POST, 'wifeage');
      $education = filter_input(INPUT_POST, 'education');
      $wifejob = filter_input(INPUT_POST, 'wifejob');
      $wifestatus = filter_input(INPUT_POST, 'wifestatus');
      $gender = filter_input(INPUT_POST, 'gender');

      $mirragefromY = (filter_input(INPUT_POST, 'mirragefromy') > 0) ? filter_input(INPUT_POST, 'mirragefromy') : 0;
      $mirragefromM = (filter_input(INPUT_POST, 'mirragefromm') > 0) ? filter_input(INPUT_POST, 'mirragefromm') : 0;

      $boyson = filter_input(INPUT_POST, 'boyson');
      $girlson = filter_input(INPUT_POST, 'girlson');
      $address = filter_input(INPUT_POST, 'address');
      $phone = filter_input(INPUT_POST, 'phone');
      $mobile = filter_input(INPUT_POST, 'mobile');
      $wifenationalid = filter_input(INPUT_POST, 'wifenationalid');
      $wifebl = filter_input(INPUT_POST, 'wifebl');
      $importantnote = filter_input(INPUT_POST, 'importantnote');
      $risk = filter_input(INPUT_POST, 'risk');
      $risktype = (filter_input(INPUT_POST, 'risktype') > 0) ? filter_input(INPUT_POST, 'risktype') : NULL;
      $spacialnotes = filter_input(INPUT_POST, 'spacialnotes');

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

      if ($dateofbirth == '00-00-0000') {
         $dateofbirth = Null;
      } else {
         $dateofbirth = date('Y-m-d', strtotime($dateofbirth));
      }
      if ($husbanddateofbirth == '00-00-0000') {
         $husbanddateofbirth = Null;
      } else {
         $husbanddateofbirth = date('Y-m-d', strtotime($husbanddateofbirth));
      }


      if ($boyson == '') {
         $boyson = Null;
      }

      if ($girlson == '') {
         $girlson = Null;
      }


      if ($wifebl == '') {
         $wifebl = Null;
      }





      $months = $mirragefromM + ( 12 * $mirragefromY);

      $allDate = date("Y-m-d", strtotime(date('Y-m-d') . "-" . $months . " month"));

      $mirragefrom = $mirragefromY . '.' . $mirragefromM;
      // prepar Husband data to update
      $husbandtypeid = filter_input(INPUT_POST, 'husbandtypeid');
      $husdandname = filter_input(INPUT_POST, 'husdandname');

      $husbandage = filter_input(INPUT_POST, 'husbandage');
      $husbandeducation = filter_input(INPUT_POST, 'husbandeducation');
      $husbandjob = filter_input(INPUT_POST, 'husbandjob');
      $husbandnationalid = filter_input(INPUT_POST, 'husbandnationalid');
      $husbandbl = filter_input(INPUT_POST, 'husbandbl');
      $husband_habbits = filter_input(INPUT_POST, 'husband_habbits');

      if ($wifestatus == '') {
         $wifestatus = Null;
      }

      if ($husbandtypeid == '') {
         $husbandtypeid = Null;
      }

      $oldPatient = R::load('patients', $id);

      $updatePatientData = R::load('patients', $id);
      $updatePatientData->statusno = $statusno;
      $updatePatientData->wifename = $wifename;
      $updatePatientData->wiftypeid = $wifetype;
      $updatePatientData->dateofbirth = $dateofbirth;
      $updatePatientData->wifeage = $wifeage;
      $updatePatientData->wifeeducation = $education;
      $updatePatientData->wifejob = $wifejob;
      $updatePatientData->statuesid = $wifestatus;
      $updatePatientData->mirragefrom = $mirragefrom;
      $updatePatientData->mirragefromdate = $allDate;
      $updatePatientData->boyson = $boyson;
      $updatePatientData->girlson = $girlson;
      $updatePatientData->address = $address;
      $updatePatientData->phone = $phone;
      $updatePatientData->mobile = $mobile;
      $updatePatientData->wifenationalid = $wifenationalid;
      $updatePatientData->wifebl = $wifebl;
      $updatePatientData->importantnote = $importantnote;
      $updatePatientData->risk = $risk;
      $updatePatientData->risktype = $risktype;
      $updatePatientData->spacialnotes = $spacialnotes;
      $updatePatientData->doctorid = $doctorid;

      $updatePatientData->gender = $gender;

      // Husband data that will insert
      $updatePatientData->husbandtypeid = $husbandtypeid;
      $updatePatientData->husdandname = $husdandname;
      $updatePatientData->husbanddateofbirth = $husbanddateofbirth;
      $updatePatientData->husbandage = $husbandage;
      $updatePatientData->husbandeducation = $husbandeducation;
      $updatePatientData->husbandjob = $husbandjob;
      $updatePatientData->husbandnationalid = $husbandnationalid;
      $updatePatientData->husbandbl = $husbandbl;
      $updatePatientData->husband_habbits = $husband_habbits;
      ##save patient login data
      $password = filter_input(INPUT_POST, 'password');
      if (!empty($password)) {
         //if new password use it or leave old hash
         $hash_cost_factor = (defined('HASH_COST_FACTOR') ? HASH_COST_FACTOR : null);
         $user_password_hash = password_hash($password, PASSWORD_DEFAULT, array('cost' => $hash_cost_factor));
         $updatePatientData->patient_password_hash = $user_password_hash;
      }

      //	print_r($updatePatientData->pno);

      if (is_null($updatePatientData->pno) || !($updatePatientData->pno > 0 )) {
         $updatePatientData->pno = "";
      }

      if (is_null($updatePatientData->ab) || !($updatePatientData->ab > 0 )) {
         $updatePatientData->ab = "";
      }

      if (is_null($updatePatientData->vmodel) || !($updatePatientData->vmodel > 0 )) {
         $updatePatientData->vmodel = "";
      }

      if (is_null($updatePatientData->ectopic) || !($updatePatientData->ectopic > 0 )) {
         $updatePatientData->ectopic = "";
      }


      try {
         R::store($updatePatientData);
         $this->reserveOldData($oldPatient);
         $treeId = (int) $_POST["treeId"];
         if ($treeId > 0) {
            $this->erpClient($updatePatientData);
         }
         header('Location:' . $this->hosturl . '/controllers/patienthistory.php?patientid=' . $id);
      } catch (Exception $ex) {
         echo $ex->getMessage();
         // header('Location:' . $this->hosturl . '/controllers/error?ac=notupdate&id=' . $this->controllname);
      }
   }

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

      date_default_timezone_set('Africa/Cairo');

      $edit = R::xdispense('patients_updates');
      $colums = R::getAll('DESCRIBE patients');

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

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

## START WIFE TYPE BLOCK ADD & EDIT & DELETE

   public function addwifetype() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $wifeType = filter_input(INPUT_POST, 'wifetype');
      $patientId = filter_input(INPUT_POST, 'inline');

      $wifeTypeInsert = R::dispense('wifetypes');
      $wifeTypeInsert->title = $wifeType;
      $inserted = R::store($wifeTypeInsert);
      echo $inserted;

      $patient = R::load('patients', $patientId);
      $patient->wiftypeid = $inserted;
      R::store($patient);
   }

   public function getallwifetype() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $allWifeTypes = R::findAll('wifetypes', 'order by title');
      $this->smarty->assign('allWifeTypes', $allWifeTypes);
      $this->smarty->display('patients/siglemodeltodelete/wifetypes.html');
   }

   public function updatewifetype() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $id = filter_input(INPUT_POST, 'id');
      $name = filter_input(INPUT_POST, 'name');
      $updateWifeType = R::load('wifetypes', $id);
      $updateWifeType->title = $name;
      $updated = R::store($updateWifeType);
      if (isset($updated)) {
         $allWifeTypes = R::findAll('wifetypes', 'order by title');
         $this->smarty->assign('allWifeTypes', $allWifeTypes);
         $this->smarty->display('patients/siglemodeltoupdate/wifetypes.html');
      }
   }

   function wifetypeafterup() {
      $allWifeTypes = R::findAll('wifetypes', 'order by title');
      $this->smarty->assign('allWifeTypes', $allWifeTypes);
      $this->smarty->display('patients/loadafterupdate/wifetypes.html');
   }

   public function delwifetype() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $id = filter_input(INPUT_POST, 'id');
      $patientDelete = R::load('wifetypes', $id);
      $done = 0;
      try {
         R::trash($patientDelete);
         $allWifeTypes = R::findAll('wifetypes', 'order by title');
         $this->smarty->assign('allWifeTypes', $allWifeTypes);
         $this->smarty->display('patients/wifetypeafterdelete/wifetypes.html');
      } catch (Exception $ex) {
         header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
      }
   }

## END WIFE TYPE BLOCK ADD & EDIT & DELETE && SELECT
## START EDUCATION BLOCK ADD & EDIT & DELETE && SELECT

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

      $educationWife = filter_input(INPUT_POST, 'education');
      $patientId = filter_input(INPUT_POST, 'inline');
      $type = filter_input(INPUT_POST, 'type');

      $educationWifeInsert = R::dispense('education');
      $educationWifeInsert->title = $educationWife;
      $inserted = R::store($educationWifeInsert);
      echo $inserted;

      $patient = R::load('patients', $patientId);
      if ($type == 'h') {
         $patient->husbandeducation = $inserted;
      } elseif ($type == 'w') {
         $patient->wifeeducation = $inserted;
      }

      R::store($patient);
   }

   public function getalleducation() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $allEducation = R::findAll('education', 'order by title');
      $this->smarty->assign('allEducation', $allEducation);
      $this->smarty->display('patients/siglemodeltodelete/alleducation.html');
   }

   public function updateeducation() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $id = filter_input(INPUT_POST, 'id');
      $name = filter_input(INPUT_POST, 'name');
      $updateEducation = R::load('education', $id);
      $updateEducation->title = $name;
      $updated = R::store($updateEducation);
      if (isset($updated)) {
         $allEducation = R::findAll('education', 'order by title');
         $this->smarty->assign('allEducation', $allEducation);
         $this->smarty->display('patients/siglemodeltoupdate/alleducation.html');
      }
   }

   function wifeteducationafterup() {
      $allEducation = R::findAll('education', 'order by title');
      $this->smarty->assign('allEducation', $allEducation);
      $this->smarty->display('patients/loadafterupdate/alleducation.html');
   }

   public function deleducation() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $id = filter_input(INPUT_POST, 'id');
      $patientDelete = R::load('education', $id);
      try {
         R::trash($patientDelete);
         $allEducation = R::findAll('education', 'order by title');
         $this->smarty->assign('allEducation', $allEducation);
         $this->smarty->display('patients/wifetypeafterdelete/alleducation.html');
      } catch (Exception $ex) {
         header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
      }
   }

## END EDUCATION BLOCK ADD & EDIT & DELETE
#
   ## START HUSBAND TYPES BLOCK ADD & EDIT & DELETE && SELECT

   public function addhusbandtype() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $husbandType = filter_input(INPUT_POST, 'husbandtype');
      $husbandTypeInsert = R::dispense('husbandtypes');
      $husbandTypeInsert->title = $husbandType;

      $inserted = R::store($husbandTypeInsert);
      echo $inserted;

      $patientId = filter_input(INPUT_POST, 'inline');
      $patient = R::load('patients', $patientId);
      $patient->husbandtypeid = $inserted;
      R::store($patient);
   }

   public function getallhustype() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $allHusTypes = R::findAll('husbandtypes', 'order by title');
      $this->smarty->assign('allHusTypes', $allHusTypes);
      $this->smarty->display('patients/siglemodeltodelete/husbandtypes.html');
   }

   public function updatehus() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $id = filter_input(INPUT_POST, 'id');
      $name = filter_input(INPUT_POST, 'name');

      $updateHusType = R::load('husbandtypes', $id);
      $updateHusType->title = $name;
      $updated = R::store($updateHusType);
      if (isset($updated)) {
         $allHusbandTypes = R::findAll('husbandtypes', 'order by title');
         $this->smarty->assign('allHusTypes', $allHusbandTypes);
         $this->smarty->display('patients/siglemodeltoupdate/husbandtypes.html');
      }
   }

   function husbandtypeafterup() {
      $allHusbandTypes = R::findAll('husbandtypes', 'order by title');
      $this->smarty->assign('allHusTypes', $allHusbandTypes);
      $this->smarty->display('patients/loadafterupdate/husbandtypes.html');
   }

   public function delhustype() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $id = filter_input(INPUT_POST, 'id');
      $patientDelete = R::load('husbandtypes', $id);

      try {
         R::trash($patientDelete);
         $allHusbandTypes = R::findAll('husbandtypes', 'order by title');
         $this->smarty->assign('allHusTypes', $allHusbandTypes);
         $this->smarty->display('patients/wifetypeafterdelete/husbandtypes.html');
      } catch (Exception $ex) {
         header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
      }
   }

## END HUSBAND TYPES BLOCK ADD & EDIT & DELETE && SELECT
#
   ## START HUSBAND JOBS BLOCK ADD & EDIT & DELETE && SELECT

   public function addhusbandjob() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $husbandType = filter_input(INPUT_POST, 'husjob');
      $HusbandTypeInsert = R::dispense('husbandjobs');
      $HusbandTypeInsert->title = $husbandType;
      $inserted = R::store($HusbandTypeInsert);
      echo $inserted;

      $patientId = filter_input(INPUT_POST, 'inline');
      $patient = R::load('patients', $patientId);
      $patient->husbandjob = $inserted;
      R::store($patient);
   }

   public function getallhusbandjobs() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $allHusbandJobs = R::findAll('husbandjobs', 'order by title');
      $this->smarty->assign('allHusbandJobs', $allHusbandJobs);
      $this->smarty->display('patients/siglemodeltodelete/husbandjobs.html');
   }

   public function updatehusjob() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $id = filter_input(INPUT_POST, 'id');
      $name = filter_input(INPUT_POST, 'name');

      $updateHusJob = R::load('husbandjobs', $id);
      $updateHusJob->title = $name;
      $updated = R::store($updateHusJob);
      if (isset($updated)) {
         $allHusbandJobs = R::findAll('husbandjobs', 'order by title');
         $this->smarty->assign('allHusbandJobs', $allHusbandJobs);
         $this->smarty->display('patients/siglemodeltoupdate/husbandjobs.html');
      }
   }

   function husbandjobafterup() {
      $allHusbandJobs = R::findAll('husbandjobs', 'order by title');
      $this->smarty->assign('allHusbandJobs', $allHusbandJobs);
      $this->smarty->display('patients/loadafterupdate/husbandjobs.html');
   }

   public function delhusjob() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $id = filter_input(INPUT_POST, 'id');
      $patientDelete = R::load('husbandjobs', $id);

      try {
         R::trash($patientDelete);
         $allHusbandJobs = R::findAll('husbandjobs', 'order by title');
         $this->smarty->assign('allHusbandJobs', $allHusbandJobs);
         $this->smarty->display('patients/wifetypeafterdelete/husbandjobs.html');
      } catch (Exception $ex) {
         header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
      }
   }

## END HUSBAND JOBS BLOCK ADD & EDIT & DELETE && SELECT
#
   ## START WIFE JOBS BLOCK ADD & EDIT & DELETE && SELECT

   public function addwifejob() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $jobwife = filter_input(INPUT_POST, 'jobname');
      $jobWifeInsert = R::dispense('wifejobs');
      $jobWifeInsert->title = $jobwife;
      $inserted = R::store($jobWifeInsert);
      echo $inserted;

      $patientId = filter_input(INPUT_POST, 'inline');
      $patient = R::load('patients', $patientId);
      $patient->wifejob = $inserted;
      R::store($patient);
   }

   public function getallwifejob() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $allWifeJobs = R::findAll('wifejobs', 'order by title');
      $this->smarty->assign('allWifeJobs', $allWifeJobs);
      $this->smarty->display('patients/siglemodeltodelete/wifejobs.html');
   }

   public function updatewifejob() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $id = filter_input(INPUT_POST, 'id');
      $name = filter_input(INPUT_POST, 'name');
      $updateWifeJob = R::load('wifejobs', $id);
      $updateWifeJob->title = $name;
      $updated = R::store($updateWifeJob);
      if (isset($updated)) {
         $allWifeJobs = R::findAll('wifejobs', 'order by title');
         $this->smarty->assign('allWifeJobs', $allWifeJobs);
         $this->smarty->display('patients/siglemodeltoupdate/wifejobs.html');
      }
   }

   function wifejobafterup() {
      $allWifeJobs = R::findAll('wifejobs', 'order by title');
      $this->smarty->assign('allWifeJobs', $allWifeJobs);
      $this->smarty->display('patients/loadafterupdate/wifejobs.html');
   }

   public function delwifejob() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $id = filter_input(INPUT_POST, 'id');
      $patientDelete = R::load('wifejobs', $id);

      try {
         R::trash($patientDelete);
         $allWifeJobs = R::findAll('wifejobs', 'order by title');
         $this->smarty->assign('allWifeJobs', $allWifeJobs);
         $this->smarty->display('patients/wifetypeafterdelete/wifejobs.html');
      } catch (Exception $ex) {
         header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
      }
   }

## END WIFE JOBS BLOCK ADD & EDIT & DELETE && SELECT
#
   ## START WIFE STATUS BLOCK ADD & EDIT & DELETE && SELECT

   public function addwifestatus() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $statusWife = filter_input(INPUT_POST, 'status');
      $patientId = filter_input(INPUT_POST, 'inline');

      $statusWifeInsert = R::dispense('wifestatus');
      $statusWifeInsert->title = $statusWife;

      $inserted = R::store($statusWifeInsert);
      echo $inserted;

      $patient = R::load('patients', $patientId);
      $patient->statuesid = $inserted;
      R::store($patient);
   }

   public function getallwifestatus() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $allWifeStatus = R::findAll('wifestatus', 'order by title');
      $this->smarty->assign('allWifeStatus', $allWifeStatus);
      $this->smarty->display('patients/siglemodeltodelete/wifestatus.html');
   }

   public function updatewifestatus() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $id = filter_input(INPUT_POST, 'id');
      $name = filter_input(INPUT_POST, 'name');
      $updateWifeStatus = R::load('wifestatus', $id);
      $updateWifeStatus->title = $name;
      $updated = R::store($updateWifeStatus);
      if (isset($updated)) {
         $allWifeStatus = R::findAll('wifestatus', 'order by title');
         $this->smarty->assign('allWifeStatus', $allWifeStatus);
         $this->smarty->display('patients/siglemodeltoupdate/wifestatus.html');
      }
   }

   function wifestatusafterup() {
      $allWifeStatus = R::findAll('wifestatus', 'order by title');
      $this->smarty->assign('allWifeStatus', $allWifeStatus);
      $this->smarty->display('patients/loadafterupdate/wifestatus.html');
   }

   public function delstatus() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $done = 0;
      $id = filter_input(INPUT_POST, 'id');
      if ($id == 1 || $id == 2 || $id == 3) {
         $patientDelete = R::findOne('wifestatus', "id  NOT IN (1,2 ,3)");
         $allWifeStatus = R::findAll('wifestatus', 'order by title');
         $this->smarty->assign('allWifeStatus', $allWifeStatus);
         $this->smarty->display('patients/wifetypeafterdelete/wifestatus.html');
      } else {
         $patientDelete = R::findOne('wifestatus', "id  NOT IN (1,2,3)");
         try {
            R::trash($patientDelete);
            $allWifeStatus = R::findAll('wifestatus', 'order by title');
            $this->smarty->assign('allWifeStatus', $allWifeStatus);
            $this->smarty->display('patients/wifetypeafterdelete/wifestatus.html');
         } catch (Exception $ex) {
            header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
         }
      }
   }

## END WIFE STATUS BLOCK ADD & EDIT & DELETE && SELECT
## START BLOOD TYPES BLOCK ADD & EDIT & DELETE && SELECT

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

      $bloodType = filter_input(INPUT_POST, 'bloodtype');
      $patientId = filter_input(INPUT_POST, 'inline');
      $type = filter_input(INPUT_POST, 'type');

      $bloodTypeInsert = R::dispense('bloodtypes');
      $bloodTypeInsert->title = $bloodType;
      $inserted = R::store($bloodTypeInsert);
      echo $inserted;

      $patient = R::load('patients', $patientId);
      if ($type == 'h') {
         $patient->husbandbl = $inserted;
      } elseif ($type == 'w') {
         $patient->wifebl = $inserted;
      }

      R::store($patient);
   }

   public function getallbloodtype() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $allBloodTypes = R::findAll('bloodtypes', 'order by title');
      $this->smarty->assign('allBloodTypes', $allBloodTypes);
      $this->smarty->display('patients/siglemodeltodelete/bloodtypes.html');
   }

   public function updatebl() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $id = filter_input(INPUT_POST, 'id');
      $name = filter_input(INPUT_POST, 'name');

      $updateBL = R::load('bloodtypes', $id);
      $updateBL->title = $name;
      $updated = R::store($updateBL);
      if (isset($updated)) {
         $allBloodTypes = R::findAll('bloodtypes', 'order by title');
         $this->smarty->assign('allBloodTypes', $allBloodTypes);
         $this->smarty->display('patients/siglemodeltoupdate/bloodtypes.html');
      }
   }

   function bloodtypeafterup() {
      $allBloodTypes = R::findAll('bloodtypes', 'order by title');
      $this->smarty->assign('allBloodTypes', $allBloodTypes);
      $this->smarty->display('patients/loadafterupdate/bloodtypes.html');
   }

   public function delbl() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $id = filter_input(INPUT_POST, 'id');
      $patientDelete = R::load('bloodtypes', $id);

      try {
         R::trash($patientDelete);
         $allBloodTypes = R::findAll('bloodtypes', 'order by title');
         $this->smarty->assign('allBloodTypes', $allBloodTypes);
         $this->smarty->display('patients/wifetypeafterdelete/bloodtypes.html');
      } catch (Exception $ex) {
         header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
      }
   }

## END BLOOD TYPES BLOCK ADD & EDIT & DELETE && SELECT

   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');
      $patientDelete = R::load('patients', $id);
      $patientDelete->deleted = 1;
      try {
         $this->erpClientDel($patientDelete);
         R::store($patientDelete);

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

   function Delete($path) {
      if (is_dir($path) === true) {
         $files = array_diff(scandir($path), array('.', '..'));

         foreach ($files as $file) {
            Delete(realpath($path) . '/' . $file);
         }
         return rmdir($path);
      } else if (is_file($path) === true) {
         return unlink($path);
      }
      return false;
   }

   public function addwtRow() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $tablename = filter_input(INPUT_POST, "tablename");
      $table = R::dispense($tablename);
      $table->del = 0;
      $inserted = R::store($table);
      echo $inserted;
   }

   public function caldatefromage() {

      $patientId = filter_input(INPUT_POST, 'patientId');
      $age = filter_input(INPUT_POST, 'age');
      $for = filter_input(INPUT_POST, 'type');

      $today = date('Y');
      $year = $today - $age;

//       $date = strtotime($today.' -'.$age.' year');
//       echo date('d-m-Y ', strtotime($date));
      echo '01-01-' . $year;

//        $valuenew = filter_input(INPUT_POST, 'valuenew');
//
//        echo  $valuenew ;
//
//
      $patient = R::load('patients', $patientId);

      if ($for == 'w') {
         $patient->dateofbirth = date('Y-m-d', strtotime('01-01-' . $year));
      }

      if ($for == 'h') {
         $patient->husbanddateofbirth = date('Y-m-d', strtotime('01-01-' . $year));
      }

      if ($patientId) {
         R::store($patient);
      }
   }

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

      $patientId = filter_input(INPUT_GET, 'patientid');
      $comefrom = filter_input(INPUT_GET, 'comefrom');

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

      if (!empty($comefrom) && $comefrom == 1) {
         $lastEnd = R::dispense('endvisitreports');
         $lastEnd->status = 0;
         $lastEnd->enddate = date('Y-m-d');
         $lastEnd->reason = '';
         $lastEnd->notes = '';
         $lastEnd->doctorid = $_SESSION['user_id'];
         $lastEnd->patientid = $patientId;
         R::store($lastEnd);
         header('Location:' . $this->hosturl . '/controllers/patients.php?ac=showendvisits&patientid=' . $patientId);
         exit();
      } else {
         $this->smarty->assign('patientId', $patientId);

         $endedVisits = R::findAll('endvisitreports', 'patientid = ?  order by enddate desc', [$patientId]);
         $this->smarty->assign('endedVisits', $endedVisits);

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

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

            $visit->enddate = date("d-m-Y", strtotime($visit->enddate));
         }

         $loginDoctor = R::getRow('SELECT user_name FROM awusers WHERE user_id = ? ', [$_SESSION['user_id']]);
         $this->smarty->assign('doctorName', $loginDoctor['user_name']);

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

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

   public function endvisit() {
      ## 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");
      $dated = filter_input(INPUT_POST, "dated");

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


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

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

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

      $lastEnd = R::dispense('endvisitreports');
      $lastEnd->status = 0;
      $lastEnd->enddate = date('Y-m-d');
      $lastEnd->reason = '';
      $lastEnd->notes = '';
      $lastEnd->doctorid = $_SESSION['user_id'];
      $lastEnd->patientid = $patientId;
      $lastEnd->id = R::store($lastEnd);
      echo $lastEnd->id;
   }

   ##fatma

   public function addAllPatientsToERP() {
      $programesetting = R::load('programesetting', 1);
      if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
         try {
            R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
            $count = 0;
            $start = 0;
            $limit = 30;
            $end = $start + $limit;
            R::selectDatabase('default');
            $patientsCount = R::getRow('select count(id) as id from patients');
            $count = $patientsCount["id"];
            for ($i = $start; $i <= $count; $i += $limit) {
               R::selectDatabase('default');
               $allPatients = R::findAll("patients", " order by id asc limit $start,$end ");
               R::selectDatabase('erpDB');
               if (R::testConnection()) {
                  foreach ($allPatients as $patient) {
                     $clientData = R::getRow('select clientid from client where obygyPatientId = ' . $patient->id);
                     if (empty($clientData['clientid'])) {
                        //here use NULL for new insert
                        //better to add client using erp files it self so use  curl "it is like post requist but in php"
                        $this->curlAddClient($patient, $programesetting->erpdb);
                     } else {
                        $treeId = (int) $_POST["treeId"];
                        if ($treeId > 0) {
                           //here use id to update
                           $this->curlUpdateClient($patient, $programesetting->erpdb, $clientData['clientid'], $treeId);
                        }
                     }
                  }
               } else {
                  throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
               }
               //
               $start += $limit;
               $end += $limit;
            }
            echo 1;
         } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            echo -1;
         }
         R::selectDatabase('default');
      }
   }

   public function erpClient($patient) {
      $programesetting = R::load('programesetting', 1);
      if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
         R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
         R::selectDatabase('erpDB');
         if (R::testConnection()) {
            $clientData = R::getRow('select clientid from client where obygyPatientId = ' . $patient->id);
            if (empty($clientData['clientid'])) {
               //here use NULL for new insert
               //better to add client using erp files it self so use  curl "it is like post requist but in php"
               $this->curlAddClient($patient, $programesetting->erpdb);
//                $insert_sql = "REPLACE into client (clientid, clientname, clientaddress, clientphone, clientmobile, clientdebt, clientdetails, conditions, clientdate, userid,clientareaid,clientcode,dailyentryid ,rondomtxt,clientStoreIds,obygyPatientId) VALUES
//            (NULL,'" . $patient->wifename . "' , '" . $patient->address . "', '" . $patient->phone . "', '" . $patient->mobile . "', '0', '" . $patient->importantnote . "', '0', '" . date('Y-m-d') . "', '1', '0','','','','-10','" . $patient->id . "');";
            } else {
               $treeId = (int) $_POST["treeId"];
               if ($treeId > 0) {
                  //here use id to update
                  $this->curlUpdateClient($patient, $programesetting->erpdb, $clientData['clientid'], $treeId);
               }
            }
         } else {
            throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
         }

         R::selectDatabase('default');
      }
   }

   public function erpClientDel($patient) {
      $programesetting = R::load('programesetting', 1);
      if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
         R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
         R::selectDatabase('erpDB');
         if (R::testConnection()) {
            $clientData = R::getRow('select clientid,dailyentryid from client where obygyPatientId = ' . $patient->id);
            $this->curlDelClient($programesetting->erpdb, $clientData['clientid'], $clientData['dailyentryid']);
         } else {
            throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
         }
         R::selectDatabase('default');
      }
   }

   //better to add client using erp files it self so use  curl "it is like post requist but in php"
   public function curlAddClient($patient, $erpDB) {
      // set post fields
      $post = [
          'erpDB' => $erpDB,
          'newclientName' => $patient->wifename,
          'clientaddress' => $patient->address,
          'clientphone' => $patient->phone,
          'clientmobile' => $patient->mobile,
          'newclientdebt' => 0,
          'clientdetails' => $patient->importantnote,
          'clientareaid' => 0,
          'clientcode' => '',
          'store_all' => -10,
          'obygyPatientId' => $patient->id,
      ];

      $ch = curl_init(HOST_URL_ERP . '/controllers/clientControllerAjax.php?do=addclient');
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

      // execute!
      $response = curl_exec($ch);

      // close the connection, release resources used
      curl_close($ch);

      // do anything you want with your response
      //var_dump($response);
   }

   public function curlUpdateClient($patient, $erpDB, $clientId, $treeId) {
      // set post fields
      $post = [
          'erpDB' => $erpDB,
          'id' => $clientId,
          'treeId' => $treeId,
          'newclientName' => $patient->wifename,
          'clientaddress' => $patient->address,
          'clientphone' => $patient->phone,
          'clientmobile' => $patient->mobile,
          'newclientdebt' => 0,
          'clientdetails' => $patient->importantnote,
          'clientareaid' => 0,
          'clientcode' => '',
          'store_all' => 1,
          'obygyPatientId' => $patient->id,
      ];

      $ch = curl_init(HOST_URL_ERP . '/controllers/clientControllerAjax.php?do=updateFull');
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

      // execute!
      $response = curl_exec($ch);

      // close the connection, release resources used
      curl_close($ch);

      // do anything you want with your response
      var_dump($response);
   }

   public function curlDelClient($erpDB, $clientId, $dailyentryid) {
      // set post fields
      $post = [
          'erpDB' => $erpDB,
          'id' => $clientId,
          'action' => $dailyentryid,
      ];

      $ch = curl_init(HOST_URL_ERP . '/controllers/clientControllerAjax.php?do=deleteFinaly');
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

      // execute!
      $response = curl_exec($ch);

      // close the connection, release resources used
      curl_close($ch);

      // do anything you want with your response
//        var_dump($response);
   }

   public function erpGetClientTreeId($patientId) {
      $programesetting = R::load('programesetting', 1);
      if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
         R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
         R::selectDatabase('erpDB');
         if (R::testConnection()) {
            $clientData = R::getRow('select clientid,accountstree.id from client left join accountstree on accountstree.name=client.clientname where obygyPatientId = ' . $patientId);
         } else {
            throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
         }
         R::selectDatabase('default');
         return $clientData["id"];
      } else {
         return "NO_DB";
      }
   }

   public function erpSellbill($visit) {
      $programesetting = R::load('programesetting', 1);
      if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
         R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
         R::selectDatabase('erpDB');
         if (R::testConnection()) {
            $clientData = R::getRow('select clientid from client where obygyPatientId = ' . $visit->patientid);
         } else {
            throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
         }
         R::selectDatabase('default');
      }

      // set post fields
      $post = [
          'erpDB' => $programesetting->erpdb,
          'saveid' => $programesetting->erpdbsave,
          'supplier' => $clientData['clientid'],
          'bn' => $visit->visitdate,
          'totalBill_hidden' => $visit->detectionvalue,
          'netBill_hidden' => $visit->detectionvalue,
          'productid' => $visit->detectionid,
          'visitId' => $visit->id,
      ];
      $ch = curl_init(HOST_URL_ERP . '/controllers/sellbillController.php?do=addObgyVisit');
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

      // execute!
      $response = curl_exec($ch);

      // close the connection, release resources used
      curl_close($ch);

      // do anything you want with your response
      var_dump($response);
   }

   function noteshusbands() {
      $patient_id = filter_input(INPUT_POST, 'patient_id');
      $text = filter_input(INPUT_POST, 'text');

      $patient_info = R::load('patients', $patient_id);
      $patient_info->husband_notes = $text;
      R::store($patient_info);
   }

   function habitshusbands() {
      $patient_id = filter_input(INPUT_POST, 'patient_id');
      $text = filter_input(INPUT_POST, 'text');

      $patient_info = R::load('patients', $patient_id);
      $patient_info->husband_habbits = $text;
      R::store($patient_info);
   }

   public function checkmobile() {
//check login
      autho::checkautho($this->hosturl);
//check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
      $phone = filter_input(INPUT_POST, 'phone');
      $patientId = filter_input(INPUT_POST, 'patientId');

      $data = R::findAll('patients', ' ( phone = ?  or mobile = ? )  and id != ? ', [$phone, $phone, $patientId]);

      if (count($data) > 0) {
         $found = 1;
      } else {
         $found = 0;
      }
      echo $found;
   }

   public function addprevmarr() {
      $marrFor = filter_input(INPUT_POST, 'marrFor');
      $patientId = filter_input(INPUT_POST, 'patientId');

      switch ($marrFor) {
         case 1:
            $tableName = 'previous_marriage';
            break;
         case 2:
            $tableName = 'hus_previous_marriage';
            break;
      }

      $res = R::xdispense($tableName);
      $res->patientid = $patientId;
      $res->deleted = 0;
      $res->id = R::store($res);

      $this->smarty->assign('tableName', $tableName);
      $this->smarty->assign('res', $res);
      $this->smarty->display('patients/previous_marriage.html');
   }

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