<?php

require_once("imp/_imp.php");

class Controllers {

//public vars
    public $smarty;
    public $hosturl;
    public $controllname;
    public $shcontrollname;
    public $active;
    public $time;
    public $today;

// it will run in everytime with
// default requried
    public function __construct() {
        require_once("../public/aw_config.php");
        require_once("imp/_autho.php"); //general functions
        $this->smarty = $smarty;
        $this->hosturl = $hosturl;

//here name of controll to known
        $this->controllname = 'gyna';
        $this->shcontrollname = 'GYNA';
        $this->smarty->assign('controllname', $this->controllname);
        $this->smarty->assign('shcontrollname', $this->shcontrollname);



//breadcrumbs
        require_once("../../_library/plugins/Breadcrumbs/Breadcrumbs.php");
        $acty = filter_input(INPUT_GET, 'ac');
        $bc = new breadcrumbs($hosturl, '', '', $acty);
        $bc->crumbs();
        $breadcrumbs = $bc->breadcrumbs;
        $smarty->assign('breadcrumbs', $breadcrumbs);

# here show the active page in menu
// array called active[] with level of active element
        $active[0] = 'gyna'; //controller name or tab name
        $active[1] = 'gyna'; //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;

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

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



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

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



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

        $ProgramesettingData = R::findone('programesetting');
        $this->smarty->assign('ProgramesettingData', $ProgramesettingData);
// all drugs will show in selectbox in add new drugs

        $allgyna = R::findall('gyna', 'conditions = ? and patientid = ? ORDER BY gynadate DESC ', [0, $patientid]);
        $iDsArray = '';
        $selectArray = '';
        foreach ($allgyna as $myGyna) {
            ## merge complain  and  diagnosis
            if (!empty($myGyna->diagnosistxt) && $myGyna->diagnosistxt != '') {
                $myGyna->complaint .= '-';
                $myGyna->complaint .= $myGyna->diagnosistxt;
                $myGyna->diagnosistxt = '';
                R::store($myGyna);
            }

            ##########################################################################
            $iDsArray .= $myGyna->id . ',';

            $myGyna->gynadate = date("Y/m/d", strtotime($myGyna->gynadate));

            if (!($myGyna->gynalmp == '0000-00-00' || is_null($myGyna->gynalmp))) {
                $myGyna->gynalmp = date("Y/m/d", strtotime($myGyna->gynalmp));
            }

            $selectArray = explode(',', $myGyna->diagnosisid);
            $myGyna->select = $selectArray;
            $compSelectArray = explode(',', $myGyna->complaintid);
            $myGyna->compselect = $compSelectArray;
        }
        $iDsArray = rtrim($iDsArray, ',');
        $this->smarty->assign('iDsArray', $iDsArray);
        $this->smarty->assign('allgyna', $allgyna);




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

        #################################################################### Heba : ## ultra sound data  ##############################################################################
        $programSetting = R::getAll('SELECT  ultrasound FROM programesetting limit 1');
        $ultrasoundForm = $programSetting[0]['ultrasound'];     ## 0 for simple form  , 1 for complete form
        $this->smarty->assign('ultrasoundForm', $ultrasoundForm);

        $allgynaUS = R::findall('gynaus', 'deleted = ? and patientid = ? ORDER BY date DESC ', [0, $patientid]);
        foreach ($allgynaUS as $us) {
            $us->date = date("Y/m/d", strtotime($us->date));

            $doctordata = R::getRow('SELECT user_name FROM awusers WHERE user_id = ? ', [$us->doctorid]);
            $us->doctorname = $doctordata['user_name'];
        }
        $this->smarty->assign('allgynaUS', $allgynaUS);

        #################################################################### Heba : ## Drugs Data   ##############################################################################
        ## get id and distinct drugname
        $this->getprescription($patientid, date("Y-m-d"), 0);
        $this->smarty->assign('presDate', date("Y/m/d"));
        #################################################################### Heba : ## Investigation data  ##############################################################################
        $questions1 = R::findall('investcats', 'deleted = ? and displayorder in (1 , 2) order by displayorder ', [0]);
        foreach ($questions1 as $cat) {
            $invests = R::findall('invests', 'investcatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->invests = $invests;
        }

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

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

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

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

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


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

        //$this->smarty->assign('allInvCats',$questions);
        $this->smarty->assign('favorites', $favorites);
        $this->smarty->assign('group1', $questions1);
        $this->smarty->assign('group2', $questions2);
        $this->smarty->assign('group3', $questions3);
        $this->smarty->assign('group4', $questions4);
        $this->smarty->assign('group5', $questions5);
        $this->smarty->assign('others', $others);

        //Save entering gyna
        $lastVisitData = R::findOne('lastvisit', 'patientid = ? order by id desc', [$patientid]);

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


        $main_Obj = R::findOne('maingyna', 'patientid = ?', [$patientid]);
        $main_Obj_count = R::count('maingyna', 'patientid = ?', [$patientid]);
        if ($main_Obj_count < 1) {
            $mainObj = R::dispense('maingyna');
            $mainObj->patientid = $patientid;
            $mainObj->create_date = date('Y-m-d H:i:s'); //$this->today;
            $mainObj->notes = '';
            R::store($mainObj);

            $main_Obj = R::findOne('maingyna', 'patientid = ?', [$patientid]);
        }
        $this->smarty->assign('main_Obj', $main_Obj);


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

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


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

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

    public function del() {

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

        $id = filter_input(INPUT_POST, "id");
        $invId = filter_input(INPUT_POST, "invId");
        $tableName = filter_input(INPUT_POST, "tableName");
        $dataFor = filter_input(INPUT_POST, "dataFor");
        $date = filter_input(INPUT_POST, "date");
        $date = date("Y-m-d", strtotime($date));
        $patientId = filter_input(INPUT_POST, "patientId");
        if (!empty($invId)) {
            if ($dataFor < 2) {
                $table_obj = R::findall($tableName, 'patientid = ? and date = ? and forhusband = ? ', [$patientId, $date, $dataFor]);
                foreach ($table_obj as $row) {
                    $row->deleted = 1;
                    R::store($row);
                }
            } else {
                $table_obj = R::load($tableName, $invId);
                $table_obj->deleted = 1;
                R::store($table_obj);
            }
            echo 1;
        } else {
            try {
                $gyna_obj = R::load('gyna', $id);
                $gyna_obj->conditions = 1;
                R::store($gyna_obj);

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

    public function deldiagnosis() {

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

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

        try {
            $gyna_obj = R::load($tableName, $id);
            $gyna_obj->conditions = 1;
            R::store($gyna_obj);

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

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

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

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

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

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

        $patientid = filter_input(INPUT_GET, "id");
        $gyna_obj = R::dispense('gyna');
        $gyna_obj->patientid = $patientid;
        $gyna_obj->doctorid = $_SESSION['user_id'];
        $gyna_obj->gynadate = $this->today;
        //       $gyna_obj->gynalmp = $this->today;
        $gyna_obj->complaint = '';
        $gyna_obj->diagnosisid = '';
        $gyna_obj->complaintid = '';
        $gyna_obj->notes = '';
        $gyna_obj->conditions = 0;
        //call other class with other content


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

            $gyna_obj->gynadate = date("Y/m/d", strtotime($gyna_obj->gynadate));
            //    $gyna_obj->gynalmp = date("Y/m/d", strtotime($gyna_obj->gynalmp));

            $alldiagnosis = R::findall('diagnosis', 'conditions = 0 order by name');
            $this->smarty->assign('alldiagnosis', $alldiagnosis);
            $allcomplaint = R::findall('complaint', 'conditions = 0 order by name');
            $this->smarty->assign('allcomplaint', $allcomplaint);
            $this->smarty->assign('gyna_obj', $gyna_obj);
            $this->smarty->display('gyna/newrow.html');
            //header('Location:' . $this->hosturl . '/' . $this->controllname );
        } catch (Exception $e) {
            //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

    public function alldiagnosis() {

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

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

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

    public function update() {

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

        $id = filter_input(INPUT_POST, "id");
        $tablename = filter_input(INPUT_POST, "tableName");
        $colname = filter_input(INPUT_POST, "colName");
        $value = filter_input(INPUT_POST, "value");

        $dated = filter_input(INPUT_POST, "dated");
        if ($tablename == 'gynadrugs') {
            $this->updatedrugs($id, $tablename, $colname, $value);
        } else {





            if ($dated == 1) {
                $value = date("Y-m-d", strtotime($value));
            }
            if ($colname == "diagnosisid") {
                $diagnosis = json_decode($value);
                sort($diagnosis);
                $value = "";
                foreach ($diagnosis as $myname) {
                    $value = $value . $myname . ",";
                }
                $value = substr($value, 0, -1);
            }
            if ($colname == "complaintid") {
                $complaint = json_decode($value);
                sort($complaint);
                $value = "";
                foreach ($complaint as $myname) {
                    $value = $value . $myname . ",";
                }
                $value = substr($value, 0, -1);
            }

            try {
                $gyna_obj = R::load($tablename, $id);
                if ($colname == "gynadate" || $colname == "gynalmp") {
                    $value = date("Y-m-d", strtotime($value));
                }

                if ($colname == "bmi") {
                    $gyna_obj->patientid = filter_input(INPUT_POST, "patientId");
                    $gyna_obj->doctorid = $_SESSION['user_id'];
                    $gyna_obj->del = 0;
                }
                $gyna_obj->$colname = $value;
                R::store($gyna_obj);


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

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

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

    public function adddiagnosis() {

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

        $name = filter_input(INPUT_POST, "diagnosisName");
        $id = filter_input(INPUT_POST, "id");
        $table = filter_input(INPUT_POST, "table");
        try {
            $diagnosis = R::dispense($table);
            $diagnosis->name = $name;
            $diagnosis->conditions = 0;
            $did = R::store($diagnosis);
            $mygyna = R::findone('gyna', 'id=? ', [$id]);

            if ($table == "diagnosis") {
                if (empty($mygyna->diagnosisid))
                    $mygyna->diagnosisid = $did;
                else
                    $mygyna->diagnosisid = $mygyna->diagnosisid . ',' . $did;
            } else {
                if (empty($mygyna->complaintid))
                    $mygyna->complaintid = $did;
                else
                    $mygyna->complaintid = $mygyna->complaintid . ',' . $did;
            }
            R::store($mygyna);


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

    public function loadusrow() {       ## new row at ultrasound  form model
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

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

        $patientId = filter_input(INPUT_POST, "patientId");
        $type = filter_input(INPUT_POST, "type");   ## ussimple or uscomplete or usantenatal
        $itr = filter_input(INPUT_POST, "itr");
        $status = filter_input(INPUT_POST, "status");

        if ($type == "ussimple" || $type == "uscomplete") {
            $gynaUltrasound = R::dispense('gynaus');
            $gynaUltrasound->patientid = $patientId; //
            $gynaUltrasound->doctorid = $_SESSION['user_id'];
            $gynaUltrasound->date = $this->today;
            $gynaUltrasound->deleted = 0;
            //call other class with other content
            try {
                $id = R::store($gynaUltrasound);
                $gynaUltrasound->id = $id;
                $gynaUltrasound->date = date('Y/m/d', strtotime($gynaUltrasound->date));

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

                $this->smarty->assign('gUs', $gynaUltrasound);
                $this->smarty->assign('itr', $itr);
                $this->smarty->assign('type', $type);
                $this->smarty->display('gyna/newrowUS.html');
                //header('Location:' . $this->hosturl . '/' . $this->controllname );
            } catch (Exception $e) {
                header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
            }
        } elseif ($type == "usantenatal") {
            $this->smarty->display('gyna/newrowUS.html');
        } elseif ($type == "ltovary" || $type == "rtovary") {
            $gynaUsId = $patientId;

            if ($type == "rtovary") {
                $s = 1;
            }
            if ($type == "ltovary") {
                $s = 0;
            }
            if ($status == "show") {
                $focils = R::findall('gynausficils', 'gynausid = ? and type = ?', [$gynaUsId, $s]);
                $this->smarty->assign('focils', $focils);
            }

            $this->smarty->assign('gynaUsId', $gynaUsId);
            $this->smarty->assign('type', $type);
            $this->smarty->assign('status', $status);
            $this->smarty->display('gyna/newrowUS.html');
        }
    }

    public function drawRow() {       ## new row without database insert
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $type = filter_input(INPUT_POST, "type");   ## ussimple or uscomplete or usantenatal
        $itr = filter_input(INPUT_POST, "itr");
        $preFor = filter_input(INPUT_POST, "preFor");
        $patientId = filter_input(INPUT_POST, "patientId");
        $presDate = filter_input(INPUT_POST, "presDate");

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

        $tablename = filter_input(INPUT_POST, "tableName");
        $mainAntenatalId = filter_input(INPUT_POST, 'mainAntenatalId');
        $followId = filter_input(INPUT_POST, 'followid');  ## main Antenatal Id

        if ($type == "drug") {
            #################################################################### Heba : ## Drugs Data   ##############################################################################


            $gynaDrug = R::dispense($tablename);
            $gynaDrug->patientid = $patientId;
            $gynaDrug->date = date("Y-m-d", strtotime($presDate));
            $gynaDrug->drugid = '';
            $gynaDrug->drugtype = '';
            $gynaDrug->drugdos = '';
            $gynaDrug->forhusband = $preFor;
            $gynaDrug->doctorid = $_SESSION['user_id'];
            $gynaDrug->deleted = 0;
            $gynaDrug->recepittmpid = 0;
            $gynaDrug->recepitdrugid = 0;
            if ($tablename == "mainantenentaldrugs") {
                $gynaDrug->mainantenatalid = $mainAntenatalId;
            } elseif ($tablename == "followupdrugs") {
                $gynaDrug->followid = $followId;
            } elseif ($tablename == "ancsheetdrugs") {
                $gynaDrug->ancsheetid = $mainAntenatalId;
            }

            $gynaDrug->id = R::store($gynaDrug);

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

            $this->smarty->assign('drugs', $drugs);
            $this->smarty->assign('allDrugcats', $allDrugcats);
            $this->smarty->assign('allDrugTypes', $allDrugTypes);
            $this->smarty->assign('allDrugDoses', $allDrugDoses);
            $this->smarty->assign('itr', $itr);
            $this->smarty->assign('type', $type);
            $this->smarty->assign('gynaDrug', $gynaDrug);
            if ($tablename == "mainantenentaldrugs") {
                $this->smarty->display('antenalvisit/newrowUS.html');
            } elseif ($tablename == "followupdrugs") {
                $this->smarty->display('followup/newrowUS.html');
            } elseif ($tablename == "recorddrugs") {
                $this->smarty->display('record/newrowUS.html');
            } elseif ($tablename == "infertilitydrugs") {
                $this->smarty->display('infertility/newrowUS.html');
            } elseif ($tablename == "mointoringsheetdrugs") {
                $this->smarty->display('monitoring/newrowUS.html');
            } elseif ($tablename == "ancsheetdrugs") {
                $this->smarty->display('ancsheet/newrowUS.html');
            } elseif ($tablename == "infertilitysheetdrugs") {
                $this->smarty->display('infertilitysheet/newrowUS.html');
            } elseif ($tablename == "gynasheetdrugs") {
                $this->smarty->display('gynasheet/newrowUS.html');
            } else {
                $this->smarty->display('gyna/newrowUS.html');
            }
        }
    }

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

        $type = filter_input(INPUT_POST, "type");   ## define where to search in DB
        $value = filter_input(INPUT_POST, "value");

        if ($type == "type") {
            $drugId = filter_input(INPUT_POST, "drugId");
            $drug = R::load('drugs', $drugId);
            $doses = R::getAll('SELECT distinct drugdos FROM drugs where drugname = "' . $drug->drugname . '" and drugtype = "' . $value . '"  order by drugdos asc');
            if (count($doses) > 0) {
                echo $doses[0]['drugdos'];
            } else {
                echo -1;
            }
        } else {
            if ($value) {
                switch ($type) {
                    case "cat":
                        $drugs = R::getAll('select a.id , a.drugname from drugs a inner join (select distinct drugname, min(id) '
                                        . 'as id from drugs group by drugname ) as b on a.drugname = b.drugname and a.id = b.id where a.drugcat = "' . $value . '"');
                        $this->smarty->assign('drugs', $drugs);
                        break;
                    case "name_type":
                        $drug = R::load('drugs', $value);
                        $types = R::getAll('SELECT distinct  drugtype   FROM drugs where drugname = "' . $drug->drugname . '" order by drugtype asc');
                        $this->smarty->assign('types', $types);
                        $allTypes = R::getAll('SELECT distinct  drugtype  FROM drugs order by drugtype asc');
                        $this->smarty->assign('allTypes', $allTypes);
                        break;
                    case "name_dos":
                        $drug = R::load('drugs', $value);
                        $dos = R::getAll('SELECT distinct  drugdos   FROM drugs where drugname = "' . $drug->drugname . '" order by drugdos asc');
                        $this->smarty->assign('doses', $dos);
                        $allDos = R::getAll('SELECT distinct  drugdos   FROM drugs order by drugdos asc');
                        $this->smarty->assign('allDos', $allDos);
                        break;
                    default:
                        break;
                }
            } else {
                switch ($type) {
                    case "cat":
                        ## get id and distinct drugname
                        $drugs = R::getAll('select a.id , a.drugname from drugs a inner join (select distinct drugname, min(id) as id from drugs group by drugname ) as b on a.drugname = b.drugname and a.id = b.id');
                        $this->smarty->assign('drugs', $drugs);
                        break;
                    case "name_type":
                        $types = R::getAll('SELECT distinct  drugtype  FROM drugs order by drugtype asc');
                        $this->smarty->assign('types', $types);
                        break;
                    case "name_dos":
                        $dos = R::getAll('SELECT distinct  drugdos   FROM drugs order by drugdos asc');
                        $this->smarty->assign('doses', $dos);
                        break;

                    default:
                        break;
                }
            }


            $this->smarty->assign('type', $type);
            $this->smarty->display('gyna/newselectvalues.html');
        }
    }

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

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

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

    public function loadDrugModal() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        #################################### Heba : ## Drugs Data   ####################
        $patientId = filter_input(INPUT_POST, "patientId");

        $this->getprescription($patientId, date("Y-m-d"), 0);

        $this->smarty->assign('drugsTable', 'gynadrugs');
        $this->smarty->assign('controller', 'gyna');

        $this->smarty->display('monitoring/drugmodal.html');
    }

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

        $tovaryType = filter_input(INPUT_POST, "tovaryType");   ## left or right


        switch ($tovaryType) {
            case "left":
                $focilNo = filter_input(INPUT_POST, 'folliclesNumbers');
                $gynaUsId = filter_input(INPUT_POST, 'lgynaUsId');
                $type = 0;
                $colName = "lfolliclesno";
                break;

            case "right":
                $focilNo = filter_input(INPUT_POST, 'RfolliclesNumbers');
                $gynaUsId = filter_input(INPUT_POST, 'rgynaUsId');
                $type = 1;
                $colName = "rfolliclesno";
                break;

            default:
                break;
        }


        $gynaus = R::load('gynaus', $gynaUsId);
        $gynaus->$colName = $focilNo;

        $focils = array();
        for ($i = 1; $i <= $focilNo; $i++) {
            $name = filter_input(INPUT_POST, 'name' . $i);
            $length = filter_input(INPUT_POST, 'length' . $i);
            $width = filter_input(INPUT_POST, 'width' . $i);
            $volume = filter_input(INPUT_POST, 'volume' . $i);


            $focil = R::dispense('gynausficils');
            $focil->gynausid = $gynaUsId;
            $focil->name = $name;
            $focil->length = $length;
            $focil->width = $width;
            $focil->volume = $volume;
            $focil->type = $type;
            $focil->sysdate = date('Y-m-d');

            array_push($focils, $focil);
        }

        R::begin();
        try {
            R::store($gynaus);
            R::storeAll($focils);
            R::commit();
        } catch (Exception $e) {
            R::rollback();
            header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

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

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

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


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


                $j = 0;

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

                    $j++;
                }

                $j = 0;

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

                    $j++;
                }

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


                $i++;
            }

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

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

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

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

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

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

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

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

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

        if (!empty($investsList)) {
            $invests = array();
            foreach ($investsList as $check) {
                $gynaInvest = R::dispense('gynainvestigation');
                $gynaInvest->patientid = $patientId;
                $gynaInvest->date = date("Y-m-d", strtotime($invDate));
                $gynaInvest->investid = $check;
                $gynaInvest->doctorid = $_SESSION['user_id'];
                $gynaInvest->deleted = 0;
                $gynaInvest->forhusband = $forHusband;

                array_push($invests, $gynaInvest);
            }

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

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

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

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




            foreach ($PatientInvByDateHusband as $in) {
                $invest = R::load('invests', $in->investid);
                $in->invname = $invest->name;
            }

            foreach ($PatientInvByDateWife as $in) {
                $invest = R::load('invests', $in->investid);
                $in->invname = $invest->name;
            }


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

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


            $i++;
        }


        $this->smarty->assign('countHusband', $countHusband);
        $this->smarty->assign('countWife', $countWife);
        $this->smarty->assign('dates', $dates);
        $this->smarty->display('gyna/showInvestigation.html');
    }

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

        $patientId = filter_input(INPUT_POST, "patientId");
        $date = filter_input(INPUT_POST, "date");
        $printDate = filter_input(INPUT_POST, "printDate");
        $preFor = filter_input(INPUT_POST, "preFor");
        $patient = R::load('patients', $patientId);
        $wifetypes = R::load('wifetypes', $patient->wiftypeid);
        $husbandtypes = R::load('husbandtypes', $patient->husbandtypeid);



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



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


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

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

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


        if ($ProgramesettingData->print_diag == 1) {
            $gyna = R::findone('gyna', 'conditions = ? and patientid = ? ORDER BY gynadate DESC ', [0, $patientId]);
            $diagnosisArray = explode(',', $gyna->diagnosisid);
            $lastDiadnosis = '';
            $v = 0;
            foreach ($diagnosisArray as $value) {
                if ($v > 0) {
                    $lastDiadnosis .= ' ,  ';
                }
                $diag = R::load('diagnosis', $value);
                $lastDiadnosis .= $diag->name;
                $v++;
            }

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

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

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

        $patientId = filter_input(INPUT_POST, "patientId");
        $date = filter_input(INPUT_POST, "date");
        $dataFor = filter_input(INPUT_POST, "dataFor");

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


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



        if ($dataFor == 'wife') {
            $this->smarty->assign('name', $patient->wifename);
            $this->smarty->assign('title', $wifetypes->title);
        } elseif ($dataFor == 'husband') {
            $this->smarty->assign('name', $patient->husdandname);
            $this->smarty->assign('title', $husbandtypes->title);
        }


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



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

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

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

    public function checktransfer() {       ## check transfer
//
//        ### data from setup database
//        $a = R::findall('drugs');
//        ## define another database
//
//        $db_host = '192.168.1.8';
//        $db_name = 'test';
//        $db_user = 'ahmed';
//        $db_password = '123456';
//
//
//        ## define another database
//        R::addDatabase("old", 'mysql:host=' . $db_host . ';dbname=' . $db_name . '', '' . $db_user . '', '' . $db_password . '');
//
//        ## switch to the new database
//        R::selectDatabase("old");
//
//        ### needed operations on new database
//
//        $a = R::findall('drugs');
//        print_r($a);
//        ## bact to default database defined at setup
//        R::selectDatabase('default');
        require_once("Java.inc");
        $demo = new java("mac.Mac"); // it is `package name.class name`
        //print_r($demo->getMac());
        // get instance of Java class java.lang.System in PHP
//                $system = new Java('java.lang.System');
//
//                // demonstrate property access
//                echo 'Java version=' . $system->getProperty('java.version') . '<br />';
//                echo 'Java vendor=' . $system->getProperty('java.vendor') . '<br />';
//                echo 'OS=' . $system->getProperty('os.name') . ' ' .
//                $system->getProperty('os.version') . ' on ' .
//                $system->getProperty('os.arch') . ' <br />';
//
//                // java.util.Date example
//                $formatter = new Java('java.text.SimpleDateFormat',"EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz");
//
//                echo $formatter->format(new Java('java.util.Date'));
    }

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

        $this->smarty->display('gyna/newDrug.html');
    }

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

        $cat = filter_input(INPUT_POST, "drugcat");   ## No of drugs choosen by doctor
        $name = filter_input(INPUT_POST, "drugname");   ## array hlds all itr of selected drugs after delete or update
        $dos = filter_input(INPUT_POST, 'drugdos');
        $type = filter_input(INPUT_POST, 'drugtype');  ## add or edit

        if ($cat == "") {
            $cat = "--";
        }
        if ($name == "") {
            $name = "--";
        }
        if ($dos == "") {
            $dos = "--";
        }
        if ($type == "") {
            $type = "--";
        }

        $drug = R::dispense('drugs');

        $drug->drugname = $name;
        $drug->drugtype = $type;
        $drug->drugcat = $cat;
        $drug->drugdos = $dos;
        try {
            R::store($drug);
            echo '1-' . $cat . '-' . $name . '-' . $type . '-' . $dos;
        } catch (Exception $ex) {
            echo 'sorry !!!! drug could not be added';
        }
    }

    public function addNewRow() {

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

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

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

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

        echo $insertid;
    }

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

        $usRowsId = json_decode(stripslashes(filter_input(INPUT_POST, 'jsonString')));
        $patientId = filter_input(INPUT_POST, "patientId");
        $type = filter_input(INPUT_POST, "type");


        $usRows = array();

        if (!empty($patientId)) {
            $patient = R::load('patients', $patientId);

            $wifetypes = R::load('wifetypes', $patient->wiftypeid);
            $this->smarty->assign('name', $patient->wifename);
            $this->smarty->assign('title', $wifetypes->title);
            $this->smarty->assign('statusNo', $patient->statusno);
        } else {
            $patientId = 0;
        }

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


        if ($type == "usgyna") {
            foreach ($usRowsId as $id) {
                $row = R::load('gynaus', $id);
                array_push($usRows, $row);
            }
        } elseif ($type == "usantenatal") {
            foreach ($usRowsId as $id) {
                $row = R::load('mainantenentalus', $id);
                array_push($usRows, $row);
            }
        }

        $today = date("Y/m/d");
        $this->smarty->assign('date', $today);
        $this->smarty->assign('usRows', $usRows);
        $this->smarty->assign('type', $type);
        $this->smarty->display('gyna/printus.html');
    }

    public function addphmodel() {
        //check login
        autho::checkautho($this->hosturl);
        $this->smarty->assign('today', date("Y/m/d"));
        #################################################################### Heba : ## Investigation data  ##############################################################################
        $questions1 = R::findall('presenthistoryquestions', 'deleted = ? and displayorder in (1 , 2 , 3 ) order by displayorder ', [0]);
        foreach ($questions1 as $cat) {
            $answers = R::findall('presenthistoryanswers', 'presenthistorycatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->answers = $answers;
        }

        $questions2 = R::findall('presenthistoryquestions', 'deleted = ? and displayorder in (4 , 5 , 6  ) order by displayorder ', [0]);
        foreach ($questions2 as $cat) {
            $answers = R::findall('presenthistoryanswers', 'presenthistorycatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->answers = $answers;
        }

        $questions3 = R::findall('presenthistoryquestions', 'deleted = ? and displayorder in (7 , 8 , 9 ) order by displayorder ', [0]);
        foreach ($questions3 as $cat) {
            $answers = R::findall('presenthistoryanswers', 'presenthistorycatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->answers = $answers;
        }

        $questions4 = R::findall('presenthistoryquestions', 'deleted = ? and displayorder  in (10 , 11 , 12) order by displayorder ', [0]);
        foreach ($questions4 as $cat) {
            $answers = R::findall('presenthistoryanswers', 'presenthistorycatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->answers = $answers;
        }

        $questions5 = R::findall('presenthistoryquestions', 'deleted = ? and displayorder > 12 order by displayorder ', [0]);
        foreach ($questions5 as $cat) {
            $answers = R::findall('presenthistoryanswers', 'presenthistorycatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->answers = $answers;
        }

        $others = R::findall('presenthistoryquestions', 'deleted = ? and displayorder = ?  order by displayorder ', [0, 0]);
        foreach ($others as $cat) {
            $answers = R::findall('presenthistoryanswers', 'presenthistorycatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->answers = $answers;
        }
        //  $favorites = R::findall('presenthistoryanswers', 'deleted = ? and  favorite= ?', [0, 1]);
        //$this->smarty->assign('allInvCats',$questions);
        $this->smarty->assign('favorites', $favorites);
        $this->smarty->assign('group1', $questions1);
        $this->smarty->assign('group2', $questions2);
        $this->smarty->assign('group3', $questions3);
        $this->smarty->assign('group4', $questions4);
        $this->smarty->assign('group5', $questions5);
        $this->smarty->assign('others', $others);

        $this->smarty->display('gyna/addphmodel.html');
    }

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

        $patientId = filter_input(INPUT_POST, 'patientId');
        $catIdList = $_POST['catId'];


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

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

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

        $this->smarty->assign('date', date("Y/m/d", strtotime($printDate)));
        $questions = array();
        if (!empty($catIdList)) {

            $x = 0;
            foreach ($catIdList as $catId) {
                $catAnswer = array();
                $investsList = $_POST['invCheck' . $catId];
                foreach ($investsList as $ansId) {
                    $gynaInvest = R::dispense('gynaph');
                    $gynaInvest->patientid = $patientId;
                    $gynaInvest->date = date("Y-m-d", strtotime($invDate));
                    $gynaInvest->catid = $catId;
                    $gynaInvest->answerid = $ansId;
                    $gynaInvest->doctorid = $_SESSION['user_id'];
                    $gynaInvest->deleted = 0;

                    R::store($gynaInvest);

                    $an = R::load('presenthistoryanswers', $gynaInvest->answerid);
                    $gynaInvest->ans_name = $an->name;
                    array_push($catAnswer, $gynaInvest);
                }

                $q = R::load('presenthistoryquestions', $catId);

                $questions[$x]['id'] = $catId;
                $questions[$x]['ques_name'] = $q->name;
                $questions[$x]['ans'] = $catAnswer;
                $x++;
            }

            try {
                $this->smarty->assign('name', $patient->wifename);
                $this->smarty->assign('title', $wifetypes->title);

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

                $this->smarty->display('gyna/printph.html');
            } catch (Exception $e) {
                //      print_r($e);
                header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
            }
        }
    }

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

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

        $dates = R::getAll('SELECT DISTINCT date  FROM gynaph WHERE deleted = ? and patientid = ?  order by date desc ', [0, $patientId]);
        $i = 0;
        foreach ($dates as $date) {

            ## show all investigations of patient
            $questions = R::getAll('SELECT DISTINCT gynaph.catid , presenthistoryquestions.name as questionname'
                            . '      FROM gynaph '
                            . ' join presenthistoryquestions on presenthistoryquestions.id = gynaph.catid  '
                            . 'WHERE gynaph.deleted = ? and gynaph.patientid = ?  and gynaph.date = ? ', [0, $patientId, $date['date']]);


            $j = 0;
            foreach ($questions as $question) {
                //        $gynaph = R::findall('gynaph', 'deleted = ? and patientid = ? and catid = ?  ', [0, $patientId, $question['catid']]);
                $gynaph = R::getAll('SELECT DISTINCT gynaph.answerid , presenthistoryanswers.name as answername  '
                                . '      FROM gynaph '
                                . ' join presenthistoryanswers on presenthistoryanswers.id = gynaph.answerid  '
                                . 'WHERE gynaph.deleted = ? and gynaph.patientid = ?  and gynaph.catid = ? and gynaph.date = ?  '
                                , [0, $patientId, $question['catid'], $date['date']]);

                $questions[$j]['answers'] = $gynaph;
                $j++;
            }

            $dates[$i]['questions'] = $questions;
            $dates[$i]['date'] = date("Y/m/d", strtotime($dates[$i]['date']));
            $i++;
        }

        $this->smarty->assign('dates', $dates);
        $this->smarty->display('gyna/showph.html');
    }

    public function delPh() {

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

        $cat_id = filter_input(INPUT_POST, "invId");
        $date = filter_input(INPUT_POST, "date");
        $date = date("Y-m-d", strtotime($date));
        $tableName = filter_input(INPUT_POST, "tableName");
        $patientId = filter_input(INPUT_POST, "patientId");

        try {

            R::exec('update  gynaph set deleted = 1  WHERE  patientid = ? and date = ?   ', [$patientId, $date]);

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

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

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

        $date = filter_input(INPUT_POST, "date");
        $questions = R::getAll('SELECT DISTINCT gynaph.catid as id  
                                               , presenthistoryquestions.name as ques_name
                                        FROM gynaph 
                                       join presenthistoryquestions                  on presenthistoryquestions.id = gynaph.catid  
                                          WHERE 
                                        gynaph.deleted = ? and gynaph.patientid = ?  and gynaph.date = ? '
                        , [0, $patientId, $date]);

        $x = 0;
        foreach ($questions as $que) {
            $catAnswer = R::getAll('SELECT DISTINCT gynaph.answerid , presenthistoryanswers.name as ans_name  '
                            . '      FROM gynaph '
                            . ' join presenthistoryanswers on presenthistoryanswers.id = gynaph.answerid  '
                            . 'WHERE gynaph.deleted = ? and gynaph.patientid = ?  and gynaph.catid = ? and gynaph.date = ?  '
                            , [0, $patientId, $que['id'], $date]);

            $questions[$x]['ans'] = $catAnswer;
            $x++;
        }


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

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

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

        $this->smarty->assign('name', $patient->wifename);
        $this->smarty->assign('title', $wifetypes->title);
        $this->smarty->assign('statusNo', $patient->statusno);
        $this->smarty->assign('questions', $questions);
        $this->smarty->assign('array', 1);

        $this->smarty->display('gyna/printph.html');
    }

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

        $plans = R::findall('gynainfertilityplan', ' patientId = ? and deleted = 0 order by id asc', [$patientId]);
        if (count($plans) < 1) {
            $plans = R::dispense('gynainfertilityplan');
            $plans->patientid = $patientId;
            $plans->plan = '';
            $plans->itr = 0;
            $plans->deleted = 0;

            R::store($plans);
        }

        $plans = R::findall('gynainfertilityplan', ' patientId = ? and deleted = 0 order by id asc', [$patientId]);

        $types = R::findall('gynainfertilitytype', ' deleted = 0 order by name');

        $infertility = R::findOne('gynainfertility', ' patientId = ?', [$patientId]);
        if (count($infertility) < 1) {
            $infertility = R::dispense('gynainfertility');
            $infertility->patientid = $patientId;
            $infertility->date = date("Y-m-d");

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

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

        $this->smarty->assign('planItr', count($plans));
        $this->smarty->assign('plans', $plans);
        $this->smarty->assign('types', $types);
        $this->smarty->assign('infertility', $infertility);
        $this->smarty->display('gyna/infertility.html');
    }

    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 "type":
                    $table = "gynainfertilitytype";
                    $col = "name";
                    break;

                default:
                    break;
            }

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


            $infertility = R::findOne('gynainfertility', ' patientId = ?', [$patientId]);
            $infertility->$colname = $id;
            R::store($infertility);

            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 'type':

                $table = "gynainfertilitytype";
                $col = "Types";

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

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


        try {

            $plan = R::dispense('gynainfertilityplan');
            $plan->patientid = $patientId;
            $plan->plan = '';
            $plan->itr = 0;
            $plan->deleted = 0;
            $plan->id = R::store($plan);

            $this->smarty->assign('plan', $plan);
            $this->smarty->assign('newItr', $newItr);
            $this->smarty->display('gyna/newrowplan.html');
        } catch (Exception $e) {
            echo $e;
        }
    }

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

}
