<?php

require_once("imp/_imp.php");

class Controllers {

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

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

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


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

# here show the active page in menu
// array called active[] with level of active element
        $active[0] = 'antenalvisit'; //controller name or tab name
        $active[1] = 'antenalvisit'; //controller name
// do name  // switch($do)
        switch ($acty) {
            case '':
                $active[2] = 'show';
                break;
            case 'show':
                $active[2] = 'show';
                break;
            default :
                $active[2] = 'show';
                break;
        }
        $this->active = $active;


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

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

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


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

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

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


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


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


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


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

        $svd = $getAllPatientData['svd'];

        $new_p = $cscounter + $pcounter + $svd;

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

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

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


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


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

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

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

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


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


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


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

        $iDsArray = '';
        $selectArray = '';
        foreach ($allantenalvisit as $myvisit) {
            $date1 = new DateTime($myvisit->antenaldate);
            $date2 = new DateTime($mainObj->lmp);
            $interval = $date1->diff($date2);

            $diff = round(abs(strtotime($myvisit->antenaldate) - strtotime($mainObj->lmp)) / 86400);
            $myvisit->w = intval($diff / 7) . 'W ' . ($diff % 7) . 'D';

            //echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
            // shows the total amount of days (not divided into years, months and days like above)
            //    $myvisit->w = round($interval->days / 7);
            $myvisit->dateFlag = 0;
            $myvisit->antenaldate = date("Y/m/d", strtotime($myvisit->antenaldate));
            if ($myvisit->antenaldate < $mainObj->lmp) {
                $myvisit->dateFlag = 1;
            }
            $iDsArray .= $myvisit->id . ',';
            $selectArray = explode(',', $myvisit->diagnosisid);
            $myvisit->select = $selectArray;

            $compSelectArray = explode(',', $myvisit->complaintid);
            $myvisit->compselect = $compSelectArray;
        }
        $iDsArray = rtrim($iDsArray, ',');
        $this->smarty->assign('iDsArray', $iDsArray);
        $this->smarty->assign('allantenalvisit', $allantenalvisit);

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

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


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

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

        #################################################################### Heba : ## ultra sound data  ##############################################################################

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

            $date1 = new DateTime($us->date);
            $date2 = new DateTime($mainObj->lmp);
            $interval = $date1->diff($date2);
            $us->w = round($interval->days / 7);
        }
        $this->smarty->assign('allAntUS', $allAntUS);
        if ($lastAntUS) {
            $this->smarty->assign('lastPlacenta', $lastAntUS->placenta);
        } else {
            $this->smarty->assign('lastPlacenta', '');
        }


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

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

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

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

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

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

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


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

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


//Save entering antenatal visit
        $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);


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

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

    private function getprescription($patientId, $date, $preFor, $mainAntenatalId) {
        $PatientPresByDate = R::findall('mainantenentaldrugs', 'deleted = ? and patientid = ? and date = ?  and mainantenatalid = ? and forhusband = ?  ', [0, $patientId, $date, $mainAntenatalId, $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");

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

    public function archive() {

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


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

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

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


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

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

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

    public function pregdetail() {

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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


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


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


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

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

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

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

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

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

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

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

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

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

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

                $gyna_obj->$colname = $value;

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

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

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

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


                R::store($gyna_obj);
            }
        }
    }

    private function updatedrugs($id, $tablename, $colname, $value) {
        $obj = R::load($tablename, $id);
        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 endpreg() {

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

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

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

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


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

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

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


            try {


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

    public function addtermination() {

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

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

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

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

    public function addplace() {

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

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

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

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

    public function alltermination() {

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

        try {

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

    public function allplace() {

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

        try {

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

    public function deltermination() {

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

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

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

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

    public function delplace() {

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

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

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

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

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

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

        $patientId = filter_input(INPUT_POST, "patientId");
        $type = filter_input(INPUT_POST, "type");   ## ussimple or uscomplete or usantenatal
        $itr = filter_input(INPUT_POST, "itr");
        $mainAntenatalId = filter_input(INPUT_POST, "mainAntenatalId");
        $mainObj = R::load('mainantenental', $mainAntenatalId);

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

            $antUltrasound->nga = '';
            $antUltrasound->gs = '';
            $antUltrasound->crl = '';
            $antUltrasound->fhr = '';
            $antUltrasound->bpd = '';
            $antUltrasound->fl = '';
            $antUltrasound->placenta = '';
            $antUltrasound->ai = '';
            $antUltrasound->fwt = '';
            $antUltrasound->notes = '';



            //call other class with other content
            try {
                $id = R::store($antUltrasound);
                $antUltrasound->id = $id;


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



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

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

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

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

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

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

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

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

        $patientId = filter_input(INPUT_POST, "patientId");
        $mainAntenatalId = filter_input(INPUT_POST, "mainAntenatalId");
        $archive = filter_input(INPUT_POST, "archive");
        $type = filter_input(INPUT_POST, "type");  ## show or edit
        $preFor = filter_input(INPUT_POST, "preFor");
        $countHusband = '';
        $countWife = '';

        ## show all prescription of patient
        if ($type == "show") {
            $dates = R::getAll('SELECT DISTINCT date  FROM mainantenentaldrugs WHERE deleted = ? and patientid = ? and mainantenatalid = ?  order by date desc', [0, $patientId, $mainAntenatalId]);
            $i = 0;
            foreach ($dates as $date) {
                ## all prescription of certain patient
                $PatientPresByDateWife = R::findall('mainantenentaldrugs', 'deleted = ? and patientid = ? and date = ?  and mainantenatalid = ? and forhusband = ? ', [0, $patientId, $date['date'], $mainAntenatalId, 0]);
                $PatientPresByDateHusband = R::findall('mainantenentaldrugs', 'deleted = ? and patientid = ? and date = ?  and mainantenatalid = ? and forhusband = ? ', [0, $patientId, $date['date'], $mainAntenatalId, 1]);


                $j = 0;

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

                    $j++;
                }

                $j = 0;

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

                    $j++;
                }

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

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

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

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

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

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

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

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


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

                array_push($invests, $antInvest);
            }

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

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

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

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

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


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

            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->assign('archive', $archive);

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

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

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

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

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

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

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

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

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

        ## all prescription of certain patient
        $PatientPresByDate = R::findall('mainantenentaldrugs', 'deleted = ? and patientid = ? and date = ? and mainantenatalid = ? and forhusband = ? ', [0, $patientId, $date, $mainAntenatalId, $preFor]);

        if ($preFor == 1) {
            $this->smarty->assign('name', $patient->husdandname);
            $this->smarty->assign('title', $husbandtypes->title);
        } elseif ($preFor == 0) {
            $this->smarty->assign('name', $patient->wifename);
            $this->smarty->assign('title', $wifetypes->title);
        }

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


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

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

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

        if ($ProgramesettingData->print_diag == 1) {
            $antenal = R::findone('antenalvisit', 'conditions = 0 AND mainantenentalid = ? 
                    ORDER BY antenaldate DESC ', [$mainAntenatalId]);

            $diagnosisArray = explode(',', $antenal->diagnosisid);
            $lastDiadnosis = '';
            $v = 0;
            foreach ($diagnosisArray as $value) {
                if ($v > 0) {
                    $lastDiadnosis .= ' ,  ';
                }
                $diag = R::load('diagnosisant', $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");
        $mainAntenatalId = filter_input(INPUT_POST, 'mainAntenatalId');  ## main Antenatal Id
        $dataFor = filter_input(INPUT_POST, "dataFor");

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


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


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


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

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

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

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

    public function adddiagnosis() {

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

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


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

    public function alldiagnosis() {

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

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

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

    public function deldiagnosis() {

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

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

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

    public function addNewRow() {

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

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

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

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

        echo $insertid;
    }

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

}
