<?php

require_once("imp/_imp.php");

class Controllers {

//public vars
    public $smarty;
    public $hosturl;
    public $controllname;
    public $shcontrollname;
    public $active;
    public $time;
    public $today;
    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 = 'and_visits';
        $this->shcontrollname = 'and_visits';
        $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] = 'andrology'; //controller name or tab name
        $active[1] = 'and_visits'; //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');
        $this->patientId = patientdata::patientid();
    }

    public function index() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        ## check if patient is choosen 
        $patientid = filter_input(INPUT_GET, "patientid");

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

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


        #################################################################### Heba : ## get all rays category ##############################################################################
        $elements = R::findall('andvisits', 'deleted = 0  and patientid = ' . $this->patientId . '   ORDER BY date DESC');

        $iDsArray = '';
        $selectArray = '';

        foreach ($elements as $element) {
            $userData = R::getRow('select user_name from awusers where user_id = ' . $element->doctorid);
            $element->doctorName = $userData['user_name'];

            ## merge complain  and  diagnosis
            if (!empty($element->diagnosistxt) && $element->diagnosistxt != '') {
                $element->complaint .= '-';
                $element->complaint .= $element->diagnosistxt;
                $element->diagnosistxt = '';
                R::store($element);
            }

            ##########################################################################
            $iDsArray .= $element->id . ',';
            $element->date = date("Y/m/d", strtotime($element->date));
            $selectArray = explode(',', $element->diagnosisid);
            $element->select = $selectArray;
            $compSelectArray = explode(',', $element->complaintid);
            $element->compselect = $compSelectArray;
        }

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

        $anddiagnosis = R::findall('anddiagnosis', 'deleted = 0 order by name');
        $this->smarty->assign('alldiagnosis', $anddiagnosis);
        $andcomplaint = R::findall('andcomplaint', 'deleted = 0 order by name');
        $this->smarty->assign('allcomplaint', $andcomplaint);

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

        $this->loadRaysDetails();
        $this->loadInvestigationDetails();
        $this->loadPrescriptionDetails($patientid, date("Y-m-d"), 1);

        $allgynaUS = R::findall('andvisitsus', 'deleted = ? and patientid = ? ORDER BY date DESC ', [0, $patientid]);
        foreach ($allgynaUS as $us) {
            $us->date = date("Y/m/d", strtotime($us->date));
            $doctordata = R::getRow('SELECT user_name FROM awusers WHERE user_id = ? ', [$us->doctorid]);
            $us->doctorname = $doctordata['user_name'];
        }
        $this->smarty->assign('allgynaUS', $allgynaUS);

        $geneticTesting = R::findall('andvisitsgenetictesting', 'deleted = ? and patientid = ? ORDER BY date DESC ', [0, $patientid]);
        foreach ($geneticTesting as $us) {
            $us->date = date("Y/m/d", strtotime($us->date));
            $doctordata = R::getRow('SELECT user_name FROM awusers WHERE user_id = ? ', [$us->doctorid]);
            $us->doctorname = $doctordata['user_name'];
        }
        $this->smarty->assign('geneticTesting', $geneticTesting);

        $semen = R::findall('andvisitssemen', 'deleted = ? and patientid = ? ORDER BY date DESC ', [0, $patientid]);
        foreach ($semen as $us) {
            $us->date = date("Y/m/d", strtotime($us->date));
            $doctordata = R::getRow('SELECT user_name FROM awusers WHERE user_id = ? ', [$us->doctorid]);
            $us->doctorname = $doctordata['user_name'];
        }
        $this->smarty->assign('semen', $semen);

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

    private function loadRaysDetails() {
        $allRayCats1 = R::findall('rayscats', 'deleted = ? and displayorder in (1 , 2) order by displayorder ', [0]);
        foreach ($allRayCats1 as $cat) {
            $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->rays = $rays;
        }

        $allRayCats2 = R::findall('rayscats', 'deleted = ? and displayorder = 3 order by displayorder ', [0]);
        foreach ($allRayCats2 as $cat) {
            $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->rays = $rays;
        }

        $allRayCats3 = R::findall('rayscats', 'deleted = ? and displayorder in (4 , 5) order by displayorder ', [0]);
        foreach ($allRayCats3 as $cat) {
            $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->rays = $rays;
        }

        $allRayCats4 = R::findall('rayscats', 'deleted = ? and displayorder  between 6 and  11 order by displayorder ', [0]);
        foreach ($allRayCats4 as $cat) {
            $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->rays = $rays;
        }

        $allRayCats5 = R::findall('rayscats', 'deleted = ? and displayorder > 11 order by displayorder ', [0]);
        foreach ($allRayCats5 as $cat) {
            $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->rays = $rays;
        }

        $otherRays = R::findall('rayscats', 'deleted = ? and displayorder = ?  order by displayorder ', [0, 0]);
        foreach ($otherRays as $cat) {
            $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->rays = $rays;
        }


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

        $this->smarty->assign('favoritesRays', $favoritesRays);
        $this->smarty->assign('allRayCats1', $allRayCats1);
        $this->smarty->assign('allRayCats2', $allRayCats2);
        $this->smarty->assign('allRayCats3', $allRayCats3);
        $this->smarty->assign('allRayCats4', $allRayCats4);
        $this->smarty->assign('allRayCats5', $allRayCats5);
        $this->smarty->assign('otherRays', $otherRays);
    }

    private function loadInvestigationDetails() {
        ####################################################################  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);

        $invoffers = R::findall('invoffer', 'active = ? and  del = ? ', [1, 0]);
        foreach ($invoffers as $offer) {
            $invs = R::getRow('SELECT  sum(price) as price   FROM  invofferdetails where invoffer_id = ? and  del = ?  '
                            , [$offer->id, 0]);
            $offer->price = $invs['price'];
        }
        $this->smarty->assign('invoffers', $invoffers);
    }

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


        $drugs = R::getAll('SELECT  id , drugname ,minimumbalance  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 newrow() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

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

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

        $this->addTableRow($patientId, $tableName, $type);
        $this->smarty->display('andrology/newrow.html');
        ################################################################################################################################################################################
    }

    private function addTableRow($patientId, $tableName, $type) {
        $element = R::dispense($tableName);
        $element->doctorid = $_SESSION['user_id'];
        $element->patientid = $patientId;
        $element->date = $this->today;
        $element->deleted = 0;

        $id = R::store($element);
        $element->id = $id;
        $element->date = date("Y/m/d", strtotime($element->date));

        $userData = R::getRow('select user_name from awusers where user_id = ' . $_SESSION['user_id']);
        $element->doctorName = $userData['user_name'];
        $element->doctorname = $userData['user_name'];

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

        $this->smarty->assign('element', $element);
        $this->smarty->assign('type', $type);

        if ($type == "and_visits") {
            $anddiagnosis = R::findall('anddiagnosis', 'deleted = 0 order by name');
            $this->smarty->assign('alldiagnosis', $anddiagnosis);
            $andcomplaint = R::findall('andcomplaint', 'deleted = 0 order by name');
            $this->smarty->assign('allcomplaint', $andcomplaint);
        }
    }

    public function update() {

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

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

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

        try {
            $obj = R::load($tablename, $id);

            $obj->$colname = $value;
            R::store($obj);

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

    public function del() {      ## delete row from investcat table 
        //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");

        $ogj = R::load($tableName, $id);
        $ogj->deleted = 1;

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

    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 = "anddiagnosis";
        else
            $table = "andcomplaint";
        try {

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

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

        $tableName = filter_input(INPUT_POST, "tableName");
        $name = filter_input(INPUT_POST, "name");
        $patientid = filter_input(INPUT_POST, "patientid");
        $rowoftableid = filter_input(INPUT_POST, "rowoftableid");
        $maintableName = filter_input(INPUT_POST, "maintableName");


        $alldata = R::findAll($tableName, 'deleted = 0');

        $this->smarty->assign('tablename', $tableName);
        $this->smarty->assign('selectname', $name);
        $this->smarty->assign('alldata', $alldata);
        $this->smarty->assign('patientid', $patientid);
        $this->smarty->assign('rowoftableid', $rowoftableid);
        $this->smarty->assign('maintableName', $maintableName);

        $this->smarty->display('andrology/editmodel.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->deleted = 0;
            $did = R::store($diagnosis);
            $mygyna = R::load('andvisits', $id);

            if ($table == "anddiagnosis") {
                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 addray() {       ## add prescription to patient
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

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

        $rayDate = filter_input(INPUT_POST, 'rayDate');
        $printDate = filter_input(INPUT_POST, 'printrayDate');

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

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

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

        if (!empty($raysList)) {
            $rays = array();
            foreach ($raysList as $check) {
                $gynaRays = R::dispense('andvisitsrays');
                $gynaRays->patientid = $patientId;
                $gynaRays->date = date("Y-m-d", strtotime($rayDate));
                $gynaRays->rayid = $check;
                $gynaRays->doctorid = $_SESSION['user_id'];
                $gynaRays->deleted = 0;
                $gynaRays->forhusband = $forHusband;

                array_push($rays, $gynaRays);
            }

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

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

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

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




            foreach ($PatientRayByDateHusband as $in) {
                $ray = R::load('rays', $in->rayid);
                $in->invname = $ray->name;
            }

            foreach ($PatientRayByDateWife as $in) {
                $ray = R::load('rays', $in->rayid);
                $in->invname = $ray->name;
            }


            $dates[$i]['raysh'] = $PatientRayByDateHusband;
            $dates[$i]['raysw'] = $PatientRayByDateWife;
            $dates[$i]['date'] = date("Y/m/d", strtotime($dates[$i]['date']));

            $countHusband[$dates[$i]['date']] = count($PatientRayByDateHusband);
            $countWife[$dates[$i]['date']] = count($PatientRayByDateWife);


            $i++;
        }


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

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

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

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


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



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


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



        foreach ($PatientRayByDate as $invest) {
            $ray = R::load('rays', $invest->rayid);
            $invest->name = $ray->name;
        }
        $this->smarty->assign('investigations', $PatientRayByDate);

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

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

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

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

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

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

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

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

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

        $invests = array();

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

                array_push($invests, $gynaInvest);
            }
        }

        if (!empty($offersList)) {
            foreach ($offersList as $offer_id) {
                $invofferdetails = R::findall('invofferdetails', 'del = ? and invoffer_id = ?  ', [0, $offer_id]);
                foreach ($invofferdetails as $data) {
                    $gynaInvest = R::dispense('andvisitsinvestigation');
                    $gynaInvest->patientid = $patientId;
                    $gynaInvest->date = date("Y-m-d", strtotime($invDate));
                    $gynaInvest->investid = $data->inv_id;
                    $gynaInvest->doctorid = $_SESSION['user_id'];
                    $gynaInvest->deleted = 0;
                    $gynaInvest->forhusband = $forHusband;
                    $gynaInvest->offer_id = $offer_id;

                    array_push($invests, $gynaInvest);
                }
            }
        }

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

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

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

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




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

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


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

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


            $i++;
        }


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

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

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

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


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



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


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



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

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

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

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

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

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

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


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


                $j = 0;

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

                    $j++;
                }

                $j = 0;

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

                    $j++;
                }

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


                $i++;
            }

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

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

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

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

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



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



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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

            default:
                break;
        }


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

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


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

            array_push($focils, $focil);
        }

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

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

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

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


        $usRows = array();

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

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

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


        if ($type == "semenPrint") {
            foreach ($usRowsId as $id) {
                $row = R::load('andvisitssemen', $id);
                array_push($usRows, $row);
            }
        } elseif ($type == "geneticPrint") {
            foreach ($usRowsId as $id) {
                $row = R::load('andvisitsgenetictesting', $id);
                switch ($row->chromosome) {
                    case 1:
                        $row->chromosome = "normal";
                        break;
                    case 2:
                        $row->chromosome = "abnormal";
                        break;
                    default:
                        $row->chromosome = "";
                        break;
                }
                switch ($row->azf) {
                    case 1:
                        $row->azf = "normal";
                        break;
                    case 2:
                        $row->azf = "delection";
                        break;
                    default:
                        $row->azf = "";
                        break;
                }
                array_push($usRows, $row);
            }
        }

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

// at the end of class call

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

}
