<?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 = 'followup';
        $this->shcontrollname = 'followup';
        $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] = 'followup'; //controller name or tab name
        $active[1] = 'followup'; //controller name
// do name  // switch($do)
        switch ($acty) {
            case '':$active[2] = 'show';
                break;
            case 'show':$active[2] = 'show';
                break;
            default :$active[2] = 'show';
                break;
        }
        $this->active = $active;



//here will call all php pages
        require_once("_header.php");
        require_once("_patientdata.php");
        require_once("_sidebar.php");
        require_once("_leftsidebar.php");
        require_once("_footer.php");

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

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



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

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

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

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


        $followup = R::findOne('followup', ' patientid = ? and status = ?', [$patientid, 0]);

        if (count($followup) > 0) {

        } else {
            $followup = R::dispense('followup');
            $followup->patientid = $patientid;
            $followup->status = 0;
            $followup->lmp = $this->today;
            $followup->eed = date("Y-m-d", strtotime("+ 7 days", strtotime($followup->lmp . ' +9 months ')));
            $followup->ivf = date("Y-m-d", strtotime("- 7 days", strtotime($followup->lmp . ' +9 months ')));

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

                $followupvisit = R::dispense('followupvisit');
                $followupvisit->followid = $id;
                $followupvisit->date = $this->today;
                try {
                    R::store($followupvisit);
                } catch (Exception $e) {

                }
            } catch (Exception $e) {

            }
        }

        ## diagnosis
        $diagnosis = R::findAll('followupdiagnosis', ' followid = ? and del = ? order by date desc ', [$followup->id, 0]);
        foreach ($diagnosis as $record) {
            $record->date = date("d-m-Y", strtotime($record->date));
        }

        ## Examination
        $examination = R::findAll('followupexam', ' followid = ? and del = ? order by date desc', [$followup->id, 0]);
        foreach ($examination as $record) {
            $record->date = date("d-m-Y", strtotime($record->date));
        }

        ## Investigation
        $invest = R::findAll('followupinvest', ' followid = ? and del = ? order by date desc', [$followup->id, 0]);
        foreach ($invest as $record) {
            $record->date = date("d-m-Y", strtotime($record->date));
        }

        ## Visits
        $visits = R::findAll('followupvisit', ' followid = ? and del = ? order by date desc', [$followup->id, 0]);
        foreach ($visits as $record) {
            $date1 = new DateTime($record->date);
            $date2 = new DateTime($followup->lmp);
            $interval = $date1->diff($date2);
            $record->ga = round($interval->days / 7);
            $record->dateFlag = 0;
            //print_r($record->date < $followup->lmp);
            if ($record->date < $followup->lmp) {
                $record->dateFlag = 1;
            }
            $record->date = date("d-m-Y", strtotime($record->date));
        }


        $followup->lmp = date("d-m-Y", strtotime($followup->lmp));
        $followup->eed = date("d-m-Y", strtotime($followup->eed));
        $followup->ivf = date("d-m-Y", strtotime($followup->ivf));


        $this->smarty->assign('followup', $followup);
        $this->smarty->assign('diagnosis', $diagnosis);
        $this->smarty->assign('examination', $examination);
        $this->smarty->assign('invest', $invest);
        $this->smarty->assign('visits', $visits);


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

        ##################################################################################################################################################
        //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('followup/add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

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

    //------------------------------ ajax calls ------------------------------//
    public function newdiag() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $followId = filter_input(INPUT_POST, "followId");
        $record = R::dispense('followupdiagnosis');
        $record->followid = $followId;
        $record->date = $this->today;
        $record->del = 0;
        try {
            $id = R::store($record);
            $record->id = $id;
            $record->date = date("d-m-Y", strtotime($record->date));
            $this->smarty->assign('diag', $record);
            $this->smarty->assign('type', 'diadnosis');
            $this->smarty->display('followup/newrow.html');
        } catch (Exception $e) {
            //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

    public function newdiagsimple() {
        //check login
        autho::checkautho($this->hosturl);

        $record = R::dispense('simplediagnosis');
        $record->date = $this->today;
        $record->del = 0;
        try {
            $id = R::store($record);
            $record->id = $id;
            $record->date = date("d-m-Y", strtotime($record->date));
            $this->smarty->assign('diag', $record);
            $this->smarty->assign('type', 'diadnosisimple');
            $this->smarty->display('followup/newrow.html');
        } catch (Exception $e) {
            //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

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

        $followId = filter_input(INPUT_POST, "followId");
        $record = R::dispense('followupexam');
        $record->followid = $followId;
        $record->date = $this->today;
        $record->del = 0;
        try {
            $id = R::store($record);
            $record->id = $id;
            $record->date = date("d-m-Y", strtotime($record->date));
            $this->smarty->assign('diag', $record);
            $this->smarty->assign('type', 'exam');
            $this->smarty->display('followup/newrow.html');
        } catch (Exception $e) {
            //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

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

        $followId = filter_input(INPUT_POST, "followId");
        $followup = R::load('followup', $followId);

        $record = R::dispense('followupvisit');
        $record->followid = $followId;
        $record->date = $this->today;
        $record->del = 0;
        try {
            $id = R::store($record);
            $record->id = $id;

            $date1 = new DateTime($record->date);
            $date2 = new DateTime($followup->lmp);
            $interval = $date1->diff($date2);
            $record->ga = round($interval->days / 7);
            $record->dateFlag = 0;
            //print_r($record->date < $followup->lmp);
            if ($record->date < $followup->lmp) {
                $record->dateFlag = 1;
            }


            $record->date = date("d-m-Y", strtotime($record->date));
            $this->smarty->assign('diag', $record);
            $this->smarty->assign('type', 'visit');
            $this->smarty->display('followup/newrow.html');
        } catch (Exception $e) {
            //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

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

        $followId = filter_input(INPUT_POST, "followId");
        $record = R::dispense('followupinvest');
        $record->followid = $followId;
        $record->date = $this->today;
        $record->del = 0;
        try {
            $id = R::store($record);
            $record->id = $id;
            $record->date = date("d-m-Y", strtotime($record->date));
            $this->smarty->assign('diag', $record);
            $this->smarty->assign('type', 'inv');
            $this->smarty->display('followup/newrow.html');
        } catch (Exception $e) {
            //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

    public function update() {

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

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

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



        try {
            $record = R::load($tablename, $id);
            $record->$colname = $value;
            if ($colname == 'lmp') {
                $record->eed = date("Y-m-d", strtotime("+ 7 days", strtotime($record->$colname . ' +9 months ')));
                $record->ivf = date("Y-m-d", strtotime("- 7 days", strtotime($record->$colname . ' +9 months ')));
                $data = date("d-m-Y", strtotime($record->eed));
                $data .= ',' . date("d-m-Y", strtotime($record->ivf));
                echo $data;
            }
            R::store($record);
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname.'.php?ac=index' );
        } catch (Exception $e) {
            //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

    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 {
            $record = R::load($tablename, $id);
            $record->del = 1;
            R::store($record);

            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 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('followupdrugs', $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");
        $followId = filter_input(INPUT_POST, 'followid');  ## main Antenatal Id
        $archive = filter_input(INPUT_POST, "archive");
        $type = filter_input(INPUT_POST, "type");  ## show or edit
        $preFor = filter_input(INPUT_POST, "preFor");
        $countHusband = '';
        $countWife = '';

        ## show all prescription of patient
        if ($type == "show") {
            $dates = R::getAll('SELECT DISTINCT date  FROM followupdrugs WHERE deleted = ? and patientid = ? and followid = ?  order by date desc', [ 0, $patientId, $followId]);
            $i = 0;
            foreach ($dates as $date) {
                ## all prescription of certain patient
                $PatientPresByDateWife = R::findall('followupdrugs', 'deleted = ? and patientid = ? and date = ?  and followid = ? and forhusband = ? ', [ 0, $patientId, $date['date'], $followId, 0]);
                $PatientPresByDateHusband = R::findall('followupdrugs', 'deleted = ? and patientid = ? and date = ?  and followid = ? and forhusband = ? ', [ 0, $patientId, $date['date'], $followId, 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("d-m-Y", 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('followup/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("Y-m-d"), $preFor, $followId);
            $this->smarty->assign('type', "drugedit");
            $this->smarty->display('followup/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");
        $preFor = filter_input(INPUT_POST, "preFor");
        $followId = filter_input(INPUT_POST, 'followid');  ## main Antenatal Id

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



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


        ## all prescription of certain patient
        $PatientPresByDate = R::findall('followupdrugs', 'deleted = ? and patientid = ? and date = ? and forhusband = ? and followid = ? ', [ 0, $patientId, $date, $preFor, $followId]);
        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 archive() {

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




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

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

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



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

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

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

    public function pregdetail() {

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




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

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

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

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

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

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

        $followup = R::load('followup', $pregno);



        if (count($followup) > 0) {
            ## diagnosis
            $diagnosis = R::findAll('followupdiagnosis', ' followid = ? and del = ? order by date desc ', [$followup->id, 0]);
            foreach ($diagnosis as $record) {
                $record->date = date("d-m-Y", strtotime($record->date));
            }

            ## Examination
            $examination = R::findAll('followupexam', ' followid = ? and del = ? order by date desc', [$followup->id, 0]);
            foreach ($examination as $record) {
                $record->date = date("d-m-Y", strtotime($record->date));
            }


            ## Investigation
            $invest = R::findAll('followupinvest', ' followid = ? and del = ? order by date desc', [$followup->id, 0]);
            foreach ($invest as $record) {
                $record->date = date("d-m-Y", strtotime($record->date));
            }

            ## Visits
            $visits = R::findAll('followupvisit', ' followid = ? and del = ? order by date desc', [$followup->id, 0]);
            foreach ($visits as $record) {
                $date1 = new DateTime($record->date);
                $date2 = new DateTime($followup->lmp);
                $interval = $date1->diff($date2);
                $record->ga = round($interval->days / 7);
                $record->dateFlag = 0;
                //print_r($record->date < $followup->lmp);
                if ($record->date < $followup->lmp) {
                    $record->dateFlag = 1;
                }
                $record->date = date("d-m-Y", strtotime($record->date));
            }

            $followup->lmp = date("d-m-Y", strtotime($followup->lmp));
            $followup->eed = date("d-m-Y", strtotime($followup->eed));
            $followup->ivf = date("d-m-Y", strtotime($followup->ivf));

            $this->smarty->assign('followup', $followup);
            $this->smarty->assign('diagnosis', $diagnosis);
            $this->smarty->assign('examination', $examination);
            $this->smarty->assign('invest', $invest);
            $this->smarty->assign('visits', $visits);
            # get id and distinct drugname
            $this->getprescription($patientid, date("Y-m-d"), 0, $followup->id);
            $this->smarty->assign('presDate', date("d-m-Y"));
            $this->smarty->display('followup/pregdetail.html');
        }

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

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

}
