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


        $infertility = R::findOne('infertility', ' patientid = ?', [$patientid]);

        if (count($infertility) > 0) {

        } else {
            $infertility = R::dispense('infertility');
            $infertility->patientid = $patientid;
            try {
                $id = R::store($infertility);
                $infertility->id = $id;
                ## diagnosis
                $diagnosis = R::dispense('infertilitydiagnosis');
                $diagnosis->infertid = $id;
                $diagnosis->date = $this->today;
                ## LMP
                $lmp = R::dispense('infertilitylmp');
                $lmp->infertid = $id;
                $lmp->date = $this->today;
                ## Gyna Exam
                $gyna = R::dispense('infertilitygyna');
                $gyna->infertid = $id;
                $gyna->date = $this->today;
                ## Investigation
                $invest = R::dispense('infertilityinvest');
                $invest->infertid = $id;
                $invest->date = $this->today;
                ## Notes
                $notes = R::dispense('infertilitynotes');
                $notes->infertid = $id;
                $notes->date = $this->today;

                try {
                    R::storeAll(array($diagnosis, $lmp, $gyna, $invest, $notes));
                } catch (Exception $e) {

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

        ## LMP
        $lmp = R::findAll('infertilitylmp', 'infertid = ? order by date desc', [$infertility->id]);
        foreach ($lmp as $record) {
            $record->date = date("d-m-Y", strtotime($record->date));
        }

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

        ## Gyna Exam
        $gyna = R::findAll('infertilitygyna', ' infertid = ? and del = 0 order by date desc', [$infertility->id]);
        foreach ($gyna as $record) {
            $record->date = date("d-m-Y", strtotime($record->date));
        }

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

        ## Notes
        $notes = R::findAll('infertilitynotes', ' infertid = ? and del = ? order by date desc', [$infertility->id, 0]);
        foreach ($notes as $record) {
            $record->date = date("d-m-Y", strtotime($record->date));
        }


        $this->smarty->assign('infertility', $infertility);
        $this->smarty->assign('notes', $notes);
        $this->smarty->assign('invest', $invest);
        $this->smarty->assign('gyna', $gyna);
        $this->smarty->assign('diagnosis', $diagnosis);
        $this->smarty->assign('lmp', $lmp);

        #################################################################### Heba : ## Drugs Data   ##############################################################################
        ## get id and distinct drugname
        $this->getprescription($patientid, date("Y-m-d"), 0);
        $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('infertility/add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    private function getprescription($patientId, $date, $preFor) {
        $PatientPresByDate = R::findall('infertilitydrugs', '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));
    }

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

        $infertid = filter_input(INPUT_POST, "infertilityId");
        $record = R::dispense('infertilitydiagnosis');
        $record->infertid = $infertid;
        $record->date = $this->today;
        try {
            $id = R::store($record);
            $record->id = $id;
            $record->date = date("d-m-Y", strtotime($record->date));
            $this->smarty->assign('record', $record);
            $this->smarty->assign('type', 'diadnosis');
            $this->smarty->display('infertility/newrow.html');
        } catch (Exception $e) {
            //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

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

        $infertid = filter_input(INPUT_POST, "infertilityId");
        $record = R::dispense('infertilitylmp');
        $record->infertid = $infertid;
        $record->date = $this->today;
        try {
            $id = R::store($record);
            $record->id = $id;
            $record->date = date("d-m-Y", strtotime($record->date));
            $this->smarty->assign('record', $record);
            $this->smarty->assign('type', 'lmp');
            $this->smarty->display('infertility/newrow.html');
        } catch (Exception $e) {
            //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

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

        $infertid = filter_input(INPUT_POST, "infertilityId");
        $record = R::dispense('infertilitygyna');
        $record->infertid = $infertid;
        $record->date = $this->today;
        try {
            $id = R::store($record);
            $record->id = $id;
            $record->date = date("d-m-Y", strtotime($record->date));
            $this->smarty->assign('record', $record);
            $this->smarty->assign('type', 'gyna');
            $this->smarty->display('infertility/newrow.html');
        } catch (Exception $e) {
            //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

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

        $infertid = filter_input(INPUT_POST, "infertilityId");
        $record = R::dispense('infertilityinvest');
        $record->infertid = $infertid;
        $record->date = $this->today;
        try {
            $id = R::store($record);
            $record->id = $id;
            $record->date = date("d-m-Y", strtotime($record->date));
            $this->smarty->assign('record', $record);
            $this->smarty->assign('type', 'invest');
            $this->smarty->display('infertility/newrow.html');
        } catch (Exception $e) {
            //header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

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

        $infertid = filter_input(INPUT_POST, "infertilityId");
        $record = R::dispense('infertilitynotes');
        $record->infertid = $infertid;
        $record->date = $this->today;
        try {
            $id = R::store($record);
            $record->id = $id;
            $record->date = date("d-m-Y", strtotime($record->date));
            $this->smarty->assign('record', $record);
            $this->smarty->assign('type', 'note');
            $this->smarty->display('infertility/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;
            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('infertilitydrugs', $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");
        ## show all prescription of patient
        if ($type == "show") {
            $dates = R::getAll('SELECT DISTINCT date  FROM infertilitydrugs 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('infertilitydrugs', 'deleted = ? and patientid = ? and date = ? and forhusband = ? ', [ 0, $patientId, $date['date'], 0]);
                $PatientPresByDateHusband = R::findall('infertilitydrugs', '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("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->display('infertility/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('infertility/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");
        $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('infertilitydrugs', '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');
    }

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

}
