<?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 = 'monitoring';
        $this->shcontrollname = 'Monitoring Sheet';
        $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] = 'monitoring'; //controller name or tab name
        $active[1] = 'monitoring'; //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");

        date_default_timezone_set('Africa/Cairo');

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

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

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

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

        ## load current monitor sheet details
        ##  done = 0 current sheet
        $monitorSheet = R::findOne('mointoringsheet', 'status = 0 AND patientid = ?', [$patientid]);

        if (count($monitorSheet) < 1) {
            $monitorSheet = R::dispense('mointoringsheet');
            $monitorSheet->patientid = $patientid;
            $monitorSheet->doctorid = $_SESSION['user_id'];
            $monitorSheet->monitordate = $this->today;
//            $monitorSheet->lmp = '';
            $monitorSheet->attempno = 0;
//            $monitorSheet->procedure = '';
//            $monitorSheet->protocol = '';
//            $monitorSheet->ejac = '';
//            $monitorSheet->pesa = '';
//            $monitorSheet->tese = ''; //$this->today;
//            $monitorSheet->sryo = '';
//            $monitorSheet->hmg = '';
//            $monitorSheet->agonist = '';
//            $monitorSheet->hcg = '';
            $monitorSheet->remarks = '';

            $monitorSheet->place = '';
            $monitorSheet->amp = '';
            $monitorSheet->oocytestotal = '';
            $monitorSheet->oocytesm1 = '';
            $monitorSheet->oocytesm2 = '';
            $monitorSheet->oocytesgv = '';
            $monitorSheet->ettotal = '';
            $monitorSheet->etg1 = '';
            $monitorSheet->cyroday = '';
            $monitorSheet->cyrow = '';
            $monitorSheet->p4 = '';
            $monitorSheet->outcome = '';


            $monitorSheet->status = 0;
            $monitorSheet->sysdate = $this->today;
            $monitorSheet->deleted = 0;
            $monitorSheetId = R::store($monitorSheet);
            $monitorSheet->id = $monitorSheetId;
        }
        $monitorSheet->monitordate = date("Y/m/d", strtotime($monitorSheet->monitordate));
        $monitorSheet->lmp = date("Y/m/d", strtotime($monitorSheet->lmp));
        $this->smarty->assign('monitorSheet', $monitorSheet);

        ## load all ejacs
        $ejacs = R::findAll('mointoringsheetejac', ' deleted = 0 ');
        $this->smarty->assign('ejacs', $ejacs);

        ## load all procedures
        $procedures = R::findAll('mointoringsheetprocedure', ' deleted = 0 ');
        $this->smarty->assign('procedures', $procedures);

        ## load all pesas
        $pesas = R::findAll('mointoringsheetpesa', ' deleted = 0 ');
        $this->smarty->assign('pesas', $pesas);

        ## load all teses
        $teses = R::findAll('mointoringsheettese', ' deleted = 0 ');
        $this->smarty->assign('teses', $teses);

        ## load all sryos
        $sryos = R::findAll('mointoringsheetsryo', ' deleted = 0 ');
        $this->smarty->assign('sryos', $sryos);

        ## load all protocols
        $protocols = R::findAll('mointoringsheetprotocol', ' deleted = 0 ');
        $this->smarty->assign('protocols', $protocols);

        ## load all hmgs
        $hmgs = R::findAll('mointoringsheethmg', ' deleted = 0 ');
        $this->smarty->assign('hmgs', $hmgs);

        ## load all agonists
        $agonists = R::findAll('mointoringsheetagonist', ' deleted = 0 ');
        $this->smarty->assign('agonists', $agonists);

        ## load all agonists
        $hcgs = R::findAll('mointoringsheethcg', ' deleted = 0 ');
        $this->smarty->assign('hcgs', $hcgs);

        ## load all mointoring sheet visits
        $visits = R::findAll('mointoringsheetvisits', ' deleted = 0 and mointoringsheetid =  ' . $monitorSheet->id . ' order by visitdate desc');
        foreach ($visits as $visit) {
            $date1 = new DateTime($visit->visitdate);
            $date2 = new DateTime($monitorSheet->monitordate);
            $interval = $date1->diff($date2);

            $days = 1 + $interval->days;
            $cycleDay = $days . '' . $this->ordinal($days);

            $visit->cycleday = $cycleDay;

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

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

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

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

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

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

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

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

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

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

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

        ################################################################################
//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('monitoring/add.html');

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

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

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

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

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

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

        try {
            $myObject = R::load('mointoringsheetdrugs', $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");
        $type = filter_input(INPUT_POST, "type");  ## show or edit
        $preFor = filter_input(INPUT_POST, "preFor");
        $archive = filter_input(INPUT_POST, "archive");
        ## show all prescription of patient
        if ($type == "show") {
            $dates = R::getAll('SELECT DISTINCT date  FROM mointoringsheetdrugs 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('mointoringsheetdrugs', 'deleted = ? and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date['date'], 0]);
                $PatientPresByDateHusband = R::findall('mointoringsheetdrugs', '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->assign('archive', $archive);
            $this->smarty->display('monitoring/showPrescriptions.html');
        }

        ## show  prescription of patient with determined date to edit it
        else if ($type == "edit") {
            $date = filter_input(INPUT_POST, "preDate");
            $date = date("Y-m-d", strtotime($date));
            $this->getprescription($patientId, $date, $preFor);
            $this->smarty->assign('type', "drugedit");
            $this->smarty->display('monitoring/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('mointoringsheetdrugs', '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 loadDrugModal() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        #################################### Heba : ## Drugs Data   ####################
        $patientId = filter_input(INPUT_POST, "patientId");

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

        $this->smarty->assign('drugsTable', 'mointoringsheetdrugs');
        $this->smarty->assign('controller', 'monitoring');

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

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

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

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

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

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

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

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

                array_push($invests, $gynaInvest);
            }

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

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

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

        ## show all investigations of patient
        $dates = R::getAll('SELECT DISTINCT date  FROM mointoringsheetinvestigation 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('mointoringsheetinvestigation', 'deleted = ? and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date['date'], 1]);
            $PatientInvByDateWife = R::findall('mointoringsheetinvestigation', '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->assign('archive', $archive);
        $this->smarty->display('monitoring/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('mointoringsheetinvestigation', 'deleted = ? and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date, 0]);
        } elseif ($dataFor == 'husband') {
            $PatientInvByDate = R::findall('mointoringsheetinvestigation', '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 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));
        }

        try {
            $obj = R::load($tablename, $id);
            $obj->$colname = $value;
            R::store($obj);
            echo 1;
        } catch (Exception $e) {
            echo -1;
        }
    }

    public function addNewItem() {

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

        //vars here
        $name = filter_input(INPUT_POST, 'newitem');
        $parentId = filter_input(INPUT_POST, 'id');

        ## parent = 1  ==> update in parent table
        $parent = filter_input(INPUT_POST, 'parent');

        $selectTableName = filter_input(INPUT_POST, 'selectTableName');
        $selectColName = filter_input(INPUT_POST, 'selectColName');

        $parentTableName = filter_input(INPUT_POST, 'parentTableName');
        $parentColName = filter_input(INPUT_POST, 'parentColName');


        ### insert into table
        $newItem = R::dispense($selectTableName);
        $newItem->$selectColName = $name;
        $newItem->deleted = 0;

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

        echo $insertid;

        if ($parent == 1) {
            ### update selected in parent table
            $mydata = R::load($parentTableName, $parentId);
            $mydata->$parentColName = $insertid;
            R::store($mydata);
        }
    }

    public function editselect() {

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

        $selectTableName = filter_input(INPUT_POST, 'selectTableName');
        $this->smarty->assign('selectTableName', $selectTableName);

        ##   the value of attr id of the select
        $selectId = filter_input(INPUT_POST, 'selectId');
        $this->smarty->assign('selectId', $selectId);

        ## hospitals
        $allData = R::findall($selectTableName, ' deleted = 0 ');
        $this->smarty->assign('allData', $allData);
        $this->smarty->display('monitoring/editmodel.html');
    }

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

        try {
            $obj = R::load($tableName, $id);
            $obj->deleted = 1;
            R::store($obj);
            echo 1;
        } catch (Exception $e) {
            echo -1;
        }
    }

    public function addNewVisit() {

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

        //vars here
        $monitorSheetId = filter_input(INPUT_POST, 'monitorSheetId');
        $monitorSheet = R::load('mointoringsheet', $monitorSheetId);

        $date1 = new DateTime($this->today);
        $date2 = new DateTime($monitorSheet->monitordate);
        $interval = $date1->diff($date2);

        $days = 1 + $interval->days;
        $cycleDay = $days . '' . $this->ordinal($days);


        try {
            $obj = R::dispense('mointoringsheetvisits');
            $obj->mointoringsheetid = $monitorSheetId;
            $obj->visitdate = $this->today;
            $obj->cycleday = $cycleDay;
            $obj->hmg = '';
            $obj->endo = '';
            $obj->follicright = '';
            $obj->follicleft = '';
            $obj->e2 = '';
            $obj->sysdate = $this->today;
            $obj->deleted = 0;
            $obj->id = R::store($obj);
            $this->smarty->assign('data', $obj);
            $this->smarty->display('monitoring/newrow.html');
        } catch (Exception $e) {
            echo -1;
        }
    }

    public function getCycleDay() {

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

        //vars here
        $visitId = filter_input(INPUT_POST, 'id');
        $visitdate = filter_input(INPUT_POST, 'endDate');
        $monitordate = filter_input(INPUT_POST, 'startDate');

        try {

            $date1 = new DateTime(date("Y/m/d", strtotime($visitdate)));
            $date2 = new DateTime(date("Y/m/d", strtotime($monitordate)));
            $interval = $date1->diff($date2);

            //      $days = 1 + $interval->days;
            $days = $interval->days;
            $cycleDay = $days . '' . $this->ordinal($days);


            $result = array(
                "id" => $visitId,
                "cycleDay" => $cycleDay + 1
            );

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

    ##    This function will add st, nd, rd, th to the end of numbers

    private function ordinal($i) {
        $l = substr($i, -1);
        $s = substr($i, -2, -1);

        return (($l == 1 && $s == 1) || ($l == 2 && $s == 1) || ($l == 3 && $s == 1) || $l > 3 || $l == 0 ? 'th' : ($l == 3 ? 'rd' : ($l == 2 ? 'nd' : 'st')));
    }

    public function remarkSheet() {

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

        try {

            $monitorSheetId = filter_input(INPUT_POST, 'monitorSheetId');
            $monitorSheet = R::load('mointoringsheet', $monitorSheetId);


            $result = array(
                "id" => $monitorSheetId,
                "hcg" => $monitorSheet->hcg,
                "remarks" => $monitorSheet->remarks
            );

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

    public function trigSheet() {

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

        try {

            $monitorSheetId = filter_input(INPUT_POST, 'monitorSheetId');
            $monitorSheet = R::load('mointoringsheet', $monitorSheetId);
            $monitorSheet->status = 1;
            R::store($monitorSheet);

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

    public function trials() {

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


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

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

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


        ## load all completed monitoring sheets
        #
        $monitorSheets = R::findAll('mointoringsheet', 'status = 1 AND patientid = ? and deleted = 0 
                  order by monitordate desc ', [$patientid]);
        foreach ($monitorSheets as $data) {
            $data->monitordate = date("Y/m/d", strtotime($data->monitordate));
            ##
            #
            $procedure = R::load('mointoringsheetprocedure', $data->procedure);
            $data->procedure = $procedure->name;

            ##
            #
            $protocol = R::load('mointoringsheetprotocol', $data->protocol);
            $data->protocol = $protocol->name;
        }
        $this->smarty->assign('monitorSheets', $monitorSheets);



        //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('monitoring/trials.html');

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

    public function trialdetail() {

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


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

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

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

        $monitorSheetId = filter_input(INPUT_GET, 'id');

        $sql = 'select mointoringsheet.* ,mointoringsheetprocedure.name as procedureName
                    ,mointoringsheetprotocol.name as protocolName,mointoringsheetejac.name as ejacName
                    ,mointoringsheetpesa.name as pesaName,mointoringsheettese.name as teseName
                    ,mointoringsheetsryo.name as sryoName,mointoringsheethmg.name as hmgName
                    ,mointoringsheetagonist.name as agonistName,mointoringsheethcg.name as hcgName
                from  mointoringsheet
                LEFT JOIN mointoringsheetprocedure        ON mointoringsheetprocedure.id = mointoringsheet.procedure
                LEFT JOIN mointoringsheetprotocol         ON mointoringsheetprotocol.id = mointoringsheet.protocol
                LEFT JOIN mointoringsheetejac             ON mointoringsheetejac.id = mointoringsheet.ejac
                LEFT JOIN mointoringsheetpesa             ON mointoringsheetpesa.id = mointoringsheet.pesa
                LEFT JOIN mointoringsheettese             ON mointoringsheettese.id = mointoringsheet.tese
                LEFT JOIN mointoringsheetsryo             ON mointoringsheetsryo.id = mointoringsheet.sryo
                LEFT JOIN mointoringsheethmg              ON mointoringsheethmg.id = mointoringsheet.hmg
                LEFT JOIN mointoringsheetagonist          ON mointoringsheetagonist.id = mointoringsheet.agonist
                LEFT JOIN mointoringsheethcg              ON mointoringsheethcg.id = mointoringsheet.hcg
                where mointoringsheet.id = ' . $monitorSheetId;

        $monitorSheet = r::getRow($sql);
        if ($monitorSheet['monitordate'] == '0000-00-00' || is_null($monitorSheet['monitordate']) || $monitorSheet['monitordate'] == '') {
            $monitorSheet['monitordate'] = '';
        } else {
            $monitorSheet['monitordate'] = date("Y/m/d", strtotime($monitorSheet['monitordate']));
        }


        if ($monitorSheet['lmp'] == '0000-00-00' || is_null($monitorSheet['lmp']) || $monitorSheet['lmp'] == '') {
            $monitorSheet['lmp'] = '';
        } else {
            $monitorSheet['lmp'] = date("Y/m/d", strtotime($monitorSheet['lmp']));
        }
        $this->smarty->assign('monitorSheet', $monitorSheet);


        ## load all mointoring sheet visits
        #
        $visits = R::findAll('mointoringsheetvisits', ' deleted = 0 and mointoringsheetid =  ' . $monitorSheet['id'] . ' order by visitdate desc');
        foreach ($visits as $visit) {
            $date1 = new DateTime($visit->visitdate);
            $date2 = new DateTime($monitorSheet['monitordate']);
            $interval = $date1->diff($date2);

            //       $days = 1 + $interval->days;
            $days = $interval->days;
            $cycleDay = $days . '' . $this->ordinal($days);

            $visit->cycleday = $cycleDay;

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

            if ($visit->visitdate == '0000-00-00' || is_null($visit->visitdate) || $visit->visitdate == '') {
                $visit->visitdate = '';
            } else {
                $visit->visitdate = date("Y/m/d", strtotime($visit->visitdate));
            }
        }
        $this->smarty->assign('visits', $visits);


        //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('monitoring/archive.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']);

        $fdate = filter_input(INPUT_POST, 'fdate');
        $todate = filter_input(INPUT_POST, 'todate');





        $value = filter_input(INPUT_POST, 'value');
        $hvalue = filter_input(INPUT_POST, 'hvalue');
        $type = filter_input(INPUT_POST, 'type');
        $fdate = date('Y/m/d', strtotime($fdate));
        $todate = date('Y/m/d', strtotime($todate));

        $showDate = 1;




        if (empty($value) && empty($hvalue)) {
            $sq11 = 'select sum(balance) as detectionvalue, "إضافة للمبلغ  الاجمالى" as type  '
                    . ' , totalbalance.patientid , patients.wifename, patients.husdandname, patients.address'
                    . ' from totalbalance, patients '
                    . 'where totalbalance.deleted = 0 and totalbalance.patientid = patients.id '
                    . ' and   adddate  >= "' . $fdate . '" and adddate <= "' . $todate . '" group by patientid  ';

            $sq12 = ' union all ';

            $sq13 = 'select sum(detectionvalue) as detectionvalue , "دفع قسط" as type, visits.patientid , patients.wifename'
                    . ', patients.husdandname, patients.address '
                    . 'from visits, patients where visits.deleted = 0 and visits.patientid = patients.id '
                    . '  and visitdate >= "' . $fdate . '"  and visitdate <= "' . $todate . '" '
                    . 'and visits.detectionid = -99  group by patientid   ';



            $showDate = 0;
        } else {
            if (!empty($value)) {

                $sq11 = 'select balance as detectionvalue, "إضافة للمبلغ  الاجمالى" as type , adddate as date '
                        . ' , totalbalance.patientid , patients.wifename, patients.husdandname, patients.address'
                        . ' from totalbalance, patients '
                        . 'where totalbalance.deleted = 0 and totalbalance.patientid = patients.id '
                        . '  and totalbalance.patientid = ' . $value . ' '
                        . ' and   adddate  >= "' . $fdate . '" and adddate <= "' . $todate . '"  ';

                $sq12 = ' union all ';

                $sq13 = 'select detectionvalue, "دفع قسط" as type , visitdate as date , visits.patientid , patients.wifename '
                        . ', patients.husdandname, patients.address '
                        . 'from visits, patients where visits.deleted = 0 and visits.patientid = patients.id  '
                        . ' and visits.patientid = ' . $value . '  '
                        . '  and visitdate >= "' . $fdate . '"  and visitdate <= "' . $todate . '" '
                        . 'and visits.detectionid = -99   ';
            } else {

                $sq11 = 'select balance as detectionvalue, "إضافة للمبلغ  الاجمالى" as type , adddate as date'
                        . ' , totalbalance.patientid , patients.wifename, patients.husdandname, patients.address'
                        . ' from totalbalance, patients '
                        . 'where totalbalance.deleted = 0 and totalbalance.patientid = patients.id '
                        . '  and   patients.husdandname = "' . $hvalue . '"   '
                        . '  and   adddate  >= "' . $fdate . '" and adddate <= "' . $todate . '"  ';

                $sq12 = ' union  all ';

                $sq13 = 'select detectionvalue , "دفع قسط" as type , visitdate as date  , visits.patientid , patients.wifename '
                        . ', patients.husdandname, patients.address '
                        . 'from visits, patients where visits.deleted = 0 and visits.patientid = patients.id  '
                        . '  and   patients.husdandname = "' . $hvalue . '"   '
                        . '  and visitdate >= "' . $fdate . '"  and visitdate <= "' . $todate . '" '
                        . 'and visits.detectionid = -99   ';
            }
        }


        switch ($type) {
            case 1:   ## both
                $sq1 = $sq11 . ' ' . $sq12 . ' ' . $sq13;
                break;
            case 2:   ## add     "إضافة للمبلغ  الاجمالى"
                $sq1 = $sq11;
                break;
            case 3:   ## pay     "دفع قسط"
                $sq1 = $sq13;
                break;
        }




        $allData = R::getAll($sq1);
        $totalCost = 0;

        foreach ($allData as $data) {
            if ($data['type'] == "دفع قسط" && $type == 1) {
                $totalCost -= $data['detectionvalue'];
            } else {
                $totalCost += $data['detectionvalue'];
            }
        }


//        foreach ($allData as $data) {
//            $totalCost += $data['detectionvalue'];
//        }

        $this->smarty->assign('showDate', $showDate);
        $this->smarty->assign('fdate', $fdate);
        $this->smarty->assign('totalCost', $totalCost);
        $this->smarty->assign('allData', $allData);
        $this->smarty->display('reports/financialsearch.html');
    }

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

}
