<?php

/*
 * awframework from aw.inc present aw controller
 * it will help you develop easy and fast with secure tools
 * you can edit and add what you feel right
 * don't change in strucure of file
 */
require_once("imp/_imp.php");

class Controllers {

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

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

        //here name of controll to known
        $this->controllname = 'completereport';
        $this->shcontrollname = 'Home';
        $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;
        $this->smarty->assign('breadcrumbs', $breadcrumbs);

        # here show the active page in menu
        // array called active[] with level of active element
        $active[0] = 'completereport'; //controller name or tab name
        $this->active = $active;


        //here will call all php pages
        require_once("_header.php");
        require_once("_sidebar.php");
        require_once("_leftsidebar.php");
        require_once("_footer.php");
        $this->patientid = patientdata::patientid();
    }

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

        //here will load the menu show

        $allPatient = R::findAll('patients');
        $this->smarty->assign('allPatient', $allPatient);
        $this->smarty->assign('patientid', $this->patientid);

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

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

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

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

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

        if (!empty($patientId)) {
            $this->patientdatashow($patientId);
            $this->Examination($patientId);
            $this->investigation($patientId);
            $this->gyna($patientId);
            $this->antenatal($patientId);
        }


        $this->smarty->display('reports/completesearch.html');
    }

    public function showprint() {

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

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

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

        if (!empty($patientId)) {
            $this->patientdatashow($patientId);
            $this->Examination($patientId);
            $this->investigation($patientId);
            $this->gyna($patientId);
            $this->antenatal($patientId);
        }


        $this->smarty->display('reports/completeprint.html');
    }

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

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

        $this->checkpatientlist($patientId);
        $programesetting = R::findOne('programesetting');

//        exec("$programesetting->backupdest:\wamp\bin\php\php5.5.12\php excel.php > out.txt 2> err.txt ");   // if you put & at the end of string it wil not wait exec to finish ## like   exec("$programesetting->backupdest:\wamp\bin\php\php5.5.12\php excel.php > out.txt 2> err.txt &");
        exec("$programesetting->phppath\php excel.php > out.txt 2> err.txt &");


        $result = array();
        $finalResult = '';


        $dir = '../excel_backups/' . $patient->statusno;
        $files2 = scandir($dir, 1);

        foreach ($files2 as $key => $value) {
            if (!in_array($value, array(".", ".."))) {
                $result[] = $value;
            }
        }
        foreach ($result as $fileName) {
            $finalResult .= '<tr><td><a id="download1" data-href="" href="../excel_backups/' . $patient->statusno . '/' . $fileName . '">' . $fileName . '</a></td></tr>';
        }
        print_r($finalResult);
    }

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

        $patientList = R::findAll('excelinfopatients', 'patientid = ?', [$patientId]);
        $pat = R::load('patients', $patientId);
        $statusNo = $pat->statusno;

        if (count($patientList) <= 0) {    ## not exist then add it
            $excelInfoPatient = R::dispense('excelinfopatients');
            $excelInfoPatient->patientid = $patientId;
            $excelInfoPatient->statusno = $statusNo;
            R::store($excelInfoPatient);
        }
    }

    private function patientdatashow($patientId) {

        $id = $patientId;
        //GET ALL PATIENT DATA TO SHOW IT IN ALL PROGRAM
        $getAllPatientData = R::getRow("SELECT * FROM patients WHERE id = $id");

        //GET WIFE TYPE
        if (!empty($getAllPatientData['wiftypeid'])) {
            $wifetype = R::findOne('wifetypes', 'id = ? ', [$getAllPatientData['wiftypeid']]);
            $getAllPatientData['wifetype'] = $wifetype->title;
        }

        if ($getAllPatientData['dateofbirth'] != '0000-00-00' && $getAllPatientData['dateofbirth'] != '' && $getAllPatientData['dateofbirth'] != Null) {
            $currentdate_x = time();
            $currentdateofbirth = strtotime($getAllPatientData['dateofbirth']);
            $newage = $currentdate_x - $currentdateofbirth;
            $y = ($newage / (60 * 60 * 24 * 365));
            $this->smarty->assign("new_dateofbirth_calc", floor($y));
        } else {
            $this->smarty->assign("new_dateofbirth_calc", '');
        }


        if ($getAllPatientData['husbanddateofbirth'] != '0000-00-00' && $getAllPatientData['husbanddateofbirth'] != '' && $getAllPatientData['husbanddateofbirth'] != Null) {
            $currentdate_x = time();
            $currentdateofbirth_husband = strtotime($getAllPatientData['husbanddateofbirth']);
            $new_husbandage = $currentdate_x - $currentdateofbirth_husband;
            $husband_hh = ($new_husbandage / (60 * 60 * 24 * 365));
            $this->smarty->assign("new_dateofbirth_husband", floor($husband_hh));
        } else {
            $this->smarty->assign("new_dateofbirth_husband", '');
        }
        if (!empty($getAllPatientData['mirragefromdate'])) {
            $today = new DateTime(date('Y-m-d'));
            $mirragedate = new DateTime($getAllPatientData['mirragefromdate']);
            $interval = $today->diff($mirragedate);
            $this->smarty->assign("mirrageyears", $interval->y);
            $this->smarty->assign("mirragemonths", $interval->m);
        }
        //GET HUSBAND TYPE
        if (!empty($getAllPatientData['husbandtypeid'])) {
            $husbandType = R::findOne('husbandtypes', 'id = ? ', [$getAllPatientData['husbandtypeid']]);
            $getAllPatientData['husbandtype'] = $husbandType->title;
        }
        //GET WIFE JOB
        if (!empty($getAllPatientData['wifejob'])) {
            $wifeJob = R::findOne('wifejobs', 'id = ? ', [$getAllPatientData['wifejob']]);
            $getAllPatientData['wifejob'] = $wifeJob->title;
        }
        //GET HUSBAND JOB
        if (!empty($getAllPatientData['husbandjob'])) {
            $husbandJob = R::findOne('husbandjobs', 'id = ? ', [$getAllPatientData['husbandjob']]);
            $getAllPatientData['husbandjob'] = $husbandJob->title;
        }

        //GET BL JOB

        if (!empty($getAllPatientData['husbandbl'])) {

            $wifeblpdHus = R::getRow('SELECT * FROM bloodtypes WHERE id = "' . $getAllPatientData['husbandbl'] . '"');
            $getAllPatientData['husblpatientdata'] = $wifeblpdHus['title'];
        } else {
            $getAllPatientData['husblpatientdata'] = 0;
        }
        if (!empty($getAllPatientData['wifebl'])) {
            $wifeblpd = R::getRow('SELECT * FROM bloodtypes WHERE id = "' . $getAllPatientData['wifebl'] . '"');
            $getAllPatientData['wifeblpatientdata'] = $wifeblpd['title'];
        } else {
            $getAllPatientData['wifeblpatientdata'] = 0;
        }

        $del = 0;

        ### ================================================================phmenstural for patient ========================================*/
        $myphmenstrual = R::findone('phmenstrual', 'del = ? and patientid = ? order by id DESC limit 1', [$del, $patientId]);


        $this->smarty->assign('myphmenstrual', $myphmenstrual);
        $this->smarty->assign('phmenstrualcount', count($myphmenstrual));
        if (count($myphmenstrual) > 0) {
            if (empty($myphmenstrual->menarche) && empty($myphmenstrual->duration) && empty($myphmenstrual->length) && empty($myphmenstrual->phregularity) && empty($myphmenstrual->phamount) && empty($myphmenstrual->phdysmenorrhoea)) {
                $this->smarty->assign('idData', "no");
            } else {
                $this->smarty->assign('idData', "yes");
                $phregualrity = R::findone('phregularity', 'id = ?', [$myphmenstrual->phregularity]);
                $this->smarty->assign('phregualrity', $phregualrity);



                $phamount = R::findone('phamount', 'id = ?', [$myphmenstrual->phamount]);
                $this->smarty->assign('phamount', $phamount);



                $phdysmenorrhoea = R::findone('phdysmenorrhoea', 'id = ?', [$myphmenstrual->phdysmenorrhoea]);
                $this->smarty->assign('phdysmenorrhoea', $phdysmenorrhoea);
            }
        }


        /* ================================================================================================================================ */
        $myallcontract = R::findOne('phcontraception', 'del = ? and patientid = ? order by id DESC limit 1', [$del, $patientId]);
        $this->smarty->assign('myallcontract', $myallcontract);
        $this->smarty->assign('myallcontractcount', count($myallcontract));

        if (count($myallcontract) > 0) {
            if (empty($myallcontract->contype) && empty($myallcontract->contduration) && empty($myallcontract->contstopped) && empty($myallcontract->contranote)) {
                $this->smarty->assign('idData1', "no");
            } else {
                $this->smarty->assign('idData1', "yes");
                $phcontracttype = R::load('phcontracttype', $myallcontract->contype);
                //R::findall('phcontracttype', 'id = ?', [$myallcontract->contype]);
                $this->smarty->assign('phcontracttype', $phcontracttype);
            }
        }

        /* =====================================================phobstetric=========================================================================== */

        $myallobsteric = R::getAll('select id  from phobstetric where del = ?  and patientid = ? ', [$del, $patientId]);



        $allphobstericterminate = R::findall('phobstericterminate', 'del = 0');
        #### p count
        $svddata = R::getAll('select id from phobstetric where obstermination =? and del = 0  and patientid = ?  ', [1, $patientId]);
        $csdata = R::getAll('select id from phobstetric where obstermination =? and del = 0  and patientid = ?  ', [2, $patientId]);
        // $patientwholedata = R::findOne('patients', 'id = ?', $patientId);

        $p = $getAllPatientData['pno'];

        $pcounter = count($svddata) + count($csdata) + $p;
        $this->smarty->assign('pcounter', $pcounter);



        ###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;
        $this->smarty->assign('abcounter', $abcounter);


        ###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;
        $this->smarty->assign('Ectopiccounter', $Ectopiccounter);


        ###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;
        $this->smarty->assign('vmodelcounter', $vmodelcounter);


        $obstriccountnew = count($myallobsteric) + $p + $ab + $Ectopic + $vmodel;
        $this->smarty->assign('myallobsteric', $obstriccountnew);


        /* =====================================================Past Medical H=========================================================================== */
        $allpastmedicalW = R::getAll('SELECT DISTINCT(phpastmedical.medicaldisease) AS medicaldisease,phpastmedical.id
                 ,phpastmedicaldisease.name FROM phpastmedical,phpastmedicaldisease
                 where phpastmedical.medicaldisease = phpastmedicaldisease.id  and  phpastmedical.del = ?
                 and phpastmedical.patientid = ? and phpastmedical.for_husband != 1  ', [$del, $patientId]);

        $this->smarty->assign('allpastmedicalW', $allpastmedicalW);
        $this->smarty->assign('allpastmedicalWcount', count($allpastmedicalW));

        $allpastmedicalH = R::getAll('SELECT DISTINCT(phpastmedical.medicaldisease) AS medicaldisease,phpastmedical.id
                 ,phpastmedicaldisease.name FROM phpastmedical,phpastmedicaldisease
                 where phpastmedical.medicaldisease = phpastmedicaldisease.id  and  phpastmedical.del = ?
                 and phpastmedical.patientid = ? and phpastmedical.for_husband = 1  ', [$del, $patientId]);

        $this->smarty->assign('allpastmedicalH', $allpastmedicalH);
        $this->smarty->assign('allpastmedicalHcount', count($allpastmedicalH));

        /* =====================================================Past surgical H=========================================================================== */
        $allpastsurgicalW = R::getAll('select DISTINCT(phpastsurgical.surgicaloperation) AS surgicaloperation
                ,phpastsurgical.id ,phpastsurgicaloperation.name from  phpastsurgical
                join phpastsurgicaloperation on phpastsurgicaloperation.id = phpastsurgical.surgicaloperation
                where phpastsurgical.del = ? and phpastsurgical.patientid = ? and phpastsurgical.for_husband != 1  ', [$del, $patientId]);

        $this->smarty->assign('allpastsurgicalWcount', count($allpastsurgicalW));
        $this->smarty->assign('allpastsurgicalW', $allpastsurgicalW);

        $allpastsurgicalH = R::getAll('select DISTINCT(phpastsurgical.surgicaloperation) AS surgicaloperation
                ,phpastsurgical.id ,phpastsurgicaloperation.name from  phpastsurgical
                join phpastsurgicaloperation on phpastsurgicaloperation.id = phpastsurgical.surgicaloperation
                where phpastsurgical.del = ? and phpastsurgical.patientid = ? and phpastsurgical.for_husband = 1  ', [$del, $patientId]);

        $this->smarty->assign('allpastsurgicalHcount', count($allpastsurgicalH));
        $this->smarty->assign('allpastsurgicalH', $allpastsurgicalH);

        /* =====================================================Past gynecological H=========================================================================== */

        $allphpastgynecological = R::getAll('select DISTINCT(phpastgynecological.gynecologicaloperation) AS gynecologicaloperation,phpastgynecological.id,phpastgynecologicaloperation.name from  phpastgynecological join phpastgynecologicaloperation on phpastgynecologicaloperation.id= phpastgynecological.gynecologicaloperation where phpastgynecological.del = ? and phpastgynecological.patientid = ?  ', [$del, $patientId]);

        $this->smarty->assign('allphpastgynecologicalcount', count($allphpastgynecological));
        $this->smarty->assign('allphpastgynecological', $allphpastgynecological);


        /* =====================================================Past art H=========================================================================== */
        $allphpastart = R::getAll('select DISTINCT(phpastart.arttype) AS arttype ,phpastart.id,phpastarttype.name from  phpastart join phpastarttype on phpastarttype.id= phpastart.arttype where phpastart.del = ? and phpastart.patientid = ?  ', [$del, $patientId]);

        $this->smarty->assign('allphpastartcount', count($allphpastart));
        $this->smarty->assign('allphpastart', $allphpastart);

        $monitorSheets = R::getAll('select monitordate , place from  mointoringsheet
                 where status = 1 AND patientid = ? and deleted = 0
                order by monitordate desc    limit 0,5 ', [$patientId]);

        // print_r($monitorSheets . ' -----------------------');

        $this->smarty->assign('internalphpastartcount', count($monitorSheets));
        $this->smarty->assign('internalphpastart', $monitorSheets);

        /* =====================================================familyH=========================================================================== */

        $allphfamily = R::getAll('select DISTINCT(phfamily.family_disease) AS family_disease ,phfamily.id,phfamilydisease.name from  phfamily,phfamilydisease where phfamilydisease.id =phfamily.family_disease and phfamily.del = ? and phfamily.patientid = ? ', [$del, $patientId]);
        $this->smarty->assign('allphfamilycount', count($allphfamily));
        $this->smarty->assign('allphfamily', $allphfamily);

        /* ============================================================================formodels ========================================================== */

        $this->smarty->assign('patientdata', $getAllPatientData);
        $this->smarty->assign('patientid', $patientId);
        $this->smarty->assign('patientId', $patientId);
    }

    private function Examination($patientId) {
        $allexmination = R::getAll('select examination.*, awusers.user_name as docname from examination,awusers where  examination.doctorid = awusers.user_id and del = 0 and patientid = ? and (weight != "" or height != "" or bmi != "" or b_p != "" or pulse != "" or headandneck != "" or chestandheart != "" or abdomen != "" or pelvis != "" or extremitis != "")', [$patientId]);
        for ($i = 0; $i < count($allexmination); $i++) {
            $allexmination[$i]["examinationdate"] = date("d-m-Y", strtotime($allexmination[$i]["examinationdate"]));
        }
        $this->smarty->assign('allexminationcount', count($allexmination));
        $this->smarty->assign('allexmination', $allexmination);
    }

    private function investigation($patientId) {
        //////////////////////////////SEMEN////////////////////////////////////////////////////
        $allsemen = R::getAll('select semen.*, awusers.user_name as docname from semen,awusers where  semen.doctorid = awusers.user_id and semen.patientid = ? and semen.del = 0  and (!isNull(`count`) or !isNull(`motilitya`) or !isNull(`motilityab`) or !isNull(`normal`) or !isNull(`puscell`) or !isNull(`normaltype`) or !isNull(`oligo`) or !isNull(`astheno`) or !isNull(`tetrato`) or !isNull(`notes`))', [$patientId]);
        for ($i = 0; $i < count($allsemen); $i++) {
            $allsemen[$i]["sdate"] = date("d-m-Y", strtotime($allsemen[$i]["sdate"]));
        }
        $this->smarty->assign('allsemen', $allsemen);


//////////////////////////////HSG////////////////////////////////////////////////////
        $allhsg = R::getAll('select hsg.*, awusers.user_name as docname from hsg,awusers where  hsg.doctorid = awusers.user_id and hsg.patientid = ? and hsg.del = 0 and (!isNull(`uterus`) or !isNull(`ltube`) or !isNull(`smear`) or !isNull(`rtube`) or !isNull(`notes`))', [$patientId]);
        for ($i = 0; $i < count($allhsg); $i++) {
            $allhsg[$i]["sdate"] = date("d-m-Y", strtotime($allhsg[$i]["sdate"]));
        }
        $this->smarty->assign('allhsg', $allhsg);
//////////////////////////////USTV////////////////////////////////////////////////////
        $allustv = R::getAll('select ustv.*, awusers.user_name as docname from ustv,awusers where  ustv.doctorid = awusers.user_id and ustv.patientid = ? and ustv.del = 0 and (!isNULL(`uterus`) or !isNULL(`radnexa`) or !isNULL(`ladnexa`) or !isNULL(`pelvis`) or !isNull(`notes`))', [$patientId]);
        for ($i = 0; $i < count($allustv); $i++) {
            $allustv[$i]["sdate"] = date("d-m-Y", strtotime($allustv[$i]["sdate"]));
        }
        $this->smarty->assign('allustv', $allustv);
//////////////////////////////LAPAROSCOPY////////////////////////////////////////////////////
        $alllaparoscopy = R::getAll('select laparoscopy.*, awusers.user_name as docname from laparoscopy,awusers where  laparoscopy.doctorid = awusers.user_id and laparoscopy.patientid = ? and laparoscopy.del = 0 and ( !isNull(`uterus`) or !isNull(`radnexa`) or !isNull(`ladnexa`) or !isNull(`pelvis`) or !isNull(`notes`))', [$patientId]);
        for ($i = 0; $i < count($alllaparoscopy); $i++) {
            $alllaparoscopy[$i]["sdate"] = date("d-m-Y", strtotime($alllaparoscopy[$i]["sdate"]));
        }
        $this->smarty->assign('alllaparoscopy', $alllaparoscopy);
//////////////////////////////HYSTEROSCOPY////////////////////////////////////////////////////
        $allhysteroscopy = R::getAll('select hysteroscopy.*, awusers.user_name as docname from hysteroscopy,awusers where  hysteroscopy.doctorid = awusers.user_id and hysteroscopy.patientid = ? and hysteroscopy.del = 0 and( !isNull(`cervix`) or !isNull(`uterine`) or !isNull(`rostium`) or !isNull(`lostium`) or !isNull(`notes`))', [$patientId]);
        for ($i = 0; $i < count($allhysteroscopy); $i++) {
            $allhysteroscopy[$i]["sdate"] = date("d-m-Y", strtotime($allhysteroscopy[$i]["sdate"]));
        }
        $this->smarty->assign('allhysteroscopy', $allhysteroscopy);
//////////////////////////////MRICT////////////////////////////////////////////////////
        $allmrict = R::getAll('select mrict.*, awusers.user_name as docname from mrict,awusers where  mrict.doctorid = awusers.user_id and mrict.patientid = ? and mrict.del = 0 and ( !isNull(`uterus`) or !isNull(`radnexa`) or !isNull(`ladnexa`) or !isNull(`pelvis`) or !isNull(`notes`))', [$patientId]);
        for ($i = 0; $i < count($allmrict); $i++) {
            $allmrict[$i]["sdate"] = date("d-m-Y", strtotime($allmrict[$i]["sdate"]));
        }
        $this->smarty->assign('allmrict', $allmrict);
//////////////////////////////PATHOLOGY////////////////////////////////////////////////////
        $allpathology = R::getAll('select pathology.*, awusers.user_name as docname from pathology,awusers where  pathology.doctorid = awusers.user_id and pathology.patientid = ? and pathology.del = 0 and(!isNull(`cytology`) or !isNull(`histopathology`))', [$patientId]);
        for ($i = 0; $i < count($allpathology); $i++) {
            $allpathology[$i]["sdate"] = date("d-m-Y", strtotime($allpathology[$i]["sdate"]));
        }
        $this->smarty->assign('allpathology', $allpathology);
//////////////////////////////HORMON////////////////////////////////////////////////////
        $allhormon = R::getAll('select hormon.*, awusers.user_name as docname from hormon,awusers where  hormon.doctorid = awusers.user_id and hormon.patientid = ? and hormon.del = 0 and(!isNull(`lh`) or !isNull(`prl`) or !isNull(`etwo`) or !isNull(`amh`) or !isNull(`freet`) or !isNull(`totalt`) or !isNull(`pfour`) or !isNull(`tsh`) or !isNull(`tthree`) or !isNull(`dht`) or !isNull(`bhcg`) or !isNull(`inhibinb`) or !isNull(`asd`) or !isNull(`tfour`) or !isNull(`dheas`) or !isNull(`fsh`) or !isNull(`notes`))', [$patientId]);
        for ($i = 0; $i < count($allhormon); $i++) {
            $allhormon[$i]["sdate"] = date("d-m-Y", strtotime($allhormon[$i]["sdate"]));
        }
        $this->smarty->assign('allhormon', $allhormon);
    }

    private function gyna($patientId) {
        //////////////////////////////GYNA VISITS////////////////////////////////////////////////////
        $ProgramesettingData = R::findone('programesetting');

        if ($ProgramesettingData->diagnosshow == 0) {
            $allgyna = R::getAll('select gyna.* from gyna where gyna.conditions = 0 and patientid = ? and ( complaint != "" or notes != "" or diagnosisid != "")', [$patientId]);
        } else {
            $allgyna = R::getAll('select gyna.* from gyna where gyna.conditions = 0 and patientid = ? and ( complaint != "" or notes != "" or diagnosistxt != "")', [$patientId]);
        }
        for ($i = 0; $i < count($allgyna); $i++) {
            $allgyna[$i]["gynadate"] = date("d-m-Y", strtotime($allgyna[$i]["gynadate"]));
            $doctordata = R::getRow('SELECT user_name FROM awusers WHERE user_id = ? ', [$allgyna[$i]["doctorid"]]);
            $allgyna[$i]["docname"] = $doctordata['user_name'];

            if ($ProgramesettingData->diagnosshow == 0) {
                $diag = explode(',', $allgyna[$i]["diagnosisid"]);
                $allgyna[$i]['diagnosistxt'] = '';
                foreach ($diag as $d) {
                    $dd = R::findOne('diagnosis', 'id = ?', [$d]);
                    $allgyna[$i]['diagnosistxt'] .= $dd->name . ' , ';
                }

                $complaint = explode(',', $allgyna[$i]["complaintid"]);
                $allgyna[$i]['complaintxt'] = '';
                foreach ($complaint as $co) {
                    $co = R::findOne('complaint', 'id = ?', [$co]);
                    $allgyna[$i]['complaintxt'] .= $co->name . ' , ';
                }
            }
        }


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

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

//////////////////////////////FOLLICULOMETRY////////////////////////////////////////////////////
        $allgynaUS = R::findall('gynaus', 'deleted = ? and patientid = ? and (!isNull(day) or !isNull(endo) or !isNull(ovrayll) or !isNull(ovraylw) or !isNull(ovraylv) or !isNull(ovraylno) or !isNull(ovraylsize) or !isNull(ovrayrl) or !isNull(ovrayrw) or !isNull(ovrayrv) or !isNull(ovrayrno) or !isNull(ovrayrsize) or !isNull(uterusl) or !isNull(uterusw) or !isNull(uterusv) or !isNull(cervixl) or !isNull(cervixw) or !isNull(cervixv) or !isNull(notes))', [0, $patientId]);
        foreach ($allgynaUS as $us) {
            $us->date = date('d-m-Y', strtotime($us->date));
            $doctordata = R::getRow('SELECT user_name FROM awusers WHERE user_id = ? ', [$us->doctorid]);
            $us->doctorname = $doctordata['user_name'];

            $focilsr = R::findall('gynausficils', 'gynausid = ? and type = ?', [$us->id, 1]);
            $us->focilsr = $focilsr;
            $focilsl = R::findall('gynausficils', 'gynausid = ? and type = ?', [$us->id, 0]);
            $us->focilsl = $focilsl;
        }
        $this->smarty->assign('allgynaUS', $allgynaUS);

////////////////////////////////Gyna Investigation/////////////////////////////////////////
        $idates = R::getAll('SELECT DISTINCT date  FROM gynainvestigation WHERE deleted = ? and patientid = ?  order by date', [0, $patientId]);
        $i = 0;
        foreach ($idates as $date) {
            ## all invs of certain patient
            //$PatientInvByDate = R::findall('gynainvestigation', 'deleted = ? and patientid = ? and date = ? ', [ 0, $patientId, $date['date']]);

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


            //$idates[$i]['invests'] = $PatientInvByDate;

            $idates[$i]['investsh'] = $PatientInvByDateHusband;
            $idates[$i]['investsw'] = $PatientInvByDateWife;


            $i++;
        }
        for ($i = 0; $i < count($idates); $i++) {
            $idates[$i]["date"] = date("d-m-Y", strtotime($idates[$i]["date"]));
        }

        $this->smarty->assign('idates', $idates);
//////////////////////////////TREATMENT////////////////////////////////////////////////////
        $dates = R::getAll('SELECT DISTINCT date  FROM gynadrugs WHERE deleted = ? and patientid = ?  order by date', [0, $patientId]);
        $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++;
            }
            $i++;
        }


        for ($i = 0; $i < count($dates); $i++) {
            $dates[$i]["date"] = date("d-m-Y", strtotime($dates[$i]["date"]));
        }
        $this->smarty->assign('dates', $dates);
    }

    private function antenatal($patientId) {
        //////////////////////////////ANTENATAL VISITS////////////////////////////////////////////////////
        $counter = 0;
        $allObj = R::findAll('mainantenental', ' patientid = ?', [$patientId]);
        $ProgramesettingData = R::findone('programesetting');
        $this->smarty->assign('ProgramesettingData', $ProgramesettingData);

        foreach ($allObj as $mainObj) {
            if ($ProgramesettingData->diagnosshow == 0) {
                $allantenalvisit = R::findall('antenalvisit', 'conditions = 0 AND mainantenentalid = ? and (complaint != "" or wt != "" or bp != "" or notes != "" or diagnosisid != "") order by antenaldate desc, id desc', [$mainObj->id]);
                foreach ($allantenalvisit as $myvisit) {
                    $myvisit->antenaldate = date('d-m-Y', strtotime($myvisit->antenaldate));
                    $date1 = new DateTime($myvisit->antenaldate);
                    $date2 = new DateTime($mainObj->lmp);
                    $interval = $date1->diff($date2);
                    $myvisit->w = round($interval->days / 7);

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

                    ######################diagnosis
                    $diag = explode(',', $myvisit->diagnosisid);

                    if (!empty($myvisit->diagnosisid)) {
                        $myvisit->diagnosisid = '';
                        foreach ($diag as $d) {
                            $dd = R::load('diagnosisant', $d);
                            $myvisit->diagnosisid .= $dd->name . ' , ';
                        }
                    }
                    ######################complaint
                    $complaint = explode(',', $myvisit->complaintid);
                    if (!empty($myvisit->complaintid)) {
                        $myvisit->complaintid = '';
                        foreach ($complaint as $co) {
                            $comp = R::load('complaintant', $co);
                            $myvisit->complaintid .= $comp->name . ' , ';
                        }
                    }
                }
            } else {
                $allantenalvisit = R::findall('antenalvisit', 'conditions = 0 AND mainantenentalid = ? and (complaint != "" or wt != "" or bp != "" or notes != "") order by antenaldate desc, id desc', [$mainObj->id]);
                foreach ($allantenalvisit as $myvisit) {
                    $myvisit->antenaldate = date('d-m-Y', strtotime($myvisit->antenaldate));
                    $date1 = new DateTime($myvisit->antenaldate);
                    $date2 = new DateTime($mainObj->lmp);
                    $interval = $date1->diff($date2);
                    $myvisit->w = round($interval->days / 7);

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


            $mainObj->antvisit = $allantenalvisit;
            //////////////////////////////ANTENATAL US////////////////////////////////////////////////////
            $allAntUS = R::findall('mainantenentalus', 'deleted = ? and patientid = ? and mainantenatalid = ? and( nga != "" or gs != "" or crl != ""  or fhr != "" or bpd != ""  or fl != "" or placenta != "" or fwt != "" or notes != "" ) order by date desc, id desc', [0, $patientId, $mainObj->id]);
            foreach ($allAntUS as $us) {
                $us->date = date('d-m-Y', 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);
            }
            $mainObj->Us = $allAntUS;
            //////////////////////////////ANTENATAL TTT////////////////////////////////////////////////////
            $dates = R::getAll('SELECT DISTINCT date  FROM mainantenentaldrugs WHERE deleted = ? and patientid = ? and mainantenatalid = ?  order by date desc, id desc', [0, $patientId, $mainObj->id]);
            $i = 0;
            foreach ($dates as $date) {
                ## all prescription of certain patient
                //$PatientPresByDate = R::findall('mainantenentaldrugs','deleted = ? and patientid = ? and date = ?  and mainantenatalid = ?' , [ 0 , $patientId , $date['date'] , $mainObj->id ]);
                $PatientPresByDateWife = R::findall('mainantenentaldrugs', 'deleted = ? and patientid = ? and date = ?  and mainantenatalid = ? and forhusband = ? ', [0, $patientId, $date['date'], $mainObj->id, 0]);
                $PatientPresByDateHusband = R::findall('mainantenentaldrugs', 'deleted = ? and patientid = ? and date = ?  and mainantenatalid = ? and forhusband = ? ', [0, $patientId, $date['date'], $mainObj->id, 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++;
                }

                $i++;
            }


            for ($i = 0; $i < count($dates); $i++) {
                $dates[$i]["date"] = date("d-m-Y", strtotime($dates[$i]["date"]));
            }
            $mainObj->ttt = $dates;

            //////////////////////////////ANTENATAL LAB////////////////////////////////////////////////////
            $invsdates = R::getAll('SELECT DISTINCT date  FROM mainantenentalinvest WHERE deleted = ? and patientid = ? and mainantenatalid = ?  order by date desc, id desc', [0, $patientId, $mainObj->id]);
            $i = 0;
            foreach ($invsdates as $date) {
                ## all invs of certain patient
//                    $PatientInvByDate = R::findall('mainantenentalinvest','deleted = ? and patientid = ? and date = ? and mainantenatalid = ? ' , [ 0 , $patientId , $date['date'] , $mainObj->id ]);
//                    foreach ($PatientInvByDate as $in)
//                    {
//                        $invest = R::load('invests',$in->investid);
//                        $in->invname = $invest->name ;
//                    }
//                    $invsdates[$i]['invests'] = $PatientInvByDate ;

                $PatientInvByDateHusband = R::findall('mainantenentalinvest', 'deleted = ? and patientid = ? and date = ? and mainantenatalid = ? and forhusband = ? ', [0, $patientId, $date['date'], $mainObj->id, 1]);
                $PatientInvByDateWife = R::findall('mainantenentalinvest', 'deleted = ? and patientid = ? and date = ? and mainantenatalid = ? and forhusband = ? ', [0, $patientId, $date['date'], $mainObj->id, 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;
                }


                $invsdates[$i]['investsh'] = $PatientInvByDateHusband;
                $invsdates[$i]['investsw'] = $PatientInvByDateWife;


                $i++;
            }
            for ($j = 0; $j < count($invsdates); $j++) {
                $invsdates[$j]["date"] = date("d-m-Y", strtotime($invsdates[$j]["date"]));
            }
            $mainObj->lab = $invsdates;

            if (!empty($mainObj->Us)) {
                $counter = 1;
            }
            if (!empty($mainObj->antvisit)) {
                $counter = 1;
            }
            if (!empty($mainObj->ttt)) {
                $counter = 1;
            }
            if (!empty($mainObj->lab)) {
                $counter = 1;
            }
        }
        if ($counter == 0) {
            $allObj = "";
        }
        $this->smarty->assign("allObj", $allObj);
    }

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

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

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

}
