<?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 = 'Menu control';
        $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] = 'managment'; //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);





        $ProgramesettingData = R::findone('programesetting');
        $this->smarty->assign('ProgramesettingData', $ProgramesettingData);
// all drugs will show in selectbox in add new drugs

        $allgyna = R::findall('gyna', 'conditions = ? and patientid = ? ORDER BY gynadate DESC ', [0, $patientid]);
        $iDsArray = '';
        $selectArray = '';
        foreach ($allgyna as $myGyna) {
            ## merge complain  and  diagnosis
            if (!empty($myGyna->diagnosistxt) && $myGyna->diagnosistxt != '') {
                $myGyna->complaint .= '-';
                $myGyna->complaint .= $myGyna->diagnosistxt;
                $myGyna->diagnosistxt = '';
                R::store($myGyna);
            }

            ##########################################################################
            $iDsArray .= $myGyna->id . ',';

            $myGyna->gynadate = date("Y/m/d", strtotime($myGyna->gynadate));



            if (!($myGyna->gynalmp == '0000-00-00' || is_null($myGyna->gynalmp))) {
                $myGyna->gynalmp = date("Y/m/d", strtotime($myGyna->gynalmp));
            }


            $selectArray = explode(',', $myGyna->diagnosisid);
            $myGyna->select = $selectArray;
            $compSelectArray = explode(',', $myGyna->complaintid);
            $myGyna->compselect = $compSelectArray;
        }
        $iDsArray = rtrim($iDsArray, ',');
        $this->smarty->assign('iDsArray', $iDsArray);
        $this->smarty->assign('allgyna', $allgyna);




        $alldiagnosis = R::findall('diagnosis', 'conditions = 0 order by name');
        $this->smarty->assign('alldiagnosis', $alldiagnosis);
        $allcomplaint = R::findall('complaint', 'conditions = 0 order by name');
        $this->smarty->assign('allcomplaint', $allcomplaint);

        #################################################################### Heba : ## ultra sound data  ##############################################################################
        $programSetting = R::getAll('SELECT  ultrasound FROM programesetting limit 1');
        $ultrasoundForm = $programSetting[0]['ultrasound'];     ## 0 for simple form  , 1 for complete form
        $this->smarty->assign('ultrasoundForm', $ultrasoundForm);

        $allgynaUS = R::findall('gynaus', 'deleted = ? and patientid = ? ORDER BY date DESC ', [0, $patientid]);
        foreach ($allgynaUS as $us) {
            $us->date = date("Y/m/d", strtotime($us->date));

            $doctordata = R::getRow('SELECT user_name FROM awusers WHERE user_id = ? ', [$us->doctorid]);
            $us->doctorname = $doctordata['user_name'];
        }
        $this->smarty->assign('allgynaUS', $allgynaUS);

        #################################################################### Heba : ## Drugs Data   ##############################################################################
        ## get id and distinct drugname
        $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);

        //Save entering gyna
        $lastVisitData = R::findOne('lastvisit', 'patientid', [$patientid]);

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


        $main_Obj = R::findOne('maingyna', 'patientid = ?', [$patientid]);
        $main_Obj_count = R::count('maingyna', 'patientid = ?', [$patientid]);
        if ($main_Obj_count < 1) {
            $mainObj = R::dispense('maingyna');
            $mainObj->patientid = $patientid;
            $mainObj->create_date = date('Y-m-d H:i:s'); //$this->today;
            $mainObj->notes = '';
            R::store($mainObj);

            $main_Obj = R::findOne('maingyna', 'patientid = ?', [$patientid]);
        }
        $this->smarty->assign('main_Obj', $main_Obj);

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

        if ($ancsheet) {
            $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);
        } else {
            $ancsheet = R::dispense('ancsheet');
            $ancsheet->patientid = $patientid;
            $ancsheet->endpreg = 0;
            $id = R::store($ancsheet);
            $this->smarty->assign('id', $id);
        }
        $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);
            $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/add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function Add() {
        $tableName = filter_input(INPUT_POST, 'table');
        $id = filter_input(INPUT_POST, 'id');
        $colName = filter_input(INPUT_POST, 'name');
        $value = filter_input(INPUT_POST, 'value');

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

    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);
            $diff = strtotime($today, 0) - strtotime($ancsheet->sheetlmp, 0);
            $tablenameappend->newvisitdate = $today;
            $ceil = ceil($diff / 604800);
            $tablenameappend->newvisitw = abs($ceil);
            $this->smarty->assign('newvisitw', abs($ceil));
            if ($today < $ancsheet->sheetlmp) {
                $this->smarty->assign('todayc', 1);
            }
        }
        $tablenameappendid = R::store($tablenameappend);

        $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) {
        $PatientPresByDate = R::findall('gynadrugs', '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 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");
        $ancsheet = R::findOne('ancsheet', 'patientid = ? and endpreg = 0 ', [$patientid]);

        try {
            $ancsheet->endpreg = 1;
            $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]);

        $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;
        }
    }

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

}
