<?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);

        #include upload function
        require_once("../../_library/plugins/classupload/uploadfunctions.php");


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


# 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
// 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;
        require_once("visits_common.php"); //general functions
        //here will call all php pages
        require_once("_header.php");
        require_once("_patientdata.php");
        require_once("_sidebar.php");
        require_once("_leftsidebar.php");
        require_once("_footer.php");

        //find loading time
        $this->time = microtime(true);
        $this->today = date('Y-m-d');
    }

    //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");
        $phoneUrl = filter_input(INPUT_GET, "phone");

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

        $statusNo = 0;

        if (count($savedBefore) > 0) {
            $patient = R::load('patients', $savedBefore->id);
            $statusNo = $patient->statusno;
            if (!empty($phoneUrl) && $phoneUrl != '') {
                $patient->phone = $phoneUrl;
                R::store($patient);
            }
        } else {
            $patient = R::dispense('patients');
            $patient->userid = $_SESSION['user_id'];
            $statusNo = $this->getstatusno();
            $patient->statusno = $statusNo;
            $patient->refer_doctor = -1;
            $patient->doctor1 = -1;
            $patient->doctor2 = -1;
            $patient->h_refer_doctor = -1;
            $patient->h_doctor1 = -1;
            $patient->h_doctor2 = -1;

            if (!empty($phoneUrl) && $phoneUrl != '') {
                $patient->phone = $phoneUrl;
            }
            $patient->id = R::store($patient);
        }

        if ($patient->revision_date == '0000-00-00' || is_null($patient->revision_date) || $patient->revision_date == '') {
            $patient->revision_date = '00-00-0000';
        } else {
            $patient->revision_date = date('d-m-Y ', strtotime($patient->revision_date));
        }

        $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->smarty->assign('lastpatient', $patient);

        $this->getPatientChilds($patient->id);
        $this->getPatientNotify($patient->id);
        $this->getpatientfiles($patient->id);
        $this->getVoiceRecord($patient->id);
        $this->relateddata();
        $this->createbarcode($statusNo);
        $this->createQRcode($statusNo);
        $this->initialBtns();

        $governorate_centers = R::findAll('governorate_centers'
                        , ' deleted = 0 and governorate_id = ? order by name', [$patient->governorate]);
        $this->smarty->assign('governorate_centers', $governorate_centers);
//
//
        $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'));
        $this->smarty->assign('thisDay', date('Y/m/d'));

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

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


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

        $py_all_departs = R::findAll('awrole', 'id not in (1,14,6,3,2,7,10)');
        $this->smarty->assign('py_all_departs', $py_all_departs);

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




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

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

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

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

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

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


        $this->smarty->assign('userName', $this->getUserNameById($_SESSION['user_id']));

        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 branchInfos($branchesActivate) {
        if ($branchesActivate == 1) {
            $showBrancheSelect = 0;
            $selectedBranch = '';

            $user = R::getRow('SELECT related_branches FROM awusers 
                    WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);

            if ($user['related_branches'] == 0 && $user['related_branches'] != '' && $user['related_branches'] != null) {
                $branches = R::findAll('branches');
                $showBrancheSelect = 1;
            } else {
                $related_branches = array();
                $relBranches = explode(',', $user['related_branches']);
                foreach ($relBranches as $value) {
                    $value = trim($value);
                    array_push($related_branches, $value);
                }

                if ($related_branches[0] > 0) {
                    if (count($related_branches) == 1) {
                        $selectedBranch = $related_branches[0];
                    } elseif (count($related_branches) > 1) {
                        $showBrancheSelect = 1;
                    }
                    $branches = R::findAll('branches', '  id  in ( ' . $user['related_branches'] . ' ) ');
                } else {
                    $branches = R::findAll('branches');
                    $showBrancheSelect = 1;
                }
            }

            $this->smarty->assign('branches', $branches);
            $this->smarty->assign('selectedBranch', $selectedBranch);
            $this->smarty->assign('showBrancheSelect', $showBrancheSelect);
        }
    }

    function initialBtns() {
        $allowEditRfc = 0;
        $btn15 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 15  ', [$_SESSION['role_id']]);
        if (count($btn15) > 0) {
            $allowEditRfc = $btn15->checkval;
        }
        $this->smarty->assign('allowEditRfc', $allowEditRfc);
    }

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

    public function getPatientChilds($patientId) {

        if ($patientId > 0) {
            $childs = R::findAll('patients_childs', ' deleted = 0 and patientid = ?  ', [$patientId]);
            foreach ($childs as $child) {
                if ($child->birth_date == '0000-00-00' || is_null($child->birth_date) || $child->birth_date == '') {
                    $child->birth_date = '00-00-0000';
                } else {
                    $child->birth_date = date('d-m-Y ', strtotime($child->birth_date));
                }
            }
            $this->smarty->assign('childs', $childs);
        }
    }

    public function getPatientNotify($patientId) {

        if ($patientId > 0) {
            $birthNotifications = R::findAll('patients_notify', ' deleted = 0 and patientid = ? order by notify_date   ', [$patientId]);

            foreach ($birthNotifications as $notify) {
                if ($notify->notify_date == '0000-00-00' || is_null($notify->notify_date) || $notify->notify_date == '') {
                    // $notify->notify_date = '00-00-0000';
                } else {
                    $notify->notify_date = date('Y/m/d', strtotime($notify->notify_date));
                }

                $user = R::getRow('select name  from awusers where user_id = ?', [$notify->user_id]);
                $notify->userName = $user['name'];
            }
            $this->smarty->assign('birthNotifications', $birthNotifications);
        }
    }

    function getstatusno() {
        $statusno = 1;
        $last_code = R::getRow('select max(statusno) 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);

        $awrole = R::load('awrole', $_SESSION['role_id']);

        if ($awrole->redirect_to > 1 && $awrole->redirect_to != 6) {
            $index_redirect = R::load('index_redirect', $awrole->redirect_to);
            $link = $index_redirect->link;
        } else if ($awrole->redirect_to > 1 && $awrole->redirect_to == 6) {
            $link = -2;
        } else {
            $link = -1;
        }



        $user = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);

        if ($user['role_id'] == 19 && $user['related_dr'] != 0 && !empty($user['related_dr']) &&
                $user['related_dr'] != "" && !( is_null($user['related_dr']))) {

            $doctorSearch = ' and ( patients.doctor1 in  (' . $user['related_dr'] . ' )  || patients.doctor1 = -1 || patients.doctor1 IS  NULL) ';
        } elseif ($awrole->index_search == 1) {
            $doctorSearch = ' and ( patients.doctor1 =  ' . $_SESSION['user_id'] . ' || patients.doctor1 = -1 || patients.doctor1 IS  NULL)';
        } else {
            $doctorSearch = '';
        }



        $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');
        //$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 = '';

        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%'  OR husdandname LIKE '%$resultSearchWifeName%' OR phone  LIKE '%$resultSearchWifeName%'  OR mobile  LIKE '%$resultSearchWifeName%' ) ";
            }

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

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

            ## 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%'  || husbandnationalid LIKE '%$resultSearchNationalId%'  ) ";
            }


            #################################################################################################################
            $limit = 50;
            if ($programesetting->search_result_no > 0) {
                $limit = $programesetting->search_result_no;
            }
            if (empty($resultSearchHusbandJob)) {
                $query = "SELECT patients.*   , u.name as d1    , uu.name  as hd1
                                FROM `patients`
                                  left join  awusers u     on u.user_id =  patients.doctor1
                                  left join  awusers uu     on uu.user_id =  patients.h_doctor1

                                        WHERE
                                        patients.done = 1
                                        AND patients.deleted = 0
                                        $q1  $q2  $q3  $q4 $q5 $q6 $q7 $q8 $doctorSearch
                                        limit 0,$limit ";
            } else {
                $query = "SELECT patients.* , husbandjobs.title     , u.name as d1    , uu.name  as hd1
                                FROM `patients`
                                  INNER JOIN husbandjobs ON  patients.husbandjob  = husbandjobs.id
                                   left join  awusers u     on u.user_id =  patients.doctor1
                                  left join  awusers uu     on uu.user_id =  patients.h_doctor1

                                        WHERE
                                        patients.done = 1
                                        AND patients.deleted = 0
                                        $q1  $q2  $q3  $q4 $q5 $q6 $q7 $q8 $doctorSearch
                                        limit 0,$limit ";
            }



            //  print_r($query);

            $queryString = R::getAll($query);
            $arrLinkType = array();
            $i = 0;
            foreach ($queryString as $pat) {


                if ($link == -2) {
                    $lastVisitData = R::findOne('lastvisit', 'patientid = ?', [$pat['id']]);
                    if (!empty($lastVisitData)) {
                        $queryString[$i]['link'] = $lastVisitData->control . '.php?ac=index&patientid=' . $pat['id'];
                    } else {
                        $queryString[$i]['link'] = 'patienthistory.php?ac=index&patientid=' . $pat['id'];
                    }
                }
                ##
                elseif ($link == -1) {
                    $queryString[$i]['link'] = -1;
                }
                ##
                else {
                    if ($awrole->redirect_to == 5) {
                        $queryString[$i]['link'] = $link . '' . $pat['id'] . '&patientid=' . $pat['id'];
                    } else {
                        $queryString[$i]['link'] = $link . '' . $pat['id'];
                    }
                }

                $i++;
            }

            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   $doctorSearch
                                ";
            //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() {

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

        $submitted = filter_input(INPUT_POST, 'submit');
        $submit_v = filter_input(INPUT_POST, 'submit_v');
        $id = filter_input(INPUT_POST, 'ptntid');
        $addVisit = filter_input(INPUT_POST, 'addVisit');
        $for_not_always = filter_input(INPUT_POST, 'for_not_always');

        if (!empty($submitted) || !empty($submit_v)) {

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

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

                $submitchange->done = 1;
                if ($for_not_always == 1) {
                    $submitchange->statusno = 'Out';
                }


                $statusno = filter_input(INPUT_POST, 'statusno');
                $wifename = filter_input(INPUT_POST, 'wifename');
//            $wifetype = filter_input(INPUT_POST, 'wiftypeid');
                $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');
                $mirragefromM = filter_input(INPUT_POST, 'mirragefromm');

                $refer_doctor = filter_input(INPUT_POST, 'refer_doctor');
                $h_refer_doctor = filter_input(INPUT_POST, 'h_refer_doctor');

                $nationality = filter_input(INPUT_POST, 'nationality');
                $h_nationality = filter_input(INPUT_POST, 'h_nationality');

                $religion = filter_input(INPUT_POST, 'religion');
                $h_religion = filter_input(INPUT_POST, 'h_religion');

                $doctor1 = filter_input(INPUT_POST, 'doctor1');
                $h_doctor1 = filter_input(INPUT_POST, 'h_doctor1');

                $doctor2 = filter_input(INPUT_POST, 'doctor2');
                $h_doctor2 = filter_input(INPUT_POST, 'h_doctor2');

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

                $rfc = filter_input(INPUT_POST, 'rfc');
                $wrfc = filter_input(INPUT_POST, 'wrfc');


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

                $hus_statuesid = filter_input(INPUT_POST, 'husstatus');
                $hus_mobile = filter_input(INPUT_POST, 'hus_mobile');
                $hus_passport = filter_input(INPUT_POST, 'hus_passport');


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

                $format = 'd-m-Y';

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

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

//                $d = DateTime::createFromFormat($format, $husbanddateofbirth);
//                if ($d && $d->format($format) === $husbanddateofbirth && $husbanddateofbirth != '00-00-0000') {
//                    $husbanddateofbirth = date('Y-m-d', strtotime($husbanddateofbirth));
//                } else {
//                    $husbanddateofbirth = 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');

                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->branch_id = $branch_id;

                $submitchange->passport = $passport;

                $submitchange->hus_mobile = $hus_mobile;
                $submitchange->hus_passport = $hus_passport;
                $submitchange->hus_statuesid = $hus_statuesid;

                $submitchange->refer_doctor_tb = 0;
                if ($refer_doctor[0] == "*") {
                    $refer_doctor = ltrim($refer_doctor, '*');
                    $submitchange->refer_doctor_tb = 1;
                }

                $submitchange->h_refer_doctor_tb = 0;
                if ($h_refer_doctor[0] == "*") {
                    $h_refer_doctor = ltrim($h_refer_doctor, '*');
                    $submitchange->h_refer_doctor_tb = 1;
                }

                $submitchange->refer_doctor = $refer_doctor;
                $submitchange->h_refer_doctor = $h_refer_doctor;
                $submitchange->nationality = $nationality;
                $submitchange->h_nationality = $h_nationality;
                $submitchange->religion = $religion;
                $submitchange->h_religion = $h_religion;
                $submitchange->doctor1 = $doctor1;
                $submitchange->h_doctor1 = $h_doctor1;
                $submitchange->doctor2 = $doctor2;
                $submitchange->h_doctor2 = $h_doctor2;
                $submitchange->knownfrom = $knownfrom;
                $submitchange->rfc = $rfc;
                $submitchange->wrfc = $wrfc;


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

                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");

                $password = filter_input(INPUT_POST, 'password');
                $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);
                    if ($id > 0) {
                        sendSms($id, 1);
                    }

                    ##fatma
                    $this->erpClient($submitchange);

                    R::commit();
                    ## login position

                    if (!empty($submit_v)) {
                        header('Location:' . $this->hosturl . '/controllers/visits.php?ac=index&patientid=' . $id);
                    } else {
                        header('Location:' . $this->hosturl . '/controllers/index.php?ac=index');
                    }



                    /* $loginPosition = R::getRow('select role_id from awusers where user_id = ?', [$_SESSION['user_id']]);
                      if ($loginPosition['role_id'] != 3) {
                      header('Location:' . $this->hosturl . '/controllers/patienthistory.php?patientid=' . $id);
                      } else {

                      } */
                } catch (Exception $e) {
                    echo $e;
                    R::rollback();
                    header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
                }
            } else {
                header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
            }
        } else {
            header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
        }
    }

    private function sendToDept($patientId, $for_department, $visitId, $for_husband) {
        $invType = filter_input(INPUT_POST, 'invType');
        $itr = filter_input(INPUT_POST, 'itr');
        for ($i = 1; $i <= $itr; $i++) {
            switch ($for_department) {
                case 5:
                    $obj = R::dispense('raysresults');
                    $obj->rayid = filter_input(INPUT_POST, 'selectedId' . $i);
                    $obj->raytype = $invType;
                    break;
                case 12:
                    $obj = R::dispense('investigationresults');
                    $obj->investid = filter_input(INPUT_POST, 'selectedId' . $i);
                    $obj->invtype = $invType;
                    break;
            }


            $obj->doctorid = 0;
            $obj->deleted = 0;
            $obj->visitid = $visitId;
            $obj->patientid = $patientId;
            $obj->date = date('Y-m-d');
            $obj->forhusband = $for_husband;

            R::store($obj);
        }


        #### offers

        switch ($for_department) {
            case 12:
                $itr_offer = filter_input(INPUT_POST, 'itr_offer');
                for ($i = 1; $i <= $itr_offer; $i++) {

                    $offer_id = filter_input(INPUT_POST, 'offerId' . $i);
                    $invofferdetails = R::findall('invofferdetails', 'del = ? and invoffer_id = ?  ', [0, $offer_id]);
                    foreach ($invofferdetails as $data) {
                        $obj = R::dispense('investigationresults');
                        $obj->investid = $data->inv_id;
                        $obj->invtype = $invType;
                        $obj->doctorid = 0;
                        $obj->deleted = 0;
                        $obj->visitid = $visitId;
                        $obj->patientid = $patientId;
                        $obj->date = date('Y-m-d');
                        $obj->forhusband = $for_husband;
                        $obj->offer_id = $offer_id;

                        R::store($obj);
                    }
                }
                break;
        }
    }

    ## add new patient

    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');
        $husstatus = R::findAll('husstatus', ' del != 1 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('husstatus', $husstatus);
        $this->smarty->assign('wifebl', $wifebl);
        $this->smarty->assign('husbandtypes', $husbandtypes);
        $this->smarty->assign('husbandjobs', $husbandjobs);

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

    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 ($dataupdated->done == 1) {
            echo '-999999999999999';
        } else {

            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"));
            }
            ##
            elseif ($colname == 'refer_doctor' || $colname == 'h_refer_doctor') {
                if ($valuenew[0] == "*") {
                    $valuenew = ltrim($valuenew, '*');
                }

                $dataupdated->$colname = $valuenew;
                $col = $colname . '_tb';
                $dataupdated->$col = 1;
            }
            ##
            else {
                $dataupdated->$colname = $valuenew;
//                ##fatma
//                $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);


        if ($dataupdated->done == 1) {
            echo '-999999999999999';
        } else {
            $dataupdated->wifename = $wifename;

            //$dataupdated->statusno = $id;
//            ##fatma
//            $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');

        // r::debug(true, 2);

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

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

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

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

        // r::debug(true, 2);

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

        if (count($data) > 0) {
            $found = 1;
        } else {
            $found = 0;
        }
        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 = 1;
        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 != ? and deleted != 1  ', [$wifenationalid, $patientId]);
        //$found;
        if (count($data) > 0) {
            $found = 1;
        } else {
            $found = 0;
        }
        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 != ? and deleted != 1   ', [$husbandnationalid, $patientId]);
        //$found;
        if (count($data) == 0) {
            $found = 0;
        } else {
            $found = 1;
        }
        echo $found;
    }

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


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


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

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


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


        $data = R::findAll('patients', 'hus_passport = ? and id != ? ', [$passport, $patientId]);
        //$found;
        if (count($data) > 0) {
            $found = 1;
        } else {
            $found = 0;
        }
        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']);

        $user = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);

        if ($user['role_id'] == 19 && $user['related_dr'] != 0 && !empty($user['related_dr']) &&
                $user['related_dr'] != "" && !( is_null($user['related_dr']))) {

            $doctorSearch = ' and awusers.user_id in  (' . $user['related_dr'] . ' ) ';
        } else {
            $doctorSearch = '';
        }

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

        $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 showpt() {
        //check login
        autho::checkautho($this->hosturl);

        $doctorId = filter_input(INPUT_GET, 'doctorId');
        //print_r($doctorId);
        if ($doctorId > 0) {
            $doctorSearch = ' and  patients.doctor1  = ' . $doctorId . '    ';
        } else {
            $user = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);
            if ($user['role_id'] == 19 && $user['related_dr'] != 0 && !empty($user['related_dr']) &&
                    $user['related_dr'] != "" && !( is_null($user['related_dr']))) {

                $doctorSearch = ' and ( patients.doctor1 in  (' . $user['related_dr'] . ' )  
                                                          || patients.doctor1 = -1 || patients.doctor1 IS  NULL) ';
            } else {
                $doctorSearch = '';
            }
        }




        $sIndexColumn = "id";

        /* DB table to use */
        $sTable = "patients";


        $aColumns = array('id', 'statusno', 'wifename', 'husdandname', 'address', 'phone', 'mobile', 'status'
            , 'entrydate');

        // Indexed column (used for fast and accurate table cardinality)

        /*
         * Paging
         */
        $sLimit = "";
        if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
            $sLimit = "LIMIT " . intval($_GET['iDisplayStart']) . ", " .
                    intval($_GET['iDisplayLength']);
        }


        /*
         * Ordering
         */
        $sOrder = "";
        if (isset($_GET['iSortCol_0'])) {
            $sOrder = "ORDER BY  ";
            for ($i = 0; $i < intval($_GET['iSortingCols']); $i++) {
                if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
                    $sOrder .= $aColumns[intval($_GET['iSortCol_' . $i])] . "
                    " . ($_GET['sSortDir_' . $i] === 'asc' ? 'asc' : 'desc') . ", ";
                }
            }

            $sOrder = substr_replace($sOrder, "", -2);
            if ($sOrder == "ORDER BY") {
                $sOrder = "";
            }
        }


        /*
         * Filtering
         * NOTE this does not match the built-in DataTables filtering which does it
         * word by word on any field. It's possible to do here, but concerned about efficiency
         * on very large tables, and MySQL's regex functionality is very limited
         */

        $sWhere = "WHERE (";


        if (isset($_GET['sSearch']) && $_GET['sSearch'] != "") {

            for ($i = 0; $i < count($aColumns); $i++) {
                
                          if ($i > 0) {
                    $sWhere .= "  OR ";
                }
                if ($i == 0) {
                    $sWhere .= "  (  ";
                }
                
                
                if (isset($_GET['bSearchable_' . $i]) && $_GET['bSearchable_' . $i] == "true") {
                    $sWhere .= $aColumns[$i] . " LIKE '%" . $_GET['sSearch'] . "%'   ";
                }
            }

          
            $sWhere = substr_replace($sWhere, "", -3);
               $sWhere .= " ) ";
            $sWhere .= " AND deleted != 1  and done = 1 $doctorSearch ";
        } else {
            $sWhere .= " deleted != 1  and done = 1 $doctorSearch ";
        }


        $sWhere .= ' )';

        $sQuery = "SELECT  " . str_replace(" , ", " ", implode(", ", $aColumns)) . " FROM  $sTable $sWhere $sOrder $sLimit ";
        // print_r($sQuery);
        $rResult = R::getAll($sQuery);

        /* Data set length after filtering */
        $sQuery = "SELECT COUNT(*)  as countAll FROM  $sTable $sWhere $sOrder  ";

        $rResultFilterTotal = R::getRow($sQuery);
        //$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
        $iFilteredTotal = $rResultFilterTotal['countAll'];
        //print_r($rResultFilterTotal['countAll']);
        /* Total data set length */
        $sQuery = "SELECT $sIndexColumn FROM  $sTable ";
        $rResultTotal = R::getAll($sQuery);
        //$aResultTotal = mysql_fetch_array($rResultTotal);
        $iTotal = count($rResultTotal);

        $output = array(
            //"sEcho" => intval($_GET['sEcho']),
            "iTotalRecords" => $iTotal,
            "iTotalDisplayRecords" => $rResultFilterTotal['countAll'],
            "aaData" => array()
        );

        $aColumns = array('statusno', 'wifename', 'husdandname', 'address', 'phone', 'mobile', 'entrydate');

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

        $programesetting = R::findOne('programesetting');
        foreach ($rResult as $aRow) {
            $row = array();
            for ($i = 0; $i < count($aColumns); $i++) {
                if ($aColumns[$i] == "husdandname") {
                    if ($programesetting->system_lang == 1) {
                        $row[] = $aRow[$aColumns[$i]];
                    }
                }
                ##
                else if ($aColumns[$i] == "entrydate" && !($aRow[$aColumns[$i]] == '0000-00-00' || is_null($aRow[$aColumns[$i]]))) {
                    $row[] = date('Y/m/d ', strtotime($aRow[$aColumns[$i]]));
                }
                ##
                else if ($aColumns[$i] != ' ') {
                    /* General output */
                    $row[] = $aRow[$aColumns[$i]];
                }
            }


            $row[] = '<a class="label  label-default printPtBar"  data-id="' . $aRow['id'] . ' " ><i class="fa fa-print"></i></a>';

            $row[] = '<a class="label  label-primary printPtQr"  data-id="' . $aRow['id'] . ' " ><i class="fa fa-print"></i></a>';

            $row[] = '<a class="label  label-success printPtCard"  data-id="' . $aRow['id'] . ' " ><i class="fa fa-print"></i></a>';



            if ($aRow['status'] != 1) {
                $row[] = '<a class="label  label-primary" href="' . $this->hosturl . '/controllers/patients.php?ac=edit&id=' . $aRow['id'] . ' ">تعديل</a>';
            } else {
                $row[] = '';
            }

            if ($allowSuspPat == 1 && $aRow['status'] != 1) {
                $row[] = '<a class="suspendPat label  label-warning"
                        data-id="' . $aRow['id'] . ' "  data-status="1"  >إيقاف </a>';
            } elseif ($allowSuspPat == 1 && $aRow['status'] == 1) {
                $row[] = '<a class="suspendPat label  label-default"
                        data-id="' . $aRow['id'] . ' "  data-status="0"  >تفعيل  </a>';
            } else {
                $row[] = '';
            }

            if ($_SESSION['role_id'] != 3) {
                $row[] = '<a class="deletemsgEX label  label-danger"   data-id="' . $aRow['id'] . ' " data-link="patients" data-fn="del">حذف</a>';
            }

            $output['aaData'][] = $row;
        }
        //print_r($output);
        echo json_encode($output);
    }

    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]);

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

        $this->smarty->assign('userName', $this->getUserNameById($_SESSION['user_id']));

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

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

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

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

        if (is_null($getOnePatient->cs) || !($getOnePatient->cs > 0 )) {
            $getOnePatient->cs = "";
        }

        if (is_null($getOnePatient->userid) || !($getOnePatient->userid > 0 )) {
            $getOnePatient->userid = 0;
        }

        r::store($getOnePatient);

        $governorate_centers = R::findAll('governorate_centers'
                        , ' deleted = 0 and governorate_id = ? order by name', [$getOnePatient->governorate]);
        $this->smarty->assign('governorate_centers', $governorate_centers);

        $getOnePatient->wifename = trim($getOnePatient->wifename);

        if (empty($getOnePatient->wifename) || is_null($getOnePatient->wifename) || $getOnePatient->wifename == "") {
            $this->smarty->assign('hasWife', 0);
        } else {
            $this->smarty->assign('hasWife', 1);
        }

        $getOnePatient->husdandname = trim($getOnePatient->husdandname);

        if (empty($getOnePatient->husdandname) || is_null($getOnePatient->husdandname) || $getOnePatient->husdandname == "") {
            $this->smarty->assign('hasHus', 0);
        } else {
            $this->smarty->assign('hasHus', 1);
        }


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

        if ($getOnePatient->revision_date == '0000-00-00' || is_null($getOnePatient->revision_date) || $getOnePatient->revision_date == '') {
            $getOnePatient->revision_date = '00-00-0000';
        } else {
            $getOnePatient->revision_date = date('d-m-Y ', strtotime($getOnePatient->revision_date));
        }


        $this->getpatientfiles($id);
        $this->getVoiceRecord($id);
        $this->getPatientChilds($id);
        $this->getPatientNotify($id);
        $this->initialBtns();
        $this->getOrgPatNo($id);

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

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

        $this->createbarcode($getOnePatient->statusno);
        $this->createQRcode($getOnePatient->statusno);

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

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

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

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

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

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

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

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

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


        $visit_frist = R::findOne('visits', 'patientid = ?', [$id]);
        $visit_frist_doc = R::findOne('awusers', 'user_id = ?', [$visit_frist->for_doctor]);
        $this->smarty->assign('visit_frist_doc', $visit_frist_doc);
        $this->smarty->assign('visit_frist', $visit_frist);

        ##fatma
        $treeId = $this->erpGetClientTreeId($getOnePatient->id);
        $this->smarty->assign('treeId', $treeId);
        
                if ($programesetting->organizations != 1) {
            $organizations = R::findAll('organizations', ' deleted != 1 ');
            $this->smarty->assign('organizations', $organizations);
        }

        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 getOrgPatNo($patientId) {
        if ($patientId > 0) {
            $orgPatNos = R::findAll('organizations_patient_no', ' deleted = 0 and patient_id = ?  ', [$patientId]);
            $this->smarty->assign('orgPatNos', $orgPatNos);
        }
    }

    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');
        $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');
        $mirragefromY = filter_input(INPUT_POST, 'mirragefromy');
        $mirragefromM = filter_input(INPUT_POST, 'mirragefromm');

        $refer_doctor = filter_input(INPUT_POST, 'refer_doctor');
        $h_refer_doctor = filter_input(INPUT_POST, 'h_refer_doctor');

        $nationality = filter_input(INPUT_POST, 'nationality');
        $h_nationality = filter_input(INPUT_POST, 'h_nationality');

        $religion = filter_input(INPUT_POST, 'religion');
        $h_religion = filter_input(INPUT_POST, 'h_religion');

        $doctor1 = filter_input(INPUT_POST, 'doctor1');
        $h_doctor1 = filter_input(INPUT_POST, 'h_doctor1');

        $doctor2 = filter_input(INPUT_POST, 'doctor2');
        $h_doctor2 = filter_input(INPUT_POST, 'h_doctor2');

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

        $rfc = filter_input(INPUT_POST, 'rfc');
        $wrfc = filter_input(INPUT_POST, 'wrfc');

        $passport = filter_input(INPUT_POST, 'passport');
        $revisioned = filter_input(INPUT_POST, 'revisioned');
        $vip = filter_input(INPUT_POST, 'vip');
        $vip_comment = filter_input(INPUT_POST, 'vip_comment');

        $hus_statuesid = filter_input(INPUT_POST, 'husstatus');
        $hus_mobile = filter_input(INPUT_POST, 'hus_mobile');
        $hus_passport = filter_input(INPUT_POST, 'hus_passport');

        $case_card = filter_input(INPUT_POST, 'case_card');
        $file_card = filter_input(INPUT_POST, 'file_card');
        $governorate = filter_input(INPUT_POST, 'governorate');
        $governorate_center = filter_input(INPUT_POST, 'governorate_center');
        $gender = filter_input(INPUT_POST, 'gender');



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

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

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

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


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

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

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

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

        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->revisioned = $revisioned;
        $updatePatientData->vip = $vip;
        $updatePatientData->vip_comment = $vip_comment;
        $updatePatientData->file_card = $file_card;
        $updatePatientData->case_card = $case_card;
        $updatePatientData->governorate = $governorate;
        $updatePatientData->governorate_center = $governorate_center;
        $updatePatientData->branch_id = $branch_id;
        $updatePatientData->refer_doctor_tb = 0;
        if ($refer_doctor[0] == "*") {
            $refer_doctor = ltrim($refer_doctor, '*');
            $updatePatientData->refer_doctor_tb = 1;
        }

        $updatePatientData->h_refer_doctor_tb = 0;
        if ($h_refer_doctor[0] == "*") {
            $h_refer_doctor = ltrim($h_refer_doctor, '*');
            $updatePatientData->h_refer_doctor_tb = 1;
        }

        $updatePatientData->passport = $passport;

        $updatePatientData->hus_mobile = $hus_mobile;
        $updatePatientData->hus_passport = $hus_passport;
        $updatePatientData->hus_statuesid = $hus_statuesid;
        $updatePatientData->revision_date = $revision_date;

        $updatePatientData->refer_doctor = $refer_doctor;
        $updatePatientData->h_refer_doctor = $h_refer_doctor;
        $updatePatientData->nationality = $nationality;
        $updatePatientData->h_nationality = $h_nationality;
        $updatePatientData->religion = $religion;
        $updatePatientData->h_religion = $h_religion;
        $updatePatientData->doctor1 = $doctor1;
        $updatePatientData->h_doctor1 = $h_doctor1;
        $updatePatientData->doctor2 = $doctor2;
        $updatePatientData->h_doctor2 = $h_doctor2;
        $updatePatientData->knownfrom = $knownfrom;
        $updatePatientData->gender = $gender;


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

        if ($allowEditRfc == 1) {
            $updatePatientData->rfc = $rfc;
            $updatePatientData->wrfc = $wrfc;
        }


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

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

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

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


// 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;
        try {
            R::store($updatePatientData);
            $this->reserveOldData($oldPatient);
            ##fatma
//            $treeId = (int) $_POST["treeId"];
//            if ($treeId > 0) {
            $this->erpClient($updatePatientData);
//            }1640

            if ($_SESSION['role_id'] == 4 || $_SESSION['role_id'] == 8) {
                header('Location:' . $this->hosturl . '/controllers/patienthistory.php?ac=show&patientid=' . $id);
            } else {
                header('Location:' . $this->hosturl . '/controllers/index.php');
            }
        } catch (Exception $ex) {
            print_r($ex);
        }
    }

    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 addgovernorate() {
//check login
        autho::checkautho($this->hosturl);
//check authoize
        //    autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

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

        $governorateObj = R::dispense('governorate');
        $governorateObj->name = $governorate;
        $inserted = R::store($governorateObj);
        echo $inserted;

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

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

        $governorate = filter_input(INPUT_POST, 'governorate');
        $governorate_center = filter_input(INPUT_POST, 'governorate_center');
        $patientId = filter_input(INPUT_POST, 'inline');

        $governorateObj = R::xdispense('governorate_centers');
        $governorateObj->name = $governorate_center;
        $governorateObj->governorate_id = $governorate;
        $inserted = R::store($governorateObj);
        echo $inserted;

        $patient = R::load('patients', $patientId);
        $patient->governorate_center = $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 getallgovernorate() {
//check login
        autho::checkautho($this->hosturl);
//check authoize
        //  autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $allgovernorate = R::findAll('governorate', ' deleted = 0 order by name');
        $this->smarty->assign('allgovernorate', $allgovernorate);
        $this->smarty->display('patients/siglemodeltodelete/allgovernorate.html');
    }

    public function getallgovernorate_centers() {
//check login
        autho::checkautho($this->hosturl);
        $governorate = filter_input(INPUT_POST, 'governorate');
        $allgovernorate_centers = R::findAll('governorate_centers'
                        , ' deleted = 0 and governorate_id = ? order by name', [$governorate]);
        $this->smarty->assign('allgovernorate_centers', $allgovernorate_centers);
        $this->smarty->display('patients/siglemodeltodelete/allgovernorate_centers.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);
        }
    }

    public function delgovernorate() {
//check login
        autho::checkautho($this->hosturl);
//check authoize
        //      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $id = filter_input(INPUT_POST, 'id');
        try {
            R::exec('update governorate set  deleted  = 1 where id = ' . $id);
            $allgovernorate = R::findAll('governorate', ' deleted = 0 order by name');
            $this->smarty->assign('allgovernorate', $allgovernorate);
            $this->smarty->display('patients/wifetypeafterdelete/allgovernorate.html');
        } catch (Exception $ex) {
            header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
        }
    }

    public function delgovernorate_center() {
//check login
        autho::checkautho($this->hosturl);
//check authoize
        //      autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $id = filter_input(INPUT_POST, 'id');
        $governorate_center = R::load('governorate_centers', $id);
        try {
            R::exec('update governorate_centers set  deleted  = 1 where id = ' . $id);
            $allgovernorate_centers = R::findAll('governorate_centers'
                            , ' deleted = 0 and governorate_id = ? order by name', [$governorate_center->governorate_id]);
            $this->smarty->assign('governorate', $governorate_center->governorate_id);
            $this->smarty->assign('allgovernorate_centers', $allgovernorate_centers);
            $this->smarty->display('patients/wifetypeafterdelete/allgovernorate_center.html');
        } catch (Exception $ex) {
            header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
        }
    }

    public function getGovernorateCenters() {
//check login
        autho::checkautho($this->hosturl);
        $governorate = filter_input(INPUT_POST, 'governorate');
        $allgovernorate_centers = R::findAll('governorate_centers'
                        , ' deleted = 0 and governorate_id = ? order by name', [$governorate]);
        $this->smarty->assign('governorate', $governorate);
        $this->smarty->assign('allgovernorate_centers', $allgovernorate_centers);
        $this->smarty->display('patients/wifetypeafterdelete/allgovernorate_center.html');
    }

## 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 addnewmeber() {
//check login
        autho::checkautho($this->hosturl);

        //vars here
        $name = filter_input(INPUT_POST, 'doctorname');
        $email = '';
        $role = '99';
        $special = '';
        $position = '';
        $username = $name;
        $password = '99';


        $user_name = trim($username);
        $hash_cost_factor = (defined('HASH_COST_FACTOR') ? HASH_COST_FACTOR : null);
        $user_password_hash = password_hash($password, PASSWORD_DEFAULT, array('cost' => $hash_cost_factor));
        $user_activation_hash = sha1(uniqid(mt_rand(), true));
        $user_email = trim($email);
        $user_registration_ip = $_SERVER['REMOTE_ADDR'];


        try {
            R::exec('INSERT INTO awusers (user_name, user_password_hash, user_email,user_active, user_activation_hash, user_registration_ip, user_registration_datetime,role_id,name , specialid ,positionid ) VALUES(?, ?, ?, ?,?, ?, now(),?,?,? ,?)', [$user_name, $user_password_hash, $user_email, 1, $user_activation_hash, $user_registration_ip, $role, $name, $special, $position]);
            $newuser = R::getInsertID();
            echo $newuser;
        } catch (Exception $e) {
            
        }

        $patientId = filter_input(INPUT_POST, 'inline');
        $patient = R::load('patients', $patientId);
        $patient->refer_doctor = $newuser;
        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 addhusstatus() {
//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('husstatus');
        $statusWifeInsert->title = $statusWife;

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


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

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

    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) and id = ?", [$id]);
            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);
            }
        }
    }

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

        $id = filter_input(INPUT_POST, 'id');
        $husstatus = R::load('husstatus', $id);
        $husstatus->del = 1;
        R::store($husstatus);

        $allHusStatus = R::findAll('husstatus', ' del != 1 order by title');
        $this->smarty->assign('allHusStatus', $allHusStatus);
        $this->smarty->display('patients/wifetypeafterdelete/husstatus.html');
    }

## 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 {
            ##fatma
            $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");
        $governorate = filter_input(INPUT_POST, "governorate");
        $table = R::xdispense($tablename);

        $x = r::getRow('SHOW COLUMNS FROM ' . $tablename . '  LIKE "title" ');
        if (count($x) > 0) {
            $table->title = '';
        } else {
            $x = r::getRow('SHOW COLUMNS FROM ' . $tablename . '  LIKE "name" ');
            if (count($x) > 0) {
                $table->name = '';
            }
        }

        $x = r::getRow('SHOW COLUMNS FROM ' . $tablename . '  LIKE "del" ');
        if (count($x) > 0) {
            $table->del = 0;
        }

        $x = r::getRow('SHOW COLUMNS FROM ' . $tablename . '  LIKE "governorate_id" ');
        if (count($x) > 0) {
            $table->governorate_id = $governorate;
        }


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

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

        //vars here
        $name = filter_input(INPUT_POST, 'doctorname');
        $colname = filter_input(INPUT_POST, 'colname');
        $patientId = filter_input(INPUT_POST, 'inline');
        $table = "";
        $col = "";

        try {
            switch ($colname) {
                case "knownfrom":
                    $table = "knownfrom";
                    $col = "name";
                    break;

                case "refer_doctor":
                case "h_refer_doctor":
                    $table = "refer";
                    $col = "name";
                    break;

                case "nationality":
                    $table = "nationality";
                    $col = "name";
                    break;


                case "h_nationality":
                    $table = "hnationality";
                    $col = "name";
                    break;

                case "religion":
                    $table = "religion";
                    $col = "name";
                    break;


                case "h_religion":
                    $table = "hreligion";
                    $col = "name";
                    break;

//                case "doctor1":
//                case "h_doctor1":
//                case "doctor2":
//                case "h_doctor2":
//                    $table = "";
//                    $col = "";
//                    break;

                default:
                    break;
            }

            $record = R::dispense($table);
            $record->$col = $name;
            $record->deleted = 0;
            $id = R::store($record);


            $patient = R::load('patients', $patientId);
            $patient->$colname = $id;
            R::store($patient);

            echo $id;
        } catch (Exception $e) {
            
        }
    }

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

        $colname = filter_input(INPUT_POST, 'colname');
        $selectClass = filter_input(INPUT_POST, 'selectId');

        switch ($colname) {
            case "knownfrom":
                $table = "knownfrom";
                $col = "وسيلة المعرفة بالمركز";
                break;

            case "refer_doctor":
            case "h_refer_doctor":
                $table = "refer";
                $col = "محولة/ محول  من";
                break;

            case "nationality":
                $table = "nationality";
                $col = "جنسية الزوجة ";
                break;


            case "h_nationality":
                $table = "hnationality";
                $col = "جنسية الزوج ";
                break;

            case "religion":
                $table = "religion";
                $col = "ديانة الزوجة ";
                break;


            case "h_religion":
                $table = "hreligion";
                $col = "ديانة الزوج ";
                break;

            case "sampletype":
                $table = "sampletype";
                $col = " Sample Type ";
                break;

            default:
                break;
        }

        $allData = R::findAll($table, ' deleted = 0 order by name ');
        $this->smarty->assign('allData', $allData);
        $this->smarty->assign('col', $col);
        $this->smarty->assign('table', $table);
        $this->smarty->assign('selectId', $selectClass);
        $this->smarty->display('patients/siglemodeltodelete/alldata.html');
    }

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


        $id = filter_input(INPUT_POST, 'id');
        $tableName = filter_input(INPUT_POST, 'tableName');


        $obj = R::load($tableName, $id);
        $obj->deleted = 1;
        try {

            R::store($obj);
            echo 1;
        } catch (Exception $ex) {
            echo -1;
        }
    }

    public function createbarcode($statusno) {
        if (file_exists('../../upload/barcodes/' . $statusno . '.png')) {
            
        } else {
            $url = $this->hosturl . '/../_library/barcode/image.php?code=' . $statusno . '&width=300&height=60&type=C39';
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $barcode = curl_exec($ch);

            if ($barcode === false) {
                $curl_result = curl_error($ch);
            } else {
                // header( 'Content-Type: application/json' );
                ## save the file to disk 
                file_put_contents('../../upload/barcodes/' . $statusno . '.png', $barcode);
            }
            curl_close($ch);
        }
    }

    public function createQRcode($statusno) {
        require_once("../../_library/phpqrcode/qrlib.php");

        if (!file_exists('../../upload/qrcodes/' . $statusno . '.png')) {
            QRcode::png($statusno, '../../upload/qrcodes/' . $statusno . '.png');
        }
    }

    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');

        if ($patientId > 0) {
            $data = R::findAll('patients', ' ( phone = ?  or mobile = ? )  and id != ? ', [$phone, $phone, $patientId]);
        } else {
            $data = R::findAll('patients', ' ( phone = ?  or mobile = ? )  ', [$phone, $phone]);
        }

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

    public function uploadmulti() {

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

        $count = filter_input(INPUT_POST, "imgCount");
        $patientId = filter_input(INPUT_POST, "patientId");

        $folder = 'patientfiles/' . $patientId;


        try {

            for ($i = 0; $i < $count; $i++) {
                $name = 'file-' . $i;
                uploadnew($name, False, 0, 0, $folder, False);
            }

            $this->getpatientfiles($patientId);

            $this->smarty->display('patients/uploadresult.html');
        } catch (Exception $e) {
            echo -1;
        }
    }

    public function getpatientfiles($patientId) {
        $dir = '../../upload/patientfiles/' . $patientId;
        // Open a directory, and read its contents
        if (is_dir($dir)) {
            $allImgs = array();
            $allDoc = array();
            $allPdf = array();

            if ($dh = opendir($dir)) {
                while (($file = readdir($dh)) !== false) {
                    if ($file != "." && $file != ".." && $file != "thumbnail") {

                        $info = pathinfo($file);

                        switch ($info['extension']) {
                            case "jpg":
                            case "jepg":
                            case "png":
                            case "jpeg":
                            case "gif":
                                array_push($allImgs, $file);
                                break;

                            case "doc":
                            case "docx":
                                array_push($allDoc, $file);
                                break;
                            case "pdf":
                                array_push($allPdf, $file);
                                break;

                            case "": // Handle file extension for files ending in '.'
                            case NULL: // Handle no file extension
                                break;
                        }
                    }
                }

                closedir($dh);
            }
            $patien = R::load('patients', $patientId);

            $this->smarty->assign('statusno', $patien->statusno);
            $this->smarty->assign('patientId', $patientId);
            $this->smarty->assign('allImgs', $allImgs);
            $this->smarty->assign('allDoc', $allDoc);
            $this->smarty->assign('allPdf', $allPdf);
        }
    }

    public function delimg() {

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

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

        $folder = 'patientfiles/' . $patientId;


        try {

            if (file_exists('../../upload/' . $folder . '/' . $name)) {
                //echo $imageNewName;
                chmod('../../upload/' . $folder . '/' . $name, 0777);
                unlink('../../upload/' . $folder . '/' . $name);
            }

            echo 1;
        } catch (Exception $e) {
            echo -1;
        }
    }

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

        $patient_id = filter_input(INPUT_POST, "id");
        try {

            $patient = R::load('patients', $patient_id);
            $this->smarty->assign('patient', $patient);

            $doc = R::findOne('awusers', 'user_id = ?', [$patient->doctor1]);
            $h_doc = R::findOne('awusers', 'user_id = ?', [$patient->h_doctor1]);

            $this->smarty->assign('doctor_name', $doc->name);
            $this->smarty->assign('h_doctor_name', $h_doc->name);


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


            $this->smarty->display('patients/printcard.html');
            #################################
        } catch (Exception $ex) {
            echo '-1';
        }
    }

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

        $patient_id = filter_input(INPUT_POST, "id");
        try {

            $patient = R::load('patients', $patient_id);
            $this->smarty->assign('patient', $patient);

            $this->createQRcode($patient->statusno);

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


            $this->smarty->display('patients/printqrcard.html');
            #################################
        } catch (Exception $ex) {
            echo '-1';
        }
    }

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

        $patient_id = filter_input(INPUT_POST, "id");
        try {

            $patient = R::load('patients', $patient_id);
            $this->smarty->assign('patient', $patient);

            $this->createbarcode($patient->statusno);

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


            $this->smarty->display('patients/printbarcode.html');
            #################################
        } catch (Exception $ex) {
            echo '-1';
        }
    }

    public function addChild() {

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

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

        ### insert into table
        $child = R::xdispense('patients_childs');
        $child->patientid = $patientId;
        $child->gender = 1;
        $child->id = R::store($child);
        $child->birth_date = '00-00-0000';
        $this->smarty->assign('child', $child);
        $this->smarty->display('patients/new_child.html');
    }

    public function addBirthNotidy() {

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

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

        ### insert into table
        $notify = R::xdispense('patients_notify');
        $notify->patientid = $patientId;
        $notify->user_id = $_SESSION['user_id'];
        $notify->notify_date = date('Y-m-d');
        $notify->id = R::store($notify);

        $user = R::getRow('select name  from awusers where user_id = ?', [$notify->user_id]);
        $notify->userName = $user['name'];
        $notify->notify_date = date('Y/m/d', strtotime($notify->notify_date));

        $this->smarty->assign('notify', $notify);
        $this->smarty->display('patients/new_notify.html');
    }

    public function printBirthNotify() {

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

        $patientId = filter_input(INPUT_POST, 'patientId');
        $notifyDate = date('Y-m-d'); // filter_input(INPUT_POST, 'notifyDate');
        $this->addBNotify($patientId, $notifyDate);
        $this->printBNotify($patientId);
        $this->smarty->display('patients/print_notify.html');
    }

    function addBNotify($patientId, $notifyDate) {
        $notify = R::xdispense('patients_notify');
        $notify->patientid = $patientId;
        $notify->user_id = $_SESSION['user_id'];
        $notify->notify_date = $notifyDate;
        $notify->create_date = date('Y-m-d H:i:s'); //$this->today;
        $notify->id = R::store($notify);
    }

    function printBNotify($patientId) {
        if ($patientId > 0) {
            $childs = R::getRow('select distinct  birth_date as birth_date from  patients_childs where  deleted = 0 
                and patientid = ?  order by birth_date  desc ', [$patientId]);
            $date = $childs['birth_date'];
            $this->patData($patientId);
            $this->visitData($patientId, $date);
            $this->childsData($patientId, $date);
        }
    }

    function patData($patientId) {
        $patient = R::load('patients', $patientId);
        if (count($patient) > 0) {
            $this->smarty->assign('wifename', $patient->wifename);
            $this->smarty->assign('wifenationalid', $patient->wifenationalid);
            $this->smarty->assign('husdandname', $patient->husdandname);
            $this->smarty->assign('husbandnationalid', $patient->husbandnationalid);
        }
    }

    function visitData($patientId, $birth_date) {
//        $visit = R::findOne('visits', ' deleted = 0 and patientid = ? and detectionid in ( ? , ? )   and visitdate <= ? 
//                order by visitdate desc    ', [$patientId, 237, 173, $birth_date]);

        $visit = R::getRow('select visits.* ,   detections.title as birthType   from visits
               join  detections   on detections.id =   visits.detectionid
                  where visits.patientid =  ?  and visits.deleted != 1 and visits.visitdate <= ?  
                  and  detections.for_birth = 1
                order by visitdate desc    ', [$patientId, $birth_date]);

        if (count($visit) > 0) {
            switch ($visit['detectionid']) {
                case 237:
                    $birthType = '  قيصرية';
                    break;
                case 173:
                    $birthType = ' طبيعية  ';
                    break;
            }
            $this->smarty->assign('birthType', $visit['birthType']);
            $this->smarty->assign('visitDate', date('Y/m/d', strtotime($visit['visitdate'])));

            $dayName = $this->getDayNameFnAr($visit['visitdate']);
            $this->smarty->assign('dayName', $dayName);

            $dr = R::findOne('awusers', 'user_id = ?', [$visit['for_doctor']]);
            $this->smarty->assign('drName', $dr->name);
            $this->smarty->assign('license_no', $dr->license_no);
            $this->smarty->assign('register_no', $dr->register_no);
        }
    }

    function childsData($patientId, $date) {

        $childs = R::findAll('patients_childs', ' deleted = 0 and patientid = ? and birth_date = ?   ', [$patientId, $date]);
        $type = ' (  ';
        $i = 1;
        foreach ($childs as $child) {
            if ($i > 1) {
                $type .= ' - ';
            }
            if ($child->gender == 1) {
                $type .= ' ذكر';
                $childsCountEx = ' حى  مكتمل  ';
            } else {
                $type .= ' أنثى ';
                $childsCountEx = ' حية  مكتملة   ';
            }
            $i++;
        }
        $type .= ' ) ';

        switch (count($childs)) {
            case 1:
                $childsCount = ' طفل';
                break;
            case 2:
                $childsCount = ' طفلين ';
                $childsCountEx = ' أحياء مكتملين ';
                break;

            default:
                $childsCount = count($childs) . ' أطفال  ';
                $childsCountEx = ' أحياء مكتملين ';
                break;
        }
        $this->smarty->assign('childsCount', $childsCount);
        $this->smarty->assign('childsCountEx', $childsCountEx);
        $this->smarty->assign('childsType', $type);
    }

    public function loadBirthNotify() {

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

        $patientId = filter_input(INPUT_POST, 'patientId');
        $this->getPatientNotify($patientId);
        $this->smarty->display('patients/load_notify.html');
    }

    private function getDayNameFnAr($date) {
        $timestamp = strtotime($date);

        $day = date('w', $timestamp);

        switch ($day) {
            case 0:
                $name = 'الأحد  ';
                break;
            case 1:
                $name = ' الإثنين';
                break;
            case 2:
                $name = ' الثلاثاء';
                break;
            case 3:
                $name = 'الأربعاء ';
                break;
            case 4:
                $name = 'الخميس  ';
                break;
            case 5:
                $name = 'الجمعة ';
                break;
            case 6:
                $name = 'السبت ';
                break;
        }

        return $name;
    }

    ##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);
                $lastId = 0;
                $limit = 50;
                R::selectDatabase('default');
                do {
                    $rows = 0;
                    R::selectDatabase('default');
                    $allPatients = R::findAll("patients", " where id > $lastId and deleted=0 order by id asc limit $limit ");
                    //getPatientTotalDebt
//                    foreach ($allPatients as $patient) {
//                        $patient->mirragefrom = $this->getPatientTotalDebt($patient->id); //patient debt
//                        /*if ($patient->mirragefrom != 0) {
//                            $myfile = fopen("patientsDebtSqlForERP.txt", "a+") or die("Unable to open file!");
//                            $txt = "update client set clientdebt = $patient->mirragefrom where obygyPatientId = $patient->id;\r\n";
//                            fwrite($myfile, $txt);
//
//                            fclose($myfile);
//                        }*/
//                    /* //in case of looping for patientsDebtSqlForERP.txt only
//                      $rows++;
//                      $lastId = $patient->id; */
//                    }
                    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);
                                }
                            }
                            $rows++;
                            $lastId = $patient->id;
                        }
                    } else {
                        throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                    }
                } while ($rows > 0);
                echo 1;
            } catch (Exception $exc) {
                echo $exc;
                //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                echo -1;
            }
            R::selectDatabase('default');
        }
    }

    public function getPatientTotalDebt($patientId) {//copy of unction in visits.php getrestvalues() but return total not html with table
        $visits = array();
        $debtTotal = 0;

        $lastVisit = R::getAll('SELECT visits.id as visitid , visits.restdetectionvalue as rest , visits.visitdate
                                                    , detections.title  as  detectionName
                                                    FROM visits
                                                     left join  detections                on  visits.detectionid = detections.id
                                                    where  visits.patientid = ?   and  visits.restdetectionvalue >0
                                                               and visits.deleted != ?   ', [$patientId, 1]);
        $i = 0;
        foreach ($lastVisit as $data) {
            $payVisits = R::getRow('SELECT COALESCE(SUM(detectionvalue_cash),0)   as paid_cash
                                                                 , COALESCE(SUM(detectionvalue_visa),0)   as paid_visa
                                                                  , COALESCE(SUM(discount),0)   as paid_discount
                                                                 , 0 as paid
                                    FROM visits   where  patientid = ?
                               and deleted != ? and detectionid = 999 and visitid = ?   ', [$patientId, 1, $data['visitid']]);

//            ## refund
//            $refundVisits = R::getRow('SELECT COALESCE(SUM(detectionvalue_cash),0)   as refund_cash
//                                                                 , COALESCE(SUM(detectionvalue_visa),0)   as refund_visa
//                                    FROM visits   where  patientid = ?
//                               and deleted != ? and detectionid = 9999 and visitid = ?   ', [$patientId, 1, $data['visitid']]);
#
            #
#               ## what pt paid after  creating visit
            $payVisits['paid'] = $payVisits['paid_cash'] + $payVisits['paid_visa'];
//   $payVisits['paid'] = $payVisits['paid_cash'] + $payVisits['paid_visa'] - $refundVisits['refund_cash'] - $refundVisits['refund_visa'];

            if ($data['rest'] > ($payVisits['paid'] + $payVisits['paid_discount'])) {

                $v['visitdate'] = $data['visitdate'];
                $v['dept'] = $data['rest'] - $payVisits['paid'] - $payVisits['paid_discount'];
                $v['visitid'] = $data['visitid'];
                $v['detectionName'] = $data['detectionName'];

                $debtTotal += $v['dept'];
                //array_push($visits, $v);
            }
        }


        return $debtTotal;
//        if (count($visits) > 0) {
//            $this->smarty->assign('visits', $visits);
//            $this->smarty->display('visits/rest.html');
//        } else {
//            echo -1;
//        }
    }

    public function erpClient($patient) {
        $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);
                R::selectDatabase('erpDB');
                if (R::testConnection()) {
                    $clientData = R::getRow('select clientid from client where obygyPatientId = ' . $patient->id);
                    $patient->mirragefrom = $this->getPatientTotalDebt($patient->id); //patient debt
                    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');
                }
            } catch (Exception $exc) {
                //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                //echo -1;
            }

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

    public function erpClientDel($patient) {
        $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);
                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');
                }
            } catch (Exception $exc) {
                //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                //echo -1;
            }
            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) {
        $mainName = $patient->wifename;
        $secondaryName = $patient->husdandname;
        if (empty($mainName)) {
            $mainName = $patient->husdandname;
            $secondaryName = '';
        }
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'newclientName' => $mainName,
            'clientaddress' => $patient->address,
            'clientphone' => $patient->phone,
            'clientmobile' => $patient->mobile,
            'newclientdebt' => 0,
            'clientdetails' => $patient->importantnote,
            'clientareaid' => 0,
            'clientcode' => '',
            'store_all' => -10,
            'obygyPatientId' => $patient->id,
            'newclientdebt' => $patient->mirragefrom,
            'statusno' => $patient->statusno,
            'husdandname' => $secondaryName,
        ];

        try {
            $ch = curl_init(HOST_URL_ERP . '/controllers/clientControllerAjax.php?do=addclient&simplereturn=1');
            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);
        } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
        }
        // do anything you want with your response
        //var_dump($response);
    }

    public function curlUpdateClient($patient, $erpDB, $clientId, $treeId) {
        $mainName = $patient->wifename;
        $secondaryName = $patient->husdandname;
        if (empty($mainName)) {
            $mainName = $patient->husdandname;
            $secondaryName = '';
        }
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'id' => $clientId,
            'treeId' => $treeId,
            'newclientName' => $mainName,
            'clientaddress' => $patient->address,
            'clientphone' => $patient->phone,
            'clientmobile' => $patient->mobile,
            'newclientdebt' => 0,
            'clientdetails' => $patient->importantnote,
            'clientareaid' => 0,
            'clientcode' => '',
            'store_all' => 1,
            'obygyPatientId' => $patient->id,
            'newclientdebt' => $patient->mirragefrom,
            'statusno' => $patient->statusno,
            'husdandname' => $secondaryName,
        ];
        try {
            $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);
        } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
        }
        // 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,
        ];
        try {
            $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);
        } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
        }
        // 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
            try {
                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"];
            } catch (Exception $exc) {
                //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                //echo -1;
                R::selectDatabase('default');
                return "NO_DB";
            }
        } else {
            return "NO_DB";
        }
    }

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

    public function getexcel() {
        //check login
        autho::checkautho($this->hosturl);
        require_once "Classes/PHPExcel/IOFactory.php";

        $user = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);
        if ($user['role_id'] == 19 && $user['related_dr'] != 0 && !empty($user['related_dr']) &&
                $user['related_dr'] != "" && !( is_null($user['related_dr']))) {

            $doctorSearch = ' and ( patients.doctor1 in  (' . $user['related_dr'] . ' )  
                                                          || patients.doctor1 = -1 || patients.doctor1 IS  NULL) ';
        } else {
            $doctorSearch = '';
        }

        $patients = R::getAll('select  statusno , wifename , husdandname  
                from patients where deleted != 1   and done = 1 ' . $doctorSearch);
        $this->createexcel($patients);
    }

    function createexcel($patients) {
        //prepare download
        $filename = 'patients_' . date('Y-m-d') . '.xlsx';

        // Read the contents of the file into PHPExcel Reader class
        $objPHPExcel = new PHPExcel();

        $rowCount = 1;
        $objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, 'Status No');
        $objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, 'Wife Name');
        $objPHPExcel->getActiveSheet()->SetCellValue('C' . $rowCount, 'Husband Name');

        foreach ($patients as $patient) {
            $rowCount++;
            $objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, $patient['statusno']);
            $objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, trim($patient['wifename']));
            $objPHPExcel->getActiveSheet()->SetCellValue('C' . $rowCount, trim($patient['husdandname']));
        }


        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);

        ## all cells  text alignment left
        $style = array('alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,));
        $objPHPExcel->getDefaultStyle()->applyFromArray($style);
###############################################################################################################
        //prepare download
        // Pass to writer and output as needed
        $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);


        $target_dir = "../excel_backups";
        $ar = 'all';

        if (!file_exists($target_dir . '/' . $ar)) {
            mkdir($target_dir . '/' . $ar, 0777, true);
        }

        $objWriter->save('../excel_backups/' . $ar . '/' . $filename);
        //$objWriter->save(str_replace($filename,'../excel_backups/xx.xls',$filename));   ## this replace if file with the same name exist
        ######################################################################################################################################################
        ## allow user to download it in another location + default on determined above
        header('Content-Description: File Transfer');
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename=' . basename('../excel_backups/' . $ar . '/' . $filename));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize('../excel_backups/' . $ar . '/' . $filename));
        ob_clean();
        flush();
        readfile('../excel_backups/' . $ar . '/' . $filename);

        exit;

        return 1;
        //     echo "Time Elapsed: " . ((microtime(true) - $this->time) / 60) . "m";
        //exit; //done.. exiting
    }

    function style($content) {
        ## Auto size columns for active sheet
        foreach (range('D', 'Z') as $columnID) {
            $content->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
        }
        foreach (range('A', 'A') as $columnID) {
            $content->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
        }

        ## all cells  text alignment left
        $style = array('alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,));
        $content->getDefaultStyle()->applyFromArray($style);

        ##  wrap text in colum 
        $content->getActiveSheet()->getStyle('B1:B' . $content->getActiveSheet()->getHighestRow())->getAlignment()->setWrapText(true);
        ## set width to specific column 
        $content->getActiveSheet()->getColumnDimension('B')->setWidth(40);
        $content->getActiveSheet()->getColumnDimension('C')->setWidth(40);




        $colArray = array('A2:A2', 'D2:D2', 'A5:A13', 'A15:A20', 'A22:A40', 'A42:A45', 'A47:A52', 'A54:A59', 'A61:A66', 'A68:A72', 'A74:A85', 'A87:A95', 'A97:A103', 'A105:A111', 'A113:A119', 'A121:A127', 'A129:A135', 'A137:A155', 'A157:A160', 'A162:A167', 'A169:A192', 'A194:A196', 'A198:A200', 'A202:A202');

        ## backdround color   and font style
        $backColorArray = array('fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => '666666'),));
        ## make border around group of cells and style it 
        $borderArray = array('borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN, 'color' => array('rgb' => 'ffffff'),)));
        ## font color 
        $colorArray = array('font' => array('bold' => true, 'color' => array('rgb' => 'ffffff')));
        ##merge cells 
        $mergeArray = array(5, 15, 22, 42, 47, 54, 61, 68, 74, 87, 88, 97, 105, 113, 121, 129, 137, 157, 162, 169, 194, 198, 202);
        foreach ($mergeArray as $col) {
            $content->getActiveSheet()->mergeCells('A' . $col . ':R' . $col);
            $content->getActiveSheet()->getStyle('A' . $col . ':A' . $col)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $content->getActiveSheet()->getStyle('A' . $col . ':R' . $col)->applyFromArray($borderArray);
        }


        foreach ($colArray as $col) {
            $content->getActiveSheet()->getStyle($col)->applyFromArray($backColorArray);
            $content->getActiveSheet()->getStyle($col)->applyFromArray($borderArray);
            $content->getActiveSheet()->getStyle($col)->applyFromArray($colorArray);
        }
        unset($backColorArray);
        unset($colorArray);
        unset($borderArray);




        return $content;
    }

    public function uploadRecord() {
        $input = $_FILES['audio_data']['tmp_name']; //temporary name that PHP gave to the uploaded file
        $fileExt = filter_input(INPUT_POST, "fileExt");
        $fileName = filter_input(INPUT_POST, "fileName");
        $dirName = filter_input(INPUT_POST, "dirName");
        if (!file_exists('./../../upload/' . $dirName)) {
            mkdir('./../../upload/' . $dirName, 0777, true);
        }
        $target_dir = "../../upload/$dirName/" . $fileName . "." . $fileExt;


        $target_delW = "../../upload/$dirName/" . $fileName . ".wav";
        $target_delM = "../../upload/$dirName/" . $fileName . ".mp3";

        if (file_exists($target_delW)) {
            chmod($target_delW, 0777);
            unlink($target_delW);
        }

        if (file_exists($target_delM)) {
            chmod($target_delM, 0777);
            unlink($target_delM);
        }
        move_uploaded_file($input, $target_dir);
    }

    public function getVoiceRecord($patientId) {
        $file = '../../upload/patientrecords/' . $patientId . '.wav';
        $file1 = '../../upload/patientrecords/' . $patientId . '.mp3';
        $voiceRecord = 0;
        if (file_exists($file)) {
            $voiceRecord = 1;
            $this->smarty->assign('voiceExt', 'wav');
        } elseif (file_exists($file1)) {
            $voiceRecord = 1;
            $this->smarty->assign('voiceExt', 'mp3');
        }
        $this->smarty->assign('voiceRecord', $voiceRecord);
    }

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

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

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

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

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

        require_once "Classes/PHPExcel/IOFactory.php";

        $fromDate = filter_input(INPUT_GET, 'findate');
        $toDate = filter_input(INPUT_GET, 'todate');
        $patients = R::getAll('select  statusno , wifename , husdandname  , phone , mobile 
            , DATE(entrydate) as entryDate
                from patients where deleted != 1   and done = 1 and patients.entrydate between  ? and ?   '
                        , [$fromDate, $toDate]);
        $this->createexcel2($patients, $fromDate, $toDate);
    }

    function createexcel2($patients, $fromDate, $toDate) {
        $fromDate = date('Y-m-d', strtotime($fromDate));
        $toDate = date('Y-m-d', strtotime($toDate));
        $filename = 'patients_' . $fromDate . '_' . $toDate . '.xlsx';

        // Read the contents of the file into PHPExcel Reader class
        $objPHPExcel = new PHPExcel();

        $rowCount = 1;
        $objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, 'Status No');
        $objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, 'Wife Name');
        $objPHPExcel->getActiveSheet()->SetCellValue('C' . $rowCount, 'Husband Name');
        $objPHPExcel->getActiveSheet()->SetCellValue('D' . $rowCount, 'Phone');
        $objPHPExcel->getActiveSheet()->SetCellValue('E' . $rowCount, 'Mobile');
        $objPHPExcel->getActiveSheet()->SetCellValue('F' . $rowCount, 'Date');

        foreach ($patients as $patient) {
            $rowCount++;
            $objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, $patient['statusno']);
            $objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, trim($patient['wifename']));
            $objPHPExcel->getActiveSheet()->SetCellValue('C' . $rowCount, trim($patient['husdandname']));
            $objPHPExcel->getActiveSheet()->SetCellValue('D' . $rowCount, trim($patient['phone']));
            $objPHPExcel->getActiveSheet()->SetCellValue('E' . $rowCount, trim($patient['mobile']));
            $objPHPExcel->getActiveSheet()->SetCellValue('F' . $rowCount, trim($patient['entryDate']));
        }


        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);

        ## all cells  text alignment left
        $style = array('alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,));
        $objPHPExcel->getDefaultStyle()->applyFromArray($style);
###############################################################################################################
        //prepare download
        // Pass to writer and output as needed
        $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);


        $target_dir = "../excel_backups";
        $ar = 'all';

        if (!file_exists($target_dir . '/' . $ar)) {
            mkdir($target_dir . '/' . $ar, 0777, true);
        }

        $objWriter->save('../excel_backups/' . $ar . '/' . $filename);
        //$objWriter->save(str_replace($filename,'../excel_backups/xx.xls',$filename));   ## this replace if file with the same name exist
        ######################################################################################################################################################
        ## allow user to download it in another location + default on determined above
        header('Content-Description: File Transfer');
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename=' . basename('../excel_backups/' . $ar . '/' . $filename));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize('../excel_backups/' . $ar . '/' . $filename));
        ob_clean();
        flush();
        readfile('../excel_backups/' . $ar . '/' . $filename);

        exit;

        return 1;
        //     echo "Time Elapsed: " . ((microtime(true) - $this->time) / 60) . "m";
        //exit; //done.. exiting
    }


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

    public function addOrgPatNo() {

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

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

        ### insert into table
        $org = R::xdispense('organizations_patient_no');
        $org->patient_id = $patientId;
        $org->user_id = $_SESSION['user_id'];
        $org->create_date = date('Y-m-d H:i:s');
        $org->deleted = 0;
        $org->id = R::store($org);
        $this->smarty->assign('orgPatNo', $org);
        
          $organizations = R::findAll('organizations', ' deleted != 1 ');
            $this->smarty->assign('organizations', $organizations);
        
        
        $this->smarty->display('patients/new_patno.html');
    }
    #########################################################

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

}
