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

#include upload function
        require_once("../../_library/plugins/classupload/uploadfunctions.php");

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

#################################################################### Heba : ## get all rays category ##############################################################################

        $searchValues = array('invests', $this->today, $this->today, 0, 0);
        $visits = $this->searchInvests($searchValues);

        $this->smarty->assign('today', $this->today);
        $this->smarty->assign('requests', $visits);
        $this->smarty->assign('rescount', count($visits));

//        $allPatients = R::findAll('patients', 'deleted = ? and done = ?', [0, 1]);
//        $this->smarty->assign('allPatients', $allPatients);
################################################################################################################################################################################
//call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('lab/show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function searchrecord() {
//check login
        autho::checkautho($this->hosturl);
//check authoize
// autho::checkauthoize($this->controllname, $this->hosturl . "/../core", $_SESSION['role_id']);
        $searchValues = json_decode(stripslashes(filter_input(INPUT_POST, 'jsonString')));
        $searchType = $searchValues[0];

        switch ($searchType) {
            case 'rays':
                $this->searchRays($searchValues);
                break;

            case 'invests':
                $res = $this->searchInvests($searchValues);
                $this->smarty->assign('reportType', $searchType);
                $this->smarty->assign('requests', $res);
                $this->smarty->assign('rescount', count($res));
                $this->smarty->display('lab/result_invests.html');
                break;

            default:
                break;
        }
    }

    private function searchInvests($searchValues) {
        $dateFrom = $searchValues[1];
        $dateTo = $searchValues[2];
        $patientId = $searchValues[4];

        $result_2 = array();
        $result_3 = array();
        $result_4 = array();
        $result_5 = array();
        $result_6 = array();
        $result_9 = array();


        if ($patientId > 0) {
            $sqlPat = ' and  patients.id =  ' . $patientId;
        } else {
            $sqlPat = '';
        }

        $sqlDate = '';

        if (!empty($dateFrom)) {
            $sqlDate .= ' and  visits.visitdate >=  "' . $dateFrom . '"    ';
        }

        if (!empty($dateTo)) {
            $sqlDate .= ' and  visits.visitdate <=  "' . $dateTo . '"    ';
        }

        $sql = ' select distinct investigationresults.visitid , visits.visitdate as visitDate ,   patients.statusno
            , patients.wifename as  wifeName ,   patients.husdandname as  husbandName , visits.for_husband  
            ,   patients_childs.gender  as child_gender   ,   visits.child ,   patients_childs.child_name 
                        from    investigationresults
                         join     visits                                               on visits.id  = investigationresults.visitid
                          join       patients                                           on patients.id  = visits.patientid  
                          left  join       patients_childs                       on patients_childs.id  = visits.child
                        where   investigationresults.deleted = 0  and  visits.deleted = 0
                        ' . $sqlDate . '   ' . $sqlPat . '  order by visits.visitdate desc  , visits.id asc   ';

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

        $i = 0;
        foreach ($res as $inv) {
            $sql = ' select sum(filled) as filledSum  , sum(verified) as verifiedSum 
                                , sum(printed) as printedSum  , sum(delivered) as deliveredSum 
                                , count(id) as  noOfInvs  , sum(sent) as sentSum 
                        from    investigationresults
                       where   deleted = 0 and   visitid =      ' . $inv['visitid'] . '   ';

            $details = R::getRow($sql);
            $totalSum = $details['filledSum'] + $details['verifiedSum'] + $details['deliveredSum'];
            $noOfInvs = $details['noOfInvs'];


            if ($totalSum == 0) {
                $res[$i]['status'] = 1;      ##  new 
                $res[$i]['statusImg'] = 'new.jpeg';
            } else if ($details['deliveredSum'] == $noOfInvs) {
                $res[$i]['status'] = 4;     ##  delivered 
                $res[$i]['statusImg'] = 'delivered.jpeg';
            } else if ($details['verifiedSum'] == $noOfInvs) {
                $res[$i]['status'] = 3;     ##  verified 
                $res[$i]['statusImg'] = 'verified.jpeg';
            } else {
                $res[$i]['status'] = 2;     ##  in progress 
                $res[$i]['statusImg'] = 'inProgress.jpeg';
            }

######    still new 
            if ($details['filledSum'] == 0) {
                array_push($result_2, $res[$i]);
            }
######
            elseif ($details['filledSum'] > 0 && $details['filledSum'] < $noOfInvs) {
                array_push($result_3, $res[$i]);
            }
######
            elseif ($details['filledSum'] == $noOfInvs && $details['verifiedSum'] < $noOfInvs && $details['verifiedSum'] > 0) {
                array_push($result_6, $res[$i]);
            }
######
            elseif ($details['filledSum'] == $noOfInvs && $details['verifiedSum'] == $noOfInvs && $details['printedSum'] < $noOfInvs) {
                array_push($result_4, $res[$i]);
            }
######
            elseif ($details['filledSum'] == $noOfInvs && $details['verifiedSum'] == $noOfInvs && $details['printedSum'] == $noOfInvs) {
                array_push($result_5, $res[$i]);
            }


            if ($details['sentSum'] > 0) {
                array_push($result_9, $res[$i]);
            }


            $i++;
        }

        $this->smarty->assign('requests_2', $result_2);
        $this->smarty->assign('requests_3', $result_3);
        $this->smarty->assign('requests_4', $result_4);
        $this->smarty->assign('requests_5', $result_5);
        $this->smarty->assign('requests_6', $result_6);
        $this->smarty->assign('requests_9', $result_9);
        $this->smarty->assign('requests_all', $res);

        $this->smarty->assign('res2count', count($result_2));
        $this->smarty->assign('res3count', count($result_3));
        $this->smarty->assign('res4count', count($result_4));
        $this->smarty->assign('res5count', count($result_5));
        $this->smarty->assign('res6count', count($result_6));
        $this->smarty->assign('res9count', count($result_9));

        return $res;
    }

    function searchRays($searchValues) {

        $searchType = $searchValues[0];
        $dateFrom = $searchValues[1];
        $dateTo = $searchValues[2];
        $status = $searchValues[3];


        $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 "' . $dateFrom . '"  AND  "' . $dateTo . '"  
                and  raysresults.deleted = 0  and  visits.deleted = 0  
                and raysresults.status = ' . $status . '  
                order by visits.visitdate desc   , visits.id asc ';
        $res = R::getAll($sql);

        $this->smarty->assign('reportType', $searchType);
        $this->smarty->assign('res', $res);
        $this->smarty->assign('rescount', count($res));
        $this->smarty->display('lab/result_rays.html');
    }

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

        $paid = $this->checkVisitBalance($visitId);
        $this->smarty->assign('paid', $paid);


        $visit = R::load('visits', $visitId);
        $patient = R::getRow("SELECT * FROM patients WHERE id = $visit->patientid");
        $patientInfo = $this->patientInfo($patient, $visit->for_husband, $visit->child);

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

        $this->smarty->assign('patientNo', $patient['statusno']);
        $this->smarty->assign('invPatientName', $patientInfo['name']);

// print_r(77777777777777777);
        $this->smarty->assign('visit', $visit);
################################################################################################################################################################################
//call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('lab/labs/labs_head.html');
        $this->details($invs, $patientInfo['sex'], $patientInfo['ageNo'], $patientInfo['ageUnit']);
// patientdata::patientdatashow($this->smarty, $this->hosturl);
//        $this->smarty->display('lab/labs.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    function details($invs, $gender, $age, $ageUnit) {
        $normal = array();

        foreach ($invs as $in) {
            $obj = R::load('invests', $in->investid);

            if ($obj->type == 1) {
                $in->hasPdf = 1;
            } else {
                $in->hasPdf = $obj->pdf;
            }

            $in->invname = $obj->name;

            $in->special_inv_type = $obj->special_inv_type;

            switch ($obj->special_inv_type) {
## urine 
                case 2:

                    $urine = R::findOne('investigationresults_urine', 'investigationresults_id = ? ', [$in->id]);
                    if (count($urine) < 1) {
                        $urine = R::xdispense('investigationresults_urine');
                        $urine->investigationresults_id = $in->id;
                        $urine = $this->loadUrineSelects($urine);
                        $urine->id = r::store($urine);
                    } else {
                        $this->loadUrineSelects();
                    }

                    $in->urine = $urine;

                    $in->tableName = 'investigationresults_urine';
                    $this->smarty->assign('inv', $in);
                    $this->smarty->display('lab/labs/labs_2.html');
                    break;

## stool 
                case 3:

                    $stool = R::findOne('investigationresults_stool', 'investigationresults_id = ? ', [$in->id]);
                    if (count($stool) < 1) {
                        $stool = R::xdispense('investigationresults_stool');
                        $stool->investigationresults_id = $in->id;
                        $stool = $this->loadStoolSelects($stool);
                        $stool->id = r::store($stool);
                    } else {
                        $this->loadStoolSelects();
                    }

                    $in->stool = $stool;



                    $in->tableName = 'investigationresults_stool';
                    $this->smarty->assign('inv', $in);
                    $this->smarty->display('lab/labs/labs_3.html');
                    break;

## blood picture 
                case 1:

                    $blood_count = R::count('investigationresults_blood', 'investigationresults_id = ?', [$in->id]);
                    if ($blood_count < 1) {
                        $blood = R::xdispense('investigationresults_blood');
                        $blood->investigationresults_id = $in->id;
                        $blood->othercells = 100;
                        $blood->id = r::store($blood);
                    }

                    $in->blood = $this->loadBloodRanges($in, $gender, $age, $ageUnit);

                    $in->tableName = 'investigationresults_blood';
                    $this->smarty->assign('inv', $in);
                    $this->smarty->display('lab/labs/labs_1.html');
                    break;

## Culture
                case 4:

                    $culture_count = R::count('investigationresults_culture', 'investigationresults_id = ?', [$in->id]);
                    if ($culture_count < 1) {
                        $culture = R::xdispense('investigationresults_culture');
                        $culture->investigationresults_id = $in->id;
                        r::store($culture);
                    }

                    $this->loadCultureSelects();
                    $in->culture = loadCultureDetails($in->id, $this->smarty, 0);

                    $in->tableName = 'investigationresults_culture';

                    $this->smarty->assign('inv', $in);
                    $this->smarty->display('lab/labs/labs_4.html');
                    break;

## ESR
                case 5:
                    $esr_count = R::count('investigationresults_esr', 'investigationresults_id = ?', [$in->id]);
                    if ($esr_count < 1) {
                        $esr = R::xdispense('investigationresults_esr');
                        $esr->investigationresults_id = $in->id;
                        r::store($esr);
                    }

                    $this->loadEsrSelects();
                    $in->esr = loadEsrRanges($in, $gender, $age, $ageUnit, $this->smarty);

                    $in->tableName = 'investigationresults_esr';

                    $this->smarty->assign('inv', $in);
                    $this->smarty->display('lab/labs/labs_5.html');
                    break;

## Cross Matching
                case 6:
                    $cross_count = R::count('investigationresults_cross', 'investigationresults_id = ?', [$in->id]);
                    if ($cross_count < 1) {
                        $cross = R::xdispense('investigationresults_cross');
                        $cross->investigationresults_id = $in->id;
                        r::store($cross);
                    }

                    $this->loadCrossSelects();
                    $in->cross = loadCrossDetails($in->id, $this->smarty, 0);

                    $in->tableName = 'investigationresults_cross';

                    $this->smarty->assign('inv', $in);
                    $this->smarty->display('lab/labs/labs_6.html');
                    break;

## Fluid
                case 7:
                    break;

## Custom
                case 11:
                    $this->loadCustomSelects();
                    $in->elements = customInvDetails($in, $gender, $age, $ageUnit, $this->smarty, 0);
                    $in->tableName = 'investigationresults_custom';

                    $this->smarty->assign('inv', $in);
                    $this->smarty->display('lab/labs/labs_11.html');
                    break;

## Clothing time
                case 8:
                    $clothing_count = R::count('investigationresults_times', 'investigationresults_id = ?', [$in->id]);
                    if ($clothing_count < 1) {
                        $clothing = R::xdispense('investigationresults_times');
                        $clothing->investigationresults_id = $in->id;
                        r::store($clothing);
                    }

                    $in->clothing = loadClothingDetails($in, $gender, $age, $ageUnit, $this->smarty, 0);

                    $in->tableName = 'investigationresults_times';

                    $this->smarty->assign('inv', $in);
                    $this->smarty->display('lab/labs/labs_8.html');
                    break;

## PT + APTT
                case 9:
## PT 
                case 12:
##  APTT
                case 13:
                    $pt_count = R::count('investigationresults_pt', 'investigationresults_id = ?', [$in->id]);
                    if ($pt_count < 1) {
                        $pt = R::xdispense('investigationresults_pt');
                        $pt->investigationresults_id = $in->id;
                        $pt->control_time = 13;
                        $pt->control_time1 = 30;
                        $pt->isi = 1.06;
                        $pt->id = r::store($pt);
                    }

                    $in->pt = loadPtDetails($in, $gender, $age, $ageUnit, $this->smarty, 0);

                    $in->tableName = 'investigationresults_pt';

                    $this->smarty->assign('inv', $in);
                    $this->smarty->display('lab/labs/labs_9.html');

                    break;

## ABO/RH
                case 10:
                    $aborh_count = R::count('investigationresults_aborh', 'investigationresults_id = ?', [$in->id]);
                    if ($aborh_count < 1) {
                        $aborh = R::xdispense('investigationresults_aborh');
                        $aborh->investigationresults_id = $in->id;
                        r::store($aborh);
                    }

                    $this->loadAborhSelects();
                    $in->aborh = loadAborhDetails($in->id, $this->smarty, 0);

                    $in->tableName = 'investigationresults_aborh';

                    $this->smarty->assign('inv', $in);
                    $this->smarty->display('lab/labs/labs_10.html');

                    break;


                default:
                    $in->ranges = $this->commonRanges($in, $gender, $age, $ageUnit);
                    $in->rangesCount = count($in->ranges);

                    $in->tableName = 'investigationresults';
                    array_push($normal, $in);
                    break;
            }
        }

        $this->smarty->assign('normal', $normal);
        $this->smarty->assign('normalCount', count($normal));
        $this->smarty->display('lab/labs/labs_normal.html');
        $this->smarty->display('lab/labs/labs_footer.html');
    }

    function loadDefaults($obj, $special_inv_type) {
        
    }

    function loadCustomSelects() {
        $data = R::findAll('custom_select', ' deleted = 0 ');
        $this->smarty->assign('custom_select', $data);
    }

    function commonRanges($in, $gender, $age, $ageUnit) {
        $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and agefrom <= ? 
                    and ageto >= ?  and investid = ?  and age_units = ?  
                    ', [$gender, '', -1, $age, $age, $in->investid, $ageUnit]);

        if (count($range) > 0 && $in->rangeid < 1) {
            $in->rangeid = $range->id;
            r::store($in);
        }

        if (!(count($range) > 0 )) {
            $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and ( agefrom = ?  || agefrom = ?  ) 
                    and ( ageto = ?  || ageto = ?  )   and investid = ?  
                    ', [$gender, '', -1, Null, '', Null, '', $in->investid]);

            if (count($range) > 0 && $in->rangeid < 1) {
                $in->rangeid = $range->id;
                r::store($in);
            }
        }


        $ranges = R::findAll('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and investid = ?  
                    ', [$gender, '', -1, $in->investid]);

        return $ranges;
    }

    function loadBloodRanges($in, $gender, $age, $ageUnit) {

        $blood = R::findOne('investigationresults_blood', 'investigationresults_id = ? ', [$in->id]);

        $elements = array("Hgb" => "hgb", "RBC" => "rbc", "Plt" => "plt", "WBC" => "wbc");

        foreach ($elements as $showName => $dbName) {

            $range = Null;

            $hName = $dbName . '_high';
            $lName = $dbName . '_low';
            $rangestxt = $dbName . '_ranges';
            $rangeid = $dbName . '_rangeid';

            if ($blood->$rangeid && $blood->$rangeid > 0) {
                $range = R::load('inv_ranges', $blood->$rangeid);
            }

            if (!(count($range) > 0 )) {
                $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and agefrom <= ? 
                    and ageto >= ?  and investid = ?  and age_units = ?   and invest_child = ?  
                    ', [$gender, '', -1, $age, $age, $in->investid, $ageUnit, $showName]);

                if (count($range) > 0 && $blood->$rangeid < 1) {
                    r::exec(' update investigationresults_blood set  ' . $rangeid . ' = ' . $range->id . '  where id =  ' . $blood->id);
                }


                if (!(count($range) > 0 )) {

                    $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?   || gender = ?)  and ( agefrom = ?  || agefrom = ?  ) 
                    and ( ageto = ?  || ageto = ?  )   and investid = ?   and invest_child = ?  
                    ', [$gender, '', -1, Null, '', Null, '', $in->investid, $showName]);

                    if (count($range) > 0 && $blood->$rangeid < 1) {
                        r::exec(' update investigationresults_blood set  ' . $rangeid . ' = ' . $range->id . '  where id =  ' . $blood->id);
                    }
                }
            }


            $blood->$hName = 0;
            $blood->$lName = 0;

            if (count($range) > 0) {

                $blood->$rangeid = $range->id;

                $range_txt = $dbName . '_range_txt';
//                $n2 = $dbName . '_range_low';
//                $n3 = $dbName . '_range_high';
//                $n4 = $dbName . '_invest_units';
//
                $blood->$range_txt = $range->range_txt;
//                $urine[$n2] = $range->range_low;
//                $urine[$n3] = $range->range_high;
//                $urine[$n4] = $range->invest_units;

                if (is_numeric($range->range_low) && is_numeric($blood->$dbName) && $blood->$dbName < $range->range_low) {
                    $blood->$lName = 1;
                }

####
                elseif (is_numeric($range->range_high) && is_numeric($blood->$dbName) && $blood->$dbName > $range->range_high) {
                    $blood->$hName = 1;
                }
            }


            $ranges = R::findAll('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and investid = ?  and invest_child = ?    
                    ', [$gender, '', -1, $in->investid, $showName]);

            $blood->$rangestxt = $ranges;
        }

        return $blood;
    }

    function bloodElementRanges($in, $gender, $age, $ageUnit) {

        $blood = R::findOne('investigationresults_blood', 'investigationresults_id = ? ', [$in->id]);

        $elements = array("Hgb" => "hgb", "RBC" => "rbc", "Plt" => "volume", "plt" => "wbc");

        foreach ($elements as $single) {
            $esr = elementRanges($in, $gender, $age, $ageUnit, $single, $esr, 'investigationresults_esr', $this->smarty);
        }

        return $blood;
    }

    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 {
            if ($colname == "default_value") {
                r::exec(' update  ' . $tablename . '  set  ' . $colname . ' = 0  where 1  ');
            }

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

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

            R::store($obj);
            echo $time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
//header('Location:' . $this->hosturl . '/controllers/' . $this->controllname.'.php?ac=index' );
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

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

        $data = json_decode(stripslashes($_POST['data']));
        $id = filter_input(INPUT_POST, "id");
        $tablename = filter_input(INPUT_POST, "tableName");

        try {

            $obj = R::load($tablename, $id);

            foreach ($data as $one) {
                $colname = $one[0];
                $value = $one[1];

                $obj->$colname = $value;

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

            R::store($obj);

            echo $time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
        } catch (Exception $ex) {
            echo '-1';
        }
    }

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

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


        $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 : ## Investigation data  ##############################################################################
        $allInvCats1 = R::findall('investcats', 'deleted = ? and displayorder in (1 , 2) order by displayorder ', [0]);
        foreach ($allInvCats1 as $cat) {
            $invests = R::findall('invests', 'investcatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->invests = $invests;
        }

        $allInvCats2 = R::findall('investcats', 'deleted = ? and displayorder = 3 order by displayorder ', [0]);
        foreach ($allInvCats2 as $cat) {
            $invests = R::findall('invests', 'investcatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->invests = $invests;
        }

        $allInvCats3 = R::findall('investcats', 'deleted = ? and displayorder in (4 , 5) order by displayorder ', [0]);
        foreach ($allInvCats3 as $cat) {
            $invests = R::findall('invests', 'investcatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->invests = $invests;
        }

        $allInvCats4 = R::findall('investcats', 'deleted = ? and displayorder  between 6 and  11 order by displayorder ', [0]);
        foreach ($allInvCats4 as $cat) {
            $invests = R::findall('invests', 'investcatid = ? and deleted = ?', [$cat->id, 0]);
            $cat->invests = $invests;
        }

        $allInvCats5 = R::findall('investcats', 'deleted = ? and displayorder > 11 order by displayorder ', [0]);
        foreach ($allInvCats5 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',$allInvCats);
        $this->smarty->assign('favorites', $favorites);
        $this->smarty->assign('group1', $allInvCats1);
        $this->smarty->assign('group2', $allInvCats2);
        $this->smarty->assign('group3', $allInvCats3);
        $this->smarty->assign('group4', $allInvCats4);
        $this->smarty->assign('group5', $allInvCats5);
        $this->smarty->assign('others', $others);

        $invoffers = R::findall('invoffer', 'active = ? and  del = ? ', [1, 0]);
        foreach ($invoffers as $offer) {
            $invs = R::getRow('SELECT  sum(price) as price   FROM  invofferdetails where invoffer_id = ? and  del = ?  '
                            , [$offer->id, 0]);
            $offer->price = $invs['price'];
        }
        $this->smarty->assign('invoffers', $invoffers);

################################################################################################################################################################################
//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/invsdept.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);
        }

#### offers 

        switch ($for_department) {
            case 12:
                $itr_offer = filter_input(INPUT_POST, 'itr_offer');
                for ($i = 1; $i <= $itr_offer; $i++) {

                    $offer_id = filter_input(INPUT_POST, 'offerId' . $i);
                    $invofferdetails = R::findall('invofferdetails', 'del = ? and invoffer_id = ?  ', [0, $offer_id]);
                    foreach ($invofferdetails as $data) {
                        $obj = R::dispense('investigationresults');
                        $obj->investid = $data->inv_id;
                        $obj->invtype = $invType;

                        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');
                        $obj->forhusband = $for_husband;
                        $obj->offer_id = $offer_id;

                        R::store($obj);
                    }
                }
                break;
        }
    }

    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 investigationresults.visitid , visits.visitdate as visitDate 
                    , patients.wifename as  wifeName ,   patients.husdandname as  husbandName
                        from    investigationresults
                         join     visits                                               on visits.id  = investigationresults.visitid
                          join       patients                                           on patients.id  = visits.patientid
        where  visits.visitdate  between "' . $this->today . '"  AND  "' . $this->today . '"  and  
                 investigationresults.deleted = 0 and investigationresults.status = 1  order by visits.visitdate desc ';

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

    public function printresults() {

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

//        $invResIds = array(39886);
//        $visitId = 50555;
        $invResIds = json_decode(stripslashes(filter_input(INPUT_POST, 'jsonString')));
        $visitId = filter_input(INPUT_POST, "visitId");

        switch ($_SESSION['role_id']) {
            case 3:
                $balance = $this->checkVisitBalance($visitId);
                if ($balance == 1) {
                    $this->resultDetails($invResIds, $visitId);
                } else {
                    echo '-33';
                }
                break;

            default:
                $this->resultDetails($invResIds, $visitId);
                break;
        }
    }

    function checkVisitBalance($visitId) {
        $res = 1;
        $visit = R::load('visits', $visitId);
        if ($visit->restdetectionvalue > 0) {
            $payVisits = R::getRow('SELECT COALESCE(SUM(detectionvalue_cash),0)   as paid_cash 
                                                                 , COALESCE(SUM(detectionvalue_visa),0)   as paid_visa  
                                                                  , COALESCE(SUM(discount),0)   as paid_discount 
                                                                 , 0 as paid   
                                    FROM visits   where   deleted != ? and detectionid = 999 and visitid = ?   ', [1, $visitId]);

            $paid = $payVisits['paid_cash'] + $payVisits['paid_visa'];
            $dept = $visit->restdetectionvalue - $paid - $payVisits['paid_discount'];

            if ($dept > 0) {
                $res = 0;
            }
        }

        return $res;
    }

    function resultDetails($invResIds, $visitId) {
        $visit = R::load('visits', $visitId);
        if (!empty($visit->for_doctor)) {
            $doc_info = R::getRow('select * from awusers where user_id = ?', [$visit->for_doctor]);
            $this->smarty->assign('doctor_name', $doc_info['name']);
        } else {
            $this->smarty->assign('doctor_name', '');
        }

        $today = date("Y/m/d");
        $this->smarty->assign('date', $today);
        $this->smarty->assign('dateTime', date("Y/m/d h:i A"));
        $this->smarty->assign('req_date', date('Y/m/d ', strtotime($visit->visitdate)));
        if (!(is_null($visit->visittime))) {
            $this->smarty->assign('req_time', date('h:i A ', strtotime($visit->visittime)));
        }

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

        $patientG = R::getRow("SELECT * FROM patients WHERE id = $visit->patientid");
        $patientInfo = $this->patientInfo($patientG, $visit->for_husband, $visit->child);
        $this->smarty->assign('name', $patientInfo['name']);
        $this->smarty->assign('title', $patientInfo['title']);
        $this->smarty->assign('sex', $patientInfo['gender']);

        $this->smarty->assign('age', $patientInfo['age']);

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

        investsForPrint($invResIds, $patientInfo['sex'], $patientInfo['ageNo'], $patientInfo['ageUnit'], $this->smarty, 1);
    }

    public function createbarcode($statusno) {
        if (file_exists('../../upload/barcodes/' . $statusno . '.png')) {
            
        } else {
            $url = $this->hosturl . '/../_library/barcode/image.php?code=' . $statusno . '&width=300&height=60&type=C39';
## create bar code 
            $barcode = file_get_contents($url);
## save the file to disk 
            file_put_contents('../../upload/barcodes/' . $statusno . '.png', $barcode);
        }
    }

    public function finishRequest() {

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

        $visitId = filter_input(INPUT_GET, "id");
        $invs = R::findall('investigationresults', '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 deleteinv() {
//check login
        autho::checkautho($this->hosturl);

        $invResId = filter_input(INPUT_POST, "invResId");
        $invResult = R::load('investigationresults', $invResId);

        try {
### delete from   urine or stool or blood table if exist

            switch ($invResult->investid) {
                case 83:
                    $urine = R::findOne('investigationresults_urine', 'investigationresults_id = ? ', [$invResId]);
                    if (count($urine) > 0) {
                        r::trash($urine);
                    }
                    break;

                case 412:
                    $stool = R::findOne('investigationresults_stool', 'investigationresults_id = ? ', [$invResId]);
                    if (count($stool) > 0) {
                        r::trash($stool);
                    }
                    break;

                case 446:
                    $blood = R::findOne('investigationresults_blood', 'investigationresults_id = ? ', [$invResId]);
                    if (count($blood) > 0) {
                        r::trash($blood);
                    }
                    break;
            }

### remove inv cost from visit balance 


            $visit = R::load('visits', $invResult->visitid);
            $visit->totaldetectionvalue = $visit->totaldetectionvalue - $invResult->price;

            if ($visit->restdetectionvalue >= $invResult->price) {
                $visit->restdetectionvalue = $visit->restdetectionvalue - $invResult->price;
            } else {
                $visit->restdetectionvalue = 0;
            }

            $visit->detectionvalue_cash = $visit->totaldetectionvalue - $visit->discount - $visit->restdetectionvalue - $visit->detectionvalue_visa;
            R::store($visit);

### delete from   investigationresults table

            r::trash($invResult);
            echo 1;
        } catch (Exception $ex) {
            echo -1;
        }
    }

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

//vars here
        $table = filter_input(INPUT_POST, 'selectId');
        $name = filter_input(INPUT_POST, 'new_name');

        $obj_id = filter_input(INPUT_POST, 'id');
        $tableName = filter_input(INPUT_POST, 'tableName');
        $colName = filter_input(INPUT_POST, 'colName');

        try {

            $record = R::xdispense($table);
            $record->name = $name;
            $record->deleted = 0;
            $id = R::store($record);

            if ($obj_id > 0) {

                $obj = R::load($tableName, $obj_id);
                $obj->$colName = $id;
                R::store($obj);
            }


            echo $id;
        } catch (Exception $e) {
            echo $e;
        }
    }

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

        $cross_id = filter_input(INPUT_POST, 'cross_id');
        $new_itr = filter_input(INPUT_POST, 'new_itr');


        try {

            $donner = R::xdispense('investigationresults_cross_donners');

            if ($cross_id > 0) {
                $donner->investigationresults_cross_id = $cross_id;
                $donner->id = r::store($donner);
            } else {
                $donner->id = 0;
            }
            $this->loadCrossSelects();

            $this->smarty->assign('donner', $donner);
            $this->smarty->assign('i', $new_itr);
            $this->smarty->assign('archive', 0);

            $this->smarty->display('lab/donor.html');
        } catch (Exception $e) {
            echo -1;
        }
    }

    function loadUrineSelects($urine = 0) {
        $tables = array("volume", "color", "odor", "ova", "bacteria", "mucus", "trophazite"
            , "pbcs", "pus2", "pus", "blood", "leucocytes", "aspect", "deposit", "reaction"
            , "protein", "fungi", "artifacts", "crystal", "pbcs2", "casts2", "casts", "epithelial"
            , "urobilinigen", "bilirubin", "gravity", "nitrite", "acetone", "sugar", "bacteria2"
            , "amorphous2", "amorphous", "crystal2"
        );

        foreach ($tables as $colName) {
            $tableName = 'urine_' . $colName;
            $data = R::findAll($tableName, ' deleted = 0 ');
            $this->smarty->assign($tableName, $data);
            if ($urine != 0) {
                $default = R::findOne($tableName, ' deleted = 0 and default_value = 1  ');
                $urine->$colName = $default->id;
            }
        }
        return $urine;
    }

    function loadStoolSelects($stool = 0) {
        $tables = array("blood", "ciliate", "color", "consistency", "cysts", "flagellates"
            , "prog", "parasitology2", "parasitology", "ova2", "larva2", "cysts2"
            , "prog2", "rbc", "rbc2", "reaction", "mucus", "flagellates2", "trophozoite",
            "trophozoite2", "trophozoite3", "undigested", "odor", "food", "undigested2"
            , "undigested3", "undigested4", "wbc", "ova", "larva", "wbc2"
        );

        foreach ($tables as $colName) {
            $tableName = 'stool_' . $colName;
            $data = R::findAll($tableName, ' deleted = 0 ');
            $this->smarty->assign($tableName, $data);

            if ($stool != 0) {
                $default = R::findOne($tableName, ' deleted = 0 and default_value = 1  ');
                $stool->$colName = $default->id;
            }
        }

        return $stool;
    }

    function loadEsrSelects() {
        $tables = array("hour1", "hour2");

        foreach ($tables as $tableName) {
            $tableName = 'esr_' . $tableName;
            $data = R::findAll($tableName, ' deleted = 0 ');
            $this->smarty->assign($tableName, $data);
        }
    }

    public function esrchange() {

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

        $hour_id = filter_input(INPUT_POST, "hour");
        $rangeid = filter_input(INPUT_POST, "rangeid");
        $element = filter_input(INPUT_POST, "element");

        $range = R::load('inv_ranges', $rangeid);
        $hour = R::load('esr_' . $element, $hour_id);

        $unit = "";
        $level = "";

        if ($hour_id > 0 && $rangeid > 0) {

            if (is_numeric($range->range_low) && is_numeric($hour->name) && $hour->name < $range->range_low) {
                $level = "L";
            }

####
            elseif (is_numeric($range->range_high) && is_numeric($hour->name) && $hour->name > $range->range_high) {
                $level = "H";
            }
        }

        if (count($range) > 0) {
            $unit = $range->invest_units;
        }


        echo $unit . '-' . $level;
    }

    public function invlevel() {

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

        $value = filter_input(INPUT_POST, "value");
        $rangeid = filter_input(INPUT_POST, "rangeid");

        $range = R::load('inv_ranges', $rangeid);

        $level = "";

        if ($value >= 0 && $rangeid > 0) {
            if (is_numeric($range->range_low) && is_numeric($value) && $value < $range->range_low) {
                $level = "L";
            }

####
            elseif (is_numeric($range->range_high) && is_numeric($value) && $value > $range->range_high) {
                $level = "H";
            }
        }

        if (count($range) > 0) {
            $unit = $range->invest_units;
        }


        echo $level . '-' . $unit;
    }

    public function bloodchange() {

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

        $hgb = filter_input(INPUT_POST, "hgb");
        $rbc = filter_input(INPUT_POST, "rbc");
        $hct = filter_input(INPUT_POST, "hct");
        $bloodId = filter_input(INPUT_POST, "bloodId");


        $mcv_calc = $this->mcv_calc($hct, $rbc);
        $mch_calc = $this->mch_calc($hgb, $rbc);
        $mchc_calc = $this->mchc_calc($hct, $hgb);

        if ($bloodId > 0) {
            $blood = R::load('investigationresults_blood', $bloodId);
            $blood->mcv_calc = $mcv_calc;
            $blood->mch_calc = $mch_calc;
            $blood->mchc_calc = $mchc_calc;
            r::store($blood);
        }

        echo $mcv_calc . '-' . $mch_calc . '-' . $mchc_calc;
    }

    public function abscalc() {

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

        $value = filter_input(INPUT_POST, "value");
        $wbc = filter_input(INPUT_POST, "wbc");
        $element = filter_input(INPUT_POST, "element");
        $bloodId = filter_input(INPUT_POST, "bloodId");


        $abs_calc = $this->abs_calc($wbc, $value);

        if ($bloodId > 0) {
            $blood = R::load('investigationresults_blood', $bloodId);
            $blood->$element = $abs_calc;
            r::store($blood);
        }

        echo $abs_calc;
    }

    public function allabscalc() {

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

        $wbc = filter_input(INPUT_POST, "wbc");
        $bloodId = filter_input(INPUT_POST, "bloodId");

        if ($bloodId > 0) {
            $blood = R::load('investigationresults_blood', $bloodId);
        }

        $elements = array("neutrophil", "lymphocytes", "monocytes", "eosinophils", "basophils");

        $res = '';

        $i = 1;
        foreach ($elements as $single) {

            if ($i > 1) {
                $res .= '-';
            }

            $nameR = $single . '_r';
            $nameAbs = $single . '_abs';

            $abs_calc = $this->abs_calc($wbc, $blood->$nameR);

            if ($bloodId > 0) {
                $blood->$nameAbs = $abs_calc;
                r::store($blood);
            }

            $res .= $abs_calc;
            $i++;
        }

        echo $res;
    }

    public function allabscalcpreview() {

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

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

        $elements = array("neutrophil", "lymphocytes", "monocytes", "eosinophils", "basophils");
        $res = '';
        $i = 1;
        foreach ($elements as $single) {

            if ($i > 1) {
                $res .= '-';
            }

            $nameR = $single . '_r';

            $one = filter_input(INPUT_POST, $nameR);

            $abs_calc = $this->abs_calc($wbc, $one);
            $res .= $abs_calc;
            $i++;
        }

        echo $res;
    }

    function abs_calc($wbc, $value) {
        $res = '';

        if (is_numeric($wbc) && $wbc >= 0 && is_numeric($value) && $value >= 0) {
            $res = ( $value * $wbc) / 100;
            $res = round($res, 2);
        }

        return $res;
    }

    function mchc_calc($hct, $hgb) {
        $res = '';

        if (is_numeric($hct) && $hct > 0 && is_numeric($hgb) && $hgb >= 0) {
            $res = ( 100 * $hgb) / $hct;
            $res = round($res, 1);
        }
        return $res;
    }

    function mch_calc($hgb, $rbc) {
        $res = '';

        if (is_numeric($rbc) && $rbc > 0 && is_numeric($hgb) && $hgb >= 0) {
            $res = ( 10 * $hgb) / $rbc;
            $res = round($res, 1);
        }
        return $res;
    }

    function mcv_calc($hct, $rbc) {
        $res = '';

        if (is_numeric($rbc) && $rbc > 0 && is_numeric($hct) && $hct >= 0) {
            $res = ( 10 * $hct) / $rbc;
            $res = round($res, 1);
        }

        return $res;
    }

    function loadCultureSelects() {
        $tables = array("sample", "organism_a", "organism_b", "organism_c"
            , "condition", "condition1", "colony_count", "sensitivity_cat");

        foreach ($tables as $tableName) {
            $tableName = 'culture_' . $tableName;
            $data = R::findAll($tableName, ' deleted = 0 ');
            $this->smarty->assign($tableName, $data);
        }


#### urine part

        $table = array("reaction", "pus", "pus2", "pbcs", "pbcs2", "epithelial", "crystal"
            , "fungi", "bacteria", "other", "other1", "other2", "other3", "other4"
            , "gram", "zn_film"
        );

        foreach ($table as $tableNam) {
            $tableNam = 'urine_' . $tableNam;
            $data = R::findAll($tableNam, ' deleted = 0 ');
            $this->smarty->assign($tableNam, $data);
        }
    }

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

//vars here
        $abbr = filter_input(INPUT_POST, 'abbr');
        $scientific_name = filter_input(INPUT_POST, 'scientific_name');
        $sensitivity = filter_input(INPUT_POST, 'sensitivity');
        $culture_id = filter_input(INPUT_POST, 'culture_id');

        try {

            $record = R::xdispense('antibiotic_sensitivity');
            $record->abbr = $abbr;
            $record->scientific_name = $scientific_name;
            $record->sensitivity = $sensitivity;
            $record->deleted = 0;
            R::store($record);

            loadAllAbbr($culture_id, $this->smarty);
            $this->smarty->assign('culture_id', $culture_id);
            $this->smarty->display('lab/allabbr.html');
        } catch (Exception $e) {
            echo -1;
        }
    }

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

//vars here
        $abbr_id = filter_input(INPUT_POST, 'abbr_id');
        $activeTab = filter_input(INPUT_POST, 'activeTab');
        $culture_id = filter_input(INPUT_POST, 'culture_id');

        $tableName = 'investigationresults_culture_' . $activeTab;

        try {

            $record = R::xdispense($tableName);
            $record->investigationresults_culture_id = $culture_id;
            $record->antibiotic_sensitivity_id = $abbr_id;
            $record->deleted = 0;
            $id = R::store($record);

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

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

//vars here
        $activeTab = filter_input(INPUT_POST, 'activeTab');
        $culture_id = filter_input(INPUT_POST, 'culture_id');


        $tableName = 'investigationresults_culture_' . $activeTab;

        cultureFor($tableName, $culture_id, $this->smarty);
        $this->smarty->assign('culture_id', $culture_id);
        $this->smarty->display('lab/tabcontent.html');
    }

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

        $id = filter_input(INPUT_POST, "id");
        $tableName = filter_input(INPUT_POST, "tableName");


        try {
            $record = R::load($tableName, $id);
            $record->deleted = 1;
            R::store($record);
            echo 1;
        } catch (Exception $ex) {
            echo -1;
        }
    }

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

//vars here
        $culture_id = filter_input(INPUT_POST, 'culture_id');


        loadAllAbbr($culture_id, $this->smarty);
        $this->smarty->assign('culture_id', $culture_id);
        $this->smarty->display('lab/allabbr.html');
    }

    function loadCrossSelects() {
        $tables = array("abo", "rh", "compatibility", "hcv", "hbsag", "hv");

        foreach ($tables as $tableName) {
            $tableName = 'cross_' . $tableName;
            $data = R::findAll($tableName, ' deleted = 0 ');
            $this->smarty->assign($tableName, $data);
        }
    }

    function loadAborhSelects() {
        $tables = array("abo", "rh");

        foreach ($tables as $tableName) {
            $tableName = 'cross_' . $tableName;
            $data = R::findAll($tableName, ' deleted = 0 ');
            $this->smarty->assign($tableName, $data);
        }
    }

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

    public function inrcalc() {

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

        $pt_patient = filter_input(INPUT_POST, "pt_patient");
        $id = filter_input(INPUT_POST, "id");

        $inr = 0;
        $concentration = 0;

        if ($id > 0) {
            $pt = R::load('investigationresults_pt', $id);
            $inr = $this->inr_calc($pt_patient, $pt->control_time, $pt->isi);
            $pt->inr = $inr;

            $concentration = $this->concentration_calc($pt_patient);
            $pt->concentration = $concentration;
            r::store($pt);
        } else {
            $inr = $this->inr_calc($pt_patient, 13, 1.06);
            $concentration = $this->concentration_calc($pt_patient);
        }


        echo $inr . '-' . $concentration;
    }

    function inr_calc($pt_patient, $pt_normal, $isi) {
        $res = 0;

        if ($pt_patient > 0) {
            $base = $pt_patient / $pt_normal;
            $res = pow($base, $isi);
            $res = round($res, 2);
        }

        return $res;
    }

    function concentration_calc($pt_patient) {
        $res = 0;

        $sql = ' select id  , concentration 
                        from    pt_concentration  where   deleted = 0 and  
                       inr  =  "' . $pt_patient . '"';


        $data = R::getRow($sql);
        if (count($data) > 0) {
            $res = $data['concentration'];
        } else {
            $res = $this->concentration_average($pt_patient);
        }

        return $res;
    }

    function concentration_average($pt_patient) {
        $res = 0;
        $up = 0;
        $down = 0;

        $up_sql = ' select id  , concentration 
                        from    pt_concentration  where  deleted = 0 and 
                       inr  >  "' . $pt_patient . '" order by  inr asc';
        $up_data = R::getRow($up_sql);

        $down_sql = ' select id  , concentration 
                        from    pt_concentration  where   deleted = 0 and   
                       inr  <  "' . $pt_patient . '" order by  inr desc';
        $down_data = R::getRow($down_sql);

//        print_r($up_sql);
//        print_r($down_data);

        if (count($up_data) > 0) {
            $up = $up_data['concentration'];
        }

        if (count($down_data) > 0) {
            $down = $down_data['concentration'];
        }

        $res = ($up + $down) / 2;

        return $res;
    }

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

#################################################################### Heba : ## get all rays category ##############################################################################

        $sql = ' select id  , inr   , concentration 
                        from    pt_concentration  where 
                       deleted = 0   order by inr ';

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

        $this->smarty->assign('concentrations', $concentrations);
################################################################################################################################################################################
        $this->smarty->display('lab/calculator.html');
    }

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

#################################################################### Heba : ## get all rays category ##############################################################################

        $concentration = R::xdispense('pt_concentration');
        $concentration->deleted = 0;
        $concentration->id = r::store($concentration);

        $sql = ' select id  , inr   , concentration 
                        from    pt_concentration  where 
                       id  =  ' . $concentration->id;

        $data = R::getRow($sql);

        $this->smarty->assign('data', $data);
################################################################################################################################################################################
        $this->smarty->display('lab/newcalculation.html');
    }

    public function resforprint() {

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

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

        $in = R::load('investigationresults', $invResId);

        $visitId = $in->visitid;

        $visit = R::load('visits', $visitId);
        if (!empty($visit->for_doctor)) {
            $doc_info = R::getRow('select * from awusers where user_id = ?', [$visit->for_doctor]);
            $this->smarty->assign('doctor_name', $doc_info['name']);
        } else {
            $this->smarty->assign('doctor_name', '');
        }

        $today = date("Y/m/d");
        $this->smarty->assign('date', $today);
        $this->smarty->assign('dateTime', date("Y/m/d h:i A"));
        $this->smarty->assign('req_date', date('Y/m/d ', strtotime($visit->visitdate)));
        if (!(is_null($visit->visittime))) {
            $this->smarty->assign('req_time', date('h:i A ', strtotime($visit->visittime)));
        }

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

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

        if ($visit->for_husband == 1) {
            $col = 'husbanddateofbirth';
            $gender = 1;
            $this->smarty->assign('name', $patient->husdandname);
            $this->smarty->assign('title', $husbandtypes->title);
            $this->smarty->assign('sex', 'Male');
        } else {
            $col = 'dateofbirth';
            $gender = 0;
            $this->smarty->assign('name', $patient->wifename);
            $this->smarty->assign('title', $wifetypes->title);
            $this->smarty->assign('sex', 'Female');
        }

        if ($patient->$col == '0000-00-00' || is_null($patient->$col) || $patient->$col == '') {
            $age = 0;
        } else {
## calculate wife age
            $dateWife = new DateTime($patient->$col);
            $today1 = new DateTime(date('Y-m-d'));
            $interva2 = $today1->diff($dateWife);
            $age = $interva2->y;
        }

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

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


        $invResults = array();



        $obj = R::load('invests', $in->investid);
        $cat = R::load('investcats', $obj->investcatid);
        $in->invname = $obj->name;
        $in->special_inv_type = $obj->special_inv_type;
        $in->invests = $obj;

        switch ($obj->special_inv_type) {

## urine 
            case 2:
                $urine_count = R::count('investigationresults_urine', 'investigationresults_id = ?', [$in->id]);
                if ($urine_count < 1) {
                    $urine = R::xdispense('investigationresults_urine');
                    $urine->investigationresults_id = $in->id;
                    r::store($urine);
                }
                $in->urine = printUrine($in, $gender, $age, $this->smarty);
                break;

## stool 
            case 3:
                $stool_count = R::count('investigationresults_stool', 'investigationresults_id = ?', [$in->id]);
                if ($stool_count < 1) {
                    $stool = R::xdispense('investigationresults_stool');
                    $stool->investigationresults_id = $in->id;
                    r::store($stool);
                }
                $in->stool = printStool($in, $gender, $age, $this->smarty);
                break;

## blood picture 
            case 1:
                $blood_count = R::count('investigationresults_blood', 'investigationresults_id = ?', [$in->id]);
                if ($blood_count < 1) {
                    $blood = R::xdispense('investigationresults_blood');
                    $blood->investigationresults_id = $in->id;
                    r::store($blood);
                }
                $in->blood = printBlood($in, $gender, $age, $this->smarty);
                break;

## Culture
            case 4:

                $culture_count = R::count('investigationresults_culture', 'investigationresults_id = ?', [$in->id]);
                if ($culture_count < 1) {
                    $culture = R::xdispense('investigationresults_culture');
                    $culture->investigationresults_id = $in->id;
                    r::store($culture);
                }

                $in->culture = printCulture($in, $this->smarty);
                break;

## ESR
            case 5:
                $esr_count = R::count('investigationresults_esr', 'investigationresults_id = ?', [$in->id]);
                if ($esr_count < 1) {
                    $esr = R::xdispense('investigationresults_esr');
                    $esr->investigationresults_id = $in->id;
                    r::store($esr);
                }
//                    $in->esr = $this->printEsr($in, $gender, $age);
                $in->esr = loadEsrRanges($in, $gender, $age, $this->smarty);
                break;

## Cross Matching
            case 6:
                $cross_count = R::count('investigationresults_cross', 'investigationresults_id = ?', [$in->id]);
                if ($cross_count < 1) {
                    $cross = R::xdispense('investigationresults_cross');
                    $cross->investigationresults_id = $in->id;
                    r::store($cross);
                }

                $in->cross = printCross($in, $this->smarty);

                break;

## Fluid
            case 7:
                break;

## Custom
            case 11:
                break;

## Clothing time
            case 8:
                $clothing_count = R::count('investigationresults_times', 'investigationresults_id = ?', [$in->id]);
                if ($clothing_count < 1) {
                    $clothing = R::xdispense('investigationresults_times');
                    $clothing->investigationresults_id = $in->id;
                    r::store($clothing);
                }

                $in->clothing = loadClothingDetails($in, $gender, $age, $this->smarty, 1);
                break;

## PT
            case 9:
                $pt_count = R::count('investigationresults_pt', 'investigationresults_id = ?', [$in->id]);
                if ($pt_count < 1) {
                    $pt = R::xdispense('investigationresults_pt');
                    $pt->investigationresults_id = $in->id;
                    r::store($pt);
                }

                $in->pt = loadPtDetails($in, $gender, $age, $this->smarty, 1);
                break;

## ABO/RH
            case 10:
//                    $pt_count = R::count('investigationresults_pt', 'investigationresults_id = ?', [$in->id]);
//                    if ($pt_count < 1) {
//                        $pt = R::xdispense('investigationresults_pt');
//                        $pt->investigationresults_id = $in->id;
//                        $pt->control_time = 13;
//                        $pt->control_time1 = 30;
//                        $pt->isi = 1.06;
//                        r::store($pt);
//                    }
//
//                    $in->pt = loadPtDetails($in, $gender, $age,$this->smarty ,  0);
//
//                    $in->tableName = 'investigationresults_pt';
//
//                    array_push($special, $in);

                break;

            default :
                $in = printCommon($in, $this->smarty);
                break;
        }


        $this->smarty->assign('catName', $cat->name);
        $this->smarty->assign('inv', $in);

#######
        $this->smarty->display('_main/head.html');
        $this->smarty->display('lab/print_res.html');
    }

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

    public function invStatus() {
//check login
        autho::checkautho($this->hosturl . "/../core");
//check authoize
// autho::checkauthoize($this->controllname, $this->hosturl . "/../core", $_SESSION['role_id']);
        $visitId = filter_input(INPUT_POST, 'visitid');

        $paid = $this->checkVisitBalance($visitId);
        $this->smarty->assign('paid', $paid);

        $visit = R::load('visits', $visitId);
        $patient = R::getRow("SELECT * FROM patients WHERE id = $visit->patientid");

        $for = '';
        if ($visit->for_doctor > 0) {
            $doctor = R::getRow('select * from awusers where user_id = ?', [$visit->for_doctor]);
            $for = $doctor['name'];
        }


        $patientInfo = $this->patientInfo($patient, $visit->for_husband, $visit->child);


        $this->smarty->assign('name', $patientInfo['name']);
        $this->smarty->assign('gender', $patientInfo['gender']);
        $this->smarty->assign('for', $for);
        $this->smarty->assign('age', $patientInfo['age']);
        $this->smarty->assign('statusno', $patient['statusno']);
        $this->smarty->assign('visitid', $visitId);
        $this->smarty->assign('patientid', $visit->patientid);
        $this->smarty->assign('visitNotes', $visit->notes);
        $this->smarty->assign('role_id', $_SESSION['role_id']);



        $sql = ' select  investigationresults.*  , ""  as res
                        , invests.name as invName 
                        from    investigationresults
                          join       invests                                        on invests.id  = investigationresults.investid
                        where  investigationresults.visitid  =  ' . $visitId . '   and  investigationresults.deleted = 0     ';

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

//        $filled = 0;

        $i = 0;
        foreach ($invs as $in) {
            $obj = R::load('invests', $in['investid']);

            switch ($obj->special_inv_type) {
## urine 
                case 2:
## stool 
                case 3:
## blood picture 
                case 1:
## Culture
                case 4:
## ESR
                case 5:
## Cross Matching
                case 6:
## Fluid
                case 7:
## Clothing time
                case 8:
## PT
                case 9:
                case 10:
                case 11:
                    $invs[$i]['res'] = -1;

                    break;
                default:
                    if ($in['rangeid'] > 0) {
                        $range = R::load('inv_ranges', $in['rangeid']);
                        if (is_numeric($range->range_low) && is_numeric($in['investresult']) && $in['investresult'] < $range->range_low) {
                            $invs[$i]['res'] = "Low";
                        } elseif (is_numeric($range->range_high) && is_numeric($in['investresult']) && $in['investresult'] > $range->range_high) {
                            $invs[$i]['res'] = "High";
                        }
                    }
                    break;
            }

            $i++;
        }


        $allowChange = array(1, 12);
        if (in_array($_SESSION['role_id'], $allowChange)) {
            $this->smarty->assign('allowChange', 1);
        }

        $this->smarty->assign('requests', $invs);
        $this->smarty->display('lab/invstatus.html');
    }

    function patientInfo($patient, $for_husband, $child) {
        $programesetting = R::findOne('programesetting');
        $wifetypes = R::load('wifetypes', $patient->wiftypeid);
        $husbandtypes = R::load('husbandtypes', $patient->husbandtypeid);
        $result = array();
        $title = '';

        if ($programesetting->system_lang == 2) {
            $date = $patient['dateofbirth'];
            $name = $patient['wifename'];
            $sex = $patient['gender'];
            $title = $wifetypes->title;
        } else {
            $age = '';
            $ageUnit = 0;

            if ($for_husband == 1) {
                $date = $patient['husbanddateofbirth'];
                $name = $patient['husdandname'];
                $sex = 1;
                $title = $husbandtypes->title;
            } else if ($for_husband == 2) {
                $child = R::load('patients_childs', $child);
                $sex = $child->gender;
                $date = $child->birth_date;

                if (is_null($child->child_name) || $child->child_name == '') {
                    if ($child->gender == 1) {
                        $name = 'الطفل / ' . $patient['wifename'];
                    } else {
                        $name = 'الطفلة / ' . $patient['wifename'];
                    }
                } else {
                    $name = $child->child_name . '  /  ' . $patient['wifename'];
                }
            } else {
                $date = $patient['dateofbirth'];
                $name = $patient['wifename'];
                $sex = 0;
                $title = $wifetypes->title;
            }
        }


        if ($sex == 1) {
            $gender = 'Male';
        } else {
            $gender = 'Female';
        }


        if ($date != '0000-00-00' && $date != '' && $date != Null) {
            $dateN = new DateTime($date);
            $today1 = new DateTime(date('Y-m-d'));
            $interval = $today1->diff($dateN);
        }

        if ($interval->y > 0) {
            $ageNo = $interval->y;
            $age = $interval->y . ' Years';
            $ageUnit = 1;
        } elseif ($interval->m > 0) {
            $ageNo = $interval->m;
            $age = $interval->m . ' Months';
            $ageUnit = 2;
        } elseif ($interval->d >= 0) {
            $ageNo = 1 + $interval->d;
            $age = 1 + $interval->d . ' Days';
            $ageUnit = 3;
        }

        $result['name'] = $name;
        $result['gender'] = $gender;
        $result['sex'] = $sex;
        $result['age'] = $age;
        $result['ageNo '] = $ageNo;
        $result['ageUnit'] = $ageUnit;
        $result['title'] = $title;
        return $result;
    }

    public function invStatusChange() {
//check login
        autho::checkautho($this->hosturl . "/../core");
//check authoize
// autho::checkauthoize($this->controllname, $this->hosturl . "/../core", $_SESSION['role_id']);
        $id = filter_input(INPUT_POST, 'id');
        $colName = filter_input(INPUT_POST, 'colName');
        $value = filter_input(INPUT_POST, 'value');

        try {
            $invs = R::load('investigationresults', $id);
            $invs->$colName = $value;

            if ($colName == 'filled' || $colName == 'verified' || $colName == 'printed' || $colName == 'delivered' || $colName == 'sent') {
                $userColName = $colName . '_user';
                $invs->$userColName = $_SESSION['user_id'];
            }


            if ($colName == 'delivered' && $value == 1) {
                $obj = R::load('invests', $invs->investid);
                $uploaded = $this->uploadingFile($invs->pdf, $obj->pdf, $invs->visitid, $id);
                if ($uploaded == 1) {
                    r::store($invs);
                    echo $uploaded;
                } else {
                    echo json_encode($uploaded);
                }
            } else {
                r::store($invs);
                echo 1;
            }
        } catch (Exception $ex) {
            echo $ex;
        }
    }

    function uploadingFile($pdf, $hasPdf, $visitid, $invResId) {
        $patArray = $this->preparePatArray($visitid);
        if ($hasPdf == 1 && $pdf != '') {
            $dataArray = $this->prepareDataArray($patArray, $invResId);
            $uploaded = sendPdf($pdf, $dataArray);
        } else {
            $uploaded = $this->exportPdf($invResId, $patArray);
        }

        return $uploaded;
    }

    function exportPdf($invResId, $patArray) {

        $htmlHead = ' <html>  <head>  <style>
         .right{
            float:right;
        }
        .left{
            float:left;
        }
        .txtr{
            text-align:right;
        }
        .txtl{
            text-align:left;
        }
        .txtc{
            text-align:center;
        }
        .bold{
            font-weight: bold ;
        } 
        .underline{
            text-decoration: underline ;
        }
        .wds1{width:1% !important;}.wds2{width:2%;}.wds3{width:3%;}.wds4{width:4%;}.wds5{width:5%;}.wds6{width:6%;}.wds7{width:7%;}.wds8{width:8%;}.wds9{width:9%;}.wds10{width:10%;}.wds11{width:11%;}.wds12{width:12%;}.wds13{width:13%;}.wds14{width:14%;}.wds15{width:15%;}.wds16{width:16%;}.wds17{width:17%;}.wds18{width:18%;}.wds19{width:19%;}.wds20{width:20%;}.wds21{width:21%;}.wds22{width:22%;}.wds23{width:23%;}.wds24{width:24%;}.wds25{width:25%;}.wds26{width:26%;}.wds27{width:27%;}.wds28{width:28%;}.wds29{width:29%;}.wds30{width:30%;}.wds31{width:31%;}.wds32{width:32%;}.wds33{width:33%;}.wds34{width:34%;}.wds35{width:35%;}.wds36{width:36%;}.wds37{width:37%;}.wds38{width:38%;}.wds39{width:39%;}.wds40{width:40%;}.wds41{width:41%;}.wds42{width:42%;}.wds43{width:43%;}.wds44{width:44%;}.wds45{width:45%;}.wds46{width:46%;}.wds47{width:47%;}.wds48{width:48%;}.wds49{width:49%;}.wds50{width:50%;}.wds51{width:51%;}.wds52{width:52%;}.wds53{width:53%;}.wds54{width:54%;}.wds55{width:55%;}.wds56{width:56%;}.wds57{width:57%;}.wds58{width:58%;}.wds59{width:59%;}.wds60{width:60%;}.wds61{width:61%;}.wds62{width:62%;}.wds63{width:63%;}.wds64{width:64%;}.wds65{width:65%;}.wds66{width:66%;}.wds67{width:67%;}.wds68{width:68%;}.wds69{width:69%;}.wds70{width:70%;}.wds71{width:71%;}.wds72{width:72%;}.wds73{width:73%;}.wds74{width:74%;}.wds75{width:75%;}.wds76{width:76%;}.wds77{width:77%;}.wds78{width:78%;}.wds79{width:79%;}.wds80{width:80%;}.wds81{width:81%;}.wds82{width:82%;}.wds83{width:83%;}.wds84{width:84%;}.wds85{width:85%;}.wds86{width:86%;}.wds87{width:87%;}.wds88{width:88%;}.wds89{width:89%;}.wds90{width:90%;}.wds91{width:91%;}.wds92{width:92%;}.wds93{width:93%;}.wds94{width:94%;}.wds95{width:95%;}.wds96{width:96%;}.wds97{width:97%;}.wds98{width:98%;}.wds99{width:99%;}.wds100{width:100%;}

        .catName{
            font-size: 16px;
        }

        .vtop{
            vertical-align: top;
        }

        .col-med{
            float: left;
            position: relative;
            min-height: 1px;
            padding-right: 0;
            padding-left: 0;
        }

        ol, ul , h4 {
            margin-top:  0;
            margin-bottom:   0;
        }

        .ptop10 {
            margin-top:  10px;
        }
        
        .ptop0 {
            margin-top:  0;
        }
        
.pbottom0 {
            margin-bottom:  0;
        }

        td{
            vertical-align: top;
        }

        .p5{
            margin-right:   5px;
            margin-left : 5px;
        }

        .p10{
            padding-right:   10px;
            padding-left : 10px;
        }

        .m25{
            margin-left: 25%; 
            margin-bottom:   3px;
        }
           </style> </head>   <body>  ';

        $htmlHead .= ' <hr style="border: 1px solid black;  margin: 0;">
<br><table  style="width: 100%; " >
    <tr style="line-height: 20px; ">
        <td style="width: 25%;font-weight: bolder;"> Patient Name   </td>
        <td style="width: 25%;"> ' . $patArray['name'] . '   </td>
        <td style="width: 25%;font-weight: bolder;"> Patient ID   </td>
        <td style="width: 25%;"> <img id="xx"  src="' . $this->hosturl . '/../upload/barcodes/' . $patArray['statusno'] . '.png" height="20">     </td>
    </tr>
    <tr style="line-height: 20px; ">
        <td style="width: 25%;font-weight: bolder;"> Age / Sex    </td>
        <td style="width: 25%;">  ' . $patArray['ageAll'] . '    /  ' . $patArray['sex'] . '      </td>
        <td style="width: 25%;font-weight: bolder;"> Requested Date     </td>
        <td style="width: 25%;">  ' . $patArray['req_date'] . '   ' . $patArray['req_time'] . ' </td>
    </tr>
    <tr style="line-height: 20px; ">
        <td style="width: 25%;font-weight: bolder;"> Referred By   </td>
        <td style="width: 25%;"> ' . $patArray['doctor_name'] . '     </td>
        <td style="width: 25%;font-weight: bolder;"> Printed In   </td>
        <td style="width: 25%;">    ' . $patArray['dateTime'] . '      </td>
    </tr>
</table>
<hr style="border: 1px solid black;  margin: 0;">
<div class="row">
    <div class="col-md-12">';



        $htmlFoot = '<br><br><table   class="noborder wds98" >
    <tr style="line-height: 15px; ">
        <td style="width: 70%;">
                <span style="margin-right: 20%">        </span>
        </td>
        <td style="width: 30%;">
                <span style="float: left;    margin-left: 41%;font-weight: bolder;">Doctors Signature </span>
        </td>
    </tr>
    <tr style="line-height: 15px; ">
        <td style="width: 70%;">
                <span style="margin-right: 20%">        </span>
        </td>
        <td style="width: 30%;">
                <span style="float: left;    margin-left: 45%;font-weight: bolder;">Thanks </span>
        </td>
    </tr>
        <tr>
        <td style="width: 70%;">
                <span style="margin-right: 20%">        </span>
        </td>
        <td style="width: 30%;">
            <img   src="' . $this->hosturl . '/../upload/signatures/dr_signature.jpeg" height="50" width="150">     </td>
        </td>
    </tr>
</table></div>
</div>';

        $htmlFoot .= '</body></html>';

        $dataArray = array();
        $dataArray['name'] = $patArray['name'];
        $dataArray['royal_patient_id'] = $patArray['patientid'];
        $dataArray['age'] = $patArray['ageAll'];
        $dataArray['sex'] = $patArray['sex'];
        $dataArray['referred_by'] = $patArray['doctor_name'];
        $dataArray['phone'] = $patArray['phone'];
        $dataArray['requested_date'] = $patArray['req_date'];
        $dataArray['printed_date'] = $patArray['dateTime'];
        $dataArray['visit_id'] = $patArray['visitId'];
        $dataArray['statusno'] = $patArray['statusno'];

        $res = investsForPdf($dataArray, $htmlHead, $htmlFoot, $invResId, $patArray['gender'],
                $patArray['age'], $patArray['ageUnit'], $this->smarty, 1);
        return $res;
    }

    function prepareDataArray($patArray, $invResId) {

        $dataArray = array();
        $dataArray['name'] = $patArray['name'];
        $dataArray['royal_patient_id'] = $patArray['patientid'];
        $dataArray['age'] = $patArray['ageAll'];
        $dataArray['sex'] = $patArray['sex'];
        $dataArray['referred_by'] = $patArray['doctor_name'];
        $dataArray['phone'] = $patArray['phone'];
        $dataArray['requested_date'] = $patArray['req_date'];
        $dataArray['printed_date'] = $patArray['dateTime'];
        $dataArray['visit_id'] = $patArray['visitId'];
        $dataArray['statusno'] = $patArray['statusno'];

        $in = R::load('investigationresults', $invResId);
        $obj = R::load('invests', $in->investid);
        $cat = R::load('investcats', $obj->investcatid);

        $dataArray['test_name'] = $obj->name;
        $dataArray['invResId'] = $invResId;
        $dataArray['is_pathology'] = $cat->pathology;
        return $dataArray;
    }

    function preparePatArray($visitId) {
        $visit = R::load('visits', $visitId);


        $doctor_name = '';
        if (!empty($visit->for_doctor)) {
            $doc_info = R::getRow('select * from awusers where user_id = ?', [$visit->for_doctor]);
            $doctor_name = $doc_info['name'];
        }


        $today = date("Y/m/d");
        $this->smarty->assign('date', $today);
        $dateTime = date("Y/m/d h:i A");
        $this->smarty->assign('dateTime', date("Y/m/d h:i A"));
        $req_date = date('Y/m/d ', strtotime($visit->visitdate));
        if (!(is_null($visit->visittime))) {
            $req_time = date('h:i A ', strtotime($visit->visittime));
        }

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

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

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

        if ($visit->for_husband == 1) {
            $date = $patient->husbanddateofbirth;
            $gender = 1;

            $name = $patient->husdandname;
            $title = $husbandtypes->title;
            $sex = 'Male';
        }
###
        else if ($visit->for_husband == 2) {
            $child = R::load('patients_childs', $visit->child);
            $date = $child->birth_date;

            if ($child->gender == 1) {
                $gender = 1;
                $title = 'الطفل  ';
                $sex = 'Male  ';
            } else {
                $gender = 0;
                $title = 'الطفلة  ';
                $sex = 'Female  ';
            }

            $name = $child->child_name;
        }
###
        else {
            $date = $patient->dateofbirth;
            $gender = 0;
            $name = $patient->wifename;
            $title = $wifetypes->title;
            $sex = 'Female';
        }


        if ($date == '0000-00-00' || is_null($date) || $date == '') {
            $age = 0;
        } else {
## calculate wife age
            $dateWife = new DateTime($date);
            $today1 = new DateTime(date('Y-m-d'));
            $interval = $today1->diff($dateWife);
        }

        if ($interval->y > 0) {
            $ageAll = $interval->y . ' Years';
            $age = $interval->y;
            $ageUnit = 1;
        } elseif ($interval->m > 0) {
            $ageAll = $interval->m . ' Months';
            $age = $interval->m;
            $ageUnit = 2;
        } elseif ($interval->d > 0) {
            $ageAll = $interval->d . ' Days';
            $age = $interval->d;
            $ageUnit = 3;
        }



        $patArray = array();
        $patArray['name'] = $name;
        $patArray['statusno'] = $patient->statusno;
        $patArray['ageAll'] = $ageAll;
        $patArray['sex'] = $sex;
        $patArray['req_date'] = $req_date;
        $patArray['req_time'] = $req_time;
        $patArray['doctor_name'] = $doctor_name;
        $patArray['dateTime'] = $dateTime;
        $patArray['patientid'] = $visit->patientid;
        $patArray['phone'] = $patient->phone;
        $patArray['age'] = $age;
        $patArray['ageUnit'] = $ageUnit;
        $patArray['gender'] = $gender;
        $patArray['visitId'] = $visitId;

        return $patArray;
    }

    public function invsData() {
//check login
        autho::checkautho($this->hosturl);
//check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
#################################################################### Heba : ## get all rays category ##############################################################################

        $cats = R::findall('investcats', 'deleted = ? and displayorder != ?', [0, -1]);
        $this->smarty->assign('cats', $cats);

        $invests = R::findall('invests', ' deleted = ?', [0]);
        $this->smarty->assign('invests', $invests);

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

    public function getinvbycatid() {      ## get all investigation in certain category
//check login
        autho::checkautho($this->hosturl);
//check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

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

        if ($catId > 0) {
            $invests = R::findall('invests', 'investcatid = ? and deleted = ?', [$catId, 0]);
        } else {
            $invests = R::findall('invests', ' deleted = ?', [0]);
        }


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

        $this->smarty->display('lab/invests.html');
    }

    public function printinvs() {
//check login
        autho::checkautho($this->hosturl . "/../core");
//check authoize
// autho::checkauthoize($this->controllname, $this->hosturl . "/../core", $_SESSION['role_id']);
        $catId = filter_input(INPUT_POST, "catId");
        $invId = filter_input(INPUT_POST, "invId");
        $from = filter_input(INPUT_POST, "from");
        $to = filter_input(INPUT_POST, "to");

        $sqlPat = '';

        if ($invId > 0) {
            $sqlPat .= ' and  investigationresults.investid =  ' . $invId;
        }

        if ($catId > 0) {
            $sqlPat .= ' and  invests.investcatid =  ' . $catId;
        }

        $sql = ' select distinct   invests.investcatid as catId  , investcats.name as catName
           
                        from    investigationresults
                         join     visits                                               on visits.id  = investigationresults.visitid
                          join       invests                                        on invests.id  = investigationresults.investid 
                             left   join       investcats                          on investcats.id  = invests.investcatid 
                          left   join       sampletype                          on sampletype.id  = invests.sampletype
                        where  visits.visitdate  between "' . $from . '"  AND  "' . $to . '"  
                and  investigationresults.deleted = 0      ' . $sqlPat . '    ';

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

        $i = 0;
        foreach ($cats as $cat) {
            $sql = ' select distinct investigationresults.investid  ,  invests.name as invName
                        ,  sampletype.name as sampleType 
           
                        from    investigationresults
                         join     visits                                               on visits.id  = investigationresults.visitid
                          join       invests                                        on invests.id  = investigationresults.investid 
                             left   join       investcats                          on investcats.id  = invests.investcatid 
                          left   join       sampletype                          on sampletype.id  = invests.sampletype
                        where  visits.visitdate  between "' . $from . '"  AND  "' . $to . '"  
                and  investigationresults.deleted = 0 and invests.investcatid  =  ' . $cat['catId'] . '       ' . $sqlPat . '    ';

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

            $j = 0;
            foreach ($res as $data) {
                $sql = ' select  count(investigationresults.investid) as testsNo
                        from    investigationresults
                         join     visits                                               on visits.id  = investigationresults.visitid
                          join       invests                                        on invests.id  = investigationresults.investid
                        where  visits.visitdate  between "' . $from . '"  AND  "' . $to . '"  
                and  investigationresults.deleted = 0 and      investigationresults.investid =  ' . $data['investid'];

                $testsNo = R::getRow($sql);

                $res[$j]['testsNo'] = $testsNo['testsNo'];

                $j++;
            }

            $cats[$i]['invests'] = $res;
            $cats[$i]['invCount'] = count($res);
            $i++;
        }


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

        $this->suppliesPrint($from, $to);
        $this->smarty->display('lab/result_invest_print.html');
    }

    function suppliesPrint($from, $to) {

        $sql = ' select distinct   supplies.catid as catId  , suppliescats.name as catName
           
                        from    invests_supplies
                         join       supplies                                        on supplies.id  = invests_supplies.supply_id 
                        left   join       suppliescats                          on suppliescats.id  = supplies.catid 
                      
                        where  invests_supplies.usedate  between "' . $from . '"  AND  "' . $to . '"  
                               and  invests_supplies.deleted = 0    ';

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

        $i = 0;
        foreach ($suppCats as $cat) {
            $sql = ' select distinct invests_supplies.supply_id  ,  supplies.name as supplyName
           
                        from    invests_supplies
                        join       supplies                                        on supplies.id  = invests_supplies.supply_id 
                        
                          where  invests_supplies.usedate  between "' . $from . '"  AND  "' . $to . '"  
                               and  invests_supplies.deleted = 0  and supplies.catid  =  ' . $cat['catId'] . '      ';

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

            $j = 0;
            foreach ($res as $data) {
                $sql = ' select  sum(invests_supplies.supply_no) as testsNo
                        from    invests_supplies
                        
                             where  invests_supplies.usedate  between "' . $from . '"  AND  "' . $to . '"  
                and  invests_supplies.deleted = 0 and      invests_supplies.supply_id =  ' . $data['supply_id'];

                $testsNo = R::getRow($sql);

                $res[$j]['testsNo'] = $testsNo['testsNo'];

                $j++;
            }

            $suppCats[$i]['supplies'] = $res;
            $i++;
        }


        $this->smarty->assign('suppCats', $suppCats);
    }

    public function searchinvs() {
//check login
        autho::checkautho($this->hosturl . "/../core");
//check authoize
// autho::checkauthoize($this->controllname, $this->hosturl . "/../core", $_SESSION['role_id']);
        $catId = filter_input(INPUT_POST, "catId");
        $invId = filter_input(INPUT_POST, "invId");
        $from = filter_input(INPUT_POST, "from");
        $to = filter_input(INPUT_POST, "to");

        $sqlPat = '';

        if ($invId > 0) {
            $sqlPat .= ' and  investigationresults.investid =  ' . $invId;
        }

        if ($catId > 0) {
            $sqlPat .= ' and  invests.investcatid =  ' . $catId;
        }


        $sql = ' select distinct investigationresults.investid  ,  invests.name as invName
                        ,  sampletype.name as sampleType , investcats.name as catName
           
                        from    investigationresults
                         join     visits                                               on visits.id  = investigationresults.visitid
                          join       invests                                        on invests.id  = investigationresults.investid 
                             left   join       investcats                          on investcats.id  = invests.investcatid 
                          left   join       sampletype                          on sampletype.id  = invests.sampletype
                        where  visits.visitdate  between "' . $from . '"  AND  "' . $to . '"  
                and  investigationresults.deleted = 0      ' . $sqlPat . '    ';

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

        $i = 0;
        foreach ($res as $data) {
            $sql = ' select  investigationresults.investid  
                        from    investigationresults
                         join     visits                                               on visits.id  = investigationresults.visitid
                          join       invests                                        on invests.id  = investigationresults.investid
                        where  visits.visitdate  between "' . $from . '"  AND  "' . $to . '"  
                and  investigationresults.deleted = 0 and      investigationresults.investid =  ' . $data['investid'];

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

            $res[$i]['testsNo'] = count($invests);

            $i++;
        }


        $this->smarty->assign('requests', $res);
        $this->smarty->assign('rescount', count($res));
        $this->smarty->display('lab/result_invest_data.html');
    }

    public function checkRange() {
//check login
        autho::checkautho($this->hosturl . "/../core");
//check authoize
// autho::checkauthoize($this->controllname, $this->hosturl . "/../core", $_SESSION['role_id']);
        $id = filter_input(INPUT_POST, "id");
        $value = filter_input(INPUT_POST, "value");
        $tablename = filter_input(INPUT_POST, "tableName");
        $colname = filter_input(INPUT_POST, "colName");

        $obj = R::load($tablename, $id);

        $exist = 0;
        $investId = 0;

        if ($tablename == 'investigationresults') {
            $investId = $obj->investid;
            $invRes = $obj;
        } elseif ($obj->investigationresults_id > 0) {
            $invRes = R::load('investigationresults', $obj->investigationresults_id);
            $investId = $invRes->investid;
        }

        if ($investId > 0) {
            $invest = R::load('invests', $investId);
            $visit = R::load('visits', $invRes->visitid);

            switch ($invest->special_inv_type) {

## urine 
                case 2:
                    $elements = array("Volume" => "volume", "Color" => "color", "Odor" => "odor", "Aspect" => "aspect"
                        , "Deposit" => "deposit", "Reaction" => "reaction", "Protein" => "protein", "Sugar" => "sugar", "Acetone" => "acetone"
                        , "Nitrite" => "nitrite", "Specific Gravity" => "gravity", "Bilirubin" => "bilirubin", "Urobilinigen" => "urobilinigen"
                        , "Leucocytes" => "leucocytes", "Blood" => "blood", "Pus Cells" => "pus", "R.B.Cs" => "pbcs"
                        , "Epithelial Cells" => "epithelial", "Casts" => "casts", "Crystal" => "crystal", "Amorphous" => "amorphous"
                        , "Ova" => "ova", "Trophazite" => "trophazite", "Mucus" => "mucus", "Urine Artifacts" => "artifacts"
                        , "Fungi" => "fungi", "Bacteria" => "bacteria"
                    );
                    $exist = $this->checkElement($elements, $colname, $visit, $invest->special_inv_type, $value);
                    break;


## stool 
                case 3:
                    $elements = array("Consistency" => "consistency", "Food Particles" => "food", "Blood" => "blood"
                        , "Color" => "color", "Reaction" => "reaction", "Odor" => "odor"
                        , "Mucus" => "mucus", "Proglottids" => "prog", "Flagellates" => "flagellates"
                        , "Ciliate" => "ciliate", "Undigested Food" => "undigested", "Parasitology Artifacts" => "parasitology"
                        , "WBCs" => "wbc", "RBCs" => "rbc", "Trophozoite" => "trophozoite"
                        , "Cysts" => "cysts", "Ova" => "ova", "Larva" => "larva"
                    );
                    $exist = $this->checkElement($elements, $colname, $visit, $invest->special_inv_type, $value);
                    break;


## blood picture 
                case 1:
                    $elements = array("Hgb" => "hgb", "RBC" => "rbc", "Plt" => "plt", "WBC" => "wbc"
                        , "Hct" => "hct", "MCV" => "mcv_calc", "MCH" => "mch_calc", "MCHC" => "mchc_calc"
                        , "RDW" => "rdw", "Mentzer Index %" => "mindex", "Other Cells" => "othercells"
                        , "Segmented" => "segmented", "Band" => "band", "Pct" => "pct", "MPV" => "mpv"
                        , "PDW" => "pdw", "NRBC / 100 WBC" => "nrbc", "Promyelocyte" => "promyelocyte"
                        , "Myelocytes" => "myelocyte", "Juvenile" => "juvenile", "Blast" => "blast", "Hgb %" => "hgbpercent"
                        , "Relative Neutrophil" => "neutrophil_r", "Relative Lymphocytes" => "lymphocytes_r"
                        , "Relative Monocytes" => "monocytes_r", "Relative Eosinophils" => "eosinophils_r"
                        , "Relative Basophils" => "basophils_r", "Absolute Neutrophil" => "neutrophil_abs"
                        , "Absolute Lymphocytes" => "lymphocytes_abs", "Absolute Monocytes" => "monocytes_abs"
                        , "Absolute Eosinophils" => "eosinophils_abs", "Absolute Basophils" => "basophils_abs"
                    );
                    $exist = $this->checkElement($elements, $colname, $visit, $invest->special_inv_type, $value);
                    break;


## Culture
                case 4:

                    break;


## ESR
                case 5:
                    $elements = array("hour1" => "hour1", "hour2" => "hour2");
                    $exist = $this->checkElement($elements, $colname, $visit, $invest->special_inv_type, $value);
                    break;

## Cross Matching
                case 6:
                    break;

## Fluid
                case 7:
                    break;

## Custom
                case 11:
                    break;


## Clothing time
                case 8:
                    $elements = array("Bleeding Time" => "bleeding", "Clothing Time" => "clothing");
                    $exist = $this->checkElement($elements, $colname, $visit, $invest->special_inv_type, $value);
                    break;


## PT
                case 9:
                    $elements = array("PT Patient's Time" => "patient_time", "APTT Patient's Time" => "patient_time1"
                        , "Concentration" => "concentration", "I.N.R" => "inr", "Ratio" => "ratio"
                        , "Fibrinogen" => "fibrinogen", "FDP" => "fdp");
                    $exist = $this->checkElement($elements, $colname, $visit, $invest->special_inv_type, $value);
                    break;


                default :
                    if ($invRes->rangeid > 0) {
                        $range = R::load('inv_ranges', $invRes->rangeid);

                        if (is_numeric($range->range_low) && is_numeric($value) && $value < $range->range_low) {
                            $exist = 1;
                        } elseif (is_numeric($range->range_high) && is_numeric($value) && $value > $range->range_high) {
                            $exist = 1;
                        }
                    }
                    break;
            }
        }


        echo $exist;
    }

    function checkElement($elements, $dbName, $visit, $special_inv_type, $value) {
        $exist = 0;

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

        if ($visit->for_husband == 1) {
            $gender = 1;
            $col = 'husbanddateofbirth';
        } else {
            $gender = 0;
            $col = 'dateofbirth';
        }

        if ($patient->$col == '0000-00-00' || is_null($patient->$col) || $patient->$col == '') {
            $age = 0;
        } else {
## calculate wife age
            $dateWife = new DateTime($patient->$col);
            $today1 = new DateTime(date('Y-m-d'));
            $interva2 = $today1->diff($dateWife);
            $age = $interva2->y;
        }

        $showNameArr = array_keys($elements, $dbName);
        $showName = $showNameArr[0];

        $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and agefrom <= ? 
                    and ageto >= ?     and age_units = ?   and invest_child = ?  and special_inv_type = ? 
                    ', [$gender, '', -1, $age, $age, 1, $showName, $special_inv_type]);

        if (!(count($range) > 0 )) {


            $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?   || gender = ?)  and ( agefrom = ?  || agefrom = ?  ) 
                    and ( ageto = ?  || ageto = ?  )      and invest_child = ?   and special_inv_type = ? 
                    ', [$gender, '', -1, Null, '', Null, '', $showName, $special_inv_type]);
        }

        if (count($range) > 0) {

            if (is_numeric($range->range_low) && is_numeric($value) && $value < $range->range_low) {
                $exist = 1;
            }

####
            elseif (is_numeric($range->range_high) && is_numeric($value) && $value > $range->range_high) {
                $exist = 1;
            }
        }

        return $exist;
    }

    public function invStatusChangeAll() {
//check login
        autho::checkautho($this->hosturl . "/../core");
//check authoize
// autho::checkauthoize($this->controllname, $this->hosturl . "/../core", $_SESSION['role_id']);
        $visitId = filter_input(INPUT_POST, 'visitId');
        $colName = filter_input(INPUT_POST, 'colName');
        $userColName = $colName . '_user';

        $sum = R::getRow(' select sum(' . $colName . ') as colSum    , count(id) as  noOfInvs
                        from    investigationresults
                       where   deleted = 0 and   visitid =      ' . $visitId . '   ');

        if ($sum['colSum'] < $sum['noOfInvs']) {
            $value = 1;
        } else {
            $value = 0;
        }


        R::exec(' update  investigationresults   set  ' . $colName . '  =    ' . $value . '  
                    ,       ' . $userColName . '  =    ' . $_SESSION['user_id'] . '    
                       where   deleted = 0 and   visitid =      ' . $visitId . '   ');
    }

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

    public function suppliesModel() {
//check login
        autho::checkautho($this->hosturl);
//check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
#################################################################### Heba : ## get all rays category ##############################################################################

        $useDate = filter_input(INPUT_POST, 'useDate');
        if ($useDate == 1) {
            $date = $this->today;
        } else {
            $date = $useDate;
        }

        $cats = R::findall('suppliescats', 'deleted = ? ', [0]);
        $this->smarty->assign('cats', $cats);

        $supplies = R::findall('supplies', ' deleted = ?', [0]);
        $this->smarty->assign('supplies', $supplies);

        $this->smarty->assign('today', $date);

        $this->suppliesByDate($date, $date);

        $this->smarty->display('lab/supplies.html');
    }

    function suppliesByDate($from, $to) {

        $sql = ' select distinct   supplies.catid as catId  , suppliescats.name as catName
           
                        from    invests_supplies
                         join     supplies                                               on supplies.id  = invests_supplies.supply_id
                          join       suppliescats                                        on suppliescats.id  = supplies.catid 
                        where  invests_supplies.usedate  between "' . $from . '"  AND  "' . $to . '"  
                      and  invests_supplies.deleted = 0       ';

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

        $i = 0;
        foreach ($cats as $cat) {
            $sql = ' select   distinct  invests_supplies.supply_id as supplyId  , supplies.name as suppName
                                        ,    0 as suppNo 
                        from    invests_supplies
                         join     supplies                                               on supplies.id  = invests_supplies.supply_id
                          join       suppliescats                                        on suppliescats.id  = supplies.catid 
                        where  invests_supplies.usedate  between "' . $from . '"  AND  "' . $to . '"  
                      and  invests_supplies.deleted = 0 and  supplies.catid =   ' . $cat['catId'];

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

            $x = 0;
            foreach ($suppliers as $sup) {
                $sql = ' select    sum(invests_supplies.supply_no) as suppNos 
                        from    invests_supplies
                        where  invests_supplies.usedate  between "' . $from . '"  AND  "' . $to . '"  
                      and  invests_supplies.deleted = 0 and  invests_supplies.supply_id =   ' . $sup['supplyId'];

                $supps = R::getRow($sql);
                $suppliers[$x]['suppNo'] = $supps['suppNos'];
                $x++;
            }



            $cats[$i]['supp'] = $suppliers;

            $i++;
        }




        $this->smarty->assign('suppliesCats', $cats);
################################################################################################################################################################################
    }

    public function suppliesCatModal() {
//check login
        autho::checkautho($this->hosturl);
//check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
#################################################################### Heba : ## get all rays category ##############################################################################
        $useDate = filter_input(INPUT_POST, 'useDate');

        $cats = R::findall('suppliescats', 'deleted = ? ', [0]);
        $this->smarty->assign('cats', $cats);
        $this->smarty->assign('useDate', $useDate);

        $this->smarty->display('lab/suppliesCats.html');
    }

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

        $newcat = R::xdispense('suppliescats');
        $newcat->name = "";
        $newcat->deleted = 0;
        try {
            $id = R::store($newcat);
            echo $id;
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
################################################################################################################################################################################
    }

    public function loadDateSupplies() {
//check login
        autho::checkautho($this->hosturl);
//check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
#################################################################### Heba : ## get all rays category ##############################################################################

        $useDate = filter_input(INPUT_POST, 'useDate');

        $this->suppliesByDate($useDate, $useDate);

        $this->smarty->display('lab/invSupplies.html');
    }

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

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

        $supplies = R::findall('supplies', 'catid = ? and deleted = ?', [$catId, 0]);

        $this->smarty->assign('supplies', $supplies);
        $this->smarty->assign('catId', $catId);
// $this->smarty->assign('invest_itr', count($invests));
        $this->smarty->display('lab/suppliesByCat.html');
    }

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

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

        if ($catId == -1) {
            $supplies = R::findall('supplies', ' deleted = ?', [0]);
            $this->smarty->assign('supplies', $supplies);
        } elseif ($catId > 0) {
            $supplies = R::findall('supplies', 'catid = ? and deleted = ?', [$catId, 0]);
            $this->smarty->assign('supplies', $supplies);
        }

        $this->smarty->display('lab/supps.html');
    }

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

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

        $newcat = R::xdispense('supplies');
        $newcat->catid = $catId;
        $newcat->name = "";
        $newcat->deleted = 0;
        try {
            $id = R::store($newcat);
            echo $id;
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
################################################################################################################################################################################
    }

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

        $catId = filter_input(INPUT_POST, "suppliesCats");

        $useDate = filter_input(INPUT_POST, "usedate");
        $useDate = date('Y/m/d', strtotime($useDate));

        try {
            if ($catId == -1) {
                $supplies = R::findall('supplies', ' deleted = ?', [0]);
            } elseif ($catId > 0) {
                $supplies = R::findall('supplies', 'catid = ? and deleted = ?', [$catId, 0]);
            }

            foreach ($supplies as $supply) {
                $supply_no = filter_input(INPUT_POST, "supply_no" . $supply->id);
                if ($supply_no > 0) {
                    $newcat = R::xdispense('invests_supplies');
                    $newcat->supply_id = $supply->id;
                    $newcat->usedate = $useDate;
                    $newcat->supply_no = $supply_no;
                    $newcat->deleted = 0;

                    R::store($newcat);
                }
            }
        } catch (Exception $e) {
            echo -1;
        }
################################################################################################################################################################################
    }

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

    public function uploadone() {

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

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

        $invs = R::load('investigationresults', $id);
        $visit = R::load('visits', $invs->visitid);
        $patient = R::load('patients', $visit->patientid);

        $folder = 'inv_pdf/' . $patient->statusno;


        try {

            $name = 'file-0';
            $fileName = uploadnew($name, False, 0, 0, $folder, False);

            $invs->pdf = $fileName;
            R::store($invs);

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

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

    public function editModal() {

        $tableName = filter_input(INPUT_POST, "tableName");
        $colName = filter_input(INPUT_POST, "colName");
        $delColName = filter_input(INPUT_POST, "delColName");
        $selectClass = filter_input(INPUT_POST, "selectClass");
        $defaultValue = filter_input(INPUT_POST, "defaultValue");

        if ($defaultValue == 1) {
            $sql = ' select id  , ' . $colName . '  , default_value  from ' . $tableName;
        } else {
            $sql = ' select id  , ' . $colName . ' from ' . $tableName;
        }



        if (!empty($delColName) && $delColName != '' && $delColName != null) {
            $sql .= ' where  ' . $delColName . ' != 1 ';
        }

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

        $this->smarty->assign('alldata', $alldata);
        $this->smarty->assign('colName', $colName);
        $this->smarty->assign('tableName', $tableName);
        $this->smarty->assign('selectClass', $selectClass);
        $this->smarty->assign('defaultValue', $defaultValue);
        $this->smarty->display('lab/editmodel.html');
    }

    public function fix() {

        $urines = R::findAll('investigationresults_urine');

        print_r(' <br>  urine  <br> ');
        foreach ($urines as $urine) {
####  pus   
            if ($urine->pus > 0) {
                $pus = R::load('urine_pus', $urine->pus);
                $urine->pus = $pus->name;
            }

####  pus2   
            if ($urine->pus2 > 0) {
                $pus2 = R::load('urine_pus2', $urine->pus2);
                $urine->pus2 = $pus2->name;
            }

            if ($urine->pbcs > 0) {
                $pbcs = R::load('urine_pbcs', $urine->pbcs);
                $urine->pbcs = $pbcs->name;
            }

            if ($urine->pbcs2 > 0) {
                $pbcs2 = R::load('urine_pbcs2', $urine->pbcs2);
                $urine->pbcs2 = $pbcs2->name;
            }

            R::store($urine);

            print_r($urine->id . ' - ');
        }

        print_r(' <br>  stool <br> ');

        $stools = R::findAll('investigationresults_stool');

        foreach ($stools as $stool) {
####  wbc   
            if ($stool->wbc > 0) {
                $wbc = R::load('stool_wbc', $stool->wbc);
                $stool->wbc = $wbc->name;
            }

####  wbc2   
            if ($stool->wbc2 > 0) {
                $wbc2 = R::load('stool_wbc2', $stool->wbc2);
                $stool->wbc2 = $wbc2->name;
            }

### rbc
            if ($stool->rbc > 0) {
                $rbc = R::load('stool_rbc', $stool->rbc);
                $stool->rbc = $rbc->name;
            }


### rbc2
            if ($stool->rbc2 > 0) {
                $rbc2 = R::load('stool_rbc2', $stool->rbc2);
                $stool->rbc2 = $rbc2->name;
            }

            R::store($stool);

            print_r($stool->id . ' - ');
        }
    }

//    ##########################################################
//
//    public function uploadInvestResult($investResultId) {
//        $this->generateInvestPdf($investResultId);
//    }
//
//    public function generateInvestPdf($investResultId) {
//        ob_start();
//
//        require_once("../../_library/plugins/tcpdf/tcpdf.php");
//// create new PDF document
//        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
//
//// set document information
//        $pdf->SetCreator(PDF_CREATOR);
//        $pdf->SetAuthor('Nicola Asuni');
//        $pdf->SetTitle('TCPDF Example 006');
//        $pdf->SetSubject('TCPDF Tutorial');
//        $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
//
//// set default header data
//        $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE . ' 006', PDF_HEADER_STRING);
//
//// set header and footer fonts
//        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
//        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
//
//// set default monospaced font
//        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
//
//// set margins
//        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
//        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
//        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
//
//// set auto page breaks
//        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
//
//// set image scale factor
//        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
//
//// set some language-dependent strings (optional)
//        if (@file_exists(dirname(__FILE__) . '/lang/eng.php')) {
//            require_once(dirname(__FILE__) . '/lang/eng.php');
//            $pdf->setLanguageArray($l);
//        }
//
//// ---------------------------------------------------------
//// set font
//        //   $pdf->SetFont('dejavusans', '', 10);
//// add a page
//        $pdf->AddPage();
//
//// writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='')
//// writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='', $autopadding=true)
//// create some HTML content
//        $html = '<div    id="patient_profile_print" style="page-break-after: always;" >
//
//    <hr style="border: 1px solid black;     margin: 5px 0; ">
//    <div class="col-md-12">
//
//        <table style="width: 98%;margin: 5px auto;" cellpadding="2" class="noborder">
//            <tr>
//                <td style="width: 25%;font-weight: bold;"> Patient Name   </td>
//                <td style="width: 25%;"> aaaaaaa  </td>
//                <td style="width: 25%;font-weight: bold;"> Patient ID   </td>
//                <td style="width: 25%;"> <img id="xx"  src="{$hosturl}/../upload/barcodes/1.png" height="20">     </td>
//            </tr>
//            <tr>
//                <td style="width: 25%;font-weight: bold;"> Age / Sex    </td>
//                <td style="width: 25%;"> 11   / 111     </td>
//                <td style="width: 25%;font-weight: bold;"> Requested Date     </td>
//                <td style="width: 25%;">  444444</td>
//            </tr>
//            <tr>
//                <td style="width: 25%;font-weight: bold;"> Referred By   </td>
//                <td style="width: 25%;">asdf     </td>
//                <td style="width: 25%;font-weight: bold;"> Printed In   </td>
//                <td style="width: 25%;">   wert  </td>
//            </tr>
//        </table>
//    </div>
//
//    <hr style="border: 1px solid black;  margin: 5px 0;">
//
//    <div class="row">
//
//        <div class="col-md-12">
//
//<table   class="noborder wds98" style="    margin-top: 15px;" >
//    <tr>
//        <td style="width: 50%;">
//            <h4 >
//                <span style="margin-right: 20%">        </span>
//            </h4>
//        </td>
//        <td style="width: 50%;">
//            <h4>
//                <span style="float: left;    margin-left: 41%;font-weight: bold;">Doctor s Signature </span>
//            </h4>
//        </td>
//    </tr>
//    <tr>
//        <td style="width: 50%;">
//            <h4>
//                <span style="margin-right: 20%">        </span>
//            </h4>
//        </td>
//        <td style="width: 50%;">
//            <h4 >
//                <span style="float: left;    margin-left: 45%;font-weight: bold;">Thanks </span>
//            </h4>
//        </td>
//    </tr>
//</table>
//
//</div>
//</div>
//
//</div>';
//
//// output the HTML content
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//
//// output some RTL HTML content
//        $html = '<div style="text-align:center">The words &#8220;<span dir="rtl">&#1502;&#1494;&#1500; [mazel] &#1496;&#1493;&#1489; [tov]</span>&#8221; mean &#8220;Congratulations!&#8221;</div>';
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// test some inline CSS
//        $html = '<p>This is just an example of html code to demonstrate some supported CSS inline styles.
//<span style="font-weight: bold;">bold text</span>
//<span style="text-decoration: line-through;">line-trough</span>
//<span style="text-decoration: underline line-through;">underline and line-trough</span>
//<span style="color: rgb(0, 128, 64);">color</span>
//<span style="background-color: rgb(255, 0, 0); color: rgb(255, 255, 255);">background color</span>
//<span style="font-weight: bold;">bold</span>
//<span style="font-size: xx-small;">xx-small</span>
//<span style="font-size: x-small;">x-small</span>
//<span style="font-size: small;">small</span>
//<span style="font-size: medium;">medium</span>
//<span style="font-size: large;">large</span>
//<span style="font-size: x-large;">x-large</span>
//<span style="font-size: xx-large;">xx-large</span>
//</p>';
//
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// reset pointer to the last page
//        $pdf->lastPage();
//
//// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//// Print a table
//// add a page
//        $pdf->AddPage();
//
//// create some HTML content
//        $subtable = '<table border="1" cellspacing="6" cellpadding="4"><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>';
//
//        $html = '<h2>HTML TABLE:</h2>
//<table border="1" cellspacing="3" cellpadding="4">
//    <tr>
//        <th>#</th>
//        <th align="right">RIGHT align</th>
//        <th align="left">LEFT align</th>
//        <th>4A</th>
//    </tr>
//    <tr>
//        <td>1</td>
//        <td bgcolor="#cccccc" align="center" colspan="2">A1 ex<i>amp</i>le <a href="http://www.tcpdf.org">link</a> column span. One two tree four five six seven eight nine ten.<br />line after br<br /><small>small text</small> normal <sub>subscript</sub> normal <sup>superscript</sup> normal  bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla<ol><li>first<ol><li>sublist</li><li>sublist</li></ol></li><li>second</li></ol><small color="#FF0000" bgcolor="#FFFF00">small small small small small small small small small small small small small small small small small small small small</small></td>
//        <td>4B</td>
//    </tr>
//    <tr>
//        <td>' . $subtable . '</td>
//        <td bgcolor="#0000FF" color="yellow" align="center">A2 € &euro; &#8364; &amp; è &egrave;<br/>A2 € &euro; &#8364; &amp; è &egrave;</td>
//        <td bgcolor="#FFFF00" align="left"><font color="#FF0000">Red</font> Yellow BG</td>
//        <td>4C</td>
//    </tr>
//    <tr>
//        <td>1A</td>
//        <td rowspan="2" colspan="2" bgcolor="#FFFFCC">2AA<br />2AB<br />2AC</td>
//        <td bgcolor="#FF0000">4D</td>
//    </tr>
//    <tr>
//        <td>1B</td>
//        <td>4E</td>
//    </tr>
//    <tr>
//        <td>1C</td>
//        <td>2C</td>
//        <td>3C</td>
//        <td>4F</td>
//    </tr>
//</table>';
//
//// output the HTML content
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// Print some HTML Cells
//
//        $html = '<span color="red">red</span> <span color="green">green</span> <span color="blue">blue</span><br /><span color="red">red</span> <span color="green">green</span> <span color="blue">blue</span>';
//
//        $pdf->SetFillColor(255, 255, 0);
//
//        $pdf->writeHTMLCell(0, 0, '', '', $html, 'LRTB', 1, 0, true, 'L', true);
//        $pdf->writeHTMLCell(0, 0, '', '', $html, 'LRTB', 1, 1, true, 'C', true);
//        $pdf->writeHTMLCell(0, 0, '', '', $html, 'LRTB', 1, 0, true, 'R', true);
//
//// reset pointer to the last page
//        $pdf->lastPage();
//
//// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//// Print a table
//// add a page
//        $pdf->AddPage();
//
//// create some HTML content
//        $html = '<h1>Image alignments on HTML table</h1>
//<table cellpadding="1" cellspacing="1" border="1" style="text-align:center;">
//<tr><td><img src="images/logo_example.png" border="0" height="41" width="41" /></td></tr>
//<tr style="text-align:left;"><td><img src="images/logo_example.png" border="0" height="41" width="41" align="top" /></td></tr>
//<tr style="text-align:center;"><td><img src="images/logo_example.png" border="0" height="41" width="41" align="middle" /></td></tr>
//<tr style="text-align:right;"><td><img src="images/logo_example.png" border="0" height="41" width="41" align="bottom" /></td></tr>
//<tr><td style="text-align:left;"><img src="images/logo_example.png" border="0" height="41" width="41" align="top" /></td></tr>
//<tr><td style="text-align:center;"><img src="images/logo_example.png" border="0" height="41" width="41" align="middle" /></td></tr>
//<tr><td style="text-align:right;"><img src="images/logo_example.png" border="0" height="41" width="41" align="bottom" /></td></tr>
//</table>';
//
//// output the HTML content
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// reset pointer to the last page
//        $pdf->lastPage();
//
//// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//// Print all HTML colors
//// add a page
//        $pdf->AddPage();
//
//        $textcolors = '<h1>HTML Text Colors</h1>';
//        $bgcolors = '<hr /><h1>HTML Background Colors</h1>';
//
//        foreach (TCPDF_COLORS::$webcolor as $k => $v) {
//            $textcolors .= '<span color="#' . $v . '">' . $v . '</span> ';
//            $bgcolors .= '<span bgcolor="#' . $v . '" color="#333333">' . $v . '</span> ';
//        }
//
//// output the HTML content
//        $pdf->writeHTML($textcolors, true, false, true, false, '');
//        $pdf->writeHTML($bgcolors, true, false, true, false, '');
//
//// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//// Test word-wrap
//// create some HTML content
//        $html = '<hr />
//<h1>Various tests</h1>
//<a href="#2">link to page 2</a><br />
//<font face="courier"><b>thisisaverylongword</b></font> <font face="helvetica"><i>thisisanotherverylongword</i></font> <font face="times"><b>thisisaverylongword</b></font> thisisanotherverylongword <font face="times">thisisaverylongword</font> <font face="courier"><b>thisisaverylongword</b></font> <font face="helvetica"><i>thisisanotherverylongword</i></font> <font face="times"><b>thisisaverylongword</b></font> thisisanotherverylongword <font face="times">thisisaverylongword</font> <font face="courier"><b>thisisaverylongword</b></font> <font face="helvetica"><i>thisisanotherverylongword</i></font> <font face="times"><b>thisisaverylongword</b></font> thisisanotherverylongword <font face="times">thisisaverylongword</font> <font face="courier"><b>thisisaverylongword</b></font> <font face="helvetica"><i>thisisanotherverylongword</i></font> <font face="times"><b>thisisaverylongword</b></font> thisisanotherverylongword <font face="times">thisisaverylongword</font> <font face="courier"><b>thisisaverylongword</b></font> <font face="helvetica"><i>thisisanotherverylongword</i></font> <font face="times"><b>thisisaverylongword</b></font> thisisanotherverylongword <font face="times">thisisaverylongword</font>';
//
//// output the HTML content
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// Test fonts nesting
//        $html1 = 'Default <font face="courier">Courier <font face="helvetica">Helvetica <font face="times">Times <font face="dejavusans">dejavusans </font>Times </font>Helvetica </font>Courier </font>Default';
//        $html2 = '<small>small text</small> normal <small>small text</small> normal <sub>subscript</sub> normal <sup>superscript</sup> normal';
//        $html3 = '<font size="10" color="#ff7f50">The</font> <font size="10" color="#6495ed">quick</font> <font size="14" color="#dc143c">brown</font> <font size="18" color="#008000">fox</font> <font size="22"><a href="http://www.tcpdf.org">jumps</a></font> <font size="22" color="#a0522d">over</font> <font size="18" color="#da70d6">the</font> <font size="14" color="#9400d3">lazy</font> <font size="10" color="#4169el">dog</font>.';
//
//        $html = $html1 . '<br />' . $html2 . '<br />' . $html3 . '<br />' . $html3 . '<br />' . $html2;
//
//// output the HTML content
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//// test pre tag
//// add a page
//        $pdf->AddPage();
//
//        $html = <<<EOF
//<div style="background-color:#880000;color:white;">
//Hello World!<br />
//Hello
//</div>
//<pre style="background-color:#336699;color:white;">
//int main() {
//    printf("HelloWorld");
//    return 0;
//}
//</pre>
//<tt>Monospace font</tt>, normal font, <tt>monospace font</tt>, normal font.
//<br />
//<div style="background-color:#880000;color:white;">DIV LEVEL 1<div style="background-color:#008800;color:white;">DIV LEVEL 2</div>DIV LEVEL 1</div>
//<br />
//<span style="background-color:#880000;color:white;">SPAN LEVEL 1 <span style="background-color:#008800;color:white;">SPAN LEVEL 2</span> SPAN LEVEL 1</span>
//EOF;
//
//// output the HTML content
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//// test custom bullet points for list
//// add a page
//        $pdf->AddPage();
//
//        $html = <<<EOF
//<h1>Test custom bullet image for list items</h1>
//<ul style="font-size:14pt;list-style-type:img|png|4|4|images/logo_example.png">
//    <li>test custom bullet image</li>
//    <li>test custom bullet image</li>
//    <li>test custom bullet image</li>
//    <li>test custom bullet image</li>
//<ul>
//EOF;
//
//// output the HTML content
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//// reset pointer to the last page
//        $pdf->lastPage();
//
//// ---------------------------------------------------------
//        $fileName = '5555.pdf';
////Close and output PDF document
//        $pdf->Output(__DIR__ . '/../../upload/lab_pdf/' . $fileName, 'F');
//
//        $this->sendPdf($fileName);
//
////============================================================+
//// END OF FILE
////============================================================+
//    }
//    function sendPdf($fileName) {
//
//        $url = 'http://lab.royal-fc.net/api/patient-test';
//        $apiKey = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Im1lZGljYWxfdGVzdHMiLCJwYXNzd29yZCI6Im1lZGljYWxfdGVzdHNAcGFzc3dvcmQifQ.6_o87c9NR48MsyMoer2OQzJ8PCDBVgLFJpeNo449RDA';
//
//        $data = array(
//            'name' => 'Huda'
//            , 'royal_patient_id' => 1
//            , 'age' => 35
//            , 'sex' => 'Female'
//            , 'test_name' => 'test'
//            , 'referred_by' => 'dr'
//            , 'phone' => '111111'
//            , 'requested_date' => '2022-02-25'
//            , 'printed_date' => '2022-02-25'
//            , 'test_pdf' => new CURLFile(__DIR__ . '\\..\\..\\upload\\lab_pdf\\' . $fileName, 'application/pdf')
//            , 'plus_file' => ''
//            , 'visit_id' => 1
//            , 'invest_id' => 9
//            , 'is_pathology' => 1
//        );
//
//        // Initializes a new cURL session
//        $curl = curl_init($url);
//
//        // 1. Set the CURLOPT_RETURNTRANSFER option to true
//        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//// 2. Set the CURLOPT_POST option to true for POST request
//        curl_setopt($curl, CURLOPT_POST, true);
//// 3. Set the request data 
//        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
//// 4. Set  headers for API Auth 
//
//        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
//            //'Content-Type: application/json',
//            'Authorization: Bearer ' . $apiKey
//        ));
//
//        // Execute cURL request with all previous settings
//        $response = curl_exec($curl);
//
//
//
//        // Close cURL session
//        curl_close($curl);
//
//        echo $response . PHP_EOL;
//    }
//    public function testPDF() {
//        $this->testPDFEx();
//    }
//
//    public function testPDFEx() {
//        ob_start();
//
//        require_once("../../_library/plugins/tcpdf/tcpdf.php");
//// create new PDF document
//        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
//
//// set document information
//        $pdf->SetCreator(PDF_CREATOR);
//        $pdf->SetAuthor('Nicola Asuni');
//        $pdf->SetTitle('TCPDF Example 006');
//        $pdf->SetSubject('TCPDF Tutorial');
//        $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
//
//// set default header data
//        $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE . ' 006', PDF_HEADER_STRING);
//
//// set header and footer fonts
//        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
//        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
//
//// set default monospaced font
//        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
//
//// set margins
//        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
//        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
//        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
//
//// set auto page breaks
//        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
//
//// set image scale factor
//        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
//
//// set some language-dependent strings (optional)
//        if (@file_exists(dirname(__FILE__) . '/lang/eng.php')) {
//            require_once(dirname(__FILE__) . '/lang/eng.php');
//            $pdf->setLanguageArray($l);
//        }
//
//// ---------------------------------------------------------
//// set font
//        //   $pdf->SetFont('dejavusans', '', 10);
//// add a page
//        $pdf->AddPage();
//
//// writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='')
//// writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='', $autopadding=true)
//// create some HTML content
//        $html = '<div    id="patient_profile_print" style="page-break-after: always;" >
//
//    <hr style="border: 1px solid black;     margin: 5px 0; ">
//    <div class="col-md-12">
//
//        <table style="width: 98%;margin: 5px auto;" cellpadding="2" class="noborder">
//            <tr>
//                <td style="width: 25%;font-weight: bold;"> Patient Name   </td>
//                <td style="width: 25%;"> aaaaaaa  </td>
//                <td style="width: 25%;font-weight: bold;"> Patient ID   </td>
//                <td style="width: 25%;"> <img id="xx"  src="{$hosturl}/../upload/barcodes/1.png" height="20">     </td>
//            </tr>
//            <tr>
//                <td style="width: 25%;font-weight: bold;"> Age / Sex    </td>
//                <td style="width: 25%;"> 11   / 111     </td>
//                <td style="width: 25%;font-weight: bold;"> Requested Date     </td>
//                <td style="width: 25%;">  444444</td>
//            </tr>
//            <tr>
//                <td style="width: 25%;font-weight: bold;"> Referred By   </td>
//                <td style="width: 25%;">asdf     </td>
//                <td style="width: 25%;font-weight: bold;"> Printed In   </td>
//                <td style="width: 25%;">   wert  </td>
//            </tr>
//        </table>
//    </div>
//
//    <hr style="border: 1px solid black;  margin: 5px 0;">
//
//    <div class="row">
//
//        <div class="col-md-12">
//{if $source != 5 }
//<table   class="noborder wds98" style="    margin-top: 15px;" >
//    <tr>
//        <td style="width: 50%;">
//            <h4 >
//                <span style="margin-right: 20%">        </span>
//            </h4>
//        </td>
//        <td style="width: 50%;">
//            <h4>
//                <span style="float: left;    margin-left: 41%;font-weight: bold;">Doctor s Signature </span>
//            </h4>
//        </td>
//    </tr>
//    <tr>
//        <td style="width: 50%;">
//            <h4>
//                <span style="margin-right: 20%">        </span>
//            </h4>
//        </td>
//        <td style="width: 50%;">
//            <h4 >
//                <span style="float: left;    margin-left: 45%;font-weight: bold;">Thanks </span>
//            </h4>
//        </td>
//    </tr>
//</table>
//{/if}
//</div>
//</div>
//
//</div>';
//
//// output the HTML content
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//
//// output some RTL HTML content
//        $html = '<div style="text-align:center">The words &#8220;<span dir="rtl">&#1502;&#1494;&#1500; [mazel] &#1496;&#1493;&#1489; [tov]</span>&#8221; mean &#8220;Congratulations!&#8221;</div>';
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// test some inline CSS
//        $html = '<p>This is just an example of html code to demonstrate some supported CSS inline styles.
//<span style="font-weight: bold;">bold text</span>
//<span style="text-decoration: line-through;">line-trough</span>
//<span style="text-decoration: underline line-through;">underline and line-trough</span>
//<span style="color: rgb(0, 128, 64);">color</span>
//<span style="background-color: rgb(255, 0, 0); color: rgb(255, 255, 255);">background color</span>
//<span style="font-weight: bold;">bold</span>
//<span style="font-size: xx-small;">xx-small</span>
//<span style="font-size: x-small;">x-small</span>
//<span style="font-size: small;">small</span>
//<span style="font-size: medium;">medium</span>
//<span style="font-size: large;">large</span>
//<span style="font-size: x-large;">x-large</span>
//<span style="font-size: xx-large;">xx-large</span>
//</p>';
//
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// reset pointer to the last page
//        $pdf->lastPage();
//
//// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//// Print a table
//// add a page
//        $pdf->AddPage();
//
//// create some HTML content
//        $subtable = '<table border="1" cellspacing="6" cellpadding="4"><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>';
//
//        $html = '<h2>HTML TABLE:</h2>
//<table border="1" cellspacing="3" cellpadding="4">
//    <tr>
//        <th>#</th>
//        <th align="right">RIGHT align</th>
//        <th align="left">LEFT align</th>
//        <th>4A</th>
//    </tr>
//    <tr>
//        <td>1</td>
//        <td bgcolor="#cccccc" align="center" colspan="2">A1 ex<i>amp</i>le <a href="http://www.tcpdf.org">link</a> column span. One two tree four five six seven eight nine ten.<br />line after br<br /><small>small text</small> normal <sub>subscript</sub> normal <sup>superscript</sup> normal  bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla<ol><li>first<ol><li>sublist</li><li>sublist</li></ol></li><li>second</li></ol><small color="#FF0000" bgcolor="#FFFF00">small small small small small small small small small small small small small small small small small small small small</small></td>
//        <td>4B</td>
//    </tr>
//    <tr>
//        <td>' . $subtable . '</td>
//        <td bgcolor="#0000FF" color="yellow" align="center">A2 € &euro; &#8364; &amp; è &egrave;<br/>A2 € &euro; &#8364; &amp; è &egrave;</td>
//        <td bgcolor="#FFFF00" align="left"><font color="#FF0000">Red</font> Yellow BG</td>
//        <td>4C</td>
//    </tr>
//    <tr>
//        <td>1A</td>
//        <td rowspan="2" colspan="2" bgcolor="#FFFFCC">2AA<br />2AB<br />2AC</td>
//        <td bgcolor="#FF0000">4D</td>
//    </tr>
//    <tr>
//        <td>1B</td>
//        <td>4E</td>
//    </tr>
//    <tr>
//        <td>1C</td>
//        <td>2C</td>
//        <td>3C</td>
//        <td>4F</td>
//    </tr>
//</table>';
//
//// output the HTML content
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// Print some HTML Cells
//
//        $html = '<span color="red">red</span> <span color="green">green</span> <span color="blue">blue</span><br /><span color="red">red</span> <span color="green">green</span> <span color="blue">blue</span>';
//
//        $pdf->SetFillColor(255, 255, 0);
//
//        $pdf->writeHTMLCell(0, 0, '', '', $html, 'LRTB', 1, 0, true, 'L', true);
//        $pdf->writeHTMLCell(0, 0, '', '', $html, 'LRTB', 1, 1, true, 'C', true);
//        $pdf->writeHTMLCell(0, 0, '', '', $html, 'LRTB', 1, 0, true, 'R', true);
//
//// reset pointer to the last page
//        $pdf->lastPage();
//
//// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//// Print a table
//// add a page
//        $pdf->AddPage();
//
//// create some HTML content
//        $html = '<h1>Image alignments on HTML table</h1>
//<table cellpadding="1" cellspacing="1" border="1" style="text-align:center;">
//<tr><td><img src="images/logo_example.png" border="0" height="41" width="41" /></td></tr>
//<tr style="text-align:left;"><td><img src="images/logo_example.png" border="0" height="41" width="41" align="top" /></td></tr>
//<tr style="text-align:center;"><td><img src="images/logo_example.png" border="0" height="41" width="41" align="middle" /></td></tr>
//<tr style="text-align:right;"><td><img src="images/logo_example.png" border="0" height="41" width="41" align="bottom" /></td></tr>
//<tr><td style="text-align:left;"><img src="images/logo_example.png" border="0" height="41" width="41" align="top" /></td></tr>
//<tr><td style="text-align:center;"><img src="images/logo_example.png" border="0" height="41" width="41" align="middle" /></td></tr>
//<tr><td style="text-align:right;"><img src="images/logo_example.png" border="0" height="41" width="41" align="bottom" /></td></tr>
//</table>';
//
//// output the HTML content
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// reset pointer to the last page
//        $pdf->lastPage();
//
//// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//// Print all HTML colors
//// add a page
//        $pdf->AddPage();
//
//        $textcolors = '<h1>HTML Text Colors</h1>';
//        $bgcolors = '<hr /><h1>HTML Background Colors</h1>';
//
//        foreach (TCPDF_COLORS::$webcolor as $k => $v) {
//            $textcolors .= '<span color="#' . $v . '">' . $v . '</span> ';
//            $bgcolors .= '<span bgcolor="#' . $v . '" color="#333333">' . $v . '</span> ';
//        }
//
//// output the HTML content
//        $pdf->writeHTML($textcolors, true, false, true, false, '');
//        $pdf->writeHTML($bgcolors, true, false, true, false, '');
//
//// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//// Test word-wrap
//// create some HTML content
//        $html = '<hr />
//<h1>Various tests</h1>
//<a href="#2">link to page 2</a><br />
//<font face="courier"><b>thisisaverylongword</b></font> <font face="helvetica"><i>thisisanotherverylongword</i></font> <font face="times"><b>thisisaverylongword</b></font> thisisanotherverylongword <font face="times">thisisaverylongword</font> <font face="courier"><b>thisisaverylongword</b></font> <font face="helvetica"><i>thisisanotherverylongword</i></font> <font face="times"><b>thisisaverylongword</b></font> thisisanotherverylongword <font face="times">thisisaverylongword</font> <font face="courier"><b>thisisaverylongword</b></font> <font face="helvetica"><i>thisisanotherverylongword</i></font> <font face="times"><b>thisisaverylongword</b></font> thisisanotherverylongword <font face="times">thisisaverylongword</font> <font face="courier"><b>thisisaverylongword</b></font> <font face="helvetica"><i>thisisanotherverylongword</i></font> <font face="times"><b>thisisaverylongword</b></font> thisisanotherverylongword <font face="times">thisisaverylongword</font> <font face="courier"><b>thisisaverylongword</b></font> <font face="helvetica"><i>thisisanotherverylongword</i></font> <font face="times"><b>thisisaverylongword</b></font> thisisanotherverylongword <font face="times">thisisaverylongword</font>';
//
//// output the HTML content
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// Test fonts nesting
//        $html1 = 'Default <font face="courier">Courier <font face="helvetica">Helvetica <font face="times">Times <font face="dejavusans">dejavusans </font>Times </font>Helvetica </font>Courier </font>Default';
//        $html2 = '<small>small text</small> normal <small>small text</small> normal <sub>subscript</sub> normal <sup>superscript</sup> normal';
//        $html3 = '<font size="10" color="#ff7f50">The</font> <font size="10" color="#6495ed">quick</font> <font size="14" color="#dc143c">brown</font> <font size="18" color="#008000">fox</font> <font size="22"><a href="http://www.tcpdf.org">jumps</a></font> <font size="22" color="#a0522d">over</font> <font size="18" color="#da70d6">the</font> <font size="14" color="#9400d3">lazy</font> <font size="10" color="#4169el">dog</font>.';
//
//        $html = $html1 . '<br />' . $html2 . '<br />' . $html3 . '<br />' . $html3 . '<br />' . $html2;
//
//// output the HTML content
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//// test pre tag
//// add a page
//        $pdf->AddPage();
//
//        $html = <<<EOF
//<div style="background-color:#880000;color:white;">
//Hello World!<br />
//Hello
//</div>
//<pre style="background-color:#336699;color:white;">
//int main() {
//    printf("HelloWorld");
//    return 0;
//}
//</pre>
//<tt>Monospace font</tt>, normal font, <tt>monospace font</tt>, normal font.
//<br />
//<div style="background-color:#880000;color:white;">DIV LEVEL 1<div style="background-color:#008800;color:white;">DIV LEVEL 2</div>DIV LEVEL 1</div>
//<br />
//<span style="background-color:#880000;color:white;">SPAN LEVEL 1 <span style="background-color:#008800;color:white;">SPAN LEVEL 2</span> SPAN LEVEL 1</span>
//EOF;
//
//// output the HTML content
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//// test custom bullet points for list
//// add a page
//        $pdf->AddPage();
//
//        $html = <<<EOF
//<h1>Test custom bullet image for list items</h1>
//<ul style="font-size:14pt;list-style-type:img|png|4|4|images/logo_example.png">
//    <li>test custom bullet image</li>
//    <li>test custom bullet image</li>
//    <li>test custom bullet image</li>
//    <li>test custom bullet image</li>
//<ul>
//EOF;
//
//// output the HTML content
//        $pdf->writeHTML($html, true, false, true, false, '');
//
//// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//// reset pointer to the last page
//        $pdf->lastPage();
//
//// ---------------------------------------------------------
////Close and output PDF document
//        $pdf->Output(__DIR__ . '/../../upload/lab_pdf/example_11.pdf', 'F');
//
////============================================================+
//// END OF FILE
////============================================================+
//    }
// at the end of class call

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

}
