<?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 = 'raysdept';
        $this->shcontrollname = 'raysdept';
        $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);

        require_once("../../_library/plugins/classupload/uploadfunctions.php");

# here show the active page in menu
// array called active[] with level of active element
        $active[0] = 'raysdept'; //controller name or tab name
        $active[1] = 'raysdept'; //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;

        R::ext('xdispense', function ($type) {
            return R::getRedBean()->dispense($type);
        });

        require_once("invsdept_common.php"); //general functions
//here will call all php pages
        require_once("_header.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']);

        #################################################################### Heba : ## get all rays category ##############################################################################
        $sql = ' select distinct raysresults.visitid , visits.visitdate as visitDate 
            , patients.wifename as  wifeName ,   patients.husdandname as  husbandName
            , visits.for_husband      ,   patients_childs.gender  as child_gender 
            ,   visits.child ,   patients_childs.child_name 
                    from    raysresults
                     join     visits                                               on visits.id  = raysresults.visitid
                      join       patients                                           on patients.id  = visits.patientid  
                    left  join       patients_childs                       on patients_childs.id  = visits.child  
                  where  visits.visitdate  between "' . $this->today . '"  AND  "' . $this->today . '"  
                and  raysresults.deleted = 0   and  visits.deleted = 0
                and raysresults.status = 0  order by visits.visitdate desc , visits.id asc ';

        $visits = R::getAll($sql);

        $this->smarty->assign('requests', $visits);
        $this->smarty->assign('today', $this->today);
        ################################################################################################################################################################################
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('rays/show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

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

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

        $visitId = filter_input(INPUT_GET, "id");

        $sql = ' select  patients.wifename as  wifeName ,   patients.husdandname as  husbandName 
            , visits.for_husband    ,   patients.statusno  as statusNo
            ,   patients_childs.gender  as child_gender   ,   visits.child ,   patients_childs.child_name 
                         from     visits                                               
                          join       patients                                           on patients.id  = visits.patientid  
                          left  join       patients_childs                       on patients_childs.id  = visits.child
                        where   visits.id =   ' . $visitId . '      ';
        $patient = R::getRow($sql);

        if ($patient['for_husband'] == 1) {
            $patientName = $patient['husbandName'];
        } else if ($patient['for_husband'] == 2) {
            if (is_null($patient['child_name']) || $patient['child_name'] == '') {
                if ($patient['child_gender'] == 1) {
                    $patientName = 'الطفل / ' . $patient['wifeName'];
                } else {
                    $patientName = 'الطفلة / ' . $patient['wifeName'];
                }
            } else {
                $patientName = $patient['child_name'] . '  /  ' . $patient['wifeName'];
            }
        } else {
            $patientName = $patient['wifeName'];
        }

        $invs = R::findall('raysresults', 'deleted = ? and visitid = ? ', [0, $visitId]);

        foreach ($invs as $in) {
            $ray = R::load('rays', $in->rayid);
            $in->invname = $ray->name;
            $in->tableName = 'raysresults';

            $imgs = R::findall('raysresults_img', 'deleted = ? and raysresults_id = ? ', [0, $in->id]);
            $in->imgs = $imgs;
        }

        $patientD = $patientName . ' - ' . $patient['statusNo'];
        $this->smarty->assign('invsCount', count($invs));
        $this->smarty->assign('invs', $invs);
        $this->smarty->assign('visitId', $visitId);
        $this->smarty->assign('patientD', $patientD);
        $this->smarty->assign('rayPatientName', $patientName);
        $this->smarty->assign('statusNo', $patient['statusNo']);
        ################################################################################################################################################################################
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('rays/rays.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function delimg() {

        autho::checkautho($this->hosturl);

        $id = filter_input(INPUT_POST, "id");
        $tableName = filter_input(INPUT_POST, "tableName");
        $folder = filter_input(INPUT_POST, "folder");
        $colName = filter_input(INPUT_POST, "name");

        $img = R::load($tableName, $id);
        $img->deleted = 1;
        R::store($img);

        $name = $img->$colName;
        try {

            if (file_exists('../../upload/' . $folder . '/' . $name)) {
                //echo $imageNewName;
                chmod('../../upload/' . $folder . '/' . $name, 0777);
                unlink('../../upload/' . $folder . '/' . $name);
            }

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

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

        try {
            $obj = R::load($tablename, $id);
            $obj->$colname = $value;

            if ($colname == "rayresult") {
                $obj->date = date('Y-m-d');      ## result update date
                if ($obj->raytype == 1) {
                    $obj2 = R::load($obj->internaltable, $obj->internalrequestid);
                    $obj2->rayresult = $value;
                    R::store($obj2);
                }
                $obj->doctorid = $_SESSION['user_id'];
            }

            R::store($obj);
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname.'.php?ac=index' );
        } 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']);

        $this->smarty->assign('fordepartment', 5);

        $found = 0;
        $this->smarty->assign('found', $found);

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

        $allPatients = R::findAll('patients', 'deleted = ? and done = ?', [0, 1]);
        $this->smarty->assign('allPatients', $allPatients);

        $allDetections = R::findAll('detections', 'del = 0');
        $this->smarty->assign('allDetections', $allDetections);

        #################################################################### Heba : ## rays data  ##############################################################################

        $allRayCats1 = R::findall('rayscats', 'deleted = ? and displayorder in (1 , 2) order by displayorder ', [0]);
        foreach ($allRayCats1 as $cat) {
            $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->rays = $rays;
        }

        $allRayCats2 = R::findall('rayscats', 'deleted = ? and displayorder = 3 order by displayorder ', [0]);
        foreach ($allRayCats2 as $cat) {
            $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->rays = $rays;
        }

        $allRayCats3 = R::findall('rayscats', 'deleted = ? and displayorder in (4 , 5) order by displayorder ', [0]);
        foreach ($allRayCats3 as $cat) {
            $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->rays = $rays;
        }

        $allRayCats4 = R::findall('rayscats', 'deleted = ? and displayorder  between 6 and  11 order by displayorder ', [0]);
        foreach ($allRayCats4 as $cat) {
            $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->rays = $rays;
        }

        $allRayCats5 = R::findall('rayscats', 'deleted = ? and displayorder > 11 order by displayorder ', [0]);
        foreach ($allRayCats5 as $cat) {
            $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->rays = $rays;
        }

        $otherRays = R::findall('rayscats', 'deleted = ? and displayorder = ?  order by displayorder ', [0, 0]);
        foreach ($otherRays as $cat) {
            $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->rays = $rays;
        }


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

        $this->smarty->assign('favoritesRays', $favoritesRays);
        $this->smarty->assign('allRayCats1', $allRayCats1);
        $this->smarty->assign('allRayCats2', $allRayCats2);
        $this->smarty->assign('allRayCats3', $allRayCats3);
        $this->smarty->assign('allRayCats4', $allRayCats4);
        $this->smarty->assign('allRayCats5', $allRayCats5);
        $this->smarty->assign('otherRays', $otherRays);

        ################################################################################################################################################################################
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('rays/newvisit.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function savenewvisit() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //prepar wife data insert
        $patientID = filter_input(INPUT_POST, 'patientid');
        $visitDate = filter_input(INPUT_POST, 'visitdate');
        $detectionID = filter_input(INPUT_POST, 'detectionid');
        $detectionValue = filter_input(INPUT_POST, 'detectionvalue');
        $for_department = filter_input(INPUT_POST, 'fordepartment');
        $for_doctor = filter_input(INPUT_POST, 'for_doctor');
        $for_husband = filter_input(INPUT_POST, 'for_husband');

        $new_date = date('Y/m/d', strtotime($visitDate));

        //check if there
        $patientthere = R::count('visits', 'patientid = ? and visitdate = ? and deleted = 0', [$patientID, $new_date]);
        $insertnew = 1;
        if ($patientthere > 0) {
            //$insertnew = 0;
        }

        $insertDataVisits = R::dispense('visits');
        $insertDataVisits->patientid = $patientID;
        $insertDataVisits->visitdate = $new_date;
        $insertDataVisits->detectionid = $detectionID;
        $insertDataVisits->detectionvalue = $detectionValue;
        $insertDataVisits->for_department = $for_department;
        $insertDataVisits->for_doctor = $for_doctor;
        $insertDataVisits->for_husband = $for_husband;
        try {
            if ($insertnew == 1) {
                $insert = R::store($insertDataVisits);
                if ($for_department == 5 || $for_department == 12) {
                    $this->sendToDept($patientID, $for_department, $insert, $for_husband);
                }
            } else {
                $insert = 0;
            }
            header('Location:' . $this->hosturl . '/controllers/raysdept.php');
        } catch (Exception $ex) {
            echo -1;
        }
    }

    private function sendToDept($patientId, $for_department, $visitId, $for_husband) {
        $invType = filter_input(INPUT_POST, 'invType');
        $itr = filter_input(INPUT_POST, 'itr');
        for ($i = 1; $i <= $itr; $i++) {
            switch ($for_department) {
                case 5:
                    $obj = R::dispense('raysresults');
                    $obj->rayid = filter_input(INPUT_POST, 'selectedId' . $i);
                    $obj->raytype = $invType;
                    break;
                case 12:
                    $obj = R::dispense('investigationresults');
                    $obj->investid = filter_input(INPUT_POST, 'selectedId' . $i);
                    $obj->invtype = $invType;
                    break;
            }

            if ($invType == 1) {
                $obj->internalrequestid = filter_input(INPUT_POST, 'reqId' . $i);
                $obj->internaltable = filter_input(INPUT_POST, 'reqTable' . $i);
            }

            $obj->doctorid = 0;
            $obj->deleted = 0;
            $obj->visitid = $visitId;
            $obj->patientid = $patientId;
            $obj->date = date('Y-m-d');     ## result update date
            $obj->forhusband = $for_husband;

            R::store($obj);
        }
    }

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

        #################################################################### Heba : ## get all rays category ##############################################################################
        $sql = ' select distinct raysresults.visitid , visits.visitdate as visitDate , patients.wifename as  wifeName ,   patients.husdandname as  husbandName
                        from    raysresults
                         join     visits                                               on visits.id  = raysresults.visitid
                          join       patients                                           on patients.id  = visits.patientid
                         where  visits.visitdate  between "' . $this->today . '"  AND  "' . $this->today . '"  and  raysresults.deleted = 0 and raysresults.status = 1  order by visits.visitdate desc ';

        $visits = R::getAll($sql);

        $i = 0;
        foreach ($visits as $request) {
            $visit = R::load('visits', $request['visitid']);
            $patient = R::load('patients', $visit->patientid);
            $visits[$i]['wifeName'] = $patient->wifename;
            $visits[$i]['husbandName'] = $patient->husdandname;
            $visits[$i]['visitDate'] = $visit->visitdate;

            $i++;
        }


        $this->smarty->assign('requests', $visits);
        $this->smarty->assign('today', $this->today);
        ################################################################################################################################################################################
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('rays/archive.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function upload() {

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

        $id = filter_input(INPUT_POST, "Id");
        $name = 'file-0';
        //echo $_FILES['file-0']['name'];

        $img = uploadnew($name, False, 0, 0, 'rayimg');
        $raysResults = R::load('raysresults', $id);
        ## delete old file

        $oldFileName = $raysResults->rayimg;
        $fileFolder = 'rayimg';
        $raysResults->rayimg = $img;

        try {
            if ($raysResults->raytype == 1) {
                $obj2 = R::load($raysResults->internaltable, $raysResults->internalrequestid);
                $obj2->rayimg = $img;
                R::store($obj2);
            }
            $raysResults->doctorid = $_SESSION['user_id'];
            R::store($raysResults);

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


        if (!empty($oldFileName)) {
            $this->deletefile($oldFileName, $fileFolder);
        }
    }

    public function uploadMulti() {

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


        $id = filter_input(INPUT_POST, "Id");
        $count = filter_input(INPUT_POST, "imgCount");
        $patientD = filter_input(INPUT_POST, "patientD");
        $raysResults = R::load('raysresults', $id);

        try {

            for ($i = 0; $i < $count; $i++) {
                $name = 'file-' . $i;
                $img = uploadnew($name, False, 0, 0, 'rayimg', False);

                $raysresults_img = R::xdispense('raysresults_img');
                $raysresults_img->raysresults_id = $id;
                $raysresults_img->rayimg = $img;
                $raysresults_img->deleted = 0;
                $raysresults_img->id = R::store($raysresults_img);
            }

            if ($raysResults->raytype == 1) {
                $obj2 = R::load($raysResults->internaltable, $raysResults->internalrequestid);
                $obj2->rayimg = $img;
                $obj2->raysresults_id = $id;
                R::store($obj2);
            }
            $raysResults->doctorid = $_SESSION['user_id'];
            R::store($raysResults);

            $imgs = R::findall('raysresults_img', 'deleted = ? and raysresults_id = ? ', [0, $id]);

            $this->smarty->assign('imgs', $imgs);
            $this->smarty->assign('patientD', $patientD);
            $this->smarty->display('rays/ray_imgs.html');
        } catch (Exception $e) {
            echo -1;
        }
    }

    private function deletefile($fileName, $fileFolder) {
        $target_dir = "../../upload/" . $fileFolder;
        $target_file = $target_dir . '/' . $fileName;

        if (file_exists($target_file)) {
            chmod($target_file, 0777);
            unlink($target_file);
        }
    }

    public function printresults() {

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

        $invResIds = json_decode(stripslashes(filter_input(INPUT_POST, 'jsonString')));

        $visitId = filter_input(INPUT_POST, "visitId");
        $visit = R::load('visits', $visitId);

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

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

        if ($visit->for_husband != 1) {
            $this->smarty->assign('name', $patient->wifename);
            $this->smarty->assign('title', $wifetypes->title);
        } else {
            $this->smarty->assign('name', $patient->husdandname);
            $this->smarty->assign('title', $husbandtypes->title);
        }

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

        $this->smarty->assign('statusNo', $patient->statusno);

        //refer doctor
        if (!empty($patient->refer_doctor)) {
            $doc_info = R::getRow('select * from awusers where user_id = ?', [$patient->refer_doctor]);
            $this->smarty->assign('doctor_name', $doc_info['name']);
        } else {
            //select last visit by id
            $last_v = R::findOne('visits', 'patientid = ? order by id desc', [$patient->id]);
            $c_last_v = R::count('visits', 'patientid = ? order by id desc', [$patient->id]);
            if ($c_last_v > 0 && !empty($last_v->for_doctor)) {
                $doc_info = R::getRow('select * from awusers where user_id = ?', [$last_v->for_doctor]);
                $this->smarty->assign('doctor_name', $doc_info['name']);
            } else {
                $this->smarty->assign('doctor_name', '');
            }
        }

        $invResults = array();

        foreach ($invResIds as $invResId) {
            $in = R::load('raysresults', $invResId);

            $ray = R::load('rays', $in->rayid);
            $in->invname = $ray->name;
            $in->result = $in->rayresult;

            array_push($invResults, $in);
        }


        $this->smarty->assign('result', $invResults);
        $this->smarty->assign('visit', $visit);

        $this->smarty->display('rays/print.html');
    }

    public function finishRequest() {

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

        $visitId = filter_input(INPUT_GET, "id");
        $invs = R::findall('raysresults', 'deleted = ? and visitid = ? ', [0, $visitId]);

        try {
            foreach ($invs as $in) {
                $in->status = 1;
                R::store($in);
            }
            header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=index');
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

    ##########################################################

    public function rays() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        #################################################################### Heba : ## get all rays category ##############################################################################
        $patientId = filter_input(INPUT_GET, "patientid");
        //      $this->smarty->assign('patientId', $patientId);

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


        $raysVisits = loadRays($patientId, 0, 1);
        $this->smarty->assign('raysVisits', $raysVisits);
        $this->smarty->assign('raysCount', count($raysVisits));
        $this->smarty->assign('patientD', $patientId);
        ################################################################################################################################################################################
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('rays/rays_all.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();
    }
}
