<?php

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

require_once("imp/_imp.php");

class Controllers {

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

    // 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 = 'ancsheet';
        $this->shcontrollname = 'Ancsheet';
        $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, $this->controllname, $this->shcontrollname, $acty);
        $bc->crumbs();
        $breadcrumbs = $bc->breadcrumbs;
        $smarty->assign('breadcrumbs', $breadcrumbs);

        require_once("../../_library/plugins/classupload/uploadfunctions.php");
        # here show the active page in menu
        // array called active[] with level of active element
        $active[0] = 'Ancsheet'; //controller name or tab name
        $active[1] = 'Ancsheet'; //controller name
        // do name  // switch($do)
        switch ($acty) {
            case '':$active[2] = 'menuadd';
                break;
            case 'show':$active[2] = 'menushow';
                break;
            default :$active[2] = 'menushow';
                break;
        }
        $this->active = $active;


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

    //here the frist page and
    //the frist action in this class
    public function index() {

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


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

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

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

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


        #################################################################### 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);

        //Save entering gyna
        $lastVisitData = R::findOne('lastvisit', 'patientid = ? order by id desc ', [$patientid]);

        $lastVisit = R::dispense('lastvisit');
        $lastVisit->patientid = $patientid;
        $lastVisit->control = $this->controllname;
        if ($lastVisitData->patientid == $patientid) {
            $lastVisit->id = $lastVisitData->id;
        }
        R::store($lastVisit);

        // ancsheet
        $ancsheet = R::findOne('ancsheet', 'patientid = ? and endpreg = 0', [$patientid]);

        if ($ancsheet) {
            $vowels = array("--", "**");
            $ancsheet->importantnotes = str_replace($vowels, '<br>', $ancsheet->importantnote);

            $id = $ancsheet->id;
            $this->smarty->assign('id', $id);
            $this->smarty->assign('ancsheet', $ancsheet);
            $investigations = R::findAll('investigations', 'ancsheetid = ?', [$id]);
            $this->smarty->assign('investigations', $investigations);
            $ovst = R::findAll('ovst', 'ancsheetid = ?', [$id]);
            $this->smarty->assign('ovst', $ovst);
            $ancnewvisit = R::findAll('ancnewvisit', 'ancsheetid = ?', [$id]);

            foreach ($ancnewvisit as $ancnewvsit) {
                $diff = round(abs(strtotime($ancnewvsit->newvisitdate) - strtotime($ancsheet->sheetlmp)) / 86400);
                $ceil = intval($diff / 7);
                $ancnewvsit->newvisitw = intval($diff / 7) . 'W ' . ($diff % 7) . 'D';
                R::store($ancnewvsit);
            }
            $this->smarty->assign('ancnewvisit', $ancnewvisit);
            $registeration = R::findAll('registeration', 'ancsheetid = ?', [$id]);
            $this->smarty->assign('registeration', $registeration);
        } else {

            $ancsheet = R::dispense('ancsheet');
            $ancsheet->patientid = $patientid;
            $ancsheet->endpreg = 0;
            $id = R::store($ancsheet);
            $this->smarty->assign('id', $id);
        }

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

        $infertilitysheet = R::findOne('infertilitysheet', 'patientid = ?', [$patientid]);
        if ($infertilitysheet) {
            $infertilitysheetid = $infertilitysheet->id;
            $this->smarty->assign('infertilitysheetid', $infertilitysheetid);
            $this->smarty->assign('infertilitysheet', $infertilitysheet);
            $awifep = R::findAll('awifep', 'infertilitysheetid = ?', [$infertilitysheetid]);
            $this->smarty->assign('awifep', $awifep);
            $infertilityother = R::findAll('infertilityother', 'infertilitysheetid = ?', [$infertilitysheetid]);
            $this->smarty->assign('infertilityother', $infertilityother);
            $wifeepc = R::findAll('wifeepc', 'infertilitysheetid = ?', [$infertilitysheetid]);
            $this->smarty->assign('wifeepc', $wifeepc);
            $operations = R::findAll('operations', 'infertilitysheetid = ?', [$infertilitysheetid]);
            $this->smarty->assign('operations', $operations);
        } else {
            $infertilitysheet = R::dispense('infertilitysheet');
            $infertilitysheet->patientid = $patientid;
            $infertilitysheetid = R::store($infertilitysheet);
            $this->smarty->assign('infertilitysheetid', $infertilitysheetid);
        }

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


//        $gynasheet = R::findOne('gynasheet', 'patientid = ?', [$patientid]);
//
//        if ($gynasheet) {
//            $gynasheetid = $gynasheet->id;
//            $this->smarty->assign('gynasheetid', $gynasheetid);
//            $this->smarty->assign('gynasheet', $gynasheet);
//            // $newvisitg = R::findAll('newvisitg', 'gynasheetid = ?', [$gynasheetid]);
//            // $this->smarty->assign('newvisitg', $newvisitg);
//        } else {
//            $gynasheet = R::dispense('gynasheet');
//            $gynasheet->patientid = $patientid;
//            $gynasheetid = R::store($gynasheet);
//            $this->smarty->assign('gynasheetid', $gynasheetid);
//        }
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        patientdata::patientdatashow($this->smarty, $this->hosturl);
        $this->smarty->display('ancsheet/add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

// public function Add() {
//         $table = filter_input(INPUT_POST, 'table');
//         $id = filter_input(INPUT_POST, 'id');
//         $name = filter_input(INPUT_POST, 'name');
//         $value = filter_input(INPUT_POST, 'value');
//         $tableadd = R::load($table, $id);
//         $tableadd->$name = "GT4";
//         R::store($tableadd);
//     }

    public function Add() {


        $table = filter_input(INPUT_POST, 'table');
        $id = filter_input(INPUT_POST, 'id');
        $name = filter_input(INPUT_POST, 'name');
        $value = filter_input(INPUT_POST, 'value');

        try {
            $tableadd = R::exec("update $table set $name = '" . $value . "' where id = $id");
            //echo $tableadd;
        } catch (Exception $e) {
            //echo $e->getMessage();
        }
    }

    public function eedlmp() {

        $table = filter_input(INPUT_POST, 'table');
        $id = filter_input(INPUT_POST, 'id');
        $name = filter_input(INPUT_POST, 'name');
        $value = filter_input(INPUT_POST, 'value');

        $tableadd = R::load($table, $id);
        if ($name == "sheetlmp") {
            $tableadd->sheetlmp = $value;
            $tableadd->sheetedd = date("Y/m/d", strtotime("+ 7 days", strtotime($tableadd->$name . ' +9 months ')));
            $data = date("Y/m/d", strtotime($tableadd->sheetedd));
            $data .= ',' . date("Y/m/d", strtotime($tableadd->sheetlmp));
        } else {
            $tableadd->sheetedd = $value;
            $tableadd->sheetlmp = date("Y/m/d", strtotime("- 7 days", strtotime($tableadd->$name . ' -9 months ')));
            $data = date("Y/m/d", strtotime($tableadd->sheetedd));
            $data .= ',' . date("Y/m/d", strtotime($tableadd->sheetlmp));
        }
        R::store($tableadd);
        echo $data;
    }

    public function append() {


        $tablename = filter_input(INPUT_POST, 'tablename');
        $tablep = filter_input(INPUT_POST, 'tablep');
        $id = filter_input(INPUT_POST, 'id');
        $today = date("Y/m/d");
        $tablenameappend = R::dispense($tablename);
        $tablenameappend->$tablep = $id;
        if ($tablename == "ancnewvisit") {
            $ancsheet = R::load("ancsheet", $id);
            if ($ancsheet->sheetlmp) {
                $diff = round(abs(strtotime($today) - strtotime($ancsheet->sheetlmp)) / 86400);
            } else {
                $diff = round(abs(strtotime($today) - strtotime($today)) / 86400);
            }

            $tablenameappend->newvisitdate = $today;
            $ceil = intval($diff / 7);
            $tablenameappend->newvisitw = intval($diff / 7) . 'W ' . ($diff % 7) . 'D';
            $this->smarty->assign('newvisitw', $tablenameappend->newvisitw);
            if ($today < $ancsheet->sheetlmp) {
                $this->smarty->assign('todayc', 1);
            }
        }
        $tablenameappendid = R::store($tablenameappend);
        $cregisteration = R::count('registeration', 'ancsheetid = ?', [$id]);
        $this->smarty->assign('cregisteration', $cregisteration);

        $ancsheet = R::findOne('ancsheet', 'id = ?', [$id]);
        $infertilitysheet = R::findOne('infertilitysheet', 'patientid = ?', [$ancsheet->patientid]);
        $awifep = R::findAll('awifep', 'infertilitysheetid = ?', [$infertilitysheet->id]);
        $this->smarty->assign('awifep', $awifep);

        $this->smarty->assign('today', date("Y/m/d"));
        $this->smarty->assign('tablename', $tablename);
        $this->smarty->assign('id', $tablenameappendid);
        $this->smarty->display('ancsheet/append.html');
    }

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


        $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 getselectajax() {
        //check login
        autho::checkautho($this->hosturl);

        $newterm = filter_input(INPUT_POST, 'newterm');
        $celtable = filter_input(INPUT_POST, 'celtable');

        $tableadd = R::dispense($celtable);
        $tableadd->title = $newterm;
        $tableadd->del = null;
        $inserted = R::store($tableadd);
        echo $inserted;
    }

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

        $id = filter_input(INPUT_POST, 'id');
        $tablep = filter_input(INPUT_POST, 'tablep');
        $celtable = filter_input(INPUT_POST, 'celtable');
        $name = filter_input(INPUT_POST, 'name');
        $selid = filter_input(INPUT_POST, 'selid');
        $kind = filter_input(INPUT_POST, 'kind');
        $tablep = R::load($tablep, $selid);
        $celtable = R::findAll($celtable, 'del is null');
        $this->smarty->assign('tablep', $tablep);
        $this->smarty->assign('arrays', explode(',', $tablep->$name));
        $this->smarty->assign('celtable', $celtable);
        $this->smarty->assign('name', $name);
        $this->smarty->assign('id', $id);
        $this->smarty->assign('kind', $kind);
        $this->smarty->assign('selid', $selid);
        $this->smarty->display('ancsheet/select.html');
    }

    public function endpreg() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize

        $patientid = filter_input(INPUT_POST, "patientid");
        $infertilitysheet = R::findOne('infertilitysheet', 'patientid = ?', [$patientid]);
        $ancsheet = R::findOne('ancsheet', 'patientid = ? and endpreg = 0 ', [$patientid]);
        try {
            $ancsheet->endpreg = 1;
            $ancsheet->obstgn = $infertilitysheet->obstg;
            $ancsheet->obstpn = $infertilitysheet->obstp;
            $ancsheet->obstepc = $infertilitysheet->obstepc;
            $ancsheet->historytoday = date("Y-m-d H:i:s");
            R::store($ancsheet);
            echo 1;
        } catch (Exception $e) {
            echo 0;
        }
    }

    public function archive() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize


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

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

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

        // ancsheet
        $ancsheet = R::findAll('ancsheet', 'patientid = ? and endpreg = 1 order by id desc', [$patientid]);
        $this->smarty->assign('ancsheet', $ancsheet);



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

    public function historys() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize


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

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

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

        // ancsheet
        $ancsheet = R::findOne('ancsheet', 'id = ?', [$ancsheetid]);
        $vowels = array("--", "**");
        $ancsheet->importantnotes = str_replace($vowels, '<br>', $ancsheet->importantnote);

        $id = $ancsheet->id;
        $this->smarty->assign('id', $id);
        $this->smarty->assign('ancsheet', $ancsheet);
        $investigations = R::findAll('investigations', 'ancsheetid = ?', [$id]);
        $this->smarty->assign('investigations', $investigations);
        $ovst = R::findAll('ovst', 'ancsheetid = ?', [$id]);
        $this->smarty->assign('ovst', $ovst);
        $ancnewvisit = R::findAll('ancnewvisit', 'ancsheetid = ?', [$id]);
        $this->smarty->assign('ancnewvisit', $ancnewvisit);

        $infertilitysheet = R::findOne('infertilitysheet', 'patientid = ?', [$patientid]);
        if ($infertilitysheet) {
            $infertilitysheetid = $infertilitysheet->id;
            $this->smarty->assign('infertilitysheetid', $infertilitysheetid);
            $this->smarty->assign('infertilitysheet', $infertilitysheet);
            $wifep = R::findAll('wifep', 'infertilitysheetid = ?', [$infertilitysheetid]);
            $this->smarty->assign('wifep', $wifep);
            $wifeepc = R::findAll('wifeepc', 'infertilitysheetid = ?', [$infertilitysheetid]);
            $this->smarty->assign('wifeepc', $wifeepc);
        } else {
            $infertilitysheet = R::dispense('infertilitysheet');
            $infertilitysheet->patientid = $patientid;
            $infertilitysheetid = R::store($infertilitysheet);
            $this->smarty->assign('infertilitysheetid', $infertilitysheetid);
        }


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

        if ($gynasheet) {
            $gynasheetid = $gynasheet->id;
            $this->smarty->assign('gynasheetid', $gynasheetid);
            $this->smarty->assign('gynasheet', $gynasheet);
            // $newvisitg = R::findAll('newvisitg', 'gynasheetid = ?', [$gynasheetid]);
            // $this->smarty->assign('newvisitg', $newvisitg);
        } else {
            $gynasheet = R::dispense('gynasheet');
            $gynasheet->patientid = $patientid;
            $gynasheetid = R::store($gynasheet);
            $this->smarty->assign('gynasheetid', $gynasheetid);
        }


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

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

        $celtable = filter_input(INPUT_POST, 'celtable');
        $allceltable = R::findAll($celtable, 'del is null');
        $count = R::count($celtable, 'del is null');
        if ($count < 1) {
            echo "0";
            exit();
        }
        $this->smarty->assign('celtable', $celtable);
        $this->smarty->assign('allceltable', $allceltable);
        $this->smarty->display('ancsheet/delselect.html');
    }

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

        $table = filter_input(INPUT_POST, 'table');
        $id = filter_input(INPUT_POST, 'id');
        $celtables = R::load($table, $id);
        $celtables->del = 1;
        try {
            $inserted = R::store($celtables);
            echo $inserted;
        } catch (Exception $e) {
            echo 0;
        }
    }

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

        $table = filter_input(INPUT_POST, 'table');
        $celtables = R::dispense($table);
        $celtables->title = $newterm;
        $inserted = R::store($celtables);
        $out = '<tr id="remove_' . $inserted . '">
                  <td style="width: 100%">
                    <input class="form-control "  type="text"  name="title" data-id="' . $inserted . '"  data-table="' . $table . '" value="" >
                  </td>
                  <td>
                     <a href="#" style="width: 100%" class="btn red fleft deleteselect" data-table="' . $table . '" data-id="' . $inserted . '">
                     <i class="fa fa-times" ></i>
                     </a>
                  </td>
               </tr>';
        echo $out;
    }

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

        $table = filter_input(INPUT_POST, 'tablep');
        $id = filter_input(INPUT_POST, 'id');
        $celtables = R::load($table, $id);
        try {
            R::trash($celtables);
            echo 1;
        } catch (Exception $e) {
            echo 0;
        }
    }

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


        if ($tablename == 'ancsheetdrugs') {
            $this->updatedrugs($id, $tablename, $colname, $value);
        } else {
            $gyna_obj = R::load($tablename, $id);
            if ($vdateFlag == true) {
                $value = date("Y/m/d", strtotime($value));
            }

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

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

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

    private function updatedrugs($id, $tablename, $colname, $value) {
        $obj = R::load($tablename, $id);
        if ($colname == 'drugid') {
            if ($value != '') {
                $drug = R::load("drugs", $value);
                $obj->drugname = $drug->drugname;
            }
        }

        $obj->$colname = $value;
        try {
            R::store($obj);
        } 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");
        $mainAntenatalId = filter_input(INPUT_POST, "mainAntenatalId");
        $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 ancsheetdrugs WHERE deleted = ? and patientid = ? and ancsheetid = ?  order by date desc', [0, $patientId, $mainAntenatalId]);
            $i = 0;
            foreach ($dates as $date) {
                ## all prescription of certain patient
                $PatientPresByDateWife = R::findall('ancsheetdrugs', 'deleted = ? and patientid = ? and date = ?  and ancsheetid = ? and forhusband = ? ', [0, $patientId, $date['date'], $mainAntenatalId, 0]);
                $PatientPresByDateHusband = R::findall('ancsheetdrugs', 'deleted = ? and patientid = ? and date = ?  and ancsheetid = ? and forhusband = ? ', [0, $patientId, $date['date'], $mainAntenatalId, 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('ancsheet/showPrescriptions.html');
        } ## show  prescription of patient with determined date to edit it
        else if ($type == "edit") {
            $date = filter_input(INPUT_POST, "preDate");
            $date = date($date, strtotime($date));
            $this->getprescription($patientId, $date, $preFor, $mainAntenatalId);
            $this->smarty->assign('type', "drugedit");
            $this->smarty->display('ancsheet/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");
        $mainAntenatalId = filter_input(INPUT_POST, 'mainAntenatalId');  ## 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);
        if (isset($printDate) && !empty($printDate)) {
            $printDate = date("Y/m/d", strtotime($printDate));
            $this->smarty->assign('printDate', $printDate);
        } else {
            $this->smarty->assign('printDate', $date);
        }

        $date = date("Y/m/d", strtotime($date));

        ## all prescription of certain patient
        $PatientPresByDate = R::findall('ancsheetdrugs', 'deleted = ? and patientid = ? and date = ? and ancsheetid = ? and forhusband = ? ', [0, $patientId, $date, $mainAntenatalId, $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);

        if (isset($printDate) && !empty($printDate)) {
            $this->smarty->assign('printDate', $printDate);
        } else {
            $this->smarty->assign('printDate', $date);
        }



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

    public function addprescription() {       ## add prescription to patient
        //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('ancsheetdrugs', $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 addinvestigation() {       ## add prescription to 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);

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

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

        $patientId = filter_input(INPUT_POST, 'patientId');
        $ancsheetid = filter_input(INPUT_POST, 'mainId');  ## main Antenatal Id
        $investsList = $_POST['invCheck'];

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


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

                array_push($invests, $antInvest);
            }

            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('date', date("Y/m/d", strtotime($printDate)));
                $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");
        $ancsheetid = filter_input(INPUT_POST, "mainAntenatalId");
        $archive = filter_input(INPUT_POST, "archive");

        // R::debug(true, 2);
        ## show all investigations of patient
        $dates = R::getAll('SELECT DISTINCT date  FROM ancsheetinvest WHERE deleted = ? 
                and patientid = ? and ancsheetid = ?  order by date desc', [0, $patientId, $ancsheetid]);
        $countHusband = array();
        $countWife = array();

        $i = 0;
        foreach ($dates as $date) {
            ## all invs of certain patient
            $PatientInvByDateHusband = R::findall('ancsheetinvest', 'deleted = ? and patientid = ? and date = ? 
                    and ancsheetid = ? and forhusband = ? ', [0, $patientId, $date['date'], $ancsheetid, 1]);
            $PatientInvByDateWife = R::findall('ancsheetinvest', 'deleted = ? and patientid = ? and date = ? 
                    and ancsheetid = ? and forhusband = ? ', [0, $patientId, $date['date'], $ancsheetid, 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('ancsheet/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");
        $ancsheetid = filter_input(INPUT_POST, 'mainAntenatalId');  ## main Antenatal Id
        $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('ancsheetinvest', 'deleted = ? and patientid = ? and date = ? 
                    and ancsheetid = ? and forhusband = ?', [0, $patientId, $date, $ancsheetid, 0]);
        } elseif ($dataFor == 'husband') {
            $PatientInvByDate = R::findall('ancsheetinvest', 'deleted = ? and patientid = ? and date = ? 
                    and ancsheetid = ? and forhusband = ? ', [0, $patientId, $date, $ancsheetid, 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');
    }

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

}
