<?php

require_once("imp/_imp.php");

class Controllers {

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

// it will run in everytime with
// default requried
    public function __construct() {
        require_once("../public/aw_config.php");
        require_once("imp/_autho.php"); //general functions
        $this->smarty = $smarty;
        $this->hosturl = $hosturl;

//here name of controll to known
        $this->controllname = 'visits';
        $this->shcontrollname = 'Visits';
        $this->smarty->assign('controllname', $this->controllname);
        $this->smarty->assign('shcontrollname', $this->shcontrollname);

//breadcrumbs
        require_once("../../_library/plugins/Breadcrumbs/Breadcrumbs.php");
        $acty = filter_input(INPUT_GET, 'ac');
        $bc = new breadcrumbs($hosturl, '', '', $acty);
        $bc->crumbs();
        $breadcrumbs = $bc->breadcrumbs;
        $smarty->assign('breadcrumbs', $breadcrumbs);


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


        ########################   visits.detectionid     ############################
        ## 999    paying rest  visit
        ## 9999   refund  visit
        ## -88     package visit
        ###
        #
        #
        #########################################################
        require_once("erp_common.php");  ## added by heba 
        require_once("visits_common.php"); //general functions
        require_once("branch_common.php");
//here will call all php pages
        require_once("_header.php");
        require_once("_sidebar.php");
        require_once("_leftsidebar.php");
        require_once("_footer.php");
    }

//here the frist page and
//the frist action in this class
    public function index() {
//check login
        autho::checkautho($this->hosturl);
//check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
//        print_r(date('2022-11-15 H:i:s'));
// all drugs will show in selectbox in add new drugs
        $this->patientdata();

        $patientid = filter_input(INPUT_GET, "patientid");
        $deviceNo = filter_input(INPUT_GET, "deviceId");
        $patientNo = filter_input(INPUT_GET, 'patientNo');

        if ($patientNo > 0 && !($patientid > 0 )) {
            $patientid = getPatientId($patientNo);
        }

        if ($deviceNo > 0) {
            $deviceId = getDeviceId($deviceNo);
        }

        if ($deviceId > 0 && $patientid > 0) {
            saveTrackingRecord($patientid, $deviceId, 0, '', 'visits');
            $cardVisitId = visitAvailableToEdit($patientid, date('Y-m-d'));
            if ($cardVisitId > 0) {
                $this->smarty->assign('cardVisitId', $cardVisitId);
                R::exec('update visits set rec_card_add = 1
                        , recep_enterance =   "' . date("H:i") . '"
                        where id = ' . $cardVisitId . '  and ( recep_enterance  IS NULL  or recep_enterance = "")');
            } else {
                $statusNo = R::getRow('select statusno  from patients where id = ?   ', [$patientid]);
                $this->smarty->assign('statusNo', $statusNo['statusno']);
                $this->smarty->assign('patientid', $patientid);
                $this->smarty->assign('cardVisitId', 0);
                $this->smarty->assign('cardVisitPatient', $patientid);
                $this->smarty->assign('cardVisitTime', date("H:i"));
            }
        } else if ($patientid > 0) {
            $statusNo = R::getRow('select statusno  from patients where id = ?   ', [$patientid]);
            $this->smarty->assign('statusNo', $statusNo['statusno']);
            $this->smarty->assign('patientid', $patientid);
            $this->smarty->assign('cardVisitId', 0);
        }

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

        $this->initialBtns();
        $this->initialVisits();
        branchInfosVisit($programesetting->branches, $this->smarty);
        if ($programesetting->regions == 1) {
            $sub_regions = R::getAll('select sub_regions.* from sub_regions
               join  regions   on regions.id =   sub_regions.region_id
                where regions.deleted != 1  and sub_regions.deleted != 1  ');
            $this->smarty->assign('sub_regions', $sub_regions);
        }


        $py_all_doc = R::getAll('select awusers.* from awusers
               join  awrole   on awrole.id =   awusers.role_id
                where awrole.is_doctor =  1 and deleted != 1  ');
        $this->smarty->assign('py_all_doc', $py_all_doc);


        $refer = R::findAll('refer', 'deleted = 0 order by name');
        $this->smarty->assign('refer', $refer);

        if ($programesetting->organizations != 1) {
            $organizations = R::findAll('organizations', ' deleted != 1 ');
            $this->smarty->assign('organizations', $organizations);
        }

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

//Html files

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($programesetting->system_type != 2) {
            $this->smarty->display('visits/add.html');
        } else {
            $this->smarty->display('visits/add_share.html');
        }

        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    function initialBtns() {
        $allowEditVisit = 0;
        $btn3 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 3  ', [$_SESSION['role_id']]);
        if (count($btn3) > 0) {
            $allowEditVisit = $btn3->checkval;
        }
        $this->smarty->assign('allowEditVisit', $allowEditVisit);

        $allowDeleteVisit = 0;
        $btn4 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 4  ', [$_SESSION['role_id']]);
        if (count($btn4) > 0) {
            $allowDeleteVisit = $btn4->checkval;
        }
        $this->smarty->assign('allowDeleteVisit', $allowDeleteVisit);

        $rolePastVisits = 0;
        $btn7 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 7  ', [$_SESSION['role_id']]);
        if (count($btn7) > 0) {
            $rolePastVisits = $btn7->checkval;
        }
        $this->smarty->assign('rolePastVisits', $rolePastVisits);
    }

    function branchSql($branchesActivate) {
        $branchSql = '';
        if ($branchesActivate == 1) {
            $user = R::getRow('SELECT related_branches FROM awusers 
                    WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);


            $user['related_branches'] = trim($user['related_branches']);

            if ($user['related_branches'] == 0 && $user['related_branches'] != '' && $user['related_branches'] != null) {
                
            } elseif ($user['related_branches'] != 0 && $user['related_branches'] != '' && $user['related_branches'] != null) {
                $branchSql = ' and branch_id  in ( ' . $user['related_branches'] . ' ) ';
            } else {
                $branchSql = ' and branch_id =  -1  ';
            }
        }

        return $branchSql;
    }

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

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

        ####################################################
        $this->smarty->assign('today', date('Y-m-d'));
//        $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('visits/old_visits.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function oldVisits() {
        //check login
        autho::checkautho($this->hosturl);
        $date = filter_input(INPUT_POST, "date");
        $patientId = filter_input(INPUT_POST, "patientId");
        $deptId = filter_input(INPUT_POST, "deptId");

        $allvisit = $this->searchOldVisits($deptId, $date, $date, $patientId);

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

        $this->smarty->assign('allvisit', $allvisit);
        $this->smarty->display('visits/visitold.html');
    }

    function searchOldVisits($deptId, $dateFrom, $dateTo, $patientId) {
//check login
        autho::checkautho($this->hosturl);

        if ($dateFrom != '00-00-0000' && !empty($dateFrom)) {
            $dateFrom = date('Y/m/d', strtotime($dateFrom));
        } else {
            $dateFrom = '0000-00-00';
        }

        if ($dateTo != '00-00-0000' && !empty($dateTo)) {
            $dateTo = date('Y/m/d', strtotime($dateTo));
        } else {
            $dateTo = date('Y/m/d');
        }

        $ext = '';

        if ($deptId > 0) {
            $ext .= ' and for_department =  "' . $deptId . '"';
        }

        if ($patientId > 0) {
            $ext .= ' and patientid =  ' . $patientId;
        }

        //   r::debug(true, 2);

        $allvisit = R::findAll('visits', ' deleted = ?
               and  ( visitdate  between ? and ? )      ' . $ext . '
                ORDER BY visitdate desc ,  id desc', [0, $dateFrom, $dateTo]);

//        $allvisit = R::find('visits', ' deleted = 0  and  visitdate  between
//                 "' . $dateFrom . '"  and "' . $dateTo . '"   ' . $ext . '  ORDER BY visitdate asc ,  id desc');

        foreach ($allvisit as $visit) {
            $visit->visitdate = date("Y/m/d", strtotime($visit->visitdate));
            $patientName = R::getRow("SELECT * FROM patients WHERE id = $visit->patientid");

            $visit->patientName = $patientName['wifename'];
            $visit->patientstatusno = $patientName['statusno'];
            $visit->address = $patientName['address'];
            $visit->husbandname = $patientName['husdandname'];

            if ($visit->for_husband == 2) {
                $child = R::load('patients_childs', $visit->child);
                $visit->child_name = $child->child_name;
                $visit->child_gender = $child->gender;
            }

            $reserve = R::findOne('visit_hours', ' visit_id = ? and deleted = 0 ', [$visit->id]);
            if (count($reserve) > 0) {
                $visit->visitHour = date('h:i A', strtotime($reserve->visit_hour));
            } else {
                $visit->visitHour = '';
            }
//            $visit->visitHour = $reserve->visit_hour;

            if ($visit->for_department != "") {

//get name of dcotor
                $doctor = R::getRow('select * from awusers where user_id = ?', [$visit->for_doctor]);

                $depart_name = R::load('awrole', $visit->for_department);
                if ($visit->for_doctor > 0) {
                    $visit->for_department_name = $depart_name->name . '( ' . $doctor['name'] . ' )';
                    $visit->for_doctor_name = $doctor['name'];
                } else {
                    $visit->for_department_name = $depart_name->name;
                }
            }
        }

        return $allvisit;
    }

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

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

        $this->initialBtns();

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

        $this->initialVisitsLab();

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

        $refer = R::findAll('refer', 'deleted = 0 order by name');
        $this->smarty->assign('refer', $refer);

        branchInfosVisit($programesetting->branches, $this->smarty);

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

        $allTypes = R::findAll('wifetypes', 'order by title');
        $this->smarty->assign('allTypes', $allTypes);

        $husbandtypes = R::findAll('husbandtypes', 'order by title');
        $this->smarty->assign('husbandtypes', $husbandtypes);

        $py_all_doc = R::getAll('select awusers.* from awusers
               join  awrole   on awrole.id =   awusers.role_id
                where awrole.visit_show =  1 and awusers.deleted != 1 ');
        $this->smarty->assign('py_all_doc', $py_all_doc);

        if ($programesetting->organizations != 1) {
            $organizations = R::findAll('organizations', ' deleted != 1 ');
            $this->smarty->assign('organizations', $organizations);
        }

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        if ($labSetting->lab_style == 2) {
            $this->smarty->display('visits/add_lab_complete.html');
        } else {
            $this->smarty->display('visits/add_lab.html');
        }

        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    function initialVisitsLab() {

//        $invests = R::findall('invests', ' deleted = ? order by name ', [0]);
        $invests = R::getAll('select invests.id , invests.name , invests.price , invests.type as external
                                                    from invests
                                                   join  investcats      on    investcats.id = invests.investcatid
                                                 where   invests.deleted = 0 and investcats.deleted = 0
                                                 order by   invests.periority  desc  , invests.name asc ');
        $this->smarty->assign('invests', $invests);



        $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]);

            $offerInvests = R::getAll('select  invofferdetails.id , invests.name , invofferdetails.price , invests.type as external
                                                    from invofferdetails
                                                   join  invests            on    invests.id = invofferdetails.inv_id
                                                 where    invofferdetails.invoffer_id = ? and  invofferdetails.del = ? ', [$offer->id, 0]);


            $offer->price = $invs['price'];
            $offer->offerInvests = $offerInvests;
        }
        $this->smarty->assign('invoffers', $invoffers);


        $external_labs = R::findall('external_labs', 'deleted != ? ', [1]);
        $this->smarty->assign('external_labs', $external_labs);
        
                if ($_SESSION['role_id'] == 19) {
            $allDetections = R::findAll('detections', 'del = 0 and for_customer = 1 ');
        } else {
            $allDetections = R::findAll('detections', 'del = 0');
        }
        $this->smarty->assign('allDetections', $allDetections);
    }

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

        $external_labs = R::findall('external_labs', 'deleted != ? ', [1]);
        $this->smarty->assign('external_labs', $external_labs);

        $this->smarty->display('visits/external_labs.html');
    }

    function initialVisits() {

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


//        $py_all_departs = R::findAll('awrole', 'id not in (1,14,6,3,2,7,10,16)');
        $py_all_departs = R::findAll('awrole', 'visit_show = 1 ');
        $this->smarty->assign('py_all_departs', $py_all_departs);



#################################################################### 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);
#################################################################### Heba : ## rays data  ##############################################################################

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

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

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

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

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

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


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

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

## add new Visit

    public function getalldepts() {
//check login
        autho::checkautho($this->hosturl);
//check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $allDepts = R::findAll('detections', 'del = 0');

        $this->smarty->assign('allDepts', $allDepts);
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('visits/showdepts.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

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

        $deptId = filter_input(INPUT_POST, 'deptId');
        $query = "SELECT   patients.* , visits.visitdate  FROM patients
                                join  visits                on      patients.id = visits.patientid
                                where visits.detectionid = $deptId
                                and  visits.deleted = 0
                                ";
//limit 0,50 ";

        $pResult = R::getAll($query);
        foreach ($pResult as $pat) {
            $endDates = R::getAll('select enddate from endvisitreports where patientid = ?  and enddate >= ?', [$pat['id'], $pat['visitdate']]);
            if (count($endDates) < 1) {    ## still open
## add end date to this visit
                $lastEnd = R::dispense('endvisitreports');
                $lastEnd->status = 0;
                $lastEnd->enddate = date('Y/m/d');
                $lastEnd->reason = '';
                $lastEnd->notes = '';
                $lastEnd->doctorid = $_SESSION['user_id'];
                $lastEnd->patientid = $pat['id'];
                R::store($lastEnd);
            }
        }
    }

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

//        $allPatients = R::findAll('patients', 'deleted = ? and done = ?', [0, 1]);


        $extraTime = R::findOne('programesetting', 'id = 1');
        $today2 = date('Y/m/d');
        if (date("H") <= $extraTime->addshours) {
            $today2 = date("Y/m/d", strtotime($today2 . '+ 2 HOURS'));
        }


        if ($_SESSION['role_id'] == 19) {
            $allDetections = R::findAll('detections', 'del = 0 and for_customer = 1 ');
        } else {
            $allDetections = R::findAll('detections', 'del = 0');
        }



//        $allvisit = R::find('visits', 'visitdate = ? and deleted = ?     ORDER BY id asc ', [$today2, 0]);
//        foreach ($allvisit as $visit) {
//            $visit->visitdate = date("Y/m/d", strtotime($visit->visitdate));
//            $patientName = R::getRow("SELECT * FROM patients WHERE id = $visit->patientid");
//
//            $visit->patientName = $patientName['wifename'];
//            $visit->patientstatusno = $patientName['statusno'];
//            $visit->address = $patientName['address'];
//            $visit->husbandname = $patientName['husdandname'];
//
//            $user = R::findOne('awusers', 'user_id = ?', [$visit->user_id]);
//            $visit->user_name = $user->name;
//
//            if ($visit->for_husband == 2) {
//                $child = R::load('patients_childs', $visit->child);
//                $visit->child_name = $child->child_name;
//                $visit->child_gender = $child->gender;
//            }
//
//            $reserve = R::findOne('visit_hours', ' visit_id = ? and deleted = 0 ', [$visit->id]);
//            if (count($reserve) > 0) {
//                $visit->visitHour = date('h:i A', strtotime($reserve->visit_hour));
//            } else {
//                $visit->visitHour = '';
//            }
////            $visit->visitHour = $reserve->visit_hour;
//
//            if ($visit->for_department != "") {
//
////get name of dcotor
//                $doctor = R::getRow('select * from awusers where user_id = ?', [$visit->for_doctor]);
//
//                $depart_name = R::load('awrole', $visit->for_department);
//                if ($visit->for_doctor > 0) {
//                    $visit->for_department_name = $depart_name->name . '( ' . $doctor['name'] . ' )';
//                } else {
//                    $visit->for_department_name = $depart_name->name;
//                }
//            }
//
//            if ($visit->detectionid == 9999) {
//                $originalVisit = R::load('visits', $visit->visitid);
//                $detection = R::load('detections', $originalVisit->detectionid);
//                $visit->detection = 'مرتجع العملاء';
//                $visit->detection .= ' ( ' . $detection->title . ' ) ';
//            } elseif ($visit->detectionid == 999) {
//                $originalVisit = R::load('visits', $visit->visitid);
//                $detection = R::load('detections', $originalVisit->detectionid);
//                $visit->detection = 'دفع متبقى ';
//                $visit->detection .= ' ( ' . $detection->title . ' ) ';
//            } elseif ($visit->detectionid == -88) {
//                $originalVisit = R::load('visits', $visit->visitid);
//                $detection = R::load('detections', $originalVisit->detectionid);
//                $visit->detection = 'متابعة ';
//                $visit->detection .= ' ( ' . $detection->title . ' ) ';
//            } else {
//                $detection = R::load('detections', $visit->detectionid);
//                $visit->detection = $detection->title;
//            }
//        }
//Send Data to add.html to use it in insert new patient
//        $this->smarty->assign('allPatients', $allPatients);
        $this->smarty->assign('today', date('Y/m/d'));
        //   $this->smarty->assign('allvisit', $allvisit);
        $this->smarty->assign('allDetections', $allDetections);
    }

    public function editVisit() {

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

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

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


        if (count($visit) > 0) {

            $hours = '';
            $reserves = R::findAll('visit_hours', ' visit_id = ? and deleted = 0 ', [$visit->id]);
            $i = 1;
            foreach ($reserves as $reserve) {
                if ($i > 1) {
                    $hours .= '-';
                }
                $hours .= $reserve->visit_hour;
                $i++;
            }

            $invRes = '';
            if ($visit->for_department == 12) {
                $invRes = $this->loadVisitInvests($visitId);
            } else if ($visit->for_department == 5) {
                $invRes = $this->loadVisitRays($visitId);
            }

            $name = '';
            if ($patient->wifename != null) {
                $name .= $patient->wifename;
            }

            if ($patient->husdandname != null) {
                $name .= " -  " . $patient->husdandname;
            }

            $showRedirectNote = 0;
            if ($visit->is_redirect == 1 && $visit->redirect_to != '' && !is_null($visit->redirect_to)) {
                $redirectTo = explode(',', $visit->redirect_to);
                if (count($redirectTo) > 1) {
                    $userId = ' ' . $_SESSION['user_id'] . ' ';
                } else {
                    $userId = $_SESSION['user_id'];
                }
                if (in_array($userId, $redirectTo)) {
                    $showRedirectNote = 1;
                }
            }


            $refer_doctor = $this->referSelectData($visit->refer_doctor, $visit->refer_doctor_tb);


            $result = array(
                "name" => $name,
                "showRedirectNote" => $showRedirectNote,
                "redirect_note" => $visit->redirect_note,
                "sub_region_id" => $visit->sub_region_id,
                "operation_main_id" => $visit->operation_main_id,
                "unitsConsumed" => $visit->units,
                "visitdate" => date("Y/m/d", strtotime($visit->visitdate)),
                "visit_time" => $visit->visit_time,
                "patientid" => $visit->patientid,
                "detectionid" => $visit->detectionid,
                "detectionvalue_visa" => $visit->detectionvalue_visa,
                "detectionvalue_cash" => $visit->detectionvalue_cash,
                "totaldetectionvalue" => $visit->totaldetectionvalue,
                "discount" => $visit->discount,
                "restdetectionvalue" => $visit->restdetectionvalue,
                "for_department" => $visit->for_department,
                "operation_time" => $visit->operation_time,
                "for_doctor" => $visit->for_doctor,
                "notes" => $visit->notes,
                "visitHours" => $hours,
                "invRes" => $invRes,
                "child" => $visit->child,
                "organization_id" => $visit->organization_id,
                "discountRatio" => $visit->organization_discount - $visit->center_discount,
                "discountRatioType" => $visit->org_discount_type,
                "contract_price" => $visit->contract_price,
                "refer_doctor" => $refer_doctor
                , "for_husband" => $visit->for_husband
                , "branch_id" => $visit->branch_id
            );

            echo json_encode($result);
        } else {
            echo -1;
        }
    }

    function referSelectData($refer_doctor, $refer_doctor_tb) {
        $refer = 0;
        $programesetting = R::findOne('programesetting');
        if ($programesetting->refer_doctor == 1) {
            if ($refer_doctor_tb == 1) {
                $refer = '*' . $refer_doctor;
            } else {
                $refer = $refer_doctor;
            }
        }

        return $refer;
    }

    function loadVisitInvests($visitId) {
        $invRes = '';
        $totalPrice = 0;
        $invests = R::findAll('investigationresults', ' visitid  = ? and deleted = 0 ', [$visitId]);

        $invRes .= '  <input type="hidden" id="itr" name="itr"   value="' . count($invests) . '" >  ';


        $i = 1;
        foreach ($invests as $investResult) {
            $invest = R::load('invests', $investResult->investid);
            $totalPrice = $totalPrice + $investResult->price;

            $invRes .= '  <div class="col-md-3" id="visitInvDiv' . $i . '">  ';
            $invRes .= '  <a class="btn red btn-xs wds7 deleteVisitInv "   ';
            $invRes .= '  style="padding: 0; margin-left: -25px; margin-top: -11px;"     ';
            $invRes .= '    href="#" data-itr="' . $i . '"  ><i class="fa fa-close"></i> </a>  ';
            $invRes .= '  <input  class="form-control wds90"  type="text"  value="' . $invest->name . ' [ ' . $investResult->price . ']" disabled=""   ';
            $invRes .= '      name="selectedName' . $i . '" style="display: inline;">  ';
            $invRes .= '  <input  class="form-control"  type="hidden"  value=" ' . $investResult->investid . '"  name="selectedId' . $i . '">  ';
            $invRes .= '  <input  class="form-control"  type="hidden"  value="' . $investResult->price . '"    ';
            $invRes .= '   name="selectedPrice' . $i . '" id="selectedPrice' . $i . '">  ';
            $invRes .= '  <input  class="form-control"  type="hidden"  value="' . $investResult->offer_id . '"  name="selectedOffer' . $i . '">  ';
            $invRes .= '  <input  class="form-control"  type="hidden"  value="' . $investResult->id . '"  name="invRes' . $i . '">  ';
            $invRes .= ' </div>  ';

            $i++;
        }

        $invRes .= '  <input type="hidden" id="temp_price"  value="' . $totalPrice . '" >  ';

        return $invRes;
    }

    function loadVisitRays($visitId) {
        $invRes = '';
        $totalPrice = 0;
        $rays = R::findAll('raysresults', ' visitid  = ? and deleted = 0 ', [$visitId]);

        $invRes .= '  <input type="hidden" id="itr" name="itr"   value="' . count($rays) . '" >  ';


        $i = 1;
        foreach ($rays as $rayResult) {
            $ray = R::load('rays', $rayResult->rayid);
            $totalPrice = $totalPrice + $rayResult->price;

            $invRes .= '  <div class="col-md-3" id="visitInvDiv' . $i . '">  ';
            $invRes .= '  <a class="btn red btn-xs wds7 deleteVisitInv "   ';
            $invRes .= '  style="padding: 0; margin-left: -25px; margin-top: -11px;"     ';
            $invRes .= '    href="#" data-itr="' . $i . '"  ><i class="fa fa-close"></i> </a>  ';
            $invRes .= '  <input  class="form-control wds90"  type="text"  value="' . $ray->name . ' [ ' . $ray->price . ']" disabled=""   ';
            $invRes .= '      name="selectedName' . $i . '" style="display: inline;">  ';
            $invRes .= '  <input  class="form-control"  type="hidden"  value=" ' . $rayResult->rayid . '"  name="selectedId' . $i . '">  ';
            $invRes .= '  <input  class="form-control"  type="hidden"  value="' . $rayResult->price . '"    ';
            $invRes .= '   name="selectedPrice' . $i . '" id="selectedPrice' . $i . '">  ';
            $invRes .= '  <input  class="form-control"  type="hidden"  value="' . $rayResult->id . '"  name="invRes' . $i . '">  ';
            $invRes .= ' </div>  ';

            $i++;
        }

        $invRes .= '  <input type="hidden" id="temp_price"  value="' . $totalPrice . '" >  ';

        return $invRes;
    }

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

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

        $visitId = filter_input(INPUT_POST, "visitId");
        $visitComment = filter_input(INPUT_POST, 'visitComment');

        if ($visitId > 0) {

            $visit = R::load('visits', $visitId);
            $visitOld = R::load('visits', $visitId);
            $visit->notes = $visitComment;
            R::store($visit);
            echo $visitId;

            $this->reserveOldVisit($visitOld);
        }
    }

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

        $visitId = filter_input(INPUT_POST, "mVisitId");
        $patientID = filter_input(INPUT_POST, 'patientid');
        $visitDate = filter_input(INPUT_POST, 'visitdate');
        $detectionID = filter_input(INPUT_POST, 'detectionid');
        $detectionValue_cash = filter_input(INPUT_POST, 'detectionvalue_cash');
        $detectionValue_visa = filter_input(INPUT_POST, 'detectionvalue_visa');
        $totaldetectionvalue = filter_input(INPUT_POST, 'totaldetectionvalue');
        $discount = filter_input(INPUT_POST, 'discount');
        $restdetectionvalue = filter_input(INPUT_POST, 'restdetectionvalue');
        $for_department = filter_input(INPUT_POST, 'fordepartment');
        $for_doctor = filter_input(INPUT_POST, 'for_doctor');
        $for_husband = filter_input(INPUT_POST, 'for_husband');
        $reserveId = filter_input(INPUT_POST, 'reserveId');
        $notes = filter_input(INPUT_POST, 'notes');
        $child = filter_input(INPUT_POST, 'child');
        $unitsConsumed = filter_input(INPUT_POST, 'unitsConsumed');
        $refer_doctor = filter_input(INPUT_POST, 'refer_doctor');
        $branch_id = filter_input(INPUT_POST, 'branch_id');
        $detect_cat = 1;

        if ($visitId > 0) {

            $visit = R::load('visits', $visitId);
            $visitOld = R::load('visits', $visitId);
            $programesetting = R::findOne('programesetting');
            $detection = R::load('detections', $detectionID);

            $organizationId = filter_input(INPUT_POST, 'organizations');

            if ($organizationId > 0) {
                if ($visit->organization_id != $organizationId && $programesetting->organizations == 2) {
                    $org = R::getRow('SELECT COALESCE(center_discount ,0)   as center_discount  ,
                COALESCE(organization_discount ,0)   as organization_discount    , discount_type
                FROM organizations WHERE id = ? ', [$organizationId]);

                    $visit->center_discount = $org['center_discount'];
                    $visit->organization_discount = $org['organization_discount'];

                    $visit->org_discount_type = $org['discount_type'];

                    if ($org['discount_type'] == 1) {
                        $center_discount_value = ($totaldetectionvalue * $org['center_discount']) / 100;
                        $organization_discount_value = ($totaldetectionvalue * $org['organization_discount']) / 100;
                    } else {
                        $center_discount_value = $org['center_discount'];
                        $organization_discount_value = $org['organization_discount'];
                    }

                    $visit->center_discount_value = $center_discount_value;
                    $visit->organization_discount_value = $organization_discount_value;
                }

                if (($visit->organization_id != $organizationId || $visit->detectionid != $detectionID) && $programesetting->organizations == 3) {
                    $visitOrg = R::load('organizations', $organizationId);
                    $org_discount = R::findOne('organization_discount', ' list_id = ? and detect_id = ?    and detect_cat = ?
                           and offer_id = 0 and deleted = ?  ', [$visitOrg->list_id, $detectionID, $detect_cat, 0]);
                    $visit->contract_price = $org_discount->contract_price;
                    $visit->original_price = $detection->detectionval;
                    $visit->patient_hold = $org_discount->patient_hold;
                    $visit->organ_discount_type = $org_discount->discount_type;
                }
            } else {
                $visit->contract_price = 0;
                $visit->original_price = 0;
                $visit->patient_hold = 0;
                $visit->organ_discount_type = 0;
                $visit->center_discount = 0;
                $visit->organization_discount = 0;
            }


            $visit->organization_id = $organizationId;

            $oldReserveId = $visit->operation_main_id;

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




            $patient = R::load('patients', $patientID);
            if ($programesetting->refer_doctor == 1) {
                $visit->refer_doctor_tb = 0;
                if ($refer_doctor[0] == "*") {
                    $refer_doctor = ltrim($refer_doctor, '*');
                    $visit->refer_doctor_tb = 1;
                }
                $visit->refer_doctor = $refer_doctor;
            } else {
                if ($for_husband == 1) {
                    $visit->refer_doctor = $patient->h_refer_doctor;
                    $visit->refer_doctor_tb = $patient->h_refer_doctor_tb;
                } else {
                    $visit->refer_doctor = $patient->refer_doctor;
                    $visit->refer_doctor_tb = $patient->refer_doctor_tb;
                }
            }

            if ($for_husband == 1) {
                $visit->rfc = $patient->rfc;
            } else {
                $visit->rfc = $patient->wrfc;
            }


            if ($detectionValue_cash > 0 && $visit->printserial == 0) {
                $visit->printserial = $this->printSerial('last_serial');
            }

            $old_for_department = $visit->for_department;
            $old_for_doctor = $visit->for_doctor;

            $visit->patientid = $patientID;
            $visit->visitdate = $new_date;
            $visit->visittime = date("H:i:s");
            $visit->visit_time = $visit_time;
            $visit->detectionid = $detectionID;
            $visit->detectionvalue_cash = $detectionValue_cash;
            $visit->detectionvalue_visa = $detectionValue_visa;
            $visit->totaldetectionvalue = $totaldetectionvalue;
            $visit->discount = $discount;
            $visit->restdetectionvalue = $restdetectionvalue;
            $visit->for_department = $for_department;
            $visit->for_doctor = $for_doctor;
            $visit->for_husband = $for_husband;
            $visit->operation_time = $operation_time;
            $visit->child = $child;
            $visit->units = $unitsConsumed;
            $visit->branch_id = $branch_id;


            if ($_SESSION['role_id'] != 16) {
                $visit->user_id = $_SESSION['user_id'];
            }


            if ($for_husband == 2) {
                $visit->child = $child;
            }

            $visit->notes = $notes;

            if ($_SESSION['role_id'] == 19) {
                $visit->customer_add = 1;
            } else {
                $visit->customer_add = 0;
                $visit->service_edit = 1;

                if ($visit->recep_p_exit == NULL || $visit->recep_p_exit == "") {
                    $visit->recep_p_exit = date("H:i");
                }
            }

            if ($old_for_doctor != $for_doctor) {
                $visit->dr_salary = $detection->dr_salary;
            }




            if (($old_for_department == 5 || $old_for_department == 12) && $old_for_department != $for_department) {
                $this->removeFromDept($old_for_department, $visitId);
            }

            if ($for_department == 5 || $for_department == 12) {
                $this->removeFromDept($for_department, $visitId);
                //   $this->sendToDept($patientID, $for_department, $visitId, $for_husband);
                $this->updateDept($patientID, $for_department, $visitId, $for_husband, $visitId);
            }

            R::store($visit);

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

            calcBalance($visit->patientid);

            if ($visit->visitdate != $visitOld->visitdate || $visit->for_doctor != $visitOld->for_doctor || $visit->branch_id != $visitOld->branch_id) {
                //  echo 'xxxxx';
                $this->addVisitOrder($visitId, $new_date, $for_doctor, $branch_id);
            }


            if ($visit->visitdate != $visitOld->visitdate ||
                    $visit->for_doctor != $visitOld->for_doctor || $visit->patientid != $visitOld->patientid ||
                    $visit->visit_time != $visitOld->visit_time || $visit->for_husband != $visitOld->for_husband) {
                $patient = R::load('patients', $visit->patientid);
                if ($visit->for_husband == 1) {
                    $patient_name = $patient->husdandname;
                } else {
                    $patient_name = $patient->wifename;
                }
                $doctor_name = '';
                if ($visit->for_doctor > 0) {
                    $doctorIn = R::getRow('select name  from awusers where user_id = ?', [$visit->for_doctor]);
                    $doctor_name = $doctorIn['name'];
                }

                $data = array(
                    'name' => $patient_name
                    , 'visit_id' => $visitId
                    , 'doctor_name' => $doctor_name
                    , 'visit_order' => $visit->visit_order
                    , 'visit_date' => $visit->visitdate
                    , 'visit_time' => $visit->visit_time
                    , 'branch_id' => $visit->branch_id
                );

                updateToSite($data);
            }

            if ($_SESSION['role_id'] == 19) {
                sendSms($visitId, 3);
            }

            $this->erpSellbillUpdate($visit);

            echo $visitId;

            $this->updateArchiveRequest($visitId, $patientID, $visitDate, $for_doctor, $branch_id);
            $this->reserveOldVisit($visitOld);
        }
    }

    function updateArchiveRequest($visitId, $patientID, $visitDate, $for_doctor, $branch_id) {
        $obj = R::findOne('archive_request', ' visit_id = ? ', [$visitId]);
        if (count($obj) > 0) {
            $obj->patient_id = $patientID;
            $obj->request_date = date($visitDate . ' H:i:s');
            $obj->doctor_id = $for_doctor;
            $obj->branch_id = $branch_id;
            $obj->update_date = date('Y-m-d H:i:s');

            R::store($obj);
        }
    }

    function cancelArchiveRequest($visitId) {
        $obj = R::findOne('archive_request', ' visit_id = ? ', [$visitId]);
        if (count($obj) > 0) {
            $obj->ready_userid = -1;
            $obj->cancel_userid = $_SESSION['user_id'];
            $obj->cancel_date = date('Y-m-d H:i:s'); //$this->today;
            r::store($obj);
        }
    }

    private function updateDept($patientId, $for_department, $visitId, $for_husband) {
        $invType = filter_input(INPUT_POST, 'invType');
        $itr = filter_input(INPUT_POST, 'itr');
        for ($i = 1; $i <= $itr; $i++) {

            if ((filter_input(INPUT_POST, 'selectedId' . $i) ) > 0) {
                switch ($for_department) {
                    case 5:
                        $tableName = 'raysresults';
                        $colName = 'rayid';
                        break;
                    case 12:
                        $tableName = 'investigationresults';
                        $colName = 'investid';
                        break;
                }

                $exist = R::findOne($tableName, ' ' . $colName . '  = ?   and  visitid = ?   order by id desc
                         ', [filter_input(INPUT_POST, 'selectedId' . $i), $visitId]);

                if (count($exist) > 0) {
                    $exist->deleted = 0;
                    $exist->patientid = $patientId;
                    $exist->forhusband = $for_husband;
                    R::store($exist);
                } else {
                    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->price = filter_input(INPUT_POST, 'selectedPrice' . $i);
                            $obj->offer_id = filter_input(INPUT_POST, 'selectedOffer' . $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');
                    $obj->forhusband = $for_husband;

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

    private function removeFromDept($for_department, $visitId) {

        switch ($for_department) {
            case 5:
                $obj = R::findAll('raysresults', ' visitid = ? and deleted = 0  ', [$visitId]);
                break;
            case 12:
                $obj = R::findAll('investigationresults', ' visitid = ? and deleted = 0   ', [$visitId]);
                break;
        }

        foreach ($obj as $data) {
            $data->deleted = 1;
            R::store($data);
        }
    }

    public function restorevisit() {

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

        $visitId = filter_input(INPUT_POST, "visitId");
        $visit = R::load('visits', $visitId);
        $patientName = R::getRow("SELECT * FROM patients WHERE id = $visit->patientid");
        $detection = R::getRow("SELECT * FROM detections WHERE id = $visit->detectionid");

        $for_department_name = '';
        if ($visit->for_department != "") {

//get name of dcotor
            $doctor = R::getRow('select * from awusers where user_id = ?', [$visit->for_doctor]);

            $depart_name = R::load('awrole', $visit->for_department);
            if ($visit->for_department == 8 || $visit->for_department == 4) {
                $for_department_name = $depart_name->name . '( ' . $doctor['name'] . ' )';
            } else {
                $for_department_name = $depart_name->name;
            }
        }

        $result = array(
            "husbandName" => $patientName['husdandname'],
            "address" => $patientName['address'],
            "detectionType" => $detection['title'],
            "for_department_name" => $for_department_name,
            "for_husband" => $visit->for_husband
        );

        echo json_encode($result);
    }

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

        $forDepartment = filter_input(INPUT_POST, 'forDepartment');
        $patientId = filter_input(INPUT_POST, 'patientId');
        $orgId = filter_input(INPUT_POST, 'orgId');
        $labVisit = filter_input(INPUT_POST, 'labVisit');
        $programesetting = R::findOne('programesetting');
        $listId = 0;
        if ($orgId > 0) {
            $visitOrg = R::load('organizations', $orgId);
            $listId = $visitOrg->list_id;
        }

        switch ($forDepartment) {
            case 5:   ##  rays
                $sql = '(SELECT DISTINCT date  FROM gynarays WHERE deleted = 0 and patientid = ' . $patientId . '  and rayresult is null )';
                $sql .= ' union ';
                $sql .= '( SELECT DISTINCT date  FROM mainantenentalrays WHERE deleted = 0 and patientid = ' . $patientId . '  and rayresult is null )  ';
                $sql .= ' union ';
                $sql .= '( SELECT DISTINCT date  FROM andvisitsrays WHERE deleted = 0 and patientid = ' . $patientId . '  and rayresult is null )  ';
                $sql .= ' order by date desc';

                $dates = R::getAll($sql);
                $countHusband = array();
                $countWife = array();
                $i = 0;

#################################################################### Heba : ## get all unfinished rays ##############################################################################

                foreach ($dates as $date) {
## all invs of certain patient
                    $PatientRayByDateHusbandGyna = R::findall('gynarays', 'deleted = ? and rayresult is null  and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date['date'], 1]);
                    $PatientRayByDateHusbandAnd = R::findall('andvisitsrays', 'deleted = ? and rayresult is null  and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date['date'], 1]);
                    $PatientRayByDateHusbandAntenatal = R::findall('mainantenentalrays', 'deleted = ? and rayresult is null  and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date['date'], 1]);

                    $PatientRayByDateWifeGyna = R::findall('gynarays', 'deleted = ? and rayresult is null  and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date['date'], 0]);
                    $PatientRayByDateWifeAnd = R::findall('andvisitsrays', 'deleted = ? and rayresult is null  and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date['date'], 0]);
                    $PatientRayByDateWifeAntenatal = R::findall('mainantenentalrays', 'deleted = ? and rayresult is null  and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date['date'], 0]);




                    foreach ($PatientRayByDateHusbandAntenatal as $in) {
                        $ray = R::load('rays', $in->rayid);
                        $in->invname = $ray->name;
                        $in->origin = $this->ray($ray, $listId, $programesetting->organizations, $orgId);
                        $in->tableName = 'mainantenentalrays';
                    }

                    foreach ($PatientRayByDateWifeAntenatal as $in) {
                        $ray = R::load('rays', $in->rayid);
                        $in->invname = $ray->name;
                        $in->origin = $this->ray($ray, $listId, $programesetting->organizations, $orgId);
                        $in->tableName = 'mainantenentalrays';
                    }

                    foreach ($PatientRayByDateHusbandGyna as $in) {
                        $ray = R::load('rays', $in->rayid);
                        $in->invname = $ray->name;
                        $in->origin = $this->ray($ray, $listId, $programesetting->organizations, $orgId);
                        $in->tableName = 'gynarays';
                    }

                    foreach ($PatientRayByDateWifeGyna as $in) {
                        $ray = R::load('rays', $in->rayid);
                        $in->invname = $ray->name;
                        $in->origin = $this->ray($ray, $listId, $programesetting->organizations, $orgId);
                        $in->tableName = 'gynarays';
                    }

                    foreach ($PatientRayByDateHusbandAnd as $in) {
                        $ray = R::load('rays', $in->rayid);
                        $in->invname = $ray->name;
                        $in->origin = $this->ray($ray, $listId, $programesetting->organizations, $orgId);
                        $in->tableName = 'andvisitsrays';
                    }

                    foreach ($PatientRayByDateWifeAnd as $in) {
                        $ray = R::load('rays', $in->rayid);
                        $in->invname = $ray->name;
                        $in->origin = $this->ray($ray, $listId, $programesetting->organizations, $orgId);
                        $in->tableName = 'andvisitsrays';
                    }


                    $dates[$i]['rayshG'] = $PatientRayByDateHusbandGyna;
                    $dates[$i]['rayswG'] = $PatientRayByDateWifeGyna;
                    $dates[$i]['rayshA'] = $PatientRayByDateHusbandAntenatal;
                    $dates[$i]['rayswA'] = $PatientRayByDateWifeAntenatal;
                    $dates[$i]['rayshN'] = $PatientRayByDateHusbandAnd;
                    $dates[$i]['rayswN'] = $PatientRayByDateWifeAnd;
                    $dates[$i]['date'] = date("Y/m/d", strtotime($dates[$i]['date']));

                    $countHusband[$dates[$i]['date']] = count($PatientRayByDateHusbandAntenatal) + count($PatientRayByDateHusbandGyna) + count($PatientRayByDateHusbandAnd);
                    $countWife[$dates[$i]['date']] = count($PatientRayByDateWifeAntenatal) + count($PatientRayByDateWifeGyna) + count($PatientRayByDateWifeAnd);


                    $i++;
                }
                $this->smarty->assign('title', 'Rays');
                break;

            case 12:  ## investigation
                $sql = '(SELECT DISTINCT date  FROM gynainvestigation WHERE deleted = 0 and patientid = ' . $patientId . '  and investresult is null )';
                $sql .= ' union ';
                $sql .= '( SELECT DISTINCT date  FROM mainantenentalinvest WHERE deleted = 0 and patientid = ' . $patientId . '  and investresult is null )  ';
                $sql .= ' union ';
                $sql .= '( SELECT DISTINCT date  FROM andvisitsinvestigation WHERE deleted = 0 and patientid = ' . $patientId . '  and investresult is null )  ';
                $sql .= ' order by date desc';

                $dates = R::getAll($sql);
                $countHusband = array();
                $countWife = array();
                $i = 0;

#################################################################### Heba : ## get all unfinished rays ##############################################################################

                foreach ($dates as $date) {
## all invs of certain patient
                    $PatientRayByDateHusbandAnd = R::findall('andvisitsinvestigation', 'deleted = ? and investresult is null  and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date['date'], 1]);
                    $PatientRayByDateHusbandGyna = R::findall('gynainvestigation', 'deleted = ? and investresult is null  and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date['date'], 1]);
                    $PatientRayByDateHusbandAntenatal = R::findall('mainantenentalinvest', 'deleted = ? and investresult is null  and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date['date'], 1]);

                    $PatientRayByDateWifeAnd = R::findall('andvisitsinvestigation', 'deleted = ? and investresult is null  and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date['date'], 0]);
                    $PatientRayByDateWifeGyna = R::findall('gynainvestigation', 'deleted = ? and investresult is null  and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date['date'], 0]);
                    $PatientRayByDateWifeAntenatal = R::findall('mainantenentalinvest', 'deleted = ? and investresult is null  and patientid = ? and date = ? and forhusband = ? ', [0, $patientId, $date['date'], 0]);




                    foreach ($PatientRayByDateHusbandAntenatal as $in) {
                        $ray = R::load('invests', $in->investid);
                        $in->invname = $ray->name;
                        $in->origin = $ray;
                        $in->tableName = 'mainantenentalinvest';
                    }

                    foreach ($PatientRayByDateWifeAntenatal as $in) {
                        $ray = R::load('invests', $in->investid);
                        $in->invname = $ray->name;
                        $in->origin = $ray;
                        $in->tableName = 'mainantenentalinvest';
                    }

                    foreach ($PatientRayByDateHusbandGyna as $in) {
                        $ray = R::load('invests', $in->investid);
                        $in->invname = $ray->name;
                        $in->origin = $ray;
                        $in->tableName = 'gynainvestigation';
                    }

                    foreach ($PatientRayByDateWifeGyna as $in) {
                        $ray = R::load('invests', $in->investid);
                        $in->invname = $ray->name;
                        $in->origin = $ray;
                        $in->tableName = 'gynainvestigation';
                    }

                    foreach ($PatientRayByDateHusbandAnd as $in) {
                        $ray = R::load('invests', $in->investid);
                        $in->invname = $ray->name;
                        $in->origin = $ray;
                        $in->tableName = 'andvisitsinvestigation';
                    }

                    foreach ($PatientRayByDateWifeAnd as $in) {
                        $ray = R::load('invests', $in->investid);
                        $in->invname = $ray->name;
                        $in->origin = $ray;
                        $in->tableName = 'andvisitsinvestigation';
                    }


                    $dates[$i]['rayshG'] = $PatientRayByDateHusbandGyna;
                    $dates[$i]['rayswG'] = $PatientRayByDateWifeGyna;
                    $dates[$i]['rayshA'] = $PatientRayByDateHusbandAntenatal;
                    $dates[$i]['rayswA'] = $PatientRayByDateWifeAntenatal;
                    $dates[$i]['rayshN'] = $PatientRayByDateHusbandAnd;
                    $dates[$i]['rayswN'] = $PatientRayByDateWifeAnd;
                    $dates[$i]['date'] = date("Y/m/d", strtotime($dates[$i]['date']));

                    $countHusband[$dates[$i]['date']] = count($PatientRayByDateHusbandAntenatal) + count($PatientRayByDateHusbandGyna) + count($PatientRayByDateHusbandAnd);
                    $countWife[$dates[$i]['date']] = count($PatientRayByDateWifeAntenatal) + count($PatientRayByDateWifeGyna) + count($PatientRayByDateWifeAnd);


                    $i++;
                }

                $this->smarty->assign('title', 'Investigations');
                break;
        }

        $this->smarty->assign('countHusband', $countHusband);
        $this->smarty->assign('countWife', $countWife);
        $this->smarty->assign('dates', $dates);
        $this->smarty->assign('labVisit', $labVisit);
        $this->smarty->display('visits/showinternal.html');
    }

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

        $extraTime = R::findOne('programesetting', 'id = 1');
        $today2 = date('Y/m/d');
        if (date("H") <= $extraTime->addshours) {
            $today2 = date("Y/m/d", strtotime($today2 . '+ 2 HOURS'));
        }
        $allvisit = R::find('visits', 'visitdate = ? and deleted = ? and detectionid != 999   ORDER BY id asc', [$today2, 0]);

        foreach ($allvisit as $visit) {
            $visit->visitdate = date("Y/m/d", strtotime($visit->visitdate));
            $patientName = R::getRow('SELECT * FROM patients WHERE id = "' . $visit->patientid . '"');
            $visit->patientName = $patientName['wifename'];
            $visit->patientstatusno = $patientName['statusno'];
            $visit->husbandname = $patientName['husdandname'];
            $visit->address = $patientName['address'];
            $detection = R::getRow('SELECT * FROM detections WHERE id = "' . $visit->detectionid . '"');
            $visit->detectionType = $detection['title'];

            $user = R::findOne('awusers', 'user_id = ?', [$visit->user_id]);
            $visit->user_name = $user->name;

            if ($visit->for_husband == 2) {
                $child = R::load('patients_childs', $visit->child);
                $visit->child_name = $child->child_name;
                $visit->child_gender = $child->gender;
            }

            if ($visit->for_department != "") {

//get name of dcotor
                $doctor = R::getRow('select * from awusers where user_id = ?', [$visit->for_doctor]);

                $depart_name = R::load('awrole', $visit->for_department);
                if ($visit->for_doctor > 0) {
                    $visit->for_department_name = $depart_name->name . '( ' . $doctor['name'] . ' )';
                } else {
                    $visit->for_department_name = $depart_name->name;
                }
            }

            $reserve = R::findOne('visit_hours', ' visit_id = ? and deleted = 0 ', [$visit->id]);
            if (count($reserve) > 0) {
                $visit->visitHour = date('h:i A', strtotime($reserve->visit_hour));
            } else {
                $visit->visitHour = '';
            }
//            $visit->visitHour = $reserve->visit_hour;
        }

        $allowEditVisit = 0;
        $btn3 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 3  ', [$_SESSION['role_id']]);
        if (count($btn3) > 0) {
            $allowEditVisit = $btn3->checkval;
        }
        $this->smarty->assign('allowEditVisit', $allowEditVisit);

        $allowDeleteVisit = 0;
        $btn4 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 4  ', [$_SESSION['role_id']]);
        if (count($btn4) > 0) {
            $allowDeleteVisit = $btn4->checkval;
        }
        $this->smarty->assign('allowDeleteVisit', $allowDeleteVisit);

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

        $this->smarty->assign('allvisit', $allvisit);
        $this->smarty->display('visits/visitdiv.html');
    }

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

        date_default_timezone_set('Africa/Cairo');

        $visitEdit = R::xdispense('visits_updates');
        $colums = R::getAll('DESCRIBE visits');

        foreach ($colums as $col) {
            $colName = $col['Field'];
            if ($colName != id) {
                $visitEdit->$colName = $oldVisit->$colName;
            }
        }

        $visitEdit->userid_edit = $_SESSION['user_id'];
        $visitEdit->date_edit = date('Y-m-d H:i:s'); //$this->today;
        $visitEdit->patientid_edit = $oldVisit->id;
        R::store($visitEdit);
    }

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

    function addVisitOrder($visitId, $visitDate, $doctorId, $branch_id) {
        $visit = R::load('visits', $visitId);

        if ($doctorId > 0 && $visit->detectionid != 999 && $visit->detectionid != 9999 && $visit->detectionid != -88) {
            $departs = $this->getOrderDepts();
            if (in_array($visit->for_department, $departs)) {
                $data = R::getRow('SELECT MAX(visit_order) as last_order
                 FROM visits  where visitdate = ? and for_doctor = ?  
                  and branch_id = ?  ', [$visitDate, $doctorId, $branch_id]);
                $last_order = $data['last_order'];
                $visit->visit_order = $last_order + 1;
                R::store($visit);
            }
        }
    }

    function getOrderDepts($text = 0) {
        $departs = array();
        $departsText = '';
        $sql = ' select   id      from    awrole     where doctor_visit_show = 1       order by id asc ';
        $depts = R::getAll($sql);

        $i = 0;
        foreach ($depts as $dept) {
            array_push($departs, $dept['id']);
            if ($i > 0) {
                $departsText .= ' , ';
            }
            $departsText .= $dept['id'];
            $i++;
        }
        if ($text == 1) {
            return $departsText;
        } else {
            return $departs;
        }
    }

    public function add() {
//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_cash = filter_input(INPUT_POST, 'detectionvalue_cash');
        $detectionValue_visa = filter_input(INPUT_POST, 'detectionvalue_visa');
        $totaldetectionvalue = filter_input(INPUT_POST, 'totaldetectionvalue');
        //    $discount = filter_input(INPUT_POST, 'discount');
        $restdetectionvalue = filter_input(INPUT_POST, 'restdetectionvalue');
        $for_department = filter_input(INPUT_POST, 'fordepartment');
        $for_doctor = filter_input(INPUT_POST, 'for_doctor');
        $for_husband = filter_input(INPUT_POST, 'for_husband');
        $child = filter_input(INPUT_POST, 'child');
        $reserveId = filter_input(INPUT_POST, 'reserveId');
        $notes = filter_input(INPUT_POST, 'notes');
        $unitsConsumed = filter_input(INPUT_POST, 'unitsConsumed');
        $cardVisitPatient = filter_input(INPUT_POST, 'cardVisitPatient');
        $cardVisitTime = filter_input(INPUT_POST, 'cardVisitTime');
        $refer_doctor = filter_input(INPUT_POST, 'refer_doctor');
        $branch_id = filter_input(INPUT_POST, 'branch_id');
        $subRegionId = filter_input(INPUT_POST, 'subRegionId');

        if ($for_department == 13 && $reserveId) {
            $x = ' select operations_main.operation_hours  , operations_rooms.name as roomName
                  , operations_main.residence_hours    , residence_rooms.name as roomNameRes
                    , operations_main.operations_rooms_id    , operations_main.residence_rooms_id
                    from  operations_main
                    left join  operations_rooms   on operations_rooms.id =  operations_main.operations_rooms_id
                    left join  residence_rooms   on residence_rooms.id =  operations_main.residence_rooms_id
                    where  operations_main.id =  ?  ';
            $reservation = R::getRow($x, [$reserveId]);

            $operation_hours = explode(',', $reservation['operation_hours']);
            $operation_time = $operation_hours[0];
            $operation_main_id = $reserveId;

            $len = count($operation_hours) - 1;

            $room_no = $reservation['operations_rooms_id'];
            $enterance = $operation_hours[0];
            $time = strtotime($operation_hours[$len]);
            $p_exit = date("H:i", strtotime('+30 minutes', $time));

            $residence_hours = explode(',', $reservation['residence_hours']);
            $len = count($residence_hours) - 1;
            $res_room_no = $reservation['residence_rooms_id'];
            $res_enterance = $residence_hours[0];
            $time = strtotime($residence_hours[$len]);
            $res_p_exit = date("H:i", strtotime('+1 hour', $time));

            //   $recep_enterance = '';
            //    $recep_p_exit = '';
        } else {
            $operation_time = '';
            $operation_main_id = 0;

            $room_no = '';
            $enterance = '';
            $p_exit = '';

            $res_room_no = '';
            $res_enterance = '';
            $res_p_exit = '';

            //   $recep_enterance = '';
            //  $recep_p_exit = '';
        }

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

        $discountType = filter_input(INPUT_POST, 'discountType');
        if ($discountType == 1) {
            $discountRatio = filter_input(INPUT_POST, 'discount');
            $discount = $totaldetectionvalue * ($discountRatio / 100 );
        } else {
            $discount = filter_input(INPUT_POST, 'discount');
            $discountType = 0;
            $discountRatio = 0;
        }

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

        $doctor_percent = 0;
        if ($for_doctor > 0) {
            $doctorIn = R::getRow('select * from awusers where user_id = ?', [$for_doctor]);
            $detection = R::load('detections', $detectionID);
            switch ($detection->type) {
                case 1:
                    $doctor_percent = $doctorIn['pulse_per'];
                    break;

                case 2:
                    $doctor_percent = $doctorIn['session_per'];
                    break;
            }
        }

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

        $insertDataVisits = R::dispense('visits');

        $insertDataVisits->patientid = $patientID;
        $insertDataVisits->visitdate = $new_date;
        $insertDataVisits->visittime = date("H:i:s");
        $insertDataVisits->visit_time = $visit_time;
        $insertDataVisits->detectionid = $detectionID;
        $insertDataVisits->detectionvalue_cash = $detectionValue_cash;
        $insertDataVisits->detectionvalue_visa = $detectionValue_visa;
        $insertDataVisits->totaldetectionvalue = $totaldetectionvalue;
        $insertDataVisits->discount = $discount;
        $insertDataVisits->restdetectionvalue = $restdetectionvalue;
        $insertDataVisits->for_department = $for_department;
        $insertDataVisits->for_doctor = $for_doctor;
        $insertDataVisits->for_husband = $for_husband;
        $insertDataVisits->units = $unitsConsumed;
        $insertDataVisits->doctor_percent = $doctor_percent;
        $insertDataVisits->branch_id = $branch_id;
        $insertDataVisits->operation_time = $operation_time;
        $insertDataVisits->operation_main_id = $operation_main_id;
        $insertDataVisits->notes = $notes;
        $insertDataVisits->user_id = $_SESSION['user_id'];
        $insertDataVisits->create_date = date('Y-m-d H:i:s'); //$this->today;

        $insertDataVisits->discount_type = $discountType;
        $insertDataVisits->discount_ratio = $discountRatio;
        $insertDataVisits->sub_region_id = $subRegionId;

        $insertDataVisits->room_no = $room_no;
        $insertDataVisits->enterance = $enterance;
        $insertDataVisits->p_exit = $p_exit;

        $insertDataVisits->res_room_no = $res_room_no;
        $insertDataVisits->res_enterance = $res_enterance;
        if ($res_p_exit != '') {
            $insertDataVisits->res_p_exit = $res_p_exit;
        }


        $programesetting = R::findOne('programesetting');
        $detection = R::load('detections', $detectionID);
        $detect_cat = 1;

        $organizationId = filter_input(INPUT_POST, 'organizations');
        $insertDataVisits->organization_id = $organizationId;
        if ($organizationId > 0 && $programesetting->organizations == 2) {
            $org = R::getRow('SELECT COALESCE(center_discount ,0)   as center_discount  ,
                COALESCE(organization_discount ,0)   as organization_discount    , discount_type
                FROM organizations WHERE id = ? ', [$organizationId]);

            $insertDataVisits->center_discount = $org['center_discount'];
            $insertDataVisits->organization_discount = $org['organization_discount'];
            $insertDataVisits->org_discount_type = $org['discount_type'];
            if ($org['discount_type'] == 1) {
                $center_discount_value = ($totaldetectionvalue * $org['center_discount']) / 100;
                $organization_discount_value = ($totaldetectionvalue * $org['organization_discount']) / 100;
            } else {
                $center_discount_value = $org['center_discount'];
                $organization_discount_value = $org['organization_discount'];
            }

            $insertDataVisits->center_discount_value = $center_discount_value;
            $insertDataVisits->organization_discount_value = $organization_discount_value;
        } else if ($organizationId > 0 && $programesetting->organizations == 3) {
            $visitOrg = R::load('organizations', $organizationId);
            $org_discount = R::findOne('organization_discount', ' list_id = ? and detect_id = ?    and detect_cat = ?
                          and offer_id = 0  and deleted = ?  ', [$visitOrg->list_id, $detectionID, $detect_cat, 0]);
            $insertDataVisits->contract_price = $org_discount->contract_price;
            $insertDataVisits->original_price = $detection->detectionval;
            $insertDataVisits->patient_hold = $org_discount->patient_hold;
            $insertDataVisits->organ_discount_type = $org_discount->discount_type;
        }



        $insertDataVisits->dr_salary = $detection->dr_salary;


        if ($for_husband == 2) {
            $insertDataVisits->child = $child;
        } else {
            $insertDataVisits->child = 0;
        }

        if ($_SESSION['role_id'] == 19) {
            $insertDataVisits->customer_add = 1;
            $insertDataVisits->recep_p_exit = '';
        } else {
            $insertDataVisits->customer_add = 0;
            $insertDataVisits->recep_p_exit = date("H:i");
        }

        if ($cardVisitPatient == $patientID && $cardVisitTime != "" && $_SESSION['role_id'] != 19) {
            $insertDataVisits->recep_enterance = $cardVisitTime;
            $insertDataVisits->rec_card_add = 1;
        }

        if ($detectionValue_cash > 0) {
            $insertDataVisits->printserial = $this->printSerial('last_serial');
        } else {
            $insertDataVisits->printserial = 0;
        }


        $patient = R::load('patients', $patientID);
        if ($programesetting->refer_doctor == 1) {
            $insertDataVisits->refer_doctor_tb = 0;
            if ($refer_doctor[0] == "*") {
                $refer_doctor = ltrim($refer_doctor, '*');
                $insertDataVisits->refer_doctor_tb = 1;
            }
            $insertDataVisits->refer_doctor = $refer_doctor;
        } else {
            if ($for_husband == 1) {
                $insertDataVisits->refer_doctor = $patient->h_refer_doctor;
                $insertDataVisits->refer_doctor_tb = $patient->h_refer_doctor_tb;
            } else {
                $insertDataVisits->refer_doctor = $patient->refer_doctor;
                $insertDataVisits->refer_doctor_tb = $patient->refer_doctor_tb;
            }
        }

        if ($for_husband == 1) {
            $insertDataVisits->rfc = $patient->rfc;
        } else {
            $insertDataVisits->rfc = $patient->wrfc;
        }


        try {
            if ($insertnew == 1) {
                $insert = R::store($insertDataVisits);
                $this->addVisitOrder($insert, $new_date, $for_doctor, $branch_id);
                calcBalance($insertDataVisits->patientid);

                if ($for_department == 5 || $for_department == 12) {
                    $this->sendToDept($patientID, $for_department, $insert, $for_husband);
                }
                if ($_SESSION['role_id'] == 19) {
                    $doctorId = (filter_input(INPUT_POST, 'for_doctor') > 0) ? filter_input(INPUT_POST, 'for_doctor') : 0;
                    $this->archiveRequestAdd($patientID, $insert, $doctorId, $new_date, $branch_id);
                }



//                if ($insertDataVisits->detectionvalue_cash) {//only payed visits make bills in erp
                $this->erpSellbill($insertDataVisits);
//                }
////                if ($detectionValue_cash > 0) {
////                    $this->printrecept($insert);
////                }
//
//
                if ($insert > 0) {
                    sendSms($insert, 2);
                    if ($_SESSION['role_id'] == 19) {
                        sendSms($insert, 3);
                    }
                }
            } else {
                $insert = 0;
            }
            echo $insert;
        } catch (Exception $ex) {
            echo -1;
        }
    }

    function printSerial($serialCol) {

        $currentMonth = date('Y-m');
        $programesetting = R::findOne('programesetting');

        if ($programesetting->serial_month == $currentMonth) {
            $printserial = $programesetting->$serialCol + 1;
            $programesetting->$serialCol = $printserial;
        } else {
            $programesetting->serial_month = $currentMonth;
            $printserial = 1;
            $programesetting->last_serial = $printserial;
            $programesetting->last_refund_serial = $printserial;
        }

        r::store($programesetting);

        return $printserial;
    }

    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++) {

            if ((filter_input(INPUT_POST, 'selectedId' . $i) ) > 0) {

                switch ($for_department) {
                    case 5:
                        $obj = R::dispense('raysresults');
                        $obj->rayid = filter_input(INPUT_POST, 'selectedId' . $i);
                        $obj->raytype = $invType;
                        break;
                    case 12:
                        $invest = R::load('invests', filter_input(INPUT_POST, 'selectedId' . $i));
                        $obj = R::dispense('investigationresults');
                        $obj->investid = filter_input(INPUT_POST, 'selectedId' . $i);
                        $obj->price = filter_input(INPUT_POST, 'selectedPrice' . $i);
                        $obj->offer_id = filter_input(INPUT_POST, 'selectedOffer' . $i);
                        $obj->invtype = $invType;
                        $obj->lab_to_lab_price = $invest->lab_to_lab_price;
                        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');
                $obj->forhusband = $for_husband;

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

    public function show() {
//check login
        autho::checkautho($this->hosturl);
//check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $allVisits = R::findAll('visits', ' detectionid != 999');

        foreach ($allVisits as $sngVisit) {

// GET PAIRNTDATA TO SHOW IN VISIT

            $ptData = R::getRow('SELECT * FROM patients WHERE id="' . $sngVisit->patientid . '"');
            $sngVisit->patientdata = $ptData;
//GET DETECTION TYPE
//$detectionType = R::findOne('detections', 'id = ?', [$sngVisit->detectionid]);
            $detectionType = R::getRow('SELECT * FROM detections WHERE id = "' . $sngVisit->detectionid . '"');
            $sngVisit->detection = $detectionType['title'];
        }

        $this->smarty->assign('allVisits', $allVisits);
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('visits/show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

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

        $id = filter_input(INPUT_POST, 'id');
        $dttitle = filter_input(INPUT_POST, 'title');
        $dtvalue = filter_input(INPUT_POST, 'value');
        $isERPPayment = (int) filter_input(INPUT_POST, 'isERPPayment');

        $updatedt = R::load('detections', $id);
        $updatedt->title = $dttitle;
        $updatedt->detectionval = $dtvalue;
        $updatedt->iserppayment = $isERPPayment;
        try {
            R::store($updatedt);
            $doctor = R::getRow('select user_id , name  from awusers where user_id = ?', [$updatedt->doctor_id]);
            if (isset($doctor->name) && !empty($doctor->name)) {
                $updatedt->title .= " - " . $doctor->name;
            }
            $this->erpProduct($updatedt);
        } catch (Exception $ex) {
            
        }
    }

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

        $allDetection = R::findAll('detections', 'del = 0');
        $this->smarty->assign('allDetection', $allDetection);
        $this->smarty->display('visits/loadalldtselected.html');
    }

    function adddetection() {
//check login
        autho::checkautho($this->hosturl);
//check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $detetion = filter_input(INPUT_POST, 'detection');
        $dtvalue = filter_input(INPUT_POST, 'dtvalue');

        $insertDataDetection = R::dispense('detections');
        $insertDataDetection->title = $detetion;
        $insertDataDetection->detectionval = $dtvalue;
        $insertDataDetection->del = 0;
        $insertDataDetection->create_date = date('Y-m-d');
        $inserted = 0;
        try {
            $inserted = R::store($insertDataDetection);
            $insertDataDetection->id = $inserted;
            $doctor = R::getRow('select user_id , name  from awusers where user_id = ?', [$insertDataDetection->doctor_id]);
            if (isset($doctor->name) && !empty($doctor->name)) {
                $insertDataDetection->title .= " - " . $doctor->name;
            }
            $this->erpProduct($insertDataDetection);
            echo $inserted;
        } catch (Exception $ex) {
            
        }
    }

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

        $doctorId = filter_input(INPUT_POST, 'doctorId');
        $shareVersion = filter_input(INPUT_POST, 'shareVersion');
        $detectiontype = filter_input(INPUT_POST, 'detectiontype');
        $detectionvalue = filter_input(INPUT_POST, 'detectionvl');



        $addfrmpopdetection = R::dispense('detections');
        if ($shareVersion == 2) {
            $addfrmpopdetection->doctor_id = $doctorId;
        }
        $addfrmpopdetection->title = $detectiontype;
        $addfrmpopdetection->detectionval = $detectionvalue;
        $addfrmpopdetection->del = 0;
        $addfrmpopdetection->create_date = date('Y-m-d');
        $added = 0;
        try {
            $inserted = R::store($addfrmpopdetection);
            $addfrmpopdetection->id = $inserted;
            $doctor = R::getRow('select user_id , name  from awusers where user_id = ?', [$addfrmpopdetection->doctor_id]);
            if (isset($doctor->name) && !empty($doctor->name)) {
                $addfrmpopdetection->title .= " - " . $doctor->name;
            }

            $this->erpProduct($addfrmpopdetection);
//echo $added = 1;
            $alldetectionget = R::findAll('detections', 'del = 0');
            $this->smarty->assign('alldetectionget', $alldetectionget);
            $this->smarty->display('visits/detectiontype.html');
        } catch (Exception $ex) {
            
        }
    }

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

        return $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
    }

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

        $wifeName = filter_input(INPUT_POST, "search");
        $husName = filter_input(INPUT_POST, "searchhus");
        $dateFrom = filter_input(INPUT_POST, "searchvisitdatefrom");
        $dateTo = filter_input(INPUT_POST, "searchvisitdateto");


        if ($dateFrom != '00-00-0000' && !empty($dateFrom)) {
            $dateFrom = date('Y/m/d', strtotime($dateFrom));
        } else {
            $dateFrom = '0000-00-00';
        }

        if ($dateTo != '00-00-0000' && !empty($dateTo)) {
            $dateTo = date('Y/m/d', strtotime($dateTo));
        } else {
            $dateTo = date('Y/m/d');
        }


        $query = '';

        if (!empty($wifeName)) {
            $query .= "AND  wifename LIKE '%$wifeName%'";
        }
        if (!empty($husName)) {
            $query .= "AND husdandname LIKE '%$husName%' ";
        }
        if (!empty($dateFrom) && !empty($dateTo)) {
            $query .= 'AND visitdate  between "' . $dateFrom . '"  AND  "' . $dateTo . '"';
        }

        $queryString = R::getAll("SELECT visits.* , patients.*,visits.id as visitid
                                        FROM `visits`
                                        INNER JOIN patients          ON  visits.patientid  = patients.id
                                        WHERE
                                        patients.deleted = 0
                                        and visits.deleted = 0  and detectionid != 999
                                        $query
                                        order by  visits.visitdate
                                        limit 0,50 ");


        foreach ($queryString as $data) {
            $data['visitdate'] = date("Y/m/d", strtotime($data['visitdate']));
        }
        $this->smarty->assign('patientResult', $queryString);
        $this->smarty->display('searchresultvisit.html');
    }

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

        $dtid = filter_input(INPUT_POST, 'dtID');
        $organizationId = filter_input(INPUT_POST, 'organizations');
        $orgDiscountType = filter_input(INPUT_POST, 'orgDiscountType');
        $detect_cat = 1;

        $getprice = R::getRow('SELECT detectionval , min_paid , units FROM detections WHERE id ="' . $dtid . '"');
        if ($orgDiscountType != 3) {

            $result = array(
                "price" => $getprice['detectionval'],
                "units_no" => $getprice['units'],
                "min_paid" => $getprice['min_paid']
            );
        } else {

            $visitOrg = R::load('organizations', $organizationId);
            $org_discount = R::findOne('organization_discount', ' list_id = ? and detect_id = ?    and detect_cat = ?
                 and offer_id = 0  and deleted = ?  ', [$visitOrg->list_id, $dtid, $detect_cat, 0]);
            if ($org_discount && $org_discount->contract_price > 0) {
                if ($org_discount->discount_type == 1) {
                    $org_discount->patient_hold = ($org_discount->contract_price * $org_discount->patient_hold ) / 100;
                }
                $par_discount = $org_discount->contract_price - $org_discount->patient_hold;
                $result = array(
                    "contract_price" => $org_discount->contract_price,
                    "price" => $org_discount->patient_hold,
                    "discount_type" => $org_discount->discount_type,
                    "discountRatio" => $par_discount,
                    "discountRatioType" => $org_discount->discount_type,
                    "units_no" => $getprice['units'],
                    "min_paid" => $getprice['min_paid']
                );
            } else {
                $result = array(
                    "price" => $getprice['detectionval'],
                    "units_no" => $getprice['units'],
                    "min_paid" => $getprice['min_paid']
                );
            }
        }

        echo json_encode($result);
    }

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

        $alldtforview = R::findAll('detections', 'del = 0');
        $this->smarty->assign('alldtforview', $alldtforview);
        $this->smarty->display('visits/alldetectionview.html');
    }

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

        $id = filter_input(INPUT_POST, 'id');
        try {
            $visitview = R::load('visits', $id);
            if ($visitview->view != 1) {
                $data = R::getRow("SELECT MAX(enterordered)  FROM `visits`");
                $lastEnter = $data['MAX(enterordered)'];

                $visitview->view = 1;
                $visitview->visitorder = 0;
                $visitview->kashf_enterance = date("H:i");
                $visitview->enterordered = $lastEnter + 1;
                R::store($visitview);
            }
        } catch (Exception $ex) {
            
        }
    }

    public function checkvisipatient() {

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

//check authoize
//   autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $visitpatientid = filter_input(INPUT_POST, 'visitid');
        $date = filter_input(INPUT_POST, 'date');

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

        $data = R::find('visits', 'patientid = ? AND  visitdate = ? and deleted = ? and detectionid != 999  ', [$visitpatientid, $date, 0]);

        if (count($data) == 0) {
            $found = 0;
        } else {
            $found = 1;
        }
        echo $found;
    }

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

        $id = filter_input(INPUT_GET, 'id');

        $allPatients = R::findAll('patients');
        $allDetections = R::findAll('detections', 'del = 0');
        $editVisit = R::findOne('visits', 'id = ?', [$id]);


        $this->smarty->assign('editvisit', $editVisit);
        $this->smarty->assign('allPatients', $allPatients);
        $this->smarty->assign('allDetections', $allDetections);
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('visits/edit.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

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

        $vId = filter_input(INPUT_POST, 'vId');
        $patientid = filter_input(INPUT_POST, 'patientid');
        $visitDate = filter_input(INPUT_POST, 'visitdate');
        $detectionID = filter_input(INPUT_POST, 'detectionid');
        $detectionValue_cash = filter_input(INPUT_POST, 'detectionvalue_cash');
        $detectionValue_visa = filter_input(INPUT_POST, 'detectionvalue_visa');
        $discount = filter_input(INPUT_POST, 'discount');
        echo $vId;


        $visitLoad = R::load('visits', $vId);
        $visitLoad->patientid = $patientid;
        $visitLoad->visitdate = $visitDate;
        $visitLoad->detectionid = $detectionID;
        $visitLoad->detectionvalue_cash = $detectionValue_cash;
        $visitLoad->detectionvalue_visa = $detectionValue_visa;
        $visitLoad->discount = $discount;
        try {
            R::store($visitLoad);
            $this->erpSellbillUpdate($visitLoad);
            header('Location:' . $this->hosturl . '/controllers/visits.php?ac=show');
        } catch (Exception $ex) {
            
        }
    }

    public function updateajax() {

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

        $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 {
            $gyna_obj = R::load($tablename, $id);
            if ($colname == 'revisionedV') {
                $gyna_obj->revisioned = $value;
                $gyna_obj->revision_date = date('Y-m-d');
            } else {
                $gyna_obj->$colname = $value;
            }

            R::store($gyna_obj);
        } catch (Exception $e) {
            
        }
    }

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

        $id = filter_input(INPUT_POST, 'id');
        try {
            $refunds = R::findAll('visits', ' detectionid = 9999 and visitid = ? and deleted != 1  ', [$id]);
            if (count($refunds) > 0) {
                echo -1;
            } else {
                $patientDelete = R::load('visits', $id);
                $patientDelete->deleted = 1;
                $patientDelete->user_delete = $_SESSION['user_id'];
                $patientDelete->date_delete = date('Y-m-d H:i:s');
                R::store($patientDelete);

                $this->cancelArchiveRequest($id);
                R::exec('update visit_hours set deleted = 1  where visit_id = ' . $id . ' ');
                calcBalance($patientDelete->patientid);

                if ($patientDelete->detectionid == 9999)
                    $this->erpSellbillDel($patientDelete, 1);
                if ($patientDelete->detectionid == 999)
                    $this->delPayERPBills($patientDelete, 1);
                else
                    $this->erpSellbillDel($patientDelete);
                echo 1;
            }
        } catch (Exception $ex) {
            echo $ex;
        }
    }

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

        $id = filter_input(INPUT_GET, 'id');
        $patientDelete = R::load('visits', $id);
        try {
            $patientDelete->deleted = 1;
            R::store($patientDelete);
            calcBalance($patientDelete->patientid);
            $this->erpSellbillDel($patientDelete);
            header('Location:' . $this->hosturl . '/controllers/visits.php?ac=show');
        } catch (Exception $ex) {
            header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
        }
    }

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

        $id = filter_input(INPUT_POST, 'id');
        $detectionDelete = R::load('detections', $id);
        try {
            $detectionDelete->del = 1;
            R::store($detectionDelete);
            $this->erpProductDel($detectionDelete);
            $alldetections = R::findAll('detections', 'del = 0');
            $this->smarty->assign('alldetections', $alldetections);
            $this->smarty->display('visits/loadalldetections.html');
        } catch (Exception $ex) {
            
        }
    }

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

        $id = filter_input(INPUT_POST, 'id');
        $detectionDelete = R::load('detections', $id);
        try {
            $detectionDelete->del = 1;
            R::store($detectionDelete);
            $this->erpProductDel($detectionDelete);
        } catch (Exception $ex) {
            
        }
    }

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

        $alldetections = R::findAll('detections', 'del = 0');
        $this->smarty->assign('alldetections', $alldetections);
        $this->smarty->display('visits/loadalldetectionsselected.html');
    }

    public function delv() {
//check login
        autho::checkautho($this->hosturl);
//check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $id = filter_input(INPUT_GET, 'id');
        $patientDelete = R::load('visits', $id);

        try {
            R::trash($patientDelete);
            $this->erpSellbillDel($patientDelete);
            header('Location:' . $this->hosturl . '/controllers/visits.php');
        } catch (Exception $ex) {
            header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
        }
    }

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


        $tableName = filter_input(INPUT_POST, "tableName");
        $patientid = filter_input(INPUT_POST, "patientid");
        $colName = filter_input(INPUT_POST, "colName");
        $mainId = filter_input(INPUT_POST, "mainId");
        $doctorId = filter_input(INPUT_POST, "doctorId");
        $notAll = filter_input(INPUT_POST, "notAll");
        $selectId = filter_input(INPUT_POST, "selectId");

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

        if ($tableName == 'detections' && $programesetting->system_type == 2) {
            $alldata = R::findAll($tableName, 'del = 0 and doctor_id = ? ', [$doctorId]);
            $doctor = R::getRow('select user_id , name  from awusers where user_id = ?', [$doctorId]);
            $this->smarty->assign('doctorId', $doctorId);
            $this->smarty->assign('doctorName', $doctor['name']);
        }
        #########
        elseif ($tableName == 'organizations' || $tableName == 'price_lists' || $tableName == 'organizations_parents') {
            $alldata = R::findAll($tableName, 'deleted = 0');
        }
        #########
        else {
            $alldata = R::findAll($tableName, 'del = 0');
        }


        $this->smarty->assign('alldata', $alldata);
        $this->smarty->assign('patientid', $patientid);
        $this->smarty->assign('colName', $colName);
        $this->smarty->assign('mainId', $mainId);
        $this->smarty->assign('maintableName', $tableName);
        $this->smarty->assign('notAll', $notAll);

        if ($tableName == 'organizations' && $programesetting->organizations != 1) {
            $this->smarty->display('visits/organizations.html');
        } elseif ($tableName == 'price_lists' && $programesetting->organizations != 1) {
            $this->smarty->assign('selectId', 'price_lists');
            $this->smarty->display('organizations/price_lists.html');
        } elseif ($tableName == 'organizations_parents') {
            $this->smarty->assign('selectId', $selectId);
            $this->smarty->display('organizations/organizations_parents.html');
        } else {
            $this->smarty->display('visits/detectionmodel.html');
        }
    }

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

        $doctorId = filter_input(INPUT_POST, 'doctorId');
        $shareVersion = filter_input(INPUT_POST, 'shareVersion');

        $insertDataDetection = R::dispense('detections');
        $insertDataDetection->del = 0;
        $insertDataDetection->detectionval = 0;
        $insertDataDetection->title = '';
        $insertDataDetection->create_date = date('Y-m-d');

        if ($shareVersion == 2) {
            $insertDataDetection->doctor_id = $doctorId;
        }

        $inserted = 0;
        try {
            $inserted = R::store($insertDataDetection);
            $insertDataDetection->id = $inserted;
            $doctor = R::getRow('select user_id , name  from awusers where user_id = ?', [$insertDataDetection->doctor_id]);
            if (isset($doctor->name) && !empty($doctor->name)) {
                $insertDataDetection->title .= " - " . $doctor->name;
            }
            $this->erpProduct($insertDataDetection);
            if ($inserted == 999 || $inserted == 9999) {
                $insertDataDetection->id = $inserted;
                r::trash($insertDataDetection);

                $obj = R::dispense('detections');
                $obj->del = 0;
                $obj->detectionval = 0;
                $obj->title = '';
                $obj->create_date = date('Y-m-d');

                if ($shareVersion == 2) {
                    $insertDataDetection->doctor_id = $doctorId;
                }


                $inserted = R::store($obj);
            }


            echo $inserted;
        } catch (Exception $ex) {
            echo $ex;
        }
    }

    /**
     *  get doctor for depart in visit page
     */
    public function getDoctor() {
//check login
        autho::checkautho($this->hosturl);

        $role_id = filter_input(INPUT_POST, 'role_id');
        $regions = filter_input(INPUT_POST, 'regions');
        $subRegionId = filter_input(INPUT_POST, 'subRegionId');

        if ($regions == 1) {
            $result = $this->regionDoctors($role_id, $subRegionId);
        } else {
            $result = $this->nonRegionDoctors($role_id);
        }
        echo json_encode($result);
    }

    function regionDoctors($role_id, $subRegionId) {
        $role = R::load('awrole', $role_id);
        $doctors = '<option value="">choose</option> ';

        if ($role->doctor_show == 1 && $subRegionId > 0) {
            $original_doctors = R::getAll('select * from awusers where deleted != 1 
                and (   original_sub_regions like "% , ' . $subRegionId . ' , %" 
                     ||  original_sub_regions like "' . $subRegionId . '" 
                    ||  original_sub_regions like "%' . $subRegionId . ' , %" 
                    ||  original_sub_regions like "% , ' . $subRegionId . '%"     )
                    and   role_id in ( ' . $role->related_dr_depts . ' )');

            foreach ($original_doctors as $doctor) {
                $doctors .= '<option value="' . $doctor["user_id"] . '">' . $doctor["name"] . '</option>';
            }

            $sub_doctors = R::getAll('select * from awusers where deleted != 1 
                and (   alt_sub_regions like "% , ' . $subRegionId . ' , %" 
                     ||  alt_sub_regions like "' . $subRegionId . '" 
                    ||  alt_sub_regions like "%' . $subRegionId . ' , %" 
                    ||  alt_sub_regions like "% , ' . $subRegionId . '%"     )
                    and   role_id in ( ' . $role->related_dr_depts . ' )');

            if (count($sub_doctors) > 0) {
                $doctors .= '<option value="" disabled style=" background-color: red;" > Alternative Doctors </option>';
                foreach ($sub_doctors as $doctor) {
                    $doctors .= '<option value="' . $doctor["user_id"] . '">' . $doctor["name"] . '</option>';
                }
            }
        }

        $result = array(
            "doctor_show" => $role->doctor_show,
            "doctors" => $doctors
        );
        return $result;
    }

    function nonRegionDoctors($role_id) {
        $role = R::load('awrole', $role_id);

        $doctors = '<option value="">choose</option> ';

        if ($role->doctor_show == 1) {
            $depts_doctors = R::getAll('select * from awusers where deleted != 1 and   role_id in ( ' . $role->related_dr_depts . ' )');

            foreach ($depts_doctors as $doctor) {
                $doctors .= '<option value="' . $doctor["user_id"] . '">' . $doctor["name"] . '</option>';
            }
        }

        $result = array(
            "doctor_show" => $role->doctor_show,
            "doctors" => $doctors
        );

        return $result;
    }

    public function printrays() {

//check login
        autho::checkautho($this->hosturl);
        $visitId = filter_input(INPUT_POST, "visitId");
        $visit = R::load('visits', $visitId);

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

        $patientInfo = getPatientInfoAll($patient, $visit->for_husband, $visit->child, $visit->visitdate);
        $this->smarty->assign('name', $patientInfo['name']);
        $this->smarty->assign('title', $patientInfo['title']);
        $this->smarty->assign('gender', $patientInfo['gen']);
        $this->smarty->assign('age', $patientInfo['ageMin']);

        $docName = '';
        if ($visit->for_doctor > 0) {
            $doctorIn = R::getRow('select name  from awusers where user_id = ?', [$visit->for_doctor]);
            $docName = $doctorIn['name'];
        }
        $this->smarty->assign('docName', $docName);

        $dates = R::getAll('SELECT DISTINCT invests.sampletype  , sampletype.name as samplename
                                                                , ""  as sampleId
                                                                FROM invests
                                                               join   investigationresults     on  invests.id =  investigationresults.investid
                                                               left join sampletype            on sampletype.id = invests.sampletype
                                                              WHERE investigationresults.deleted = ?
                                                               and investigationresults.visitid = ? and  invests.sampletype IS NOT   NULL
                                                               ', [0, $visitId]);


        if (count($dates) > 0) {
            $i = 0;

            foreach ($dates as $data) {
                $showDocName = 0;
                $samId = R::getAll('SELECT  distinct  investigationresults.sample_id
                                                                FROM invests
                                                               join   investigationresults     on  invests.id =  investigationresults.investid
                                                              WHERE investigationresults.deleted = ?
                                                              and investigationresults.visitid = ? and  investigationresults.sample_id > 0 
                                                              and  invests.sampletype = ?  ', [0, $visitId, $data['sampletype']]);
                if (count($samId) > 0) {
                    $sampleId = $samId[0]['sample_id'];
                } else {
                    $sampleId = $this->createSampleId();
                }
                //  R::debug(true, 2);
                $this->createSampleBarCode($sampleId);
                $dates[$i]['sampleId'] = $sampleId;

                $invs = R::getAll('SELECT distinct   invests.id as invId , invests.name as invName ,  invests.type
                                                             ,   investigationresults.sample_id ,  investigationresults.id as invResId
                                                                FROM invests
                                                               join   investigationresults     on  invests.id =  investigationresults.investid
                                                              WHERE investigationresults.deleted = ?
                                                              and investigationresults.visitid = ?
                                                              and  invests.sampletype = ?  ', [0, $visitId, $data['sampletype']]);
                                                              
                                                              

                $invests = '';
                $x = 1;
                 $names = array();
                foreach ($invs as $row) {
                    r::exec(' update investigationresults set sample_id =  ' . $sampleId . ' where id = ' . $row['invResId']);
                    if ($row['type'] == 1) {
                        $showDocName = 1;
                    }
                                      if (!(in_array($row['invName'], $names))) {
                        if ($x > 1) {
                            $invests .= ' , ';
                        }
                        $invests .= $row['invName'];
                        $names[] = $row['invName'];
                    }
                    $x++;
                }
                // R::debug(false);

                $dates[$i]['invests'] = $invests;
                $dates[$i]['investsCount'] = count($invs);
                $dates[$i]['showDocName'] = $showDocName;

                $i++;
            }
        }


        $this->smarty->assign('sampletypes', $dates);
        $this->smarty->assign('sampletypes_count', count($dates));

        $visit->visitdate = date("d/m/Y", strtotime($visit->visitdate));
        $visit->visittime = date("h:iA", strtotime($visit->visittime));
        $this->smarty->assign('visit', $visit);


        $empty_dates = R::getAll('SELECT  distinct   invests.id as invId , invests.name as invName ,  invests.type
                                                                FROM invests
                                                               join   investigationresults     on  invests.id =  investigationresults.investid
                                                              WHERE investigationresults.deleted = ?
                                                              and investigationresults.visitid = ?
                                                              and  invests.sampletype IS NULL   ', [0, $visitId]);



        $invests = '';
        $x = 1;
        $names = array();
        $showDocName = 0;
        foreach ($empty_dates as $row) {
            if ($row['type'] == 1) {
                $showDocName = 1;
            }
             if (!(in_array($row['invName'], $names))) {
                        if ($x > 1) {
                            $invests .= ' , ';
                        }
                        $invests .= $row['invName'];
                        $names[] = $row['invName'];
                    }

            $x++;
        }



        $this->smarty->assign('empty_invests', $invests);
        $this->smarty->assign('empty_count', count($empty_dates));
        $this->smarty->assign('showDocName', $showDocName);

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

        $this->smarty->display('lab/printbar.html');
    }
    
       function loadSampleIdForInv($visitId) {
        $dates = R::getAll('SELECT DISTINCT invests.sampletype  , sampletype.name as samplename
                                                                , ""  as sampleId
                                                                FROM invests
                                                               join   investigationresults     on  invests.id =  investigationresults.investid
                                                               left join sampletype            on sampletype.id = invests.sampletype
                                                              WHERE investigationresults.deleted = ?
                                                               and investigationresults.visitid = ? and  invests.sampletype IS NOT   NULL
                                                               ', [0, $visitId]);


        if (count($dates) > 0) {
            $i = 0;

            foreach ($dates as $data) {
                $samId = R::getAll('SELECT  distinct  investigationresults.sample_id
                                                                FROM invests
                                                               join   investigationresults     on  invests.id =  investigationresults.investid
                                                              WHERE investigationresults.deleted = ?
                                                              and investigationresults.visitid = ? and  investigationresults.sample_id > 0 
                                                              and  invests.sampletype = ?  ', [0, $visitId, $data['sampletype']]);
                if (count($samId) > 0) {
                    $sampleId = $samId[0]['sample_id'];
                } else {
                    $sampleId = $this->createSampleId();
                }
                $this->createSampleBarCode($sampleId);

                $invs = R::getAll('SELECT   invests.id as invId , invests.name as invName ,  invests.type
                                                             ,   investigationresults.sample_id ,  investigationresults.id as invResId
                                                                FROM invests
                                                               join   investigationresults     on  invests.id =  investigationresults.investid
                                                              WHERE investigationresults.deleted = ?
                                                              and investigationresults.visitid = ?
                                                              and  invests.sampletype = ?  ', [0, $visitId, $data['sampletype']]);

                $x = 1;
                foreach ($invs as $row) {
                    r::exec(' update investigationresults set sample_id =  ' . $sampleId . ' where id = ' . $row['invResId']);
                }
                $i++;
            }
        }
    }

    function createSampleId() {
        $labSetting = R::findOne('programesettinglab');

        if ($labSetting->sample_serial >= 10000) {
            $sampleId = $labSetting->sample_serial + 1;
        } else {
            $sampleId = 10000;
        }
        $labSetting->sample_serial = $sampleId;
        r::store($labSetting);

        return $sampleId;
    }

    public function createSampleBarCode($sampleId) {
        if (file_exists('../../upload/samplebarcodes/' . $sampleId . '.png')) {
            
        } else {
            $url = $this->hosturl . '/../_library/barcode/image.php?code=' . $sampleId . '&type=C128A&width=230&height=60';
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $barcode = curl_exec($ch);

            if ($barcode === false) {
                $curl_result = curl_error($ch);
            } else {
                // header( 'Content-Type: application/json' );
                ## save the file to disk
                file_put_contents('../../upload/samplebarcodes/' . $sampleId . '.png', $barcode);
            }
            curl_close($ch);
        }
    }

    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';
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $barcode = curl_exec($ch);

            if ($barcode === false) {
                $curl_result = curl_error($ch);
            } else {
                // header( 'Content-Type: application/json' );
                ## save the file to disk
                file_put_contents('../../upload/barcodes/' . $statusno . '.png', $barcode);
            }
            curl_close($ch);
        }
    }

    public function createQRcode($statusno) {
        require_once("../../_library/phpqrcode/qrlib.php");

        if (!file_exists('../../upload/qrcodes/' . $statusno . '.png')) {
            QRcode::png($statusno, '../../upload/qrcodes/' . $statusno . '.png');
        }
    }

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


        $name = filter_input(INPUT_GET, "term");
        $limit = intval(filter_input(INPUT_GET, "page_limit"));

        $allPatients = R::getAll('SELECT id , statusno  FROM patients    WHERE deleted = ? and done = ?
                 and statusno  LIKE "%' . $name . '%"  ', [0, 1]);
//        echo $name . ' - ';
        echo json_encode($allPatients);
    }

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


        $name = filter_input(INPUT_GET, "term");
        $limit = intval(filter_input(INPUT_GET, "page_limit"));

        $allPatients = R::getAll('SELECT id , CONCAT(COALESCE(wifename,""), " -  ", COALESCE(husdandname,"")) AS name
            FROM patients    WHERE deleted = ? and done = ?
                 and (wifename  LIKE "%' . $name . '%"  || husdandname  LIKE "%' . $name . '%"  )  limit 0,50  ', [0, 1]);
//        echo $name . ' - ';
        echo json_encode($allPatients);
    }

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

        $statusNo = filter_input(INPUT_POST, "statusNo");
        $checkAdd = filter_input(INPUT_POST, "checkAdd");
        $allowAdd = 1;
        $visitsCount = 0;

        if ($statusNo > 0) {

            $programesetting = R::findOne('programesetting');
            $programesettingex = R::findOne('programesettingex');

            $allPatients = R::getRow('SELECT id , CONCAT(statusno , " -  ", COALESCE(wifename,""), " -  ", COALESCE(husdandname,"")) AS name
                 , wifename    ,   husdandname , statusno , wifenationalid , entrydate , status , vip , vip_comment
                 , phone , mobile  , revisioned  , "" as  phoneTxt   , "" as  govName   ,  governorate
                 , "" as  centerName   ,  governorate_center   , "" as  revisionedTxt  ,   wrfc  ,  rfc , saudi
            FROM patients    WHERE deleted = ? and done = ?    and   statusno  = ?     limit 0,50  ', [0, 1, $statusNo]);

            if ($checkAdd == 1) {
                $visits = R::count('visits', 'deleted = 0  and visitdate = ?  and patientid = ? and customer_add = 1
                       and detectionid not in (999 , 9999 , -88)   ', [date('Y-m-d'), $allPatients['id']]);
                if ($visits > 0 && $_SESSION['role_id'] == 19) {
                    $allowAdd = 0;
                }

                $visits = R::count('visits', 'deleted = 0  and visitdate = ?  and patientid = ?
                       and detectionid not in (999 , 9999 , -88)   ', [date('Y-m-d'), $allPatients['id']]);

                $visitsCount = $visits;
            }

            if ($allPatients['phone'] != '' && $allPatients['phone'] != null) {
                $allPatients['phoneTxt'] .= $allPatients['phone'];
            }

            if ($allPatients['governorate'] > 0) {
                $governorate = R::load('governorate', $allPatients['governorate']);
                $allPatients['govName'] .= $governorate->name;
            }

            if ($allPatients['governorate_center'] > 0) {
                $center = R::load('governorate_centers', $allPatients['governorate_center']);
                $allPatients['centerName'] .= $center->name;
            }

            if ($allPatients['mobile'] != '' && $allPatients['mobile'] != null) {
                if ($allPatients['phoneTxt'] != '') {
                    $allPatients['phoneTxt'] .= ' - ';
                }
                $allPatients['phoneTxt'] .= $allPatients['mobile'];
            }

            $checked = ' ';
            if ($allPatients['revisioned'] == 1) {
                $checked = '  checked ';
            }

            $allPatients['revisionedTxt'] = -1;

            if ($programesettingex->revisioned == 1) {
                $allPatients['revisionedTxt'] .= '
                               <div class="md-checkbox-inline" style="display: inline;">
                                                <div class="md-checkbox">
                                                    <input type="checkbox" id="revisioned" class="md-check updateElementCheck "
                                                    name="revisioned"    value="1"  data-id="  ' . $allPatients['id'] . ' "
                                                    data-colName="revisionedV"   data-tableName="patients"       ' . $checked . '  >
                                                    <label for="revisioned">
                                                        <span></span>
                                                        <span class="check"></span>
                                                        <span class="box"></span>
                                                        Revisioned  </label>
                                                </div>
                                            </div> ';
            }

            if ($programesetting->rfc == 1) {
                if ($allPatients['revisionedTxt'] != -1) {
                    $allPatients['revisionedTxt'] .= ' -  ';
                }

                switch ($allPatients['wrfc']) {
                    case 1:
                        $allPatients['revisionedTxt'] .= ' W : Yes  ';
                        break;

                    case 2:
                        $allPatients['revisionedTxt'] .= ' W : No  ';
                        break;

                    default:
                        $allPatients['revisionedTxt'] .= ' W :   ';
                        break;
                }

                switch ($allPatients['rfc']) {
                    case 1:
                        $allPatients['revisionedTxt'] .= ' H : Yes  ';
                        break;

                    case 2:
                        $allPatients['revisionedTxt'] .= ' H : No  ';
                        break;

                    default:
                        $allPatients['revisionedTxt'] .= ' H :   ';
                        break;
                }
            }


            $allPatients['allowAdd'] = $allowAdd;
            $allPatients['visitsCount'] = $visitsCount;
            $allPatients['stopped'] = $allPatients['status'];
            $allPatients['visit_phones'] = $programesetting->visit_phones;

            if ((empty($allPatients['wifenationalid']) || $allPatients['wifenationalid'] == "" || is_null($allPatients['wifenationalid']) ) &&
                    $allPatients['entrydate'] >= "2022-04-01 00:00:00" && $_SESSION['role_id'] != 19 &&
                    $programesetting->temp_patient == 1) {
                $allPatients['tempPatient'] = 1;
            }
        }

        echo json_encode($allPatients);
    }

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


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

        $lastVisitsAll = $this->getlastvisitObj($patientId);

        if (count($lastVisitsAll) > 0) {
            $lastVisits = $this->getlastvisitObj($patientId, " limit 0,3 ");
            $this->getlastvisitCommon($patientId, $lastVisits, count($lastVisitsAll));
        } else {
            echo -1;
        }
    }

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


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

        $lastVisits = $this->getlastvisitObj($patientId);

        if (count($lastVisits) > 0) {
            $this->getlastvisitCommon($patientId, $lastVisits);
        } else {
            echo -1;
        }
    }

    function getlastvisitObj($patientId, $limitSql = "") {

        $lastVisits = R::getAll('SELECT  visits.id as visitid ,   detections.title as detect
                                            , awrole.name as department  ,   detections.units as detectUnits
                              , CASE    WHEN detections.type = 1  THEN "نبضات"
                                WHEN detections.type = 2  THEN "جلسات"
                                ELSE "عادى"    END as detectionType
                                                , visits.for_doctor , visits.visitdate   , awusers.name as drName
                                                   , visits.detectionvalue_cash   , visits.detectionvalue_visa
                                                   , visits.units   , visits.notes as visitNote  , visits.branch_id
                                                  FROM visits
                         left  join detections    on detections.id  =  visits.detectionid
                          left  join awrole    on awrole.id  =  visits.for_department
                           left  join awusers    on awusers.user_id  =  visits.for_doctor
               where  visits.patientid = ?    and visits.deleted != ?  and visits.detectionid   != 999 and visits.detectionid   != 9999
               and visits.detectionid   != -88
                order by visits.visitdate desc , visits.id desc  ' . $limitSql, [$patientId, 1]);

        return $lastVisits;
    }

    function getlastvisitCommon($patientId, $lastVisits, $all = 0) {
        $programesetting = R::findOne('programesetting');
        $this->smarty->assign('system_type', $programesetting->system_type);
        $this->smarty->assign('branchesActivate', $programesetting->branches);

        $i = 0;
        foreach ($lastVisits as $data) {

            if ($programesetting->branches == 1) {
                $branch = R::load('branches', $data['branch_id']);
                $lastVisits[$i]['branch_name'] = $branch->name;
            }

## pay rest
            $payVisits = R::getRow('SELECT COALESCE(SUM(detectionvalue_cash),0)   as paid_cash
                                                                 , COALESCE(SUM(detectionvalue_visa),0)   as paid_visa
                                    FROM visits   where  patientid = ?
                               and deleted != ? and detectionid = 999 and visitid = ?   ', [$patientId, 1, $data['visitid']]);

## refund
            $refundVisits = R::getRow('SELECT COALESCE(SUM(detectionvalue_cash),0)   as refund_cash
                                                                 , COALESCE(SUM(detectionvalue_visa),0)   as refund_visa
                                    FROM visits   where  patientid = ?
                               and deleted != ? and detectionid = 9999 and visitid = ?   ', [$patientId, 1, $data['visitid']]);

## units attend
            $unitVisits = R::getRow('SELECT COALESCE(SUM(units),0)   as units_attend
                                    FROM visits   where  patientid = ?
                               and deleted != ? and detectionid = -88 and visitid = ?   ', [$patientId, 1, $data['visitid']]);

## all  what pt paid

            $paidAll = $payVisits['paid_cash'] + $data['detectionvalue_cash'] + $payVisits['paid_visa'] + $data['detectionvalue_visa'];
            $refundAll = $refundVisits['refund_cash'] + $refundVisits['refund_visa'];

            $lastVisits[$i]['paid_cash'] = $payVisits['paid_cash'] + $data['detectionvalue_cash'] - $refundVisits['refund_cash'];
            $lastVisits[$i]['paid_visa'] = $payVisits['paid_visa'] + $data['detectionvalue_visa'] - $refundVisits['refund_visa'];
            $lastVisits[$i]['total_paid'] = $paidAll - $refundAll;
            $lastVisits[$i]['paidAll'] = $paidAll;
            $lastVisits[$i]['refundAll'] = $refundAll;
            $lastVisits[$i]['unitsUsed'] = $lastVisits[$i]['units'] + $unitVisits['units_attend'];
            $lastVisits[$i]['unitsRest'] = $lastVisits[$i]['detectUnits'] - $lastVisits[$i]['unitsUsed'];
            $i++;
        }






        if ($all > 3) {
            $this->smarty->assign('lastVisitsAll', $all);
            $this->smarty->assign('patientId', $patientId);
        }

        $this->smarty->assign('lastVisits', $lastVisits);
        $this->smarty->display('visits/lastvisits.html');
    }

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

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

        $programesetting = R::findOne('programesetting');
        $this->getrestvaluesRoyal($patientId);
//        if (empty($programesetting->erpdb)) {
//            $this->getrestvaluesRoyal($patientId);
//        } else {
//            $this->getrestvaluesErp($patientId);
//        }
    }

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

        $patientId = filter_input(INPUT_POST, "patientId");
        //  $this->getrestvaluesPRoyal($patientId);

        $programesetting = R::findOne('programesetting');
        if (empty($programesetting->erpdb)) {
            $this->getrestvaluesPRoyal($patientId);
        } else {
            $this->getrestvaluesPErp($patientId);
        }
    }

    public function getrestvaluesPErp($patientId) {
        $erpApiLink = 'clientdept&id=0&royalid=' . $patientId;
        $result = orderFromErp($erpApiLink);
        echo $result;
    }

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

        $visits = array();
        $totalDept = 0;

        $lastVisit = R::getAll('SELECT visits.id as visitid , visits.restdetectionvalue as rest , visits.visitdate
                                                    , detections.title  as  detectionName
                                                    FROM visits
                                                     left join  detections                on  visits.detectionid = detections.id
                                                    where  visits.patientid = ?   and  visits.restdetectionvalue >0
                                                               and visits.deleted != ?   ', [$patientId, 1]);
        $i = 0;
        foreach ($lastVisit as $data) {
            $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  patientid = ?
                               and deleted != ? and detectionid = 999 and visitid = ?   ', [$patientId, 1, $data['visitid']]);

#               ## what pt paid after  creating visit
            $payVisits['paid'] = $payVisits['paid_cash'] + $payVisits['paid_visa'];
            if ($data['rest'] > ($payVisits['paid'] + $payVisits['paid_discount'])) {
                $totalDept = $totalDept + $data['rest'] - $payVisits['paid'] - $payVisits['paid_discount'];
            }
        }

        echo $totalDept;
    }

    public function getrestvaluesErp($patientId) {
        $erpApiLink = 'clientdept&id=0&royalid=' . $patientId;
        $result = orderFromErp($erpApiLink);
    }

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

        $visits = array();

        $lastVisit = R::getAll('SELECT visits.id as visitid , visits.restdetectionvalue as rest , visits.visitdate
                                                    , detections.title  as  detectionName
                                                    FROM visits
                                                     left join  detections                on  visits.detectionid = detections.id
                                                    where  visits.patientid = ?   and  visits.restdetectionvalue >0
                                                               and visits.deleted != ?   ', [$patientId, 1]);
        $i = 0;
        foreach ($lastVisit as $data) {
            $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  patientid = ?
                               and deleted != ? and detectionid = 999 and visitid = ?   ', [$patientId, 1, $data['visitid']]);

//            ## refund
//            $refundVisits = R::getRow('SELECT COALESCE(SUM(detectionvalue_cash),0)   as refund_cash
//                                                                 , COALESCE(SUM(detectionvalue_visa),0)   as refund_visa
//                                    FROM visits   where  patientid = ?
//                               and deleted != ? and detectionid = 9999 and visitid = ?   ', [$patientId, 1, $data['visitid']]);
#
            #
#               ## what pt paid after  creating visit
            $payVisits['paid'] = $payVisits['paid_cash'] + $payVisits['paid_visa'];
//   $payVisits['paid'] = $payVisits['paid_cash'] + $payVisits['paid_visa'] - $refundVisits['refund_cash'] - $refundVisits['refund_visa'];

            if ($data['rest'] > ($payVisits['paid'] + $payVisits['paid_discount'])) {

                $v['visitdate'] = $data['visitdate'];
                $v['dept'] = $data['rest'] - $payVisits['paid'] - $payVisits['paid_discount'];
                $v['visitid'] = $data['visitid'];
                $v['detectionName'] = $data['detectionName'];

                array_push($visits, $v);
            }
        }


        if (count($visits) > 0) {
            $this->smarty->assign('visits', $visits);
            $this->smarty->display('visits/rest.html');
        } else {
            echo -1;
        }
    }

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

        R::selectDatabase('default');

        $visitId = filter_input(INPUT_POST, "visitId");
        $paid_cash = filter_input(INPUT_POST, "paid_cash");
        $paid_visa = filter_input(INPUT_POST, "paid_visa");
        $patientId = filter_input(INPUT_POST, "patientId");
        $restDiscount = filter_input(INPUT_POST, "restDiscount");
        $restNotes = filter_input(INPUT_POST, "restNotes");
        $branch_id = filter_input(INPUT_POST, "branch_id");

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

        $insertDataVisits = R::dispense('visits');
        $insertDataVisits->patientid = $visit->patientid;
        $insertDataVisits->visitdate = date("Y/m/d");
        $insertDataVisits->visittime = date("H:i:s");
        $insertDataVisits->detectionid = 999;
        $insertDataVisits->detectionvalue_cash = $paid_cash;
        $insertDataVisits->detectionvalue_visa = $paid_visa;
        $insertDataVisits->totaldetectionvalue = 0;
        $insertDataVisits->restdetectionvalue = 0;
        $insertDataVisits->discount = $restDiscount;
        $insertDataVisits->for_department = $visit->for_department;
        $insertDataVisits->for_doctor = $visit->for_doctor;
        $insertDataVisits->for_husband = $visit->for_husband;
        $insertDataVisits->user_id = $_SESSION['user_id'];
        $insertDataVisits->visitid = $visitId;
        $insertDataVisits->notes = $restNotes;
        $insertDataVisits->branch_id = $branch_id;

        if ($_SESSION['role_id'] == 19) {
            $insertDataVisits->customer_add = 1;
        } else {
            $insertDataVisits->customer_add = 0;
        }


        if ($paid_cash > 0) {
            $insertDataVisits->printserial = $this->printSerial('last_serial');
        } else {
            $insertDataVisits->printserial = 0;
        }

        $insertDataVisits->create_date = date('Y-m-d H:i:s'); //$this->today;
        $insertDataVisits->refer_doctor = $visit->refer_doctor;
        $insertDataVisits->refer_doctor_tb = $visit->refer_doctor_tb;
        $insertDataVisits->rfc = $visit->rfc;

        $insertDataVisits->units = 0;


        $insert = R::store($insertDataVisits);
        ##erp fatma
        if ($paid_cash > 0 || $paid_visa > 0 || $restDiscount > 0) {
            calcBalance($visit->patientid);
            //$this->erpSellbillUpdate($visit);
            $_POST['clientIdForERP'] = $patientId;
            $_POST['billsItr'] = 1;
            $_POST['visitid1'] = $visitId;
            $_POST['payVisitId1'] = $insert;
            $_POST['cashPay1'] = $paid_cash;
            $_POST['visaPay1'] = $paid_visa;
            $_POST['billDis1'] = $restDiscount;
            $_POST['notBillPay'] = 1;
            $this->payERPBills();
        }

        if (count($insert) > 0) {
            if ($paid_cash > 0) {
                $this->printrecept($insert);
            }
        } else {
            echo -1;
        }
    }

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

        $statusNo = (!filter_input(INPUT_POST, "search")) ? "" : filter_input(INPUT_POST, "search");


## wife name or id entered
        if (!empty($statusNo)) {
            $query = "SELECT patients.id   FROM `patients`
                                        WHERE
                                        patients.done = 1
                                        AND patients.deleted = 0
                                        AND   statusno  = $statusNo  ";

//            print_r($query);
            $patient = R::getRow($query);
            echo $patient['id'];
        } else {
            echo -1;
        }


#################################################################################################################
    }

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

        $statusNo = (!filter_input(INPUT_POST, "search")) ? "" : filter_input(INPUT_POST, "search");


## wife name or id entered
        if (!empty($statusNo)) {
            $query = "SELECT patients.id  , CONCAT(COALESCE(patients.wifename,' ') , " - ", COALESCE(patients.husdandname,' ') ) AS name
                                        FROM `patients`
                                        WHERE
                                        patients.done = 1
                                        AND patients.deleted = 0
                                        AND   statusno  = $statusNo  ";

//            print_r($query);
            $patient = R::getRow($query);
            echo json_encode($patient);
        } else {
            echo -1;
        }


#################################################################################################################
    }

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

        $dateFrom = filter_input(INPUT_POST, "date_from");
        $dateTo = filter_input(INPUT_POST, "date_to");
        $deptId = filter_input(INPUT_POST, "deptId");
        $patientId = filter_input(INPUT_POST, "patientId");
        $doctorId = filter_input(INPUT_POST, "doctorId");
        $branchSearch = filter_input(INPUT_POST, "branchSearch");
        $ignoreDate = filter_input(INPUT_POST, "ignoreDate");
           $patNationalId = filter_input(INPUT_POST, "patNationalId");
        $patMobile = filter_input(INPUT_POST, "patMobile");
        $sampleId = filter_input(INPUT_POST, "sampleId");

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

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

        $user = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);

        if ($dateFrom != '00-00-0000' && !empty($dateFrom)) {
            $dateFrom = date('Y/m/d', strtotime($dateFrom));
        } else {
            $dateFrom = '0000-00-00';
        }

        if ($dateTo != '00-00-0000' && !empty($dateTo)) {
            $dateTo = date('Y/m/d', strtotime($dateTo));
        } else {
            $dateTo = date('Y/m/d');
        }

        if ($programesetting->past_search != 1) {
            $endDate = date("Y/m/d", strtotime("- 2 days", strtotime(date('Y/m/d'))));
            if ($dateFrom < $endDate) {
                $dateFrom = $endDate;
            }
        }

        $ext = ' ';
        if ($deptId > 0) {
            $ext .= ' and  visits.for_department = ' . $deptId;
            $this->smarty->assign('isLab', 1);
        }

        if ($patientId > 0) {
            $ext .= ' and  visits.patientid  = ' . $patientId;
            $ignoreDate = 1;
        }



        if ($branchSearch > 0) {
            $ext .= '  and visits.branch_id =   ' . $branchSearch;
        }
        
                if (!empty($patNationalId) && $patNationalId != '') {
            $ext .= ' and  ( patients.wifenationalid  = ' . $patNationalId . '  || patients.husbandnationalid  = ' . $patNationalId . ' ) ';
            $ignoreDate = 1;
        }

        if (!empty($patMobile) && $patMobile != '') {
            $ext .= ' and  ( patients.phone  = ' . $patMobile . '  || patients.mobile  = ' . $patMobile . ' ) ';
            $ignoreDate = 1;
        }
        
                if (!empty($sampleId) && $sampleId != '') {
            $ext .= ' and   investigationresults.sample_id  = ' . $sampleId;
            $ignoreDate = 1;
        }

        $ext .= $this->branchSql($programesetting->branches);
        $showBranchCol = showBranchCol($programesetting->branches);

        if ($doctorId > 0) {
            $ext .= ' and  visits.for_doctor  = ' . $doctorId;
        }

        if ($user['role_id'] == 19 && $user['related_dr'] != 0 && !empty($user['related_dr']) && $user['related_dr'] != "" && !( is_null($user['related_dr']))) {
            $ext .= ' and  visits.for_doctor   in  (' . $user['related_dr'] . ' ) ';
        }


        if ($ignoreDate == 1 && ($patientId > 0 || (!empty($patMobile) && $patMobile != '') ||
                 (!empty($patNationalId) && $patNationalId != '') || (!empty($sampleId) && $sampleId != ''))) {
            //        R::debug(true, 2);
             $allvisit = R::find('visits', '   join patients     on visits.patientid  = patients.id 
                 left  join investigationresults     on investigationresults.visitid  = visits.id 
                     where visits.deleted = ?    ' . $ext . '  
                ORDER BY visits.visitdate asc ,  visits.id asc', [0]);
//        R::debug(false);
        } else {
            //        R::debug(true, 2);
            $allvisit = R::find('visits', '  visits.deleted = ?    ' . $ext . '
                        and  visits.visitdate  between ? and ?
                ORDER BY visits.visitdate asc ,  visits.id asc', [0, $dateFrom, $dateTo]);
//        R::debug(false);
        }



        foreach ($allvisit as $visit) {
            $visit->visitdate = date("Y/m/d", strtotime($visit->visitdate));
            $patient = R::getRow("SELECT * FROM patients WHERE id = $visit->patientid");

            if ((empty($patient['wifenationalid']) || $patient['wifenationalid'] == "" || is_null($patient['wifenationalid']) ) &&
                    $patient['entrydate'] >= "2022-04-01 00:00:00" && $_SESSION['role_id'] != 19 &&
                    $visit->for_husband == 0 && $programesetting->temp_patient == 1) {
                $visit->tempPatient = 1;
            }

            $visit->branch_name = ' ';
            if ($showBranchCol == 1 && $visit->branch_id > 0) {
                $branch = R::load('branches', $visit->branch_id);
                $visit->branch_name = $branch->name;
            }



            $visit->patientName = $patient['wifename'];
            $visit->patientstatusno = $patient['statusno'];
            $visit->patientNatNo = $patient['wifenationalid'];
            $visit->address = $patient['address'];
            $visit->phone = $patient['phone'];
            $visit->mobile = $patient['mobile'];
            $visit->husbandname = $patient['husdandname'];



            $user = R::findOne('awusers', 'user_id = ?', [$visit->user_id]);
            $visit->user_name = $user->name;

            $visit->notes = trim($visit->notes);

            if ($visit->for_husband == 2) {
                $child = R::load('patients_childs', $visit->child);
                $visit->child_name = $child->child_name;
                $visit->child_gender = $child->gender;
            }

            $reserve = R::findOne('visit_hours', ' visit_id = ? and deleted = 0 ', [$visit->id]);
            if (count($reserve) > 0) {
                $visit->visitHour = date('h:i A', strtotime($reserve->visit_hour));
            } else {
                $visit->visitHour = '';
            }
//            $visit->visitHour = $reserve->visit_hour;

            if ($visit->for_department != "") {

//get name of dcotor
                $doctor = R::getRow('select * from awusers where user_id = ?', [$visit->for_doctor]);

                $depart_name = R::load('awrole', $visit->for_department);
                if ($visit->for_doctor > 0) {
                    $visit->for_department_name = $depart_name->name . '( ' . $doctor['name'] . ' )';
                    $visit->visitDrName = $doctor['name'];
                } else {
                    $visit->for_department_name = $depart_name->name;
                }
            }

            if ($labSetting->lab_style == 2 && $visit->for_department == 12) {
                $visit->labDoctorName = $this->labDoctorName($visit->for_doctor, $visit->refer_doctor, $visit->refer_doctor_tb);
            }

            if ($visit->detectionid == 9999) {
                $originalVisit = R::load('visits', $visit->visitid);
                $detection = R::load('detections', $originalVisit->detectionid);
                $visit->detection = 'مرتجع العملاء';
                $visit->detection .= ' ( ' . $detection->title . ' ) ';
            } elseif ($visit->detectionid == 999) {
                $originalVisit = R::load('visits', $visit->visitid);
                $detection = R::load('detections', $originalVisit->detectionid);
                $visit->detection = 'دفع متبقى ';
                $visit->detection .= ' ( ' . $detection->title . ' ) ';
            } elseif ($visit->detectionid == -88) {
                $originalVisit = R::load('visits', $visit->visitid);
                $detection = R::load('detections', $originalVisit->detectionid);
                $visit->detection = 'متابعة ';
                $visit->detection .= ' ( ' . $detection->title . ' ) ';
            } else {
                $detection = R::load('detections', $visit->detectionid);
                $visit->detection = $detection->title;
            }


            $visit->subregion = ' ';
            if ($programesetting->regions == 1 && $visit->sub_region_id > 0) {
                $sub_region = R::load('sub_regions', $visit->sub_region_id);
                $visit->subregion = $sub_region->name;

                if ($visit->for_doctor > 0) {
                    $doctor = R::getRow('select * from awusers where user_id = ?', [$visit->for_doctor]);
                    $visit->drPhone = $doctor['whatsapp_no'];
                    $visit->drWhatsappMsg = '  المريض:    ' . $visit->patientName . '  - رقم الهاتف  ' . $visit->phone . '
 - المنطقة :  ' . $visit->subregion . '   - العنوان :  ' . $visit->address . '  - الخدمة المطلوبة :   ( ' . $visit->detection . '  ) ';
                }
            }

            if ($visit->is_redirect == 1 && $visit->redirect_to != '' && !is_null($visit->redirect_to)) {
                $redirectTo = explode(',', $visit->redirect_to);
                if (count($redirectTo) > 1) {
                    $userId = ' ' . $_SESSION['user_id'] . ' ';
                } else {
                    $userId = $_SESSION['user_id'];
                }

                //  print_r('-' . $userId . '-');
                //  print_r('-' . $redirectTo[2] . '-');
                //   print_r(in_array($userId, $redirectTo) . ' - ');
                if (in_array($userId, $redirectTo)) {
                    $visit->showRedirectNote = 1;
                }
            }
       
               if ($patient['inv_link'] == -1 || is_null($patient['inv_link']) || $patient['inv_link'] == '') {
                $patient = R::load('patients', $visit->patientid);

                $dataArray = getPatientDataArr($patient); 
                $visit->inv_link = getPatientLink($dataArray);
            } else {
                $visit->inv_link = $patient['inv_link'];
            }
        }

        $allowEditVisit = 0;
        $btn3 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 3  ', [$_SESSION['role_id']]);
        if (count($btn3) > 0) {
            $allowEditVisit = $btn3->checkval;
        }
        $this->smarty->assign('allowEditVisit', $allowEditVisit);


        $allowDeleteVisit = 0;
        $btn4 = R::findOne('awrolebtn', ' role_id = ? and btn_id = 4  ', [$_SESSION['role_id']]);
        if (count($btn4) > 0) {
            $allowDeleteVisit = $btn4->checkval;
        }
        $this->smarty->assign('allowDeleteVisit', $allowDeleteVisit);

        $this->smarty->assign('allvisit', $allvisit);
        $this->smarty->assign('showBranchCol', $showBranchCol);


        if ($labSetting->lab_style == 2 && $deptId == 12) {
            $this->smarty->assign('allvisitCount', count($allvisit));
            $this->smarty->display('visits/visitdiv_lab.html');
        } else {
            $this->smarty->display('visits/visitdiv.html');
        }
    }

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

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

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

        if ($programesetting->system_type == 2) {
            $this->printreceptShare($visitId);
        } if ($programesetting->system_type == 3) {
            $this->printreceptBeauty($visitId);
        } else {
            $this->printrecept($visitId);
        }
    }

    public function printreceptBeauty($visitId) {

        try {
            $visit = R::load('visits', $visitId);
            $this->smarty->assign('visitdate', date("Y/m/d", strtotime($visit->visitdate)));
            $this->smarty->assign('detectionvalue_cash', $visit->detectionvalue_cash);
            $this->smarty->assign('detectionvalue_visa', $visit->detectionvalue_visa);
            $this->smarty->assign('for_husband', $visit->for_husband);
            $this->smarty->assign('printserial', $visit->printserial);


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

            if ($visit->detectionid == 999) {
                $originalVisitId = $visit->visitid;
                $originalVisit = R::load('visits', $visit->visitid);
                $detection = R::load('detections', $originalVisit->detectionid);
                $det = 'دفع متبقى ';
                $det .= ' ( ' . $detection->title . ' ) ';
                $this->smarty->assign('detection', $det);
                $this->smarty->assign('detectionValue', $originalVisit->totaldetectionvalue);

                $originalPaid = $originalVisit->detectionvalue_cash + $originalVisit->detectionvalue_visa;
                $originalRest = $originalVisit->restdetectionvalue;
            } else if ($visit->detectionid == 9999) {
                $originalVisitId = $visit->visitid;
                $originalVisit = R::load('visits', $visit->visitid);
                $detection = R::load('detections', $originalVisit->detectionid);
                $det = 'مرتجع العملاء';
                $det .= ' ( ' . $detection->title . ' ) ';
                $this->smarty->assign('detection', $det);
                $this->smarty->assign('detectionValue', $originalVisit->totaldetectionvalue);

                $originalPaid = $originalVisit->detectionvalue_cash + $originalVisit->detectionvalue_visa;
                $originalRest = $originalVisit->restdetectionvalue;
            } else {
                $originalVisitId = $visit->id;
                $detection = R::load('detections', $visit->detectionid);
                $this->smarty->assign('detection', $detection->title);
                $this->smarty->assign('detectionValue', $visit->totaldetectionvalue);

                $originalPaid = $visit->detectionvalue_cash + $visit->detectionvalue_visa;
                $originalRest = $visit->restdetectionvalue;
            }

            if ($visit->for_husband == 1) {
                $pat_name = $patient->husdandname;
            }
            ##
            elseif ($visit->for_husband == 2) {
                $child = R::load('patients_childs', $visit->child);

                if (is_null($child->child_name) || $child->child_name == '') {
                    if ($child->gender == 1) {
                        $pat_name = 'الطفل / ' . $patient->wifename;
                    } else {
                        $pat_name = 'الطفلة / ' . $patient->wifename;
                    }
                } else {
                    $pat_name = $child->child_name . '  /  ' . $patient->wifename;
                }
            }
            ##
            else {
                $pat_name = $patient->wifename;
            }


            $this->smarty->assign('notes', $visit->notes);
            $this->smarty->assign('detectionId', $visit->detectionid);
            $this->smarty->assign('pat_name', $pat_name);

            $user = R::findOne('awusers', 'user_id = ?', [$visit->user_id]);
            $this->smarty->assign('user_name', $user->name);


            $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  patientid = ?
                               and deleted != ? and detectionid = 999 and visitid = ?   ', [$visit->patientid, 1, $originalVisitId]);

            $totalPaid = $payVisits['paid_cash'] + $payVisits['paid_visa'] + $originalPaid;
            $this->smarty->assign('totalPaid', $totalPaid);

            $totalRest = $originalRest - $payVisits['paid_cash'] - $payVisits['paid_visa'] - $payVisits['paid_discount'];
            $this->smarty->assign('totalRest', $totalRest);

            $this->smarty->display('visits/print_beauty.html');
#################################
        } catch (Exception $ex) {
            echo '-1';
        }
    }

    public function printreceptShare($visitId) {

        try {
            $visit = R::load('visits', $visitId);
            $this->smarty->assign('visitdate', date("Y/m/d", strtotime($visit->visitdate)));
            $this->smarty->assign('detectionvalue_cash', $visit->detectionvalue_cash);
            $this->smarty->assign('detectionvalue_visa', $visit->detectionvalue_visa);
            $this->smarty->assign('for_husband', $visit->for_husband);
            $this->smarty->assign('printserial', $visit->printserial);


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

            if ($visit->detectionid == 999) {
                $originalVisit = R::load('visits', $visit->visitid);
                $detection = R::load('detections', $originalVisit->detectionid);
                $det = 'دفع متبقى ';
                $det .= ' ( ' . $detection->title . ' ) ';
                $this->smarty->assign('detection', $det);
            } else if ($visit->detectionid == 9999) {
                $originalVisit = R::load('visits', $visit->visitid);
                $detection = R::load('detections', $originalVisit->detectionid);
                $det = 'مرتجع العملاء';
                $det .= ' ( ' . $detection->title . ' ) ';
                $this->smarty->assign('detection', $det);
            } else {
                $detection = R::load('detections', $visit->detectionid);
                $this->smarty->assign('detection', $detection->title);
            }

            $this->smarty->assign('detectionId', $visit->detectionid);

            $user = R::findOne('awusers', 'user_id = ?', [$visit->user_id]);
            $this->smarty->assign('user_name', $user->name);

            $user = R::findOne('awusers', 'user_id = ?', [$visit->for_doctor]);
            $this->smarty->assign('doctorName', $user->name);


            $reserve = R::findOne('visit_hours', ' visit_id = ? and deleted = 0 ', [$visitId]);
            $this->smarty->assign('visitHour', $reserve->visit_hour);

            $room = R::load('clinic_rooms', $reserve->room_id);
            $this->smarty->assign('clinicNo', $room->name);

            $this->smarty->display('visits/print_share.html');
#################################
        } catch (Exception $ex) {
            echo '-1';
        }
    }

    public function printrecept($visitId) {
        $visit = R::load('visits', $visitId);
        $this->smarty->assign('printserial', $visit->printserial);

        $user = R::findOne('awusers', 'user_id = ?', [$visit->user_id]);
        $this->smarty->assign('user_name', $user->name);

        $patient = R::load('patients', $visit->patientid);
        $pat_name = $this->patName($visit->for_husband, $patient, $visit->child);
        $this->smarty->assign('pat_name', $pat_name);

        $labSetting = R::findOne('programesettinglab');
        if ($visit->for_department == 12 && $labSetting->receiptstyle == 2) {
            $this->receptStyle2($visit, $patient);
        } else {
            $this->receptStyle1($visit);
        }
    }

    function printVisitBill() {
        $visitId = filter_input(INPUT_POST, "visitId");

        $visit = R::load('visits', $visitId);
        $this->smarty->assign('printserial', $visit->printserial);

        $patient = R::load('patients', $visit->patientid);
        $pat_name = $this->patName($visit->for_husband, $patient, $visit->child);
        $this->smarty->assign('pat_name', $pat_name);

        $this->createbarcode($patient->statusno);
        $this->createQRcode($patient->statusno);

        $this->completeLabPrint($visit, $patient);

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

        $this->smarty->display('visits/printbill.html');
    }

    public function receptStyle1($visit) {
        try {

            $detection_name = $this->detectionName($visit);

            $this->smarty->assign('notes', $visit->notes);
            $this->smarty->assign('detectionId', $visit->detectionid);

            $this->smarty->assign('detection', $detection_name);
            $this->smarty->assign('visitdate', date("Y/m/d", strtotime($visit->visitdate)));
            $this->smarty->assign('detectionvalue_cash', $visit->detectionvalue_cash);
            $this->smarty->assign('detectionvalue_visa', $visit->detectionvalue_visa);
            $this->smarty->assign('for_husband', $visit->for_husband);

            $this->smarty->display('visits/print.html');
#################################
        } catch (Exception $ex) {
            echo '-1';
        }
    }

    public function receptStyle2($visit, $patient) {
        $this->completeLabPrint($visit, $patient);
        $this->smarty->display('visits/printreceipt2.html');
    }

    function completeLabPrint($visit, $patient) {
        $labSetting = R::findOne('programesettinglab');
        $this->smarty->assign('labSetting', $labSetting);

        $setting = R::findOne('programesetting');
        $this->smarty->assign('setting', $setting);
        
                $service = ' ';
        if ($visit->detectionid > 0) {
            $service = $this->detectionName($visit);
        }
        $this->smarty->assign('service', $service);

        $this->smarty->assign('statusno', $patient->statusno);
        $this->smarty->assign('patientId', $patient->wifenationalid);
        $this->smarty->assign('visitdate', date("d-m-Y g:ia", strtotime($visit->create_date)));
        switch ($patient->saudi) {
            case 1:
                $this->smarty->assign('nationality', 'Non Saudi');
                break;

            default:
                $this->smarty->assign('nationality', 'Saudi');
                break;
        }

        $doctorName = $this->labDoctorName($visit->for_doctor, $visit->refer_doctor, $visit->refer_doctor_tb);
        $this->smarty->assign('doctorName', $doctorName);

        $visit->totalAmount = $visit->totaldetectionvalue - $visit->discount + $visit->vat_value;

      $this->payingMethod($visit);

           $this->visitOffers($visit->id);
        $this->visitTestsWithoutOffers($visit->id);
        
        $this->smarty->assign('visit', $visit);
        
                if (!file_exists('../../upload/linkqrcodes/' . $patient->statusno . '.png')) {
            $this->patientLinkQr($patient);
        }
        

    }
    
    
        function visitTestsWithoutOffers($visitId) {
        $sql = ' select  investigationresults.price  , invests.name , sampletype.name as sampleType 
                             ,   investigationresults.sample_id
                        from    investigationresults
                          join       invests                                        on invests.id  = investigationresults.investid 
                           left join sampletype            on sampletype.id = invests.sampletype
                        where   investigationresults.deleted = 0  and  investigationresults.visitid =  ' . $visitId . '   
                            and   investigationresults.offer_id = 0 
                           order by  investigationresults.sample_id ';

        $visitTests = R::getAll($sql);
        $this->smarty->assign('visitTests', $visitTests);
          return $visitTests ;
    }
    
    
    function visitOffers($visitId) {
        $sql = ' select  distinct investigationresults.offer_id   , invoffer.name
                        from    investigationresults
                           join       invoffer                                        on invoffer.id  = investigationresults.offer_id 
                        where   investigationresults.deleted = 0  and  investigationresults.visitid =  ' . $visitId . '   
                            and   investigationresults.offer_id > 0   ';

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

        $i = 0;
        foreach ($visitOffers as $offer) {
            $price = R::getRow(' select  sum(investigationresults.price) as price 
                        from    investigationresults
                        where   investigationresults.deleted = 0  and  investigationresults.visitid =  ' . $visitId . '   
                            and   investigationresults.offer_id =  ' . $offer['offer_id'] . ' ');

            $visitOffers[$i]['price'] = $price['price'];
            $i++;
        }
        $this->smarty->assign('visitOffers', $visitOffers);
        return $visitOffers ;
    }
    
    function patientLinkQr($patient) {
        if ($patient->inv_link == -1 || is_null($patient->inv_link) || $patient->inv_link == '') {
            $dataArray = getPatientDataArr($patient);
            $link = getPatientLink($dataArray);
        }else{
            $link = $patient->inv_link;
        }

        if ($link != -1) {
            $this->createGeneralQRcode($link, 'linkqrcodes', $patient->statusno);
        }
    }
    
    public function createGeneralQRcode($value, $folder, $name) {
        require_once("../../_library/phpqrcode/qrlib.php");

        if (!file_exists('../../upload/' . $folder . '/' . $name . '.png')) {
            QRcode::png($value, '../../upload/' . $folder . '/' . $name . '.png');
        }
    }

    function labDoctorName($doctorId, $refer_doctorId, $doctor_tb) {
        $doctorName = '  ';
        $programesetting = R::findOne('programesetting');
        if ($programesetting->refer_doctor == 1) {
            if ($refer_doctorId > 0) {
                switch ($doctor_tb) {
                    case 1:
                        $user = R::findOne('awusers', 'user_id = ?', [$refer_doctorId]);
                        $doctorName = $user->name;
                        break;

                    default:
                        $refer = R::load('refer', $refer_doctorId);
                        $doctorName = $refer->name;
                        break;
                }
            }
        } else {
            if ($doctorId > 0) {
                $user = R::findOne('awusers', 'user_id = ?', [$doctorId]);
                $doctorName = $user->name;
            }
        }
        return $doctorName;
    }

 function visitTests($visitId) {
        $sql = ' select  investigationresults.price  , invests.name , sampletype.name as sampleType 
                             ,   investigationresults.sample_id  , invoffer.name   as offerName  , 1 as showMe
                        from    investigationresults
                          join       invests                                        on invests.id  = investigationresults.investid 
                           left join sampletype            on sampletype.id = invests.sampletype 
                              left join invoffer            on invoffer.id = investigationresults.offer_id
                        where   investigationresults.deleted = 0  and  investigationresults.visitid =  ' . $visitId . '   
                           order by  investigationresults.sample_id ';

        $visitTests = R::getAll($sql);
          $names = array();
                  $i = 0;
        foreach ($visitTests as $test) {
            if (in_array($test['name'], $names)) {
                $visitTests[$i]['showMe'] = 0;
            } else {
                $names[] = $test['name'];
            }
            $i++;
        }
        $this->smarty->assign('visitTests', $visitTests);
    }

    function detectionName($visit) {
        if ($visit->detectionid == 999) {
            $originalVisit = R::load('visits', $visit->visitid);
            $detection = R::load('detections', $originalVisit->detectionid);
            $det = 'دفع متبقى ';
            $det .= ' ( ' . $detection->title . ' ) ';
        } else if ($visit->detectionid == 9999) {
            $originalVisit = R::load('visits', $visit->visitid);
            $detection = R::load('detections', $originalVisit->detectionid);
            $det = 'مرتجع العملاء';
            $det .= ' ( ' . $detection->title . ' ) ';
        } else {
            $detection = R::load('detections', $visit->detectionid);
            $det = $detection->title;
        }
        return $det;
    }

    function patName($for_husband, $patient, $childId) {


        $programesetting = R::findOne('programesetting');
        if ($programesetting->system_lang == 2) {
            $pat_name = $patient->wifename;
            $date = $patient->dateofbirth;
            if ($patient->gender == 1) {
                $gender = 'Male';
            } else {
                $gender = 'Female';
            }
        } else {
            if ($for_husband == 1) {
                $pat_name = $patient->husdandname;
                $date = $patient->husbanddateofbirth;
                $gender = 'Male';
            } elseif ($for_husband == 2) {
                $child = R::load('patients_childs', $childId);

                $date = $child->birth_date;
                if ($child->gender == 1) {
                    $gender = 'Male';
                } else {
                    $gender = 'Female';
                }

                if (is_null($child->child_name) || $child->child_name == '') {
                    if ($child->gender == 1) {
                        $pat_name = 'الطفل / ' . $patient->wifename;
                    } else {
                        $pat_name = 'الطفلة / ' . $patient->wifename;
                    }
                } else {
                    $pat_name = $child->child_name . '  /  ' . $patient->wifename;
                }
            }
            ##
            else {
                $pat_name = $patient->wifename;
                $gender = 'Female';
                $date = $patient->dateofbirth;
            }
        }


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

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

        if ($interval->y > 0) {
            $age = $interval->y . 'Years';
        } elseif ($interval->m > 0) {
            $age = $interval->m . 'Months';
        } elseif ($interval->d > 0) {
            $age = $interval->d . 'Days';
        } else {
            $age = '';
        }

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

        return $pat_name;
    }

    public function getvisitinvests() {

        $investsArray = json_decode(stripslashes(filter_input(INPUT_POST, 'invests')));
        $offersArray = json_decode(stripslashes(filter_input(INPUT_POST, 'offers')));
        $result = array();
        $totalPrice = 0;

        try {

            foreach ($investsArray as $investId) {
                $obj = R::load('invests', $investId);
                $totalPrice = $totalPrice + $obj->price;

                $invest = array(
                    "offerId" => 0,
                    "invId" => $investId,
                    "name" => $obj->name,
                    "price" => $obj->price     ##   price in general
                );

                array_push($result, $invest);
            }

            foreach ($offersArray as $offerId) {
                $offerDetails = R::findall('invofferdetails', 'del = ? and invoffer_id = ?  ', [0, $offerId]);
                foreach ($offerDetails as $data) {
                    $obj = R::load('invests', $data->inv_id);
                    $totalPrice = $totalPrice + $data->price;

                    $offerInvest = array(
                        "offerId" => $offerId,
                        "invId" => $data->inv_id,
                        "name" => $obj->name,
                        "price" => $data->price     ##   price in offer
                    );

                    array_push($result, $offerInvest);
                }
            }

            $this->smarty->assign('totalPrice', $totalPrice);
            $this->smarty->assign('result', $result);
            $this->smarty->assign('resultCount', count($result));
            $this->smarty->display('visits/invests.html');
#################################
        } catch (Exception $ex) {
            echo '-1';
        }
    }

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

        $visitId = filter_input(INPUT_POST, "visitId");
        $refund_cash = filter_input(INPUT_POST, "refund_cash");
        $refund_visa = filter_input(INPUT_POST, "refund_visa");
        $patientId = filter_input(INPUT_POST, "patientId");
        $notes = filter_input(INPUT_POST, "notes");
        $branch_id = filter_input(INPUT_POST, "branch_id");

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

## pay rest
        $payVisits = R::getRow('SELECT COALESCE(SUM(detectionvalue_cash),0)   as paid_cash
                                                                 , COALESCE(SUM(detectionvalue_visa),0)   as paid_visa
                                    FROM visits   where  patientid = ?
                               and deleted != ? and detectionid = 999 and visitid = ?   ', [$patientId, 1, $visitId]);

## refund
        $refundVisits = R::getRow('SELECT COALESCE(SUM(detectionvalue_cash),0)   as refund_cash
                                                                 , COALESCE(SUM(detectionvalue_visa),0)   as refund_visa
                                    FROM visits   where  patientid = ?
                               and deleted != ? and detectionid = 9999 and visitid = ?   ', [$patientId, 1, $visitId]);

## all  what pt paid

        $paid_cash = $payVisits['paid_cash'] + $visit->detectionvalue_cash - $refundVisits['refund_cash'];
        $paid_visa = $payVisits['paid_visa'] + $visit->detectionvalue_visa - $refundVisits['refund_visa'];
        $total_paid = $paid_cash + $paid_visa;

        if ($total_paid < ($refund_cash + $refund_visa)) {
            echo -3;
        } else {
            $insertDataVisits = R::dispense('visits');
            $insertDataVisits->patientid = $visit->patientid;
            $insertDataVisits->visitdate = date("Y/m/d");
            $insertDataVisits->visittime = date("H:i:s");
            $insertDataVisits->detectionid = 9999;
            $insertDataVisits->detectionvalue_cash = $refund_cash;
            $insertDataVisits->detectionvalue_visa = $refund_visa;
            $insertDataVisits->totaldetectionvalue = 0;
            $insertDataVisits->restdetectionvalue = 0;
            $insertDataVisits->discount = 0;
            $insertDataVisits->for_department = $visit->for_department;
            $insertDataVisits->for_doctor = $visit->for_doctor;
            $insertDataVisits->for_husband = $visit->for_husband;
            $insertDataVisits->user_id = $_SESSION['user_id'];
            $insertDataVisits->visitid = $visitId;
            $insertDataVisits->notes = $notes;
            $insertDataVisits->branch_id = $branch_id;
            $insertDataVisits->create_date = date('Y-m-d H:i:s'); //$this->today;
            $insertDataVisits->refer_doctor = $visit->refer_doctor;
            $insertDataVisits->refer_doctor_tb = $visit->refer_doctor_tb;
            $insertDataVisits->rfc = $visit->rfc;

            $insertDataVisits->units = 0;


            if ($_SESSION['role_id'] == 19) {
                $insertDataVisits->customer_add = 1;
            } else {
                $insertDataVisits->customer_add = 0;
            }

            try {

                if ($refund_cash > 0) {
                    $insertDataVisits->printserial = $this->printSerial('last_refund_serial');
                } else {
                    $insertDataVisits->printserial = 0;
                }

                $insert = R::store($insertDataVisits);
                if ($refund_cash > 0) {
                    $this->printrecept($insert);
                }

                #erp fatma
                if ($refund_cash > 0 || $refund_visa > 0) {
                    $visit->detectionvalue_cash = $refund_cash;
                    $visit->detectionvalue_visa = $refund_visa;
                    $visit->insertvisitid = $insert;
                    $this->erpSellbill($visit, '', 1);
                }
            } catch (Exception $ex) {
                echo -1;
            }
        }
    }

    public function editrefundvisit() {

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

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

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

        if (count($visit) > 0) {

            $result = array(
                "visitdate" => date("Y/m/d", strtotime($visit->visitdate)),
                "detectionvalue_visa" => $visit->detectionvalue_visa,
                "detectionvalue_cash" => $visit->detectionvalue_cash,
                "notes" => $visit->notes
            );

            echo json_encode($result);
        } else {
            echo -1;
        }
    }

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

        $fundVisitId = filter_input(INPUT_POST, "visitId");
        $refund_cash = filter_input(INPUT_POST, 'detectionvalue_cash');
        $refund_visa = filter_input(INPUT_POST, 'detectionvalue_visa');
        try {

            $visitOld = R::load('visits', $fundVisitId);
            $fundVisit = R::load('visits', $fundVisitId);
            $patientId = $fundVisit->patientid;
            $originalVisitId = $fundVisit->visitid;

            $originalVisit = R::load('visits', $fundVisit->visitid);

## pay rest
            $payVisits = R::getRow('SELECT COALESCE(SUM(detectionvalue_cash),0)   as paid_cash
                                                                 , COALESCE(SUM(detectionvalue_visa),0)   as paid_visa
                                    FROM visits   where  patientid = ?
                               and deleted != ? and detectionid = 999 and visitid = ?   ', [$patientId, 1, $originalVisitId]);

## refund
            $refundVisits = R::getRow('SELECT COALESCE(SUM(detectionvalue_cash),0)   as refund_cash
                                                                 , COALESCE(SUM(detectionvalue_visa),0)   as refund_visa
                                    FROM visits   where  patientid = ?   and id != ?
                               and deleted != ? and detectionid = 9999 and visitid = ?   ', [$patientId, $fundVisitId, 1, $originalVisitId]);


            $paid_cash = $payVisits['paid_cash'] + $originalVisit->detectionvalue_cash - $refundVisits['refund_cash'];
            $paid_visa = $payVisits['paid_visa'] + $originalVisit->detectionvalue_visa - $refundVisits['refund_visa'];
            $total_paid = $paid_cash + $paid_visa;

            if ($total_paid < ($refund_cash + $refund_visa)) {
                echo -3;
            } else {
                $visitDate = filter_input(INPUT_POST, 'visitdate');
                $notes = filter_input(INPUT_POST, 'notes');
                $new_date = date('Y/m/d', strtotime($visitDate));

                $fundVisit->visitdate = $new_date;
                $fundVisit->detectionvalue_cash = $refund_cash;
                $fundVisit->detectionvalue_visa = $refund_visa;
                $fundVisit->notes = $notes;

                if ($refund_cash > 0 && $fundVisit->printserial == 0) {
                    $fundVisit->printserial = $this->printSerial('last_refund_serial');
                }


                if ($_SESSION['role_id'] == 19) {
                    $fundVisit->customer_add = 1;
                } else {
                    $fundVisit->customer_add = 0;
                    $fundVisit->service_edit = 1;
                }

                if ($_SESSION['role_id'] != 16) {
                    $fundVisit->user_id = $_SESSION['user_id'];
                }

                $insert = R::store($fundVisit);
                $this->reserveOldVisit($visitOld);
                if ($refund_cash > 0 || $refund_visa > 0) {
                    $this->erpSellbillDel($visitOld, 1);
                    $originalVisit->detectionvalue_cash = $refund_cash;
                    $originalVisit->detectionvalue_visa = $refund_visa;
                    $originalVisit->insertvisitid = $insert;
                    $this->erpSellbill($originalVisit, '', 1); //we need original visit "the kashf itself" with its data just change paying , send new visitit of refund
                }
                echo 1;
            }
        } catch (Exception $ex) {
            echo $ex;
        }
    }

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

    public function editpayvalvisit() {

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

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

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

        if (count($visit) > 0) {

            $result = array(
                "visitdate" => date("Y/m/d", strtotime($visit->visitdate)),
                "detectionvalue_visa" => $visit->detectionvalue_visa,
                "detectionvalue_cash" => $visit->detectionvalue_cash,
                "discount" => $visit->discount,
                "notes" => $visit->notes
            );

            echo json_encode($result);
        } else {
            echo -1;
        }
    }

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

        $visitId = filter_input(INPUT_POST, "visitId");
        $cash = filter_input(INPUT_POST, 'detectionvalue_cash');
        $visa = filter_input(INPUT_POST, 'detectionvalue_visa');
        $discount = filter_input(INPUT_POST, 'discount');
        try {
            $visitOld = R::load('visits', $visitId);
            $visit = R::load('visits', $visitId);
            $patientId = $visit->patientid;
            $originalVisitId = $visit->visitid;

            $originalVisit = R::load('visits', $visit->visitid);



## pay rest
            $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
                                    FROM visits   where  patientid = ?    and id != ?
                               and deleted != ? and detectionid = 999 and visitid = ?   ', [$patientId, $visitId, 1, $originalVisitId]);

## refund
            $refundVisits = R::getRow('SELECT COALESCE(SUM(detectionvalue_cash),0)   as refund_cash
                                                                 , COALESCE(SUM(detectionvalue_visa),0)   as refund_visa
                                    FROM visits   where  patientid = ?
                               and deleted != ? and detectionid = 9999 and visitid = ?   ', [$patientId, 1, $originalVisitId]);


            $paid_cash = $payVisits['paid_cash'] - $refundVisits['refund_cash'];
            $paid_visa = $payVisits['paid_visa'] - $refundVisits['refund_visa'];
            $total_paid = $paid_cash + $paid_visa;

            $rest = $originalVisit->restdetectionvalue - $total_paid - $payVisits['paid_discount'];
            $new_paid = $cash + $visa - $discount;

            if ($rest < $new_paid) {
                echo -3;
            } else {
                $visitDate = filter_input(INPUT_POST, 'visitdate');
                $notes = filter_input(INPUT_POST, 'notes');
                $new_date = date('Y/m/d', strtotime($visitDate));

                $visit->visitdate = $new_date;
                $visit->detectionvalue_cash = $cash;
                $visit->detectionvalue_visa = $visa;
                $visit->discount = $discount;
                $visit->notes = $notes;


                if ($_SESSION['role_id'] == 19) {
                    $visit->customer_add = 1;
                } else {
                    $visit->customer_add = 0;
                    $visit->service_edit = 1;
                }

                if ($_SESSION['role_id'] != 16) {
                    $visit->user_id = $_SESSION['user_id'];
                }

                $payVisitId = R::store($visit);
                $this->reserveOldVisit($visitOld);
                ##erp fatma
                $this->delPayERPBills($visitOld);
                if ($cash > 0 || $visa > 0 || $discount > 0) {
                    calcBalance($visit->patientid);
                    //$this->erpSellbillUpdate($visit);
                    $_POST['clientIdForERP'] = $patientId;
                    $_POST['billsItr'] = 1;
                    $_POST['royalUserAdd'] = $visitOld->user_id;
                    $_POST['visitid1'] = $originalVisit->id;
                    $_POST['payVisitId1'] = $payVisitId;
                    $_POST['cashPay1'] = $cash;
                    $_POST['visaPay1'] = $visa;
                    $_POST['billDis1'] = $discount;
                    $_POST['notBillPay'] = 1;
                    $this->payERPBills();
                }
                echo 1;
            }
        } catch (Exception $ex) {
            echo $ex;
        }
    }

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

    public function operationresidence() {

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

        $visitdate = filter_input(INPUT_POST, "visitdate");
        $this->smarty->assign('visitdate', $visitdate);

        $operations = R::findAll('operationotherth');
        $this->smarty->assign('operations', $operations);

        $this->smarty->assign('operationDuration', '00:00');
        $this->smarty->assign('residenceDuration', '00:00');

        $this->smarty->display('visits/operation_modal.html');
    }

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

        $operationId = filter_input(INPUT_POST, "operationId");
        $operation = R::load('operationotherth', $operationId);

        if ($operation->operation_duration == '' || $operation->operation_duration == NULL) {
            $operation->operation_duration = '00:00';
        }

        if ($operation->residence_duration == '' || $operation->residence_duration == NULL) {
            $operation->residence_duration = '00:00';
        }

        $result = array(
            "residence_duration" => $operation->residence_duration,
            "operation_duration" => $operation->operation_duration
        );

        echo json_encode($result);
    }

    public function getrooms() {

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

        $operationId = filter_input(INPUT_POST, "operationId");
        $operation_time_start = filter_input(INPUT_POST, "operation_time_start");
        $operation_duration = filter_input(INPUT_POST, "operation_duration");
        $residence_duration = filter_input(INPUT_POST, "residence_duration");

        $operation = R::load('operationotherth', $operationId);
        $operation_rooms = R::findAll('operation_room', ' operation_type = ? ', [$operation->operation_type]);
        $residence_rooms = R::findAll('residence_room', ' operation_type = ? ', [$operation->operation_type]);


        $this->smarty->assign('residence_rooms', $residence_rooms);
        $this->smarty->assign('operation_rooms', $operation_rooms);
        $this->smarty->display('visits/operation_rooms.html');
    }

    public function getdates() {

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

        $operationId = filter_input(INPUT_POST, "operationId");
        $visitdate = filter_input(INPUT_POST, "visitdate");
        $this->smarty->assign('visitdate', $visitdate);

        $operation = R::load('operationotherth', $operationId);
        $operation_rooms = R::findAll('operation_room', ' operation_type = ? ', [$operation->operation_type]);
        $residence_rooms = R::findAll('residence_room', ' operation_type = ? ', [$operation->operation_type]);


        $this->smarty->assign('residence_rooms', $residence_rooms);
        $this->smarty->assign('operation_rooms', $operation_rooms);
        $this->smarty->display('visits/operation_dates.html');
    }

    public function getroomdates() {

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

        $roomId = filter_input(INPUT_POST, "roomId");
        $room_type = filter_input(INPUT_POST, "roomType");

        switch ($room_type) {
            case 1:
                $result = $this->getOperationDates($roomId);
                $this->smarty->assign('target', 'operation_dates');
                break;

            case 2:
                $result = $this->getResidenceDates($roomId);
                $this->smarty->assign('target', 'residence_dates');
                break;
        }

        $day_times = R::findAll('day_times');
        foreach ($day_times as $obj) {
            $obj->time_from = date("g:ia", strtotime($obj->time_from));
            $obj->time_to = date("g:ia", strtotime($obj->time_to));
        }
        $this->smarty->assign('day_times', $day_times);

        $this->smarty->assign('result', $result);
        $this->smarty->display('visits/operation_data.html');
    }

    function getOperationDates($roomId) {
        $operation_room = R::load('operation_room', $roomId);
    }

    function getResidenceDates($roomId) {
        $residence_room = R::load('residence_room', $roomId);
    }

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

        $phone = (!filter_input(INPUT_POST, "phone")) ? "" : filter_input(INPUT_POST, "phone");


## wife name or id entered
        if (!empty($phone)) {

            $patient = R::getRow('SELECT patients.id , patients.statusno   FROM  patients
                    WHERE
                    patients.done = 1  AND patients.deleted = 0
                    AND  (  phone = ? || mobile = ? ) ', [$phone, $phone]);


            $result = array(
                "patientid" => $patient['id'],
                "statusno" => $patient['statusno']
            );

            echo json_encode($result);



//            echo $patient['id'];
        } else {
            echo -1;
        }


#################################################################################################################
    }

    public function getDetectionsByDoctor() {

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

        $allDetections = R::findAll('detections', 'del = 0 and doctor_id = ? ', [$doctorId]);
        $this->smarty->assign('allDetections', $allDetections);

        $this->smarty->display('visits/detection_select.html');
    }

    public function getDoctorRDetails() {

        $doctorId = filter_input(INPUT_POST, "doctorId");
        $visitdate = filter_input(INPUT_POST, "visitdate");
        $visitId = filter_input(INPUT_POST, "visitId");  ## if visitId > 0 in edit mode

        $res = $this->getDayN0($visitdate);
        $dayNo = $res['dayNo'];

        $rooms = r::getAll('select  distinct clinic_reserves.room_id     ,    clinic_rooms.name as roomName
                                        from clinic_reserves
                                         join    clinic_rooms     on   clinic_rooms.id  =  clinic_reserves.room_id
                                        where clinic_reserves.doctor_id = ?  and clinic_reserves.reserve_day_no = ?
                                  and clinic_reserves.deleted != 1 and clinic_reserves.is_active = 1 ', [$doctorId, $dayNo]);

        $i = 0;
        foreach ($rooms as $value) {
            $rHours = r::getAll('select clinic_reserves.reserve_hour     from clinic_reserves
                                        where clinic_reserves.doctor_id = ?  and clinic_reserves.reserve_day_no = ?
                                  and clinic_reserves.deleted != 1 and clinic_reserves.is_active = 1
                                     and  clinic_reserves.room_id = ?   order by clinic_reserves.reserve_hour  '
                            , [$doctorId, $dayNo, $value['room_id']]);

//            $dd = date('h:i A', strtotime($hour['reserve_hour']));
//            $dd = date('h:i A', strtotime($endTime));

            $x = 0;
            foreach ($rHours as $hour) {
                $sub_hours = array();

                $reserved = $this->reserved($doctorId, $visitdate, $hour['reserve_hour'], $value['room_id'], $visitId);
                $dd = date('h:i A', strtotime($hour['reserve_hour']));
                $sub = array('reserved' => $reserved, 'res_hour' => $hour['reserve_hour'], 'showH' => $dd);
                array_push($sub_hours, $sub);
                ######################################################
                $endTime = date('H:i', strtotime($hour['reserve_hour'] . '+15 minutes'));
                $dd = date('h:i A', strtotime($endTime));
                $reserved = $this->reserved($doctorId, $visitdate, $endTime, $value['room_id'], $visitId);
                $sub = array('reserved' => $reserved, 'res_hour' => $endTime, 'showH' => $dd);
                array_push($sub_hours, $sub);
                ######################################################
                $endTime = date('H:i', strtotime($endTime . '+15 minutes'));
                $dd = date('h:i A', strtotime($endTime));
                $reserved = $this->reserved($doctorId, $visitdate, $endTime, $value['room_id'], $visitId);
                $sub = array('reserved' => $reserved, 'res_hour' => $endTime, 'showH' => $dd);
                array_push($sub_hours, $sub);
                ######################################################
                $endTime = date('H:i', strtotime($endTime . '+15 minutes'));
                $dd = date('h:i A', strtotime($endTime));
                $reserved = $this->reserved($doctorId, $visitdate, $endTime, $value['room_id'], $visitId);
                $sub = array('reserved' => $reserved, 'res_hour' => $endTime, 'showH' => $dd);
                array_push($sub_hours, $sub);


                $rHours[$x]['sub_hours'] = $sub_hours;

                $x++;
            }

            $rooms[$i]['hours'] = $rHours;
            $i++;
        }

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

        $this->smarty->display('visits/doctor_reserve.html');
    }

    public function getDoctorweekDates() {

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

        $days = r::getAll('select distinct clinic_reserves.reserve_day_no as dayNo
             , CASE    WHEN clinic_reserves.reserve_day_no = 1  THEN "السبت"
                            WHEN clinic_reserves.reserve_day_no = 2  THEN "الأحد"
                              WHEN clinic_reserves.reserve_day_no = 3  THEN "الإثنين"
                              WHEN clinic_reserves.reserve_day_no = 4  THEN "الثلاثاء"
                              WHEN clinic_reserves.reserve_day_no = 5  THEN "الأربعاء"
                              WHEN clinic_reserves.reserve_day_no = 6  THEN "الخميس"
                              WHEN clinic_reserves.reserve_day_no = 7  THEN "الجمعة"
             ELSE ""    END as dayName

                            from clinic_reserves
                                        where clinic_reserves.doctor_id = ?
                                  and clinic_reserves.deleted != 1 and clinic_reserves.is_active = 1
                                      order by clinic_reserves.reserve_day_no  '
                        , [$doctorId]);


        $i = 0;
        foreach ($days as $day) {

            $hours = r::getAll('select clinic_reserves.reserve_hour      from clinic_reserves
                                        where clinic_reserves.doctor_id = ?   and  clinic_reserves.reserve_day_no = ?
                                  and clinic_reserves.deleted != 1 and clinic_reserves.is_active = 1
                                      order by clinic_reserves.reserve_hour  '
                            , [$doctorId, $day['dayNo']]);

            $x = 0;
            foreach ($hours as $hour) {
                $hours[$x]['reserve_hour'] = date('h:i A', strtotime($hours[$x]['reserve_hour']));
                $x++;
            }

            $days[$i]['hours'] = $hours;

            $i++;
        }

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

        $this->smarty->display('visits/doctor_dates.html');
    }

    function reserved($doctorId, $visitdate, $hour, $room_id, $visitId) {

        $res = r::getRow('select  visit_hours.visit_hour     , visit_hours.visit_id
                                        from visit_hours
                                         join    visits                      on   visits.id  =  visit_hours.visit_id
                                        where visits.for_doctor = ?  and visits.visitdate = ?   and visit_hours.visit_hour = ?
                                  and visit_hours.deleted != 1 and visit_hours.room_id = ?   '
                        , [$doctorId, $visitdate, $hour, $room_id]);


        if (count($res) > 0 && $visitId == $res['visit_id']) {
            return 2;
        } elseif (count($res) > 0 && $visitId != $res['visit_id']) {
            return 1;
        } else {
            return 0;
        }
    }

    private function getDayN0($date) {
        $timestamp = strtotime($date);
        $day = date('w', $timestamp);

        switch ($day) {
            case 0:
                $name = 'الأحد  ';
                $no = 2;
                break;
            case 1:
                $name = ' الإثنين';
                $no = 3;
                break;
            case 2:
                $name = ' الثلاثاء';
                $no = 4;
                break;
            case 3:
                $name = 'الأربعاء ';
                $no = 5;
                break;
            case 4:
                $name = 'الخميس  ';
                $no = 6;
                break;
            case 5:
                $name = 'الجمعة ';
                $no = 7;
                break;
            case 6:
                $name = 'السبت ';
                $no = 1;
                break;
        }

        $res = array('dayNo' => $no, 'dayName' => $name);

        return $res;
    }

    public function visitHoursAdd() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        ####################################################################
        $edit = filter_input(INPUT_POST, "edit");
        $visitId = filter_input(INPUT_POST, "visitId");
        $selectedHours = json_decode(stripslashes(filter_input(INPUT_POST, 'jsonString')));

        try {

            if ($edit > 0) {
                R::exec('update visit_hours set deleted = 1  where visit_id = ' . $visitId . ' ');
            }
            foreach ($selectedHours as $data) {

                $reserve = R::xdispense('visit_hours');

                $reserve->visit_hour = $data[0];
                $reserve->room_id = $data[1];
                $reserve->visit_id = $visitId;
                $reserve->deleted = 0;

                R::store($reserve);
            }

            echo 1;
        } catch (Exception $ex) {
            echo $ex;
        }
    }

    public function getVisitsByDoctor() {
        autho::checkautho($this->hosturl);

        if ($_SESSION['role_id'] == 1 || $_SESSION['role_id'] == 19) {

            $doctorId = filter_input(INPUT_POST, "doctorId");
            $visitDate = filter_input(INPUT_POST, 'visitdate');
            $forDept = filter_input(INPUT_POST, 'forDept');
            $branch_id = filter_input(INPUT_POST, 'branch_id');

            $programesetting = R::findOne('programesetting');
            if ($programesetting->branches == 1 && $branch_id > 0) {
                $sql = '  and branch_id =   ' . $branch_id;
            }

            $visits = R::count('visits', 'deleted = 0 and for_doctor = ? and visitdate = ?  ' . $sql . '  
                      and for_department = ? and detectionid not in (999 , 9999)   ', [$doctorId, $visitDate, $forDept]);

            $res = 'عدد الكشوفات اليوم =   ' . $visits;
        } else {
            $res = '';
        }
        echo $res;
    }

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

    public function addLabVisit() {

//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');
         if (!($patientId > 0)) {
            $patientId = $this->newPatient();
            $orgPatNo = filter_input(INPUT_POST, 'orgPatNoAdd');
        } else {
            $orgPatNo = filter_input(INPUT_POST, 'orgPatNoRemote');
        }

        $visitDate = filter_input(INPUT_POST, 'visitdate');
          $detectionID = (filter_input(INPUT_POST, 'detectionidLab') > 0) ? filter_input(INPUT_POST, 'detectionidLab') : 0;
                  $labDetectionPrice = (filter_input(INPUT_POST, 'labDetectionPrice') > 0) ? filter_input(INPUT_POST, 'labDetectionPrice') : 0;
        $detectionValue_cash = filter_input(INPUT_POST, 'detectionvalue_cash');
        $detectionValue_visa = filter_input(INPUT_POST, 'detectionvalue_visa');
        $totaldetectionvalue = filter_input(INPUT_POST, 'totaldetectionvalue');
        $branch_id = filter_input(INPUT_POST, 'branch_id');
        $restdetectionvalue = filter_input(INPUT_POST, 'restdetectionvalue');

        $for_department = 12;
        $for_doctor = filter_input(INPUT_POST, 'for_doctor');
        $gender = filter_input(INPUT_POST, 'gender');
        $for_husband = filter_input(INPUT_POST, 'for_husband');
        $child = filter_input(INPUT_POST, 'child');
        $notes = filter_input(INPUT_POST, 'notes');
        $refer_doctor = filter_input(INPUT_POST, 'refer_doctor');
        $vat_value = filter_input(INPUT_POST, 'vat_value');

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

        $discountType = filter_input(INPUT_POST, 'discountType');
        if ($discountType == 1) {
            $discountRatio = filter_input(INPUT_POST, 'discount');
            $discount = $totaldetectionvalue * ($discountRatio / 100 );
        } else {
            $discount = filter_input(INPUT_POST, 'discount');
            $discountType = 0;
            $discountRatio = 0;
        }

        $insertDataVisits = R::dispense('visits');
        $insertDataVisits->patientid = $patientId;
        $insertDataVisits->visitdate = $new_date;
        $insertDataVisits->visittime = date("H:i:s");
        $insertDataVisits->detectionid = $detectionID;
            $insertDataVisits->lab_detection_price = $labDetectionPrice;
        $insertDataVisits->detectionvalue_cash = $detectionValue_cash;
        $insertDataVisits->detectionvalue_visa = $detectionValue_visa;
        $insertDataVisits->totaldetectionvalue = $totaldetectionvalue;
        $insertDataVisits->discount = $discount;
        $insertDataVisits->restdetectionvalue = $restdetectionvalue;
        $insertDataVisits->for_department = $for_department;
        $insertDataVisits->for_doctor = $for_doctor;
        $insertDataVisits->for_husband = $for_husband;
        if ($for_husband == 2) {
            $insertDataVisits->child = $child;
        } else {
            $insertDataVisits->child = 0;
        }
        $insertDataVisits->operation_time = '';
        $insertDataVisits->notes = $notes;
        $insertDataVisits->user_id = $_SESSION['user_id'];
        $insertDataVisits->branch_id = $branch_id;
        $insertDataVisits->discount_type = $discountType;
        $insertDataVisits->discount_ratio = $discountRatio;
 $insertDataVisits->org_pat_no = $orgPatNo;




        if ($_SESSION['role_id'] == 19) {
            $insertDataVisits->customer_add = 1;
        } else {
            $insertDataVisits->customer_add = 0;
        }

 $labSetting = R::findOne('programesettinglab');

       if ($detectionValue_cash > 0 || $labSetting->lab_style == 2) {
            $insertDataVisits->printserial = $this->printSerial('last_serial');
        } else {
            $insertDataVisits->printserial = 0;
        }

        $insertDataVisits->create_date = date('Y-m-d H:i:s'); //$this->today;


        $programesetting = R::findOne('programesetting');
        $patient = R::load('patients', $patientId);
        if ($programesetting->refer_doctor == 1) {
            $insertDataVisits->refer_doctor_tb = 0;
            if ($refer_doctor[0] == "*") {
                $refer_doctor = ltrim($refer_doctor, '*');
                $insertDataVisits->refer_doctor_tb = 1;
            }
            $insertDataVisits->refer_doctor = $refer_doctor;
        } else {
            if ($for_husband == 1) {
                $insertDataVisits->refer_doctor = $patient->h_refer_doctor;
                $insertDataVisits->refer_doctor_tb = $patient->h_refer_doctor_tb;
            } else {
                $insertDataVisits->refer_doctor = $patient->refer_doctor;
                $insertDataVisits->refer_doctor_tb = $patient->refer_doctor_tb;
            }
        }


        if ($labSetting->vat > 0 && $patient->saudi == 1) {
            $amount = $totaldetectionvalue - $discount;
            $insertDataVisits->vat = $labSetting->vat;
            $vat_value = ($amount * $labSetting->vat) / 100;
            $insertDataVisits->vat_value = $vat_value;
        } else {
            $insertDataVisits->vat = 0;
            $insertDataVisits->vat_value = 0;
        }

        if ($for_husband == 1) {
            $insertDataVisits->rfc = $patient->rfc;
        } else {
            $insertDataVisits->rfc = $patient->wrfc;
        }


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


        if (isset($_POST['checks'])) {
            foreach ($_POST['checks'] as $choosen) {
                $insertDataVisits->$choosen = 1;
            }
        }

        if ($fasting_hours > 0) {
            $insertDataVisits->fasting_hours = $fasting_hours;
        } else {
            $insertDataVisits->fasting_hours = 0;
        }

        #############################
        $organizationId = filter_input(INPUT_POST, 'organizations');
        $insertDataVisits->organization_id = $organizationId;
        if ($organizationId > 0 && $programesetting->organizations == 2) {
            $org = R::getRow('SELECT COALESCE(center_discount ,0)   as center_discount  ,
                COALESCE(organization_discount ,0)   as organization_discount    , discount_type
                FROM organizations WHERE id = ? ', [$organizationId]);

            $insertDataVisits->center_discount = $org['center_discount'];
            $insertDataVisits->organization_discount = $org['organization_discount'];
            $insertDataVisits->org_discount_type = $org['discount_type'];
            if ($org['discount_type'] == 1) {
                $center_discount_value = ($totaldetectionvalue * $org['center_discount']) / 100;
                $organization_discount_value = ($totaldetectionvalue * $org['organization_discount']) / 100;
            } else {
                $center_discount_value = $org['center_discount'];
                $organization_discount_value = $org['organization_discount'];
            }

            $insertDataVisits->center_discount_value = $center_discount_value;
            $insertDataVisits->organization_discount_value = $organization_discount_value;
        } else if ($organizationId > 0 && $programesetting->organizations == 3) {
            $patient_hold = filter_input(INPUT_POST, 'patient_hold');
            $contractPrice = filter_input(INPUT_POST, 'contractPrice');
            $originalPrice = filter_input(INPUT_POST, 'originalPrice');
            $discountRatioType = filter_input(INPUT_POST, 'discountRatioType');

            $insertDataVisits->contract_price = $contractPrice;
            $insertDataVisits->original_price = $originalPrice;
            $insertDataVisits->patient_hold = $patient_hold;
            $insertDataVisits->organ_discount_type = $discountRatioType;
        }


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

        try {

            $insert = R::store($insertDataVisits);
//            if ($insertDataVisits->detectionvalue_cash) {//only payed visits make bills in erp
            $invstDataForERP = $_POST["invstDataForERP"];
            $this->erpSellbill($insertDataVisits, $invstDataForERP);
//            }
            $this->sendToLab($patientId, $insert, $for_husband, $programesetting->organizations);
$this->billPdf($insert);
$this->loadSampleIdForInv($insert);
            echo $insert;
        } catch (Exception $ex) {
            echo -1;
        }
    }

    function newPatient() {
        $gender = filter_input(INPUT_POST, 'gender');
        $for_doctor = filter_input(INPUT_POST, 'for_doctor');
        $wifename = filter_input(INPUT_POST, 'wifename');
        $wifetype = (filter_input(INPUT_POST, 'wifetype') > 0) ? filter_input(INPUT_POST, 'wifetype') : NULL;

        $phone = filter_input(INPUT_POST, 'phone');
        $mobile = filter_input(INPUT_POST, 'mobile');
        $address = filter_input(INPUT_POST, 'address');

        $age = filter_input(INPUT_POST, 'age');
        $ageType = filter_input(INPUT_POST, 'ageType');
        $labPatientId = filter_input(INPUT_POST, 'labPatientId');
        $saudi = (filter_input(INPUT_POST, 'saudi') > 0) ? filter_input(INPUT_POST, 'saudi') : 0;
        $branch_id = filter_input(INPUT_POST, 'branch_id');
           $orgPatNo = filter_input(INPUT_POST, 'orgPatNoAdd');

        $dateofbirth = NULL;

        if ($age > 0) {
            $today = date('Y-m-d');

            switch ($ageType) {
                case 1:
                    $dateofbirth = date("Y-m-d", strtotime("- $age years", strtotime($today)));
                    break;

                case 2:
                    $dateofbirth = date("Y-m-d", strtotime("- $age months", strtotime($today)));
                    break;

                case 3:
                    $dateofbirth = date("Y-m-d", strtotime("- $age days", strtotime($today)));
                    break;
            }
        }


        $patient = R::dispense('patients');
        $patient->userid = $_SESSION['user_id'];
        $statusNo = $this->getstatusno();
        $patient->statusno = $statusNo;

        $patient->address = $address;
        $patient->phone = $phone;
        $patient->mobile = $mobile;
                if ($orgPatNo == '' || empty($orgPatNo)) {
            $patient->saudi = $saudi;
        } else {
            $patient->saudi = 1;
        }
        $patient->gender = $gender;
        $patient->org_pat_no = $orgPatNo;

        $programesetting = R::findOne('programesetting');
        if ($programesetting->system_lang == 2) {
            $patient->wifename = $wifename;
            $patient->wiftypeid = $wifetype;
            $patient->doctor1 = $for_doctor;
            $patient->h_doctor1 = -1;
            $patient->dateofbirth = $dateofbirth;
             $patient->wifenationalid = $labPatientId;
        } else {
            if ($gender == 1) {
                $patient->husdandname = $wifename;
                $patient->husbandtypeid = $wifetype;
                $patient->doctor1 = -1;
                $patient->h_doctor1 = $for_doctor;
                $patient->husbanddateofbirth = $dateofbirth;
                 $patient->husbandnationalid = $labPatientId;
            } else {
                $patient->wifename = $wifename;
                $patient->wiftypeid = $wifetype;
                $patient->doctor1 = $for_doctor;
                $patient->h_doctor1 = -1;
                $patient->dateofbirth = $dateofbirth;
                 $patient->wifenationalid = $labPatientId;
            }
        }


        $patient->refer_doctor = -1;
        $patient->h_refer_doctor = -1;
        $patient->doctor2 = -1;
        $patient->h_doctor2 = -1;
        date_default_timezone_set('Africa/Cairo');
        $patient->entrydate = date('Y-m-d H:i:s', time());
        $patient->branch_id = $branch_id;
        $patient->done = 1;

        $patient->id = R::store($patient);
        
                if ($orgPatNo != '' && !empty($orgPatNo)) {
            $this->addOrgPatNo($orgPatNo , $patient->id);
        }
        
        
             $dataArray = getPatientDataArr($patient);
        getPatientLink($dataArray);

        $this->createbarcode($statusNo);
        $this->createQRcode($statusNo);
        $this->erpClient($patient);

        return $patient->id;
    }
    
    
    
       function addOrgPatNo($orgPatNo, $patientId) {
        autho::checkautho($this->hosturl);
        $organizationId = filter_input(INPUT_POST, 'organizations');
        $org = R::xdispense('organizations_patient_no');
        $org->patient_id = $patientId;
        $org->patient_no = $orgPatNo;
        $org->organization_id = $organizationId;
        $org->user_id = $_SESSION['user_id'];
        $org->create_date = date('Y-m-d H:i:s');
        $org->deleted = 0;
        $org->id = R::store($org);
    }

    function getstatusno() {
        $statusno = 1;
        $last_code = R::getRow('select max(statusno) as code from patients');
        if (count($last_code) > 0) {
            $statusno = $last_code['code'] + 1;
        }
        return $statusno;
    }

    private function sendToLab($patientId, $visitId, $for_husband, $orgType) {
        $invType = filter_input(INPUT_POST, 'invType');
        $organizationId = filter_input(INPUT_POST, 'organizations');

        if ($invType != 1) {
            $invType = 0;
        }

        if ($organizationId > 0 && $orgType == 3) {
            $this->sendToLabOrg($patientId, $visitId, $for_husband, $invType, $organizationId);
        } else {
            $this->sendToLabNotOrg($patientId, $visitId, $for_husband, $invType);
        }
    }

    function sendToLabOrg($patientId, $visitId, $for_husband, $invType, $orgId) {
        $visitOrg = R::load('organizations', $orgId);
        foreach ($_POST['labInvests'] as $choosen) {
            $externalLab = filter_input(INPUT_POST, 'exLabs' . $choosen);
            $xx = explode('_', $choosen);
            $organ_discount_type = 0;
            $contract_price = 0;
            $patient_hold = 0;

            if ($xx[0] == 'offer') {
                $offerDetailId = $xx[1];

                $offerDetail = R::load('invofferdetails', $offerDetailId);

                $investId = $offerDetail->inv_id;
                $price = $offerDetail->price;
                $offerId = $offerDetail->invoffer_id;
                $original_price = $offerDetail->price;

                $org_discount = R::findOne('organization_discount', ' list_id = ? and detect_id = ?
                and detect_cat = ? and offer_id = ?   and deleted = ?  ', [$visitOrg->list_id, $offerDetailId, 4, $offerId, 0]);
                if ($org_discount) {
                    $organ_discount_type = $org_discount->discount_type;
                    $contract_price = $org_discount->contract_price;
                    $patient_hold = $org_discount->patient_hold;
                }
            } else {
                $investId = $choosen;
                $org_discount = R::findOne('organization_discount', ' list_id = ? and detect_id = ?
                and detect_cat = ?  and deleted = ? and offer_id = 0   ', [$visitOrg->list_id, $investId, 2, 0]);
                $invest = R::load('invests', $investId);
                $original_price = $invest->price;
                if ($org_discount) {
                    $organ_discount_type = $org_discount->discount_type;
                    $contract_price = $org_discount->contract_price;
                    $patient_hold = $org_discount->patient_hold;
                }
                $offerId = 0;
                $price = $invest->price;
            }


            $this->saveLabInvest($investId, $price, $offerId, $invType, $visitId
                    , $patientId, $for_husband, 0, '', $externalLab, $organ_discount_type, $contract_price
                    , $patient_hold, $original_price);
        }
    }

    function sendToLabNotOrg($patientId, $visitId, $for_husband, $invType) {
        foreach ($_POST['labInvests'] as $choosen) {
            $externalLab = filter_input(INPUT_POST, 'exLabs' . $choosen);
            $xx = explode('_', $choosen);

            if ($xx[0] == 'offer') {
                $offerDetailId = $xx[1];

                $offerDetail = R::load('invofferdetails', $offerDetailId);

                $investId = $offerDetail->inv_id;
                $price = $offerDetail->price;
                $offerId = $offerDetail->invoffer_id;
            } else {
                $investId = $choosen;
                $invest = R::load('invests', $investId);
                $price = $invest->price;
                $offerId = 0;
            }


            $this->saveLabInvest($investId, $price, $offerId, $invType, $visitId
                    , $patientId, $for_husband, 0, '', $externalLab, 0, 0, 0, $price);
        }
    }

    function loadOfferInvests($offerId, $patientId, $visitId, $for_husband, $invType) {
        $offerDetails = R::findall('invofferdetails', 'del = ? and invoffer_id = ?  ', [0, $offerId]);
        foreach ($offerDetails as $data) {
            $this->saveLabInvest($data->inv_id, $data->price, $offerId, $invType, $visitId
                    , $patientId, $for_husband, 0, '');
        }
    }

    function saveLabInvest($investId, $price, $offer_id, $invType, $visitId, $patientId, $for_husband, $reqId
            , $reqTable, $externalLab = 0, $organ_discount_type = 0, $contract_price = 0, $patient_hold = 0
            , $original_price = 0) {
        $invest = R::load('invests', $investId);
        $obj = R::dispense('investigationresults');
        $obj->investid = $investId;
        $obj->price = $price;
        $obj->offer_id = $offer_id;
        $obj->invtype = $invType;
        $obj->doctorid = 0;
        $obj->deleted = 0;
        $obj->visitid = $visitId;
        $obj->patientid = $patientId;
        $obj->date = date('Y-m-d');
        $obj->forhusband = $for_husband;
        $obj->external_lab = $externalLab;
        $obj->lab_to_lab_price = $invest->lab_to_lab_price;

        $obj->contract_price = $contract_price;
        $obj->original_price = $original_price;
        $obj->patient_hold = $patient_hold;
        $obj->organ_discount_type = $organ_discount_type;

        if ($invType == 1) {
            $obj->internalrequestid = $reqId;
            $obj->internaltable = $reqTable;
        }

          $investResId = R::store($obj);
        $this->repareElementObj($invest->special_inv_type, $investResId);
    }
    
    
    
    function repareElementObj($special_inv_type, $investResId) {
        $tableName = '';
        switch ($special_inv_type) {
            case 1:           ## blood 
                $tableName = 'investigationresults_blood';
                $element = R::xdispense($tableName);
                $element->othercells = 100;
                break;
            case 2:           ## urine 
                $tableName = 'investigationresults_urine';
                $element = R::xdispense($tableName);
                $element = $this->loadUrineDefaults($element);
                break;
            case 3:           ## stool 
                $tableName = 'investigationresults_stool';
                $element = R::xdispense($tableName);
                $element = $this->loadStoolDefaults($element);
                break;
            case 4:           ## Culture 
                $tableName = 'investigationresults_culture';
                $element = R::xdispense($tableName);
                break;
            case 5:           ## ESR 
                $tableName = 'investigationresults_esr';
                $element = R::xdispense($tableName);
                break;
            case 6:           ## Cross 
                $tableName = 'investigationresults_cross';
                $element = R::xdispense($tableName);
                break;
            case 7:           ## Fluid 
                break;
            case 8:           ## Clothing 
                $tableName = 'investigationresults_times';
                $element = R::xdispense($tableName);
                break;
            case 9:           ## PT + APTT
            case 12:         ## PT  
            case 13:         ## APTT 
                $tableName = 'investigationresults_pt';
                $element = R::xdispense($tableName);
                $element->control_time = 13;
                $element->control_time1 = 30;
                $element->isi = 1.06;
                break;
            case 10:         ## ABO/RH 
                $tableName = 'investigationresults_aborh';
                $element = R::xdispense($tableName);
                break;
            case 11:         ## Custom 
                $tableName = 'investigationresults_custom';
                $element = R::xdispense($tableName);
                break;
            case 14:         ## Lipid 
                $tableName = 'investigationresults_lipid';
                $element = R::xdispense($tableName);
                break;
            case 15:         ## EGFR 
                $tableName = 'investigationresults_egfr';
                $element = R::xdispense($tableName);
                break;
            case 16:         ## Semen 
                $tableName = 'investigationresults_semen';
                $element = R::xdispense($tableName);
                break;
            default :
                break;
        }

        $this->saveElementObj($tableName, $investResId, $element);
    }

    function saveElementObj($tableName, $investResId, $element = '') {
        if ($tableName != '' && $element != '') {
            $element->investigationresults_id = $investResId;
            r::store($element);
        }
    }
    
    
        function loadUrineDefaults($urine) {
        $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;
            $default = R::findOne($tableName, ' deleted = 0 and default_value = 1  ');
            $urine->$colName = $default->id;
        }
        return $urine;
    }

    function loadStoolDefaults($stool) {
        $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;
            $default = R::findOne($tableName, ' deleted = 0 and default_value = 1  ');
            $stool->$colName = $default->id;
        }

        return $stool;
    }

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


        $name = filter_input(INPUT_GET, "term");

        $allPatients = R::getAll('SELECT id , wifename AS name
            FROM patients    WHERE deleted = ? and done = ?
                 and (wifename  LIKE "%' . $name . '%"  || husdandname  LIKE "%' . $name . '%"  )  limit 0,50  ', [0, 1]);
//        echo $name . ' - ';
        echo json_encode($allPatients);
    }

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


        $name = filter_input(INPUT_GET, "term");
        $limit = intval(filter_input(INPUT_GET, "page_limit"));

        $allPatients = R::getAll('SELECT id , husdandname AS name
            FROM patients    WHERE deleted = ? and done = ?
                 and (wifename  LIKE "%' . $name . '%"  || husdandname  LIKE "%' . $name . '%"  )  limit 0,50  ', [0, 1]);
//        echo $name . ' - ';
        echo json_encode($allPatients);
    }

    ##fatma

    public function addAllDetectionToERP() {
        $programesetting = R::load('programesetting', 1);
        if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
            try {
                R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
                $lastId = 0;
                $limit = 50;
                R::selectDatabase('default');
                do {
                    $rows = 0;
                    R::selectDatabase('default');
                    $allDetections = R::findAll("detections", " where id > $lastId and del=0 order by id asc limit $limit");
                    R::selectDatabase('erpDB');
                    if (R::testConnection()) {
                        foreach ($allDetections as $detection) {
                            $productData = R::getRow('select productId from product where obygyDetectionId = ' . $detection->id);
                            if (empty($productData['productId'])) {
                                //here use NULL for new insert
                                //better to add client using erp files it self so use  curl "it is like post requist but in php"
                                $this->curlAddProduct($detection, $programesetting->erpdb);
                            } else {
                                //here use id to update
                                $this->curlupdateProduct($detection, $programesetting->erpdb, $productData['productId']);
                            }
                            $rows++;
                            $lastId = $detection->id;
                        }
                    } else {
                        throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                    }
                } while ($rows > 0);
                echo 1;
            } catch (Exception $exc) {
                echo -1;
                //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            }
            R::selectDatabase('default');
        }
    }

    public function erpProduct($detection) {//detections
        $programesetting = R::load('programesetting', 1);
        if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
            try {
                R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
                R::selectDatabase('erpDB');
                if (R::testConnection()) {
                    $productData = R::getRow('select productId from product where obygyDetectionId = ' . $detection->id);
                    if (empty($productData['productId'])) {
                        //here use NULL for new insert
                        //better to add client using erp files it self so use  curl "it is like post requist but in php"
                        $this->curlAddProduct($detection, $programesetting->erpdb);
                    } else {
                        //here use id to update
                        $this->curlupdateProduct($detection, $programesetting->erpdb, $productData['productId']);
                    }
                } else {
                    throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                }
            } catch (Exception $exc) {
                //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                //echo -1;
            }
            R::selectDatabase('default');
        }
    }

    public function erpProductDel($detection) {//detections
        $programesetting = R::load('programesetting', 1);
        if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
            try {
                R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
                R::selectDatabase('erpDB');
                if (R::testConnection()) {
                    $productData = R::getRow('select productId from product where obygyDetectionId = ' . $detection->id);
                    $this->curlDelProduct($programesetting->erpdb, $productData['productId']);
                } else {
                    throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                }
                R::selectDatabase('default');
            } catch (Exception $exc) {
                //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                //echo -1;
            }
        }
    }

    //better to add client using erp files it self so use  curl "it is like post requist but in php"
    //category has fixed val = 'services'
    public function curlAddProduct($detection, $erpDB) {
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'detection_id' => $detection->id,
            'new_cat_id' => 'obygy',
            'level' => 'obygy',
            'obygy_cat_name' => 'Services', //'obygy services'
            'new_productName' => $detection->title,
            'new_parcode' => '',
            'new_productBuyPrice' => 0,
            'new_productbuypricereal' => 0,
            'new_buypricereal_precentage1' => 0,
            'new_productSellAllPrice' => $detection->detectionval,
            'new_buytotal_precentage1' => 0,
            'new_productSellHalfPrice' => $detection->detectionval,
            'new_buyhalf_precentage1' => 0,
            'new_productSellUnitPrice' => $detection->detectionval,
            'new_buypart_precentage1' => 0,
            'new_productquantity' => 0,
            'new_isservice1' => 1,
            'inMenu1' => 1,
            'type1' => 0,
            'new_productDate' => date('Y-m-d'),
            'expireDate' => 0,
            'productunit1' => 1,
            'productnumber1' => 1,
            'unitsItr' => 1,
        ];
        try {
            $ch = curl_init(HOST_URL_ERP . '/controllers/buyBillControllerAjax.php?do=temp&itr=1&tabIndex=-1&billnameid=1');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

            // execute!
            $response = curl_exec($ch);

            // close the connection, release resources used
            curl_close($ch);
        } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
        }
        // do anything you want with your response
//        var_dump($response);
    }

    //category has fixed val = 'obygy services'
    public function curlupdateProduct($detection, $erpDB, $productId) {
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'detection_id' => $detection->id,
            'productId' => $productId,
            'productCatId' => 'obygy',
            'level' => 'obygy',
            'obygy_cat_name' => 'Services', //'obygy services'
            'productName1' => $detection->title,
            'parcode1' => '',
            'productBuyPrice1' => 0,
            'productbuypricereal' => 0,
            'buypricereal_precentage1' => 0,
            'productSellAllPrice1' => $detection->detectionval,
            'buytotal_precentage1' => 0,
            'productSellHalfPrice1' => $detection->detectionval,
            'buyhalf_precentage1' => 0,
            'productSellUnitPrice1' => $detection->detectionval,
            'buypart_precentage1' => 0,
            'productquantity1' => 0,
            'isservice1' => 1,
            'inMenu1' => 1,
            'manufacture' => 0,
            'productDate1' => date('Y-m-d'),
            'expireDate1' => 0,
            'productunit1' => 1,
            'productnumber1' => 1,
            'unitsItr1' => 1,
        ];
        try {
            $ch = curl_init(HOST_URL_ERP . '/controllers/productControllerAjax.php?do=update');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

            // execute!
            $response = curl_exec($ch);

            // close the connection, release resources used
            curl_close($ch);
        } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
        }

        // do anything you want with your response
//        var_dump($response);
    }

    public function curlDelProduct($erpDB, $productId) {
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'productId' => $productId,
        ];
        try {
            $ch = curl_init(HOST_URL_ERP . '/controllers/productControllerAjax.php?do=deleteFinaly');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

            // execute!
            $response = curl_exec($ch);

            // close the connection, release resources used
            curl_close($ch);
        } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
        }

        // do anything you want with your response
//        var_dump($response);
    }

    public function erpSellbill($visit, $details = '', $isRefund = 0, $visitIsPaymentOnly = 0) {
        //check login
        autho::checkautho($this->hosturl);

        //load all here
        $royalUser = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);
        $patient = R::load('patients', $visit->patientid);
        $detailsArray = array();
        try {
            $programesetting = R::load('programesetting', 1);
            if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
                $detectionData = R::load('detections', $visit->detectionid);
                $isERPPayment = (int) $detectionData->iserppayment;
                $isERPZeroBill = (int) $detectionData->iserpzerobill;

                try {
                    R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
                } catch (Exception $exc) {
                    //do nothing next line is to select erpDB
                }
                R::selectDatabase('erpDB');
                if (R::testConnection()) {
                    ##try to get client data , giving time is for data entry if it is now with the bill
                    $clientData = R::getRow('select clientid,clientdebt from client where obygyPatientId = ' . $visit->patientid . ' order by clientid desc');
                    $time_start = microtime(true);
                    while ($execution_time_in_Sec < 15 && (!isset($clientData['clientid']) || (int) $clientData['clientid'] < 1)) {
                        sleep(1);
                        $clientData = R::getRow('select clientid,clientdebt from client where obygyPatientId = ' . $visit->patientid . ' order by clientid desc');
                        $time_end = microtime(true);
                        $execution_time_in_Sec = ($time_end - $time_start);
                    }
                    //in this if it means client doesnot exist =>add it
                    if (!isset($clientData['clientid']) || (int) $clientData['clientid'] < 1) {
                        $this->erpClient($patient);
                        //
                        R::selectDatabase('erpDB');
                        ##try to get client data , giving time is for data entry if it is now with the bill
                        $clientData = R::getRow('select clientid,clientdebt from client where obygyPatientId = ' . $visit->patientid . ' order by clientid desc');
                        $time_start = microtime(true);
                        $execution_time_in_Sec = 0;
                        while ($execution_time_in_Sec < 15 && (!isset($clientData['clientid']) || (int) $clientData['clientid'] < 1)) {
                            sleep(1);
                            $clientData = R::getRow('select clientid,clientdebt from client where obygyPatientId = ' . $visit->patientid . ' order by clientid desc');
                            $time_end = microtime(true);
                            $execution_time_in_Sec = ($time_end - $time_start);
                        }
                    }
                    $doctorData = R::getRow('select userid from user where conditions=0 and obygyDoctorId = ' . (int) $visit->for_doctor);
                    $royalUserInERP = R::getRow('select userid from user where conditions=0 and obygyDoctorId = ' . (int) $royalUser['user_id']);
                    if (empty($details)) {
                        $productData = R::getRow('select productId from product where obygyDetectionId = ' . $visit->detectionid);
                        //
                        $data = new stdClass();
                        $data->productId = $productData["productId"];
                        $data->price = $visit->totaldetectionvalue;
                        array_push($detailsArray, $data);
                    } else {
                        if ($isERPPayment == 0) { //invistigation or visit //as in value 1 would be payment only total needed
                            foreach (explode(',', $details) as $labVisitDetails) {
                                if (!empty($labVisitDetails)) {
                                    $labVisitDetails = explode('*', $labVisitDetails);
                                    $investigationId = $labVisitDetails[0];
                                    $investigationPrice = $labVisitDetails[1];
                                    $productData = R::getRow('select productId from product where obygyInvestigationId = ' . $investigationId);
                                    //
                                    $data = new stdClass();
                                    $data->productId = $productData["productId"];
                                    $data->price = $investigationPrice;
                                    array_push($detailsArray, $data);
                                }
                            }
                        }
                    }
                } else {
                    if (!empty($programesetting->erpdb)) //if exist addDatabase erpDB
                        $this->erpLiveComment("-- fn:erpSellbill vid:$visit->id  unable to connect to erp database");
                    throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                }
            }

            if ((!isset($clientData['clientid']) || (int) $clientData['clientid'] < 1 ) && !empty($programesetting->erpdb)) //if exist addDatabase erpDB
                $this->erpLiveComment("-- fn:erpSellbill vid:$visit->id  empty clientid,isRefund:$isRefund");



            if ($visitIsPaymentOnly == 1) {## to control function to do payment only
                $isERPZeroBill = 0;
                $isERPPayment = 1;
            }
            if ($isERPZeroBill == 1) {## to control function to do payment and zero value bill
                $isERPPayment = 0;
            }
            if ($isERPPayment == 0) {//will be a bill in erp
                $totaldetectionvalue = $visit->totaldetectionvalue;
                $discount = $visit->discount;
                $detectionvalue_cash = $visit->detectionvalue_cash;
                $detectionvalue_visa = $visit->detectionvalue_visa;
                $restdetectionvalue = $visit->restdetectionvalue;
                if ($isERPZeroBill == 1) {
                    $isERPPayment = 1;
                    $totaldetectionvalue = 0;
                    $discount = 0;
                    $detectionvalue_cash = 0;
                    $detectionvalue_visa = 0;
                    $restdetectionvalue = 0;
                }
                // set post fields
                $post = [
                    'erpDB' => $programesetting->erpdb,
                    'saveid' => $royalUser['erpsaveid'],
                    'userid' => $royalUserInERP['userid'],
                    'supplier' => $clientData['clientid'],
                    'sellerid' => $doctorData['userid'],
                    'bn' => $visit->visitdate,
                    'totalBill_hidden' => $totaldetectionvalue,
                    'discount' => $discount,
                    'netBill_hidden' => $totaldetectionvalue - $discount,
                    'cash' => $detectionvalue_cash,
                    'visa' => $detectionvalue_visa,
                    'visaAccount' => $programesetting->erpdbvisaaccount,
                    'remain' => $restdetectionvalue,
                    'totalQuantity' => count($detailsArray),
                    'hidden_itr' => count($detailsArray),
                    //'productid' => $productData['productId'],
                    'visitId' => $visit->id,
                    'insertvisitid' => $visit->insertvisitid,
                    'isRefund' => $isRefund,
                ];
                $h = 1;
                foreach ($detailsArray as $details) {
                    $post['productid' . $h] = $details->productId;
                    if ($isERPZeroBill == 1) {
                        $post['price' . $h] = 0;
                    } else {
                        $post['price' . $h] = $details->price;
                    }
                    $h++;
                }
                $ch = curl_init(HOST_URL_ERP . '/controllers/sellbillController.php?do=addObgyVisit');
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

                // execute!
                $response = curl_exec($ch);

                // close the connection, release resources used
                curl_close($ch);

                // do anything you want with your response
                //        var_dump($response);
            }
            if ($isERPPayment == 1) {//will be payment in erp
                $clientDeptChangeIdSave = 0;
                $clientDeptChangeIdBank = 0;
                if ($visit->detectionvalue_cash > 0) {
                    // set post fields
                    $post = [
                        'curlpost' => 1,
                        'clientid' => $clientData['clientid'],
                        'notPremium' => 'notPremium',
                        'voucher' => 0,
                        'idIsModelId' => 1,
                        'currentDate' => date('Y-m-d H:i:s'),
                        'debtBefore' => $clientData['clientdebt'],
                        'payedDept' => $visit->detectionvalue_cash, //$visit->totaldetectionvalue - $visit->discount,
                        'comment' => 'دفع من البرنامج الطبى',
                        'seller' => $doctorData['userid'],
                        'clientorsupplier' => 1,
                        'saveorbank' => 1, //save,2bank
                        'saveid' => $royalUser['erpsaveid'],
                            //
//                    'visitId' => $visit->id,
                    ];
                    //$royalUserInERP['userid'] = 1;
                    $sessionArr = array('dbname' => $programesetting->erpdb, 'userid' => $royalUserInERP['userid'], 'saveid' => $royalUser['erpsaveid']);
                    $post['sessionlist'] = json_encode($sessionArr);
                    $ch = curl_init(HOST_URL_ERP . '/controllers/clientPayedDeptController.php?do=add');
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

                    // execute!
                    $response = curl_exec($ch);
                    $clientDeptChangeIdSave = filter_var($response, FILTER_SANITIZE_NUMBER_INT); //required as response had red dot and "ï»¿"
                    //print_r($response);
                    // close the connection, release resources used
                    curl_close($ch);

                    // do anything you want with your response
                    //        var_dump($response);
                }
                if ($visit->detectionvalue_visa > 0) {
                    $accountData = R::getRow('select bankid from bankaccount where accountid = ' . $programesetting->erpdbvisaaccount);
                    // set post fields
                    $post = [
                        'curlpost' => 1,
                        'clientid' => $clientData['clientid'],
                        'checkdate' => date('Y-m-d H:i:s'),
                        'payedDept' => $visit->detectionvalue_visa, //$visit->totaldetectionvalue - $visit->discount,
                        'textNote' => 'دفع من البرنامج الطبى',
                        'txtUser' => $doctorData['userid'],
                        'ddlBank' => $accountData['bankid'],
                        'accountid' => $programesetting->erpdbvisaaccount,
                        'txtcheckNum' => '',
//                    'visitId' => $visit->id,
                    ];
                    //$royalUserInERP['userid'] = 1;
                    $sessionArr = array('dbname' => $programesetting->erpdb, 'userid' => $royalUserInERP['userid'], 'saveid' => $royalUser['erpsaveid']);
                    $post['sessionlist'] = json_encode($sessionArr);
                    $ch = curl_init(HOST_URL_ERP . '/controllers/depositcheckController.php?do=add');
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

                    // execute!
                    $response = curl_exec($ch);
                    $clientDeptChangeIdBank = filter_var($response, FILTER_SANITIZE_NUMBER_INT); //required as response had red dot and "ï»¿"
                    //print_r($response);
                    // close the connection, release resources used
                    curl_close($ch);

                    // do anything you want with your response
                    //        var_dump($response);
                }
                R::selectDatabase('default');
                R::exec("update visits set clientdeptchangeid_save = $clientDeptChangeIdSave,clientdeptchangeid_bank = $clientDeptChangeIdBank where id=$visit->id");
            }
            R::selectDatabase('default');
        } catch (Exception $exc) {
            //print_r($exc);
            if (!empty($programesetting->erpdb)) //if exist addDatabase erpDB
                $this->erpLiveComment("-- fn:erpSellbill vid:$visit->id, " . $exc->getTraceAsString());
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
        }
    }

    public function erpSellbillUpdate($visit, $details = '') {
        //check login
        autho::checkautho($this->hosturl);

        $detectionData = R::load('detections', $visit->detectionid);
        $isERPPayment = (int) $detectionData->iserppayment;
        $isERPZeroBill = (int) $detectionData->iserpzerobill;
        if ($isERPZeroBill == 1) {
            $isERPPayment = 0;
        }
        if ($isERPPayment == 0) {//will be a bill in erp
            //load all here
            $royalUser = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);

            $detailsArray = array();
            try {
                $programesetting = R::load('programesetting', 1);
                if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
                    R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
                    R::selectDatabase('erpDB');
                    if (R::testConnection()) {
                        $clientData = R::getRow('select clientid from client where obygyPatientId = ' . $visit->patientid . ' order by clientid desc');
                        $sellData = R::getRow('select sellbillid from sellbill where conditions = 0 and obygyVisitId = ' . $visit->id);
                        $doctorData = R::getRow('select userid from user where conditions=0 and obygyDoctorId = ' . (int) $visit->for_doctor);
                        $royalUserInERP = R::getRow('select userid from user where conditions=0 and obygyDoctorId = ' . (int) $royalUser['user_id']);
                        if (empty($details)) {
                            $productData = R::getRow('select productId from product where obygyDetectionId = ' . $visit->detectionid);
                            //
                            $data = new stdClass();
                            $data->productId = $productData["productId"];
                            $data->price = $visit->totaldetectionvalue;
                            array_push($detailsArray, $data);
                        } else {
                            foreach (explode(',', $details) as $labVisitDetails) {
                                if (!empty($labVisitDetails)) {
                                    $labVisitDetails = explode('*', $labVisitDetails);
                                    $investigationId = $labVisitDetails[0];
                                    $investigationPrice = $labVisitDetails[1];
                                    $productData = R::getRow('select productId from product where obygyInvestigationId = ' . $investigationId);
                                    //
                                    $data = new stdClass();
                                    $data->productId = $productData["productId"];
                                    $data->price = $investigationPrice;
                                    array_push($detailsArray, $data);
                                }
                            }
                        }
                    } else {
                        throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                    }
                    R::selectDatabase('default');
                }



                $totaldetectionvalue = $visit->totaldetectionvalue;
                $discount = $visit->discount;
                $detectionvalue_cash = $visit->detectionvalue_cash;
                $detectionvalue_visa = $visit->detectionvalue_visa;
                $restdetectionvalue = $visit->restdetectionvalue;
                if ($isERPZeroBill == 1) {
                    $isERPPayment = 1;
                    $totaldetectionvalue = 0;
                    $discount = 0;
                    $detectionvalue_cash = 0;
                    $detectionvalue_visa = 0;
                    $restdetectionvalue = 0;
                }
                // set post fields
                $post = [
                    'erpDB' => $programesetting->erpdb,
                    'obgyGroupId' => $royalUser['role_id'],
                    'saveid' => $royalUser['erpsaveid'],
                    'userid' => $royalUserInERP['userid'],
                    'supplier' => $clientData['clientid'],
                    'sellerid' => $doctorData['userid'],
                    'bn' => $visit->visitdate,
                    'totalBill_hidden' => $totaldetectionvalue,
                    'discount' => $discount,
                    'netBill_hidden' => $totaldetectionvalue - $discount,
                    'cash' => $detectionvalue_cash,
                    'visa' => $detectionvalue_visa,
                    'visaAccount' => $programesetting->erpdbvisaaccount,
                    'remain' => $restdetectionvalue,
                    'totalQuantity' => count($detailsArray),
                    'hidden_itr' => count($detailsArray),
                    //'productid' => $productData['productId'],
                    'visitId' => $visit->id,
                    'sellbillId' => $sellData["sellbillid"],
                ];
                $h = 1;
                foreach ($detailsArray as $details) {
                    $post['productid' . $h] = $details->productId;
                    if ($isERPZeroBill == 1) {
                        $post['price' . $h] = 0;
                    } else {
                        $post['price' . $h] = $details->price;
                    }
                    $h++;
                }

                $ch = curl_init(HOST_URL_ERP . '/controllers/sellbillController.php?do=updateObgyVisit');
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

                // execute!
                $response = curl_exec($ch);

                // close the connection, release resources used
                curl_close($ch);

                // do anything you want with your response
                //        var_dump($response);
            } catch (Exception $exc) {
                //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                //echo -1;
            }
        }
        if ($isERPPayment == 1) {//will be payment in erp
            //if ($visit->clientdeptchangeid_save > 0 || $visit->clientdeptchangeid_bank > 0) {//it is payment not bill
            $visit->discount = 0;
            $this->delPayERPBills($visit);
            $this->erpSellbill($visit, '', 0, 1);
            return;
        }
    }

    public function erpSellbillDel($visit, $isRefund = 0) {
        //check login
        autho::checkautho($this->hosturl);

        //load all here
        $detectionData = R::load('detections', $visit->detectionid);
        $isERPPayment = (int) $detectionData->iserppayment;
        $royalUser = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);
        try {
            $programesetting = R::load('programesetting', 1);
            if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
                R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
                R::selectDatabase('erpDB');
                if (R::testConnection()) {
                    if ($isRefund == 0) {
                        $sellData = R::getRow('select sellbillid from sellbill where conditions = 0 and obygyVisitId = ' . $visit->id);
                    } elseif ($isRefund == 1) {
                        $sellData = R::getRow('select returnsellbillid as sellbillid from returnsellbill where conditions = 0 and obygyVisitId = ' . $visit->id);
                    }
                    $royalUserInERP = R::getRow('select userid from user where conditions=0 and obygyDoctorId = ' . (int) $royalUser['user_id']);
                } else {
                    throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                }
            }

            if ($isERPPayment == 0) {//will be a bill in erp
                //if ($visit->clientdeptchangeid_save == 0 && $visit->clientdeptchangeid_bank == 0) {//its bill delete it
                // set post fields
                $post = [
                    'erpDB' => $programesetting->erpdb,
                    'sellbillId' => $sellData["sellbillid"],
                    'returnsellbillid' => $sellData["sellbillid"],
                    'obgyGroupId' => $royalUser['role_id'],
                    'userid' => $royalUserInERP['userid'],
                    'isRefund' => $isRefund,
                    'savePaymentDateWithBillDate' => 1,
                ];

                if ($isRefund == 0) {
                    $ch = curl_init(HOST_URL_ERP . '/controllers/sellbillController.php?do=delObgyVisit');
                } elseif ($isRefund == 1) {
                    $ch = curl_init(HOST_URL_ERP . '/controllers/returnsellbillController.php?do=delete');
                }

                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

                // execute!
                $response = curl_exec($ch);

                // close the connection, release resources used
                curl_close($ch);

                // do anything you want with your response
                //        var_dump($response);
            }
            //this is for payment visa or bank -- in this case it is not bill it is just payment
            $saveSucessFlag = 0;
            $bankSucessFlag = 0;
            if ($visit->clientdeptchangeid_save > 0) {
                // set post fields
                $post = [
                    'curlpost' => 1,
                ];
                //$royalUserInERP['userid'] = 1;
                $sessionArr = array('dbname' => $programesetting->erpdb, 'userid' => $royalUserInERP['userid']);
                $post['sessionlist'] = json_encode($sessionArr);
                $ch = curl_init(HOST_URL_ERP . '/controllers/clientPayedDeptController.php?do=remove&id=' . $visit->clientdeptchangeid_save);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

                // execute!
                $response = curl_exec($ch);
                $saveSucessFlag = filter_var($response, FILTER_SANITIZE_NUMBER_INT); //required as response had red dot and "ï»¿"
                //print_r($response);
                // close the connection, release resources used
                curl_close($ch);

                // do anything you want with your response
                //        var_dump($response);
            }
            if ($visit->clientdeptchangeid_bank > 0) {
                $CheckdepositData = R::getRow('select clientdebtchangemodelid from clientdebtchange where tablename="depositcheckController.php" and clientdebtchangetype=1 and clientdebtchangeid = ' . $visit->clientdeptchangeid_bank);
                $Checkdepositid = $CheckdepositData['clientdebtchangemodelid'];
                // set post fields
                $post = [
                    'curlpost' => 1,
                    'id' => $Checkdepositid,
                ];
                //$royalUserInERP['userid'] = 1;
                $sessionArr = array('dbname' => $programesetting->erpdb, 'userid' => $royalUserInERP['userid'], 'saveid' => $royalUser['erpsaveid']);
                $post['sessionlist'] = json_encode($sessionArr);
                $ch = curl_init(HOST_URL_ERP . '/controllers/depositcheckController.php?do=delete');
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

                // execute!
                $response = curl_exec($ch);
                $bankSucessFlag = filter_var($response, FILTER_SANITIZE_NUMBER_INT); //required as response had red dot and "ï»¿"
                //print_r($response);
                // close the connection, release resources used
                curl_close($ch);

                // do anything you want with your response
                //        var_dump($response);
            }

            R::selectDatabase('default');
            $sql = "update visits set ";
            if ($saveSucessFlag == 1) {
                $sql .= " clientdeptchangeid_save = 0 ";
            }
            if ($bankSucessFlag == 1) {
                if ($saveSucessFlag == 1) {
                    $sql .= " , ";
                }
                $sql .= " clientdeptchangeid_bank = 0 ";
            }
            $sql .= " where id=$visit->id ";

            if ($saveSucessFlag == 1 || $bankSucessFlag == 1)
                R::exec($sql);
        } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
        }
    }

    public function erpClient($patient) {
        R::selectDatabase('default');
        $programesetting = R::load('programesetting', 1);
        if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
            try {
                try {
                    R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
                } catch (Exception $exc) {
                    //do nothing next line is to select erpDB
                }
                R::selectDatabase('erpDB');
                if (R::testConnection()) {
                    $clientData = R::getRow('select clientid from client where obygyPatientId = ' . $patient->id . ' order by clientid desc');
                    if (empty($clientData['clientid'])) {
                        //here use NULL for new insert
                        //better to add client using erp files it self so use  curl "it is like post requist but in php"
                        $this->curlAddClient($patient, $programesetting->erpdb);
                        //                $insert_sql = "REPLACE into client (clientid, clientname, clientaddress, clientphone, clientmobile, clientdebt, clientdetails, conditions, clientdate, userid,clientareaid,clientcode,dailyentryid ,rondomtxt,clientStoreIds,obygyPatientId) VALUES
                        //            (NULL,'" . $patient->wifename . "' , '" . $patient->address . "', '" . $patient->phone . "', '" . $patient->mobile . "', '0', '" . $patient->importantnote . "', '0', '" . date('Y-m-d') . "', '1', '0','','','','-10','" . $patient->id . "');";
                    } else {
                        $treeId = (int) $_POST["treeId"];
                        if ($treeId > 0) {
                            //here use id to update
                            $this->curlUpdateClient($patient, $programesetting->erpdb, $clientData['clientid'], $treeId);
                        }
                    }
                } else {
                    throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                }
            } catch (Exception $exc) {
                //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                //echo -1;
            }

            R::selectDatabase('default');
        }
    }

    public function curlAddClient($patient, $erpDB) {
        $mainName = $patient->wifename;
        $secondaryName = $patient->husdandname;
        if (empty($mainName)) {
            $mainName = $patient->husdandname;
            $secondaryName = '';
        }
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'newclientName' => $mainName,
            'clientaddress' => $patient->address,
            'clientphone' => $patient->phone,
            'clientmobile' => $patient->mobile,
            'newclientdebt' => 0,
            'clientdetails' => $patient->importantnote,
            'clientareaid' => 0,
            'clientcode' => '',
            'store_all' => -10,
            'obygyPatientId' => $patient->id,
            'statusno' => $patient->statusno,
            'husdandname' => $secondaryName,
        ];

        try {
            $ch = curl_init(HOST_URL_ERP . '/controllers/clientControllerAjax.php?do=addclient&simplereturn=1');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

            // execute!
            $response = curl_exec($ch);

            // close the connection, release resources used
            curl_close($ch);
        } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
        }
        // do anything you want with your response
        //print_r($response);
    }

    public function curlUpdateClient($patient, $erpDB, $clientId, $treeId) {
        $mainName = $patient->wifename;
        $secondaryName = $patient->husdandname;
        if (empty($mainName)) {
            $mainName = $patient->husdandname;
            $secondaryName = '';
        }
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'id' => $clientId,
            'treeId' => $treeId,
            'newclientName' => $mainName,
            'clientaddress' => $patient->address,
            'clientphone' => $patient->phone,
            'clientmobile' => $patient->mobile,
            'newclientdebt' => 0,
            'clientdetails' => $patient->importantnote,
            'clientareaid' => 0,
            'clientcode' => '',
            'store_all' => 1,
            'obygyPatientId' => $patient->id,
            'statusno' => $patient->statusno,
            'husdandname' => $secondaryName,
        ];
        try {
            $ch = curl_init(HOST_URL_ERP . '/controllers/clientControllerAjax.php?do=updateFull');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

            // execute!
            $response = curl_exec($ch);

            // close the connection, release resources used
            curl_close($ch);
        } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
        }
        // do anything you want with your response
        //var_dump($response);
    }

    public function notPayedERPBills() {
        $clientId = (int) $_POST['clientid']; //on royal
        $erpClientId = 0;
        $programesetting = R::load('programesetting', 1);
        if (!empty($programesetting->erpdb) && $clientId > 0) {//if exist addDatabase erpDB
            try {
                R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
                R::selectDatabase('erpDB');
                if (R::testConnection()) {
                    $clientData = R::getRow('select clientid from client where obygyPatientId = ' . $clientId . ' order by clientid desc');
                    if (!empty($clientData['clientid'])) {
                        $erpClientId = $clientData['clientid'];
                    }
                } else {
                    throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                }
            } catch (Exception $exc) {
                //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                //echo -1;
            }
        }

        if (!empty($erpClientId)) {//get data from erp
            // set post fields
            $post = [
                'erpDB' => $programesetting->erpdb,
                'clientid' => $erpClientId,
                'curlpost' => 1,
            ];
            try {
                $ch = curl_init(HOST_URL_ERP . '/controllers/reportprovinces.php?do=getParmacyDataRoyal');
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

                // execute!
                $response = curl_exec($ch);
                // close the connection, release resources used
                curl_close($ch);


                //$bills = json_decode($response);
                //$this->smarty->assign("bills", $bills);
                echo $response;
            } catch (Exception $exc) {
                //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                //echo -1;
            }
            // do anything you want with your response
            //var_dump($response);
        }
    }

    public function payERPBills() {

        $branchId = (int) $_POST['ErpBillBranchId']; //on royal

        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {//payment from erp want to affect royal
            session_start();
            $dataArray = json_decode($_POST['data_arr']);
            $royalUser = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$dataArray[0]->user_id]);
            $useUserNameInNote = 0;
            if (isset($royalUser) && $royalUser['user_id'] > 0) {
                //its ok this is the user
            } else {
                //erp user is not in royal use user manager
                $royalUser = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [1]);
                $useUserNameInNote = 1;
            }
            $_SESSION['user_id'] = $royalUser['user_id'];
            //
            $bill_pays = array();
            foreach ($dataArray as $value) {
                $ogj = array();
                $ogj['patient_id'] = $value->patient_id;
                $ogj['bill_id'] = $value->bill_id;
                $ogj['detectionvalue_cash'] = $value->detectionvalue_cash;
                $ogj['detectionvalue_visa'] = $value->detectionvalue_visa;
                $ogj['discount'] = $value->discount;
                $ogj['note'] = ($useUserNameInNote == 1) ? $value->note . "- by " . $value->user_name : $value->note;
                $ogj['paymentfrom'] = 1; //erp
                $ogj['erp_save_or_bankaccountid'] = $value->saveOrBankAccountid;
                $ogj['cahnge_type'] = $ogj['type'] = $value->cahngeType;
                $ogj['bill_type'] = $value->billtype;
                $ogj['obgy_bill_type'] = $value->obgyBillType;
                array_push($bill_pays, $ogj);

                if (isset($value->cahngeType)) {
                    $payed = $ogj['detectionvalue_cash'] + $ogj['detectionvalue_visa'];
                    if ($value->cahngeType == 0)
                        R::exec('update patients set balance = balance - ' . $payed);
                    else if ($value->cahngeType == 1)
                        R::exec('update patients set balance = balance + ' . $payed);
                }


                //to addpayment from erp as visit
                $visitId = $value->bill_id_royal;
                $paid_cash = $ogj['detectionvalue_cash'];
                $paid_visa = $ogj['detectionvalue_visa'];
                $patientId = $ogj['patient_id'];
                $restDiscount = $ogj['discount'];
                $restNotes = $ogj['note'];

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

                $insertDataVisits = R::dispense('visits');
                $insertDataVisits->patientid = $patientId;
                $insertDataVisits->branch_id = $branchId;
                $insertDataVisits->visitdate = date("Y/m/d");
                $insertDataVisits->visittime = date("H:i:s");
                $insertDataVisits->detectionid = 999;
                $insertDataVisits->detectionvalue_cash = $paid_cash;
                $insertDataVisits->detectionvalue_visa = $paid_visa;
                $insertDataVisits->totaldetectionvalue = 0;
                $insertDataVisits->restdetectionvalue = 0;
                $insertDataVisits->discount = $restDiscount;
                $insertDataVisits->for_department = $visit->for_department;
                $insertDataVisits->for_doctor = $visit->for_doctor;
                $insertDataVisits->for_husband = $visit->for_husband;
                $insertDataVisits->user_id = $_SESSION['user_id'];
                $insertDataVisits->visitid = $visitId;
                $insertDataVisits->notes = $restNotes;

                $_SESSION['role_id'] = R::getCol('select role_id from awusers where user_id=' . $_SESSION['user_id']);
                if ($_SESSION['role_id'] == 19) {
                    $insertDataVisits->customer_add = 1;
                } else {
                    $insertDataVisits->customer_add = 0;
                }


                if ($paid_cash > 0) {
                    $insertDataVisits->printserial = $this->printSerial('last_serial');
                } else {
                    $insertDataVisits->printserial = 0;
                }

                $insertDataVisits->create_date = date('Y-m-d H:i:s'); //$this->today;
                $insertDataVisits->refer_doctor = $visit->refer_doctor;
                $insertDataVisits->refer_doctor_tb = $visit->refer_doctor_tb;
                $insertDataVisits->rfc = $visit->rfc;

                $insertDataVisits->units = 0;

                ##new columns @visit table
                $insertDataVisits->paymentfrom = 1; //1 erp , 0royal
                $insertDataVisits->erp_save_or_bankaccountid = $ogj['erp_save_or_bankaccountid'];
                ####
                $insertDataVisits->clientdeptchangeid_save = (int) $value->erp_clientdebtchangeid_save;
                $insertDataVisits->clientdeptchangeid_bank = (int) $value->erp_clientdebtchangeid_bank;


                $insertDataVisits->bill_type = (int) $ogj['bill_type'];
                $insertDataVisits->obgy_bill_type = (int) $ogj['obgy_bill_type'];
                ##

                $insert = R::store($insertDataVisits);
            }
            //to add payments to financial report
            //$this->billPayingRoyal($bill_pays, array(), 0 , $branchId); //$clientId
        } elseif ($_POST['curlpost'] != 1) {// if it is coming from erp this is the wrong code block,only if block is ok// making sure it works that way
            //affect payment in both erp,royal
            //check login
            autho::checkautho($this->hosturl);
            //load all here
            $royalUser = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);
            $royalUser_Add = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [(int) $_POST['royalUserAdd']]);

            $clientId = (int) $_POST['clientIdForERP']; //on royal
            $erpClientId = 0;
            $erpSaveName = '';
            $erpSaveName_Add = '';
            $erpAccountName = '';
            $erpUserId = '0';
            $erpUserId_Add = '0';
            //
            $clientDeptChangeIdArr = array();
            //get needed data
            $programesetting = R::load('programesetting', 1);
            if (!empty($programesetting->erpdb) && $clientId > 0) {//if exist addDatabase erpDB
                try {
                    try {
                        R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
                    } catch (Exception $exc) {
                        
                    }

                    R::selectDatabase('erpDB');
                    if (R::testConnection()) {
                        R::exec('SET NAMES latin1');
                        $royalUserInERP = R::getRow('select userid from user where conditions=0 and obygyDoctorId = ' . (int) $royalUser['user_id']);
                        if (isset($royalUserInERP) && !empty($royalUserInERP)) {
                            $erpUserId = (int) $royalUserInERP['userid'];
                        }
                        $royalUserInERP_Add = R::getRow('select userid from user where conditions=0 and obygyDoctorId = ' . (int) $_POST['royalUserAdd']);
                        if (isset($royalUserInERP_Add) && !empty($royalUserInERP_Add)) {
                            $erpUserId_Add = (int) $royalUserInERP_Add['userid'];
                        }

                        if ($royalUser['erpsaveid'] < 1) {
                            $royalUser['erpsaveid'] = $programesetting->erpdbsave;
                        }
                        $saveData = R::getRow('select savename from save where saveid = ' . $royalUser['erpsaveid']);
                        $erpSaveName = $saveData["savename"];

                        if ($royalUser_Add['erpsaveid'] < 1) {
                            $royalUser_Add['erpsaveid'] = $programesetting->erpdbsave;
                        }
                        $saveData = R::getRow('select savename from save where saveid = ' . $royalUser_Add['erpsaveid']);
                        $erpSaveName_Add = $saveData["savename"];



                        $accountData = R::getRow('select accountname,bankname
                        from bankaccount
                        join bank on bank.bankid = bankaccount.bankid
                        where accountid = ' . $programesetting->erpdbvisaaccount);
                        $erpAccountName = $accountData["bankname"] . "/" . $accountData["accountname"];

                        $clientData = R::getRow('select clientid from client where obygyPatientId = ' . $clientId . ' order by clientid desc');
                        if (isset($clientData) && !empty($clientData)) {
                            $erpClientId = $clientData['clientid'];
                        }
                    } else {
                        throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                    }
                } catch (Exception $exc) {
                    //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                    //echo -1;
                }
            }

            if (!empty($erpClientId)) {//get data from erp
                #### collect payment data of sellbill
                $billsItr = (int) $_POST["billsItr"];
                $notBillPay = (int) $_POST["notBillPay"];
                $id_pay = array();
                $bill_pays = array();
                $id_pay_as_Client_pay = array();

                for ($i = 0; $i <= $billsItr; $i++) {
                    $obj = array(); //$obj["payed"]
                    $bill_pay = array();
                    #
                    $obj["bill_id"] = (int) $_POST["billid" . $i];
                    $obj["note"] = $bill_pay["note"] = $_POST["note" . $i];
                    $bill_pay["payVisitId"] = $obj["payVisitId"] = (int) $_POST["payVisitId" . $i];

                    $bill_pay["erpClientId"] = $erpClientId;
                    $bill_pay["patient_id"] = $clientId;
                    $bill_pay["bill_id"] = $obj["bill_id"];

                    $visitid = (int) $_POST["visitid" . $i];
                    if ($visitid > 0) {
                        $sellData = R::getRow('select sellbillid from sellbill where conditions = 0 and obygyVisitId = ' . $visitid);
                        if (isset($sellData) && !empty($sellData)) {
                            $obj["bill_id"] = (int) $sellData['sellbillid'];
                        }
                        $bill_pay["visit_id"] = $obj["visit_id"] = $visitid;
                    }
                    #
                    $payed = (float) $_POST["cashPay" . $i];
                    if ($payed > 0) {
                        $obj["paytype_txt"] = 'خزنة - ' . $erpSaveName;
                        $obj["paytype_txt_Add"] = 'خزنة - ' . $erpSaveName_Add;
                        $obj["paytype"] = 'save';
                        $obj["saveId"] = $royalUser['erpsaveid'];
                        $obj["saveId_Add"] = $royalUser_Add['erpsaveid'];
                        $obj["payed"] = $bill_pay["detectionvalue_cash"] = $payed;
                        $obj["bankAccountId"] = 0;

                        if ($obj["bill_id"] > 0) {
                            array_push($id_pay, $obj);
                        } else {
                            array_push($id_pay_as_Client_pay, $obj);
                        }
                    }
                    #
                    $payed = (float) $_POST["visaPay" . $i];
                    if ($payed > 0) {
                        $obj["paytype_txt"] = 'بنك - ' . $erpAccountName;
                        $obj["paytype"] = 'bank';
                        $obj["saveId"] = 0;
                        $obj["payed"] = $bill_pay["detectionvalue_visa"] = $payed;
                        $obj["bankAccountId"] = $programesetting->erpdbvisaaccount;

                        if ($obj["bill_id"] > 0) {
                            array_push($id_pay, $obj);
                        } else {
                            array_push($id_pay_as_Client_pay, $obj);
                        }
                    }



                    #
                    //affect bill with discount
                    $billDiscount = (float) $_POST["billDis" . $i];
                    if ($billDiscount > 0) {
                        try {
                            R::selectDatabase('erpDB');
                            if (R::testConnection()) {
                                R::exec('SET NAMES latin1');

                                //reduce client debt and write it to clientdebtchange
                                $clientDebtData = R::getRow('select clientdebt from client where obygyPatientId = ' . $clientId . ' order by clientid desc');
                                $debtBefore = $clientDebtData['clientdebt'];
                                $debtAfter = $debtBefore - $billDiscount;
                                R::exec("update client set clientdebt=clientdebt-$billDiscount where clientid=$erpClientId");
                                //afect bill with discount
                                if ($obj["bill_id"] > 0) {
                                    R::exec("INSERT INTO clientdebtchange (clientid, clientdebtchangebefore, clientdebtchangeamount, clientdebtchangetype, processname, clientdebtchangemodelid, clientdebtchangeafter, clientdebtchangedate, userid, tablename, comment, totalOperationCost,discount,reciptid,dailyentryid , num , billid , paytype, costcenterid,currencyId,conversionFactor,payedInCurrency,saveConversionFactor ) VALUES
                                    ($erpClientId,$debtBefore,$billDiscount,1,'خصم على فاتورة بيع للعميل من رويال'," . $obj["bill_id"] . ", $debtAfter, '" . date('Y-m-d H:i:s') . "', $erpUserId, 'sellbillController.php', 'خصم على فاتورة بيع للعميل من رويال', $billDiscount, 0, null, 0, " . $obj["bill_id"] . ", " . $obj["bill_id"] . ",'', '0','1','1',$billDiscount,'1')");
                                    //afect bill with discount
                                    R::exec("update sellbill set sellbilldiscount=sellbilldiscount+$billDiscount
                                    ,sellbillaftertotalbill=sellbillaftertotalbill-$billDiscount,sellbillfinalbill=sellbillfinalbill-$billDiscount
                                    ,sellbilltotaldeptafter = sellbilltotaldeptafter-$billDiscount where sellbillid=" . $obj["bill_id"]);
                                } else {
                                    R::exec("INSERT INTO clientdebtchange (clientid, clientdebtchangebefore, clientdebtchangeamount, clientdebtchangetype, processname, clientdebtchangemodelid, clientdebtchangeafter, clientdebtchangedate, userid, tablename, comment, totalOperationCost,discount,reciptid,dailyentryid , num , billid , paytype, costcenterid,currencyId,conversionFactor,payedInCurrency,saveConversionFactor ) VALUES
                                    ($erpClientId,$debtBefore,$billDiscount,1,'خصم على دفع متبقى من رويال'," . $visitid . ", $debtAfter, '" . date('Y-m-d H:i:s') . "', $erpUserId, 'royalvisit.php', 'خصم على دفع متبقى من رويال', $billDiscount, 0, null, 0, " . $obj["bill_id"] . ", " . $obj["bill_id"] . ",'', '0','1','1',$billDiscount,'1')");
                                }



                                $bill_pay["discount"] = $billDiscount;
                            } else {
                                throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                            }
                        } catch (Exception $exc) {
                            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                            //echo -1;
                            echo $exc;
                        }
                    }

                    array_push($bill_pays, $bill_pay);
                }


                #### collect payment data of return sellbill
                $billsItrRet = (int) $_POST["billsItrRet"];
                $id_payRet = array();
                $bill_paysRet = array();

                for ($i = 0; $i <= $billsItrRet; $i++) {
                    $obj = array(); //$obj["payed"]
                    $bill_pay = array();
                    #
                    $obj["bill_id"] = (int) $_POST["billidRet" . $i];
                    $obj["note"] = $bill_pay["note"] = $_POST["noteRet" . $i];

                    $bill_pay["patient_id"] = $clientId;
                    $bill_pay["bill_id"] = $obj["bill_id"];

                    $visitid = (int) $_POST["visitid" . $i];
                    if ($visitid > 0) {
                        $sellData = R::getRow('select sellbillid from sellbill where conditions = 0 and obygyVisitId = ' . $visitid);
                        if (isset($sellData) && !empty($sellData)) {
                            $obj["bill_id"] = (int) $sellData['sellbillid'];
                        }
                        $bill_pay["visit_id"] = $visitid;
                    }
                    #
                    $obj["payed"] = (float) $_POST["cashPayRet" . $i];
                    if ($obj["bill_id"] > 0 && $obj["payed"] > 0) {
                        $obj["paytype_txt"] = 'خزنة - ' . $erpSaveName;
                        $obj["paytype"] = 'save';
                        $obj["saveId"] = $royalUser['erpsaveid'];
                        $obj["bankAccountId"] = 0;

                        array_push($id_payRet, $obj);
                        $bill_pay["detectionvalue_cash"] = $obj["payed"];
                    }
                    #
                    $obj["payed"] = (float) $_POST["visaPayRet" . $i];
                    if ($obj["bill_id"] > 0 && $obj["payed"] > 0) {
                        $obj["paytype_txt"] = 'بنك - ' . $erpAccountName;
                        $obj["paytype"] = 'bank';
                        $obj["saveId"] = 0;
                        $obj["bankAccountId"] = $programesetting->erpdbvisaaccount;

                        array_push($id_payRet, $obj);
                        $bill_pay["detectionvalue_visa"] = $obj["payed"];
                    }

                    #
                    //affect bill with discount
                    $billDiscount = (float) $_POST["billDisRet" . $i];
                    if ($obj["bill_id"] > 0 && $billDiscount > 0) {
                        try {
                            R::selectDatabase('erpDB');
                            if (R::testConnection()) {
                                R::exec('SET NAMES latin1');
                                //afect bill with discount
                                R::exec("update returnsellbill set returnsellbilldiscount=returnsellbilldiscount+$billDiscount
                                    ,returnsellbillaftertotalbill=returnsellbillaftertotalbill-$billDiscount,returnsellbillfinalbill=returnsellbillfinalbill+$billDiscount
                                    ,returnsellbilltotaldeptafter = returnsellbilltotaldeptafter+$billDiscount where returnsellbillid=" . $obj["bill_id"]);
                                //reduce client debt and write it to clientdebtchange
                                $clientDebtData = R::getRow('select clientdebt from client where obygyPatientId = ' . $clientId . ' order by clientid desc');
                                $debtBefore = $clientDebtData['clientdebt'];
                                $debtAfter = $debtBefore + $billDiscount;
                                R::exec("update client set clientdebt=clientdebt+$billDiscount where clientid=$erpClientId");
                                R::exec("INSERT INTO clientdebtchange (clientid, clientdebtchangebefore, clientdebtchangeamount, clientdebtchangetype, processname, clientdebtchangemodelid, clientdebtchangeafter, clientdebtchangedate, userid, tablename, comment, totalOperationCost,discount,reciptid,dailyentryid , num , billid , paytype, costcenterid,currencyId,conversionFactor,payedInCurrency,saveConversionFactor ) VALUES
                                    ($erpClientId,$debtBefore,$billDiscount,0,'خصم على فاتورة مردود بيع للعميل من رويال'," . $obj["bill_id"] . ", $debtAfter, '" . date('Y-m-d H:i:s') . "', $erpUserId, 'returnsellbillController.php', 'خصم على فاتورة مردود بيع للعميل من رويال', $billDiscount, 0, null, 0, " . $obj["bill_id"] . ", " . $obj["bill_id"] . ",'', '0','1','1',$billDiscount,'1')");

                                $bill_pay["discount"] = $billDiscount;
                            } else {
                                throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                            }
                        } catch (Exception $exc) {
                            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                            //echo -1;
                            echo $exc;
                        }
                    }

                    array_push($bill_paysRet, $bill_pay);
                }

                ################sending to erp
                if (count($id_pay) > 0) {
                    // set post fields
                    $post = [
                        'erpDB' => $programesetting->erpdb,
                        'client_id' => $erpClientId,
                        'id_pay' => json_encode($id_pay),
                        'userId' => $erpUserId,
                        'userId_Add' => $erpUserId_Add,
                        'isCurlFromRoyal' => 1, //to stop recursion curl btween erp,royal
                    ];
                    try {
                        $ch = curl_init(HOST_URL_ERP . '/controllers/sellbillAjaxController.php?do=makeSellBillPayment');
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

                        // execute!
                        $response = curl_exec($ch);
                        //print_r($response);
                        $clientDeptChangeIdArr = json_decode($response);
                        R::selectDatabase('default');
                        foreach ($clientDeptChangeIdArr as $value) {
                            if ($value->payVisitId > 0) {
                                $sql = " update visits set ";
                                if ($value->paytype == "save")
                                    $sql .= " clientdeptchangeid_save = " . $value->clientdebtchangeid;
                                elseif ($value->paytype == "bank")
                                    $sql .= " clientdeptchangeid_bank = " . $value->clientdebtchangeid;
                                $sql .= " where id=" . $value->payVisitId;
                                R::exec($sql);
                            }
                        }

                        // close the connection, release resources used
                        curl_close($ch);


                        //$bills = json_decode($response);
                        //$this->smarty->assign("bills", $bills);
                        //      echo $response;
                    } catch (Exception $exc) {
                        //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                        echo -1;
                    }
                    // do anything you want with your response
                    //var_dump($response);
                }

                if (count($id_payRet) > 0) {
                    // set post fields
                    $post = [
                        'erpDB' => $programesetting->erpdb,
                        'client_id' => $erpClientId,
                        'id_pay' => json_encode($id_payRet),
                        'userId' => $erpUserId,
                    ];
                    try {
                        $ch = curl_init(HOST_URL_ERP . '/controllers/sellbillAjaxController.php?do=makeReturnSellBillPayment');
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

                        // execute!
                        $response = curl_exec($ch);

                        // close the connection, release resources used
                        curl_close($ch);


                        //$bills = json_decode($response);
                        //$this->smarty->assign("bills", $bills);
                        //      echo $response;
                    } catch (Exception $exc) {
                        //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                        echo -1;
                    }
                    // do anything you want with your response
                    //var_dump($response);
                }

                if (count($id_pay_as_Client_pay) > 0 && $erpClientId > 0) {
                    R::selectDatabase('erpDB');
                    $royalClientInERP = R::getRow('select * from client where clientid = ' . (int) $erpClientId);
                    $sessionList = array();
                    $sessionList['userid'] = $royalUserInERP['userid'];
                    $sessionList['dbname'] = $programesetting->erpdb;

                    foreach ($id_pay_as_Client_pay as $value) {
                        try {
                            R::selectDatabase('erpDB');
                        } catch (Exception $exc) {
                            
                        }

                        if ($value['paytype'] == 'save') {
                            $last_clientdebtchangeid = (int) R::getCell('SELECT clientdebtchangeid FROM clientdebtchange 	order by clientdebtchangeid desc limit 1');
                            // set post fields
                            $post = array(
                                'curlpost' => '1',
                                'sessionlist' => json_encode($sessionList),
                                'clientid' => $royalClientInERP['clientid'],
                                'saveid' => $value['saveId'],
                                'voucher' => ($last_clientdebtchangeid + 1),
                                'oldvoucher' => ($last_clientdebtchangeid + 1),
                                'notPremium' => 'notPremium',
                                'lastDate' => date('Y-m-d'),
                                'clientnegative' => 1,
                                'currentDate' => date('Y-m-d H:i:s'),
                                'debtBefore' => $royalClientInERP['clientdebt'],
                                'payedDept' => $value['payed'],
                                'debtAfter' => ($royalClientInERP['clientdebt'] - $value['payed']),
                                'comment' => '',
                                'add_print' => 0,
                                'clientpremium' => '',
                                'premiumid' => '',
                            );
                            try {
                                $ch = curl_init(HOST_URL_ERP . '/controllers/clientPayedDeptController.php?do=add');
                                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

                                // execute!
                                $response = curl_exec($ch);
                                $clientDeptChangeIdSave = (int) filter_var($response, FILTER_SANITIZE_NUMBER_INT); //required as response had red dot
                                // close the connection, release resources used
                                curl_close($ch);

                                //print_r($response);
                            } catch (Exception $exc) {
                                //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                                echo -1;
                            }
                        } elseif ($value['paytype'] == 'bank') {

                            $bankid = (int) R::getCell('SELECT bankid FROM bankaccount WHERE accountid=' . $value['bankAccountId']);

                            // set post fields
                            $post = array(
                                'curlpost' => '1',
                                'sessionlist' => json_encode($sessionList),
                                'clientid' => $royalClientInERP['clientid'],
                                'accountid' => $value['bankAccountId'],
                                'txtAmount' => $value['payed'],
                                'textNote' => '',
                                'txtcheckNum' => 0,
                                'txtUser' => '',
                                'ddlBank' => $bankid,
                            );
                            try {
                                $ch = curl_init(HOST_URL_ERP . '/controllers/depositcheckController.php?do=add');
                                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

                                // execute!
                                $response = curl_exec($ch);
                                $clientDeptChangeIdBank = (int) filter_var($response, FILTER_SANITIZE_NUMBER_INT); //required as response had red dot and "ï»¿"
                                // close the connection, release resources used
                                curl_close($ch);

                                //print_r($response);
                            } catch (Exception $exc) {
                                //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                                echo -1;
                            }
                        }
                        //
                        R::selectDatabase('default');
                        $sql = " update visits set ";
                        if ($value['paytype'] == "save")
                            $sql .= " clientdeptchangeid_save = " . $clientDeptChangeIdSave;
                        elseif ($value['paytype'] == "bank")
                            $sql .= " clientdeptchangeid_bank = " . $clientDeptChangeIdBank;
                        $sql .= " where id=" . $value["payVisitId"];
                        R::exec($sql);
                    }
                }

                ## save to royal and print recept
                if ($notBillPay != 1) {
                    $this->billPayingRoyal($bill_pays, $clientDeptChangeIdArr, $bill_paysRet, $clientId, $branchId);
                }
            }
        }
        R::selectDatabase('default');
    }

    public function delPayERPBills($visit) {

        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {//del payment from erp want to affect royal
            session_start();
            $dataArray = json_decode($_POST['data_arr']);
            $royalUser = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$dataArray[0]->user_id]);
            $useUserNameInNote = 0;
            if (isset($royalUser) && $royalUser['user_id'] > 0) {
                //its ok this is the user
            } else {
                //erp user is not in royal use user manager
                $royalUser = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [1]);
                $useUserNameInNote = 1;
            }
            $_SESSION['user_id'] = $royalUser['user_id'];
            //supposed to be 1 itration
            foreach ($dataArray as $value) {

                $visitId = (int) $value->bill_id_royal;
                $paytype = $value->paytype;

                $queryString = '';
                $erp_clientdebtchangeid_save = 0;
                $erp_clientdebtchangeid_bank = 0;
                if ($paytype == "save") {
                    $erp_clientdebtchangeid_save = $value->erp_clientdebtchangeid_save;
                    $queryString = " and clientdeptchangeid_save=$erp_clientdebtchangeid_save ";
                }
                if ($paytype == "bank") {
                    $erp_clientdebtchangeid_bank = $value->erp_clientdebtchangeid_bank;
                    $queryString = " and clientdeptchangeid_bank=$erp_clientdebtchangeid_bank ";
                }

                //paymentfrom = 1
                $id = (int) R::getCell("select id from visits where detectionid=999
                        and visitid = $visitId " . $queryString);

                $patientDelete = R::load('visits', $id);

                if ($paytype == "save" && $patientDelete->detectionvalue_visa != 0) {//we are deleting save but it also have bank pay, dont delete
                    $patientDelete->detectionvalue_cash = 0;
                    $patientDelete->userid_edit = $_SESSION['user_id'];
                    $patientDelete->date_edit = date('Y-m-d H:i:s');
                    R::store($patientDelete);
                } else if ($paytype == "bank" && $patientDelete->detectionvalue_cash != 0) {//we are deleting bank but it also have save pay, dont delete
                    $patientDelete->detectionvalue_visa = 0;
                    $patientDelete->userid_edit = $_SESSION['user_id'];
                    $patientDelete->date_edit = date('Y-m-d H:i:s');
                    R::store($patientDelete);
                } else {//del save pay,no bank pay //or del bank pay , no save pay
                    $patientDelete->deleted = 1;
                    $patientDelete->user_delete = $_SESSION['user_id'];
                    $patientDelete->date_delete = date('Y-m-d H:i:s');
                    R::store($patientDelete);
                }


                calcBalance($patientDelete->patientid);
            }
        } else {

            //affect payment in both erp,royal
            //check login
            autho::checkautho($this->hosturl);
            //load all here
            $clientId = $visit->patientid;
            $erpClientId = 0;
            $royalUser = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);
            $programesetting = R::load('programesetting', 1);
            //get some data from erp
            if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
                try {
                    try {
                        R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
                    } catch (Exception $exc) {
                        //do nothing next line is to select erpDB
                    }
                    R::selectDatabase('erpDB');
                    if (R::testConnection()) {
                        R::exec('SET NAMES latin1');
                        $royalUserInERP = R::getRow('select userid from user where conditions=0 and obygyDoctorId = ' . (int) $royalUser['user_id']);
                        if (isset($royalUserInERP) && !empty($royalUserInERP)) {
                            $erpUserId = (int) $royalUserInERP['userid'];
                        }
                        $tableName_save = R::getCell('SELECT tablename FROM clientdebtchange where clientdebtchangeid = ' . $visit->clientdeptchangeid_save);
                        $tableName_bank = R::getCell('SELECT tablename FROM clientdebtchange where clientdebtchangeid = ' . $visit->clientdeptchangeid_bank);
                    } else {
                        throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                    }
                } catch (Exception $exc) {
                    //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                    //echo -1;
                    echo $exc->getTraceAsString();
                }
            }
            //cash part
            if ($visit->detectionvalue_cash > 0 && $visit->clientdeptchangeid_save > 0) {
                //payed as ta7seel "cash in save" -> delete it
                if ($tableName_save == "clientPayedDeptController.php") {
                    // set post fields
                    $post = [
                        'curlpost' => 1,
                        'obgyGroupId' => $royalUser['role_id'],
                    ];
                    //$royalUserInERP['userid'] = 1;
                    $sessionArr = array('dbname' => $programesetting->erpdb, 'userid' => $royalUserInERP['userid']);
                    $post['sessionlist'] = json_encode($sessionArr);
                    $ch = curl_init(HOST_URL_ERP . '/controllers/clientPayedDeptController.php?do=remove&id=' . $visit->clientdeptchangeid_save);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
                    // execute!
                    $response = curl_exec($ch);
                    $saveSucessFlag = filter_var($response, FILTER_SANITIZE_NUMBER_INT); //required as response had red dot and "ï»¿"
                    //print_r($response);
                    // close the connection, release resources used
                    curl_close($ch);

                    // do anything you want with your response
                    //        var_dump($response);
                }
                //payment on bill -> delete it
                if ($tableName_save == "clientPayedDeptSellBillsController.php") {
                    // set post fields
                    $post = [
                        'curlpost' => 1,
                        'clientdebtchangeId' => $visit->clientdeptchangeid_save,
                        'comment' => '',
                        'paytype' => 'save',
                        'savePaymentDateWithBillDate' => 1,
                        'obgyGroupId' => $royalUser['role_id'],
                    ];
                    //$royalUserInERP['userid'] = 1;
                    $sessionArr = array('dbname' => $programesetting->erpdb, 'userid' => $royalUserInERP['userid']);
                    $post['sessionlist'] = json_encode($sessionArr);
                    $ch = curl_init(HOST_URL_ERP . '/controllers/sellbillAjaxController.php?do=delMakeSellBillPayment');
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
                    // execute!
                    $response = curl_exec($ch);
                    $saveSucessFlag = filter_var($response, FILTER_SANITIZE_NUMBER_INT); //required as response had red dot and "ï»¿"
                    //print_r($response);
                    // close the connection, release resources used
                    curl_close($ch);

                    // do anything you want with your response
                    //        var_dump($response);
                }
            }
            //visa part
            if ($visit->detectionvalue_visa > 0 && $visit->clientdeptchangeid_bank > 0) {
                //payed as ta7seel "checkdeposite" -> delete it
                if ($tableName_bank == "depositcheckController.php") {
                    $CheckdepositData = R::getRow('select clientdebtchangemodelid from clientdebtchange where tablename="depositcheckController.php" and clientdebtchangetype=1 and clientdebtchangeid = ' . $visit->clientdeptchangeid_bank);
                    $Checkdepositid = $CheckdepositData['clientdebtchangemodelid'];
                    // set post fields
                    $post = [
                        'curlpost' => 1,
                        'id' => $Checkdepositid,
                        'obgyGroupId' => $royalUser['role_id'],
                    ];
                    //$royalUserInERP['userid'] = 1;
                    $sessionArr = array('dbname' => $programesetting->erpdb, 'userid' => $royalUserInERP['userid'], 'saveid' => $royalUser['erpsaveid']);
                    $post['sessionlist'] = json_encode($sessionArr);
                    $ch = curl_init(HOST_URL_ERP . '/controllers/depositcheckController.php?do=delete');
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

                    // execute!
                    $response = curl_exec($ch);
                    $bankSucessFlag = filter_var($response, FILTER_SANITIZE_NUMBER_INT); //required as response had red dot and "ï»¿"
                    //print_r($response);
                    // close the connection, release resources used
                    curl_close($ch);

                    // do anything you want with your response
                    //        var_dump($response);
                }
                //payment on bill -> delete it
                if ($tableName_bank == "clientPayedDeptSellBillsController.php") {
                    // set post fields
                    $post = [
                        'curlpost' => 1,
                        'clientdebtchangeId' => $visit->clientdeptchangeid_bank,
                        'comment' => '',
                        'paytype' => 'bank',
                        'savePaymentDateWithBillDate' => 1,
                        'obgyGroupId' => $royalUser['role_id'],
                    ];
                    //$royalUserInERP['userid'] = 1;
                    $sessionArr = array('dbname' => $programesetting->erpdb, 'userid' => $royalUserInERP['userid']);
                    $post['sessionlist'] = json_encode($sessionArr);
                    $ch = curl_init(HOST_URL_ERP . '/controllers/sellbillAjaxController.php?do=delMakeSellBillPayment');
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
                    // execute!
                    $response = curl_exec($ch);
                    $saveSucessFlag = filter_var($response, FILTER_SANITIZE_NUMBER_INT); //required as response had red dot and "ï»¿"
                    //print_r($response);
                    // close the connection, release resources used
                    curl_close($ch);

                    // do anything you want with your response
                    //        var_dump($response);
                }
            }
            //discount part
            //affect bill with discount
            $billDiscount = $visit->discount;
            $bill_id = 0;
            if ($billDiscount > 0) {
                try {
                    R::selectDatabase('erpDB');
                    if (R::testConnection()) {
                        R::exec('SET NAMES latin1');
                        ############### get some data
                        $clientData = R::getRow('select clientid from client where obygyPatientId = ' . $clientId . ' order by clientid desc');
                        if (isset($clientData) && !empty($clientData)) {
                            $erpClientId = $clientData['clientid'];
                        }
                        $visitid = $visit->visitid;
                        if ($visitid > 0) {
                            $sellData = R::getRow('select sellbillid from sellbill where conditions = 0 and obygyVisitId = ' . $visitid);
                            if (isset($sellData) && !empty($sellData)) {
                                $bill_id = (int) $sellData['sellbillid'];
                            }
                        }



                        ############# start logig
                        //increase client debt and write it to clientdebtchange
                        $clientDebtData = R::getRow('select clientdebt from client where obygyPatientId = ' . $clientId . ' order by clientid desc');
                        $debtBefore = $clientDebtData['clientdebt'];
                        $debtAfter = $debtBefore + $billDiscount;
                        R::exec("update client set clientdebt=clientdebt+$billDiscount where clientid=$erpClientId");
                        //afect bill with discount
                        if ($bill_id > 0) {
                            R::exec("INSERT INTO clientdebtchange (clientid, clientdebtchangebefore, clientdebtchangeamount, clientdebtchangetype, processname, clientdebtchangemodelid, clientdebtchangeafter, clientdebtchangedate, userid, tablename, comment, totalOperationCost,discount,reciptid,dailyentryid , num , billid , paytype, costcenterid,currencyId,conversionFactor,payedInCurrency,saveConversionFactor ) VALUES
                                    ($erpClientId,$debtBefore,$billDiscount,0,'الغاء خصم على فاتورة بيع للعميل من رويال'," . $bill_id . ", $debtAfter, '" . date('Y-m-d H:i:s') . "', $erpUserId, 'sellbillController.php', 'الغاء خصم على فاتورة بيع للعميل من رويال', $billDiscount, 0, null, 0, " . $bill_id . ", " . $bill_id . ",'', '0','1','1',$billDiscount,'1')");
                            //afect bill with discount
                            R::exec("update sellbill set sellbilldiscount=sellbilldiscount-$billDiscount
                                    ,sellbillaftertotalbill=sellbillaftertotalbill+$billDiscount,sellbillfinalbill=sellbillfinalbill+$billDiscount
                                    ,sellbilltotaldeptafter = sellbilltotaldeptafter+$billDiscount where sellbillid=" . $bill_id);
                        } else {
                            R::exec("INSERT INTO clientdebtchange (clientid, clientdebtchangebefore, clientdebtchangeamount, clientdebtchangetype, processname, clientdebtchangemodelid, clientdebtchangeafter, clientdebtchangedate, userid, tablename, comment, totalOperationCost,discount,reciptid,dailyentryid , num , billid , paytype, costcenterid,currencyId,conversionFactor,payedInCurrency,saveConversionFactor ) VALUES
                                    ($erpClientId,$debtBefore,$billDiscount,0,'الغاء خصم على دفع متبقى من رويال'," . $visitid . ", $debtAfter, '" . date('Y-m-d H:i:s') . "', $erpUserId, 'royalvisit.php', 'خصم على دفع متبقى من رويال', $billDiscount, 0, null, 0, " . $bill_id . ", " . $bill_id . ",'', '0','1','1',$billDiscount,'1')");
                        }
                    } else {
                        throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                    }
                } catch (Exception $exc) {
                    //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                    //echo -1;
                    echo $exc;
                }
            }

            R::selectDatabase('default');
        }
    }

    function billPayingRoyal($bill_pays, $clientDeptChangeIdArr, $bill_paysRet, $patientId, $branchId) {
        //check login
        autho::checkautho($this->hosturl);
        //to read this function records in erp
//        $dataToRecord = R::getAll("SELECT sellbillid,clientdebtchange.*,client.obygyPatientId,user2.obygyDoctorId
//                    FROM `clientdebtchange`
//                    join sellbill on( sellbill.sellbillid = clientdebtchange.clientdebtchangemodelid and sellbill.obgyBillType = 1 and sellbill.conditions = 0)
//                    JOIN client ON sellbill.sellbillclientid = client.clientid
//                    JOIN user as user2 ON sellbill.userid = user2.userid
//                    WHERE `tablename`='clientPayedDeptSellBillsController.php' and date(clientdebtchangedate) = '2022-09-22'");
        try {
            $bill_pay_printed = array();
            $bill_pay_printedRet = array();

            //  R::addDatabase("royalDb", 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . '', '' . DB_USER . '', '' . DB_PASS . '');
            R::selectDatabase('default');
            $totalCash = 0;
            foreach ($bill_pays as $bill_pay) {

                if ($bill_pay["detectionvalue_cash"] > 0 || $bill_pay["detectionvalue_visa"] > 0 || $bill_pay["discount"] > 0) {

                    $ogj = R::xdispense('bill_paying');
                    $ogj->patient_id = $bill_pay["patient_id"];
                    $ogj->branch_id = $branchId;
                    $ogj->bill_id = $bill_pay["bill_id"];
                    $ogj->create_date = date('Y-m-d H:i:s'); //$this->today;

                    if ($bill_pay["detectionvalue_cash"] > 0) {
                        $ogj->detectionvalue_cash = $bill_pay["detectionvalue_cash"];
                    } else {
                        $ogj->detectionvalue_cash = 0;
                    }

                    if ($bill_pay["detectionvalue_visa"] > 0) {
                        $ogj->detectionvalue_visa = $bill_pay["detectionvalue_visa"];
                    } else {
                        $ogj->detectionvalue_visa = 0;
                    }

                    if ($bill_pay["discount"] > 0) {
                        $ogj->discount = $bill_pay["discount"];
                    } else {
                        $ogj->discount = 0;
                    }

                    $ogj->notes = $bill_pay["note"];
                    $ogj->paymentfrom = (int) $bill_pay["paymentfrom"]; //1 erp , 0royal
                    $ogj->erp_save_or_bankaccountid = (int) $bill_pay["erp_save_or_bankaccountid"]; //1 erp , 0royal
                    ####
                    $x = "save-" . $bill_pay["bill_id"];
                    $y = "bank-" . $bill_pay["bill_id"];
                    $ogj->erp_clientdebtchangeid_save = (int) $clientDeptChangeIdArr->$x->clientdebtchangeid;
                    $ogj->erp_clientdebtchangeid_bank = (int) $clientDeptChangeIdArr->$y->clientdebtchangeid;


                    $ogj->cahnge_type = (int) $bill_pay["cahnge_type"];
                    $ogj->bill_type = (int) $bill_pay["bill_type"];
                    $ogj->obgy_bill_type = (int) $bill_pay["obgy_bill_type"];

                    ####
                    $ogj->totaldetectionvalue = 0;
                    $ogj->user_id = $_SESSION['user_id'];
                    $ogj->printserial = $this->printSerial('last_serial');
                    $ogj->pay_date = date("Y/m/d");
                    $ogj->type = (int) $bill_pay['type'];
                    $ogj->id = R::store($ogj);

                    $totalCash = $totalCash + $bill_pay["detectionvalue_cash"];

                    $bill_pay["printserial"] = $ogj->printserial;
                }

                if ($bill_pay["detectionvalue_cash"] > 0) {
                    array_push($bill_pay_printed, $ogj);
                }
            }


            $totalCashRet = 0;
            foreach ($bill_paysRet as $bill_pay) {

                if ($bill_pay["detectionvalue_cash"] > 0 || $bill_pay["detectionvalue_visa"] > 0 || $bill_pay["discount"] > 0) {

                    $ogj = R::xdispense('bill_paying');
                    $ogj->patient_id = $bill_pay["patient_id"];
                    $ogj->branch_id = $branchId;
                    $ogj->bill_id = $bill_pay["bill_id"];
                    $ogj->create_date = date('Y-m-d H:i:s'); //$this->today;

                    if ($bill_pay["detectionvalue_cash"] > 0) {
                        $ogj->detectionvalue_cash = $bill_pay["detectionvalue_cash"];
                    } else {
                        $ogj->detectionvalue_cash = 0;
                    }

                    if ($bill_pay["detectionvalue_visa"] > 0) {
                        $ogj->detectionvalue_visa = $bill_pay["detectionvalue_visa"];
                    } else {
                        $ogj->detectionvalue_visa = 0;
                    }

                    if ($bill_pay["discount"] > 0) {
                        $ogj->discount = $bill_pay["discount"];
                    } else {
                        $ogj->discount = 0;
                    }
                    $ogj->notes = $bill_pay["note"];
                    $ogj->paymentfrom = (int) $bill_pay["paymentfrom"]; //1 erp , 0royal
                    $ogj->totaldetectionvalue = 0;
                    $ogj->user_id = $_SESSION['user_id'];
                    $ogj->printserial = $this->printSerial('last_serial');
                    $ogj->pay_date = date("Y/m/d");
                    $ogj->type = 1;
                    $ogj->id = R::store($ogj);

                    $totalCashRet = $totalCashRet + $bill_pay["detectionvalue_cash"];

                    $bill_pay["printserial"] = $ogj->printserial;
                }

                if ($bill_pay["detectionvalue_cash"] > 0) {
                    array_push($bill_pay_printedRet, $ogj);
                }
            }

            if ($totalCash > 0 || $totalCashRet > 0) {
                $user = R::findOne('awusers', 'user_id = ?', [$_SESSION['user_id']]);
                //    $this->smarty->assign('user_name', $user->name);
                $this->printBillRecept($patientId, $bill_pay_printed, $bill_pay_printedRet, $user->name);
            }
            #################################
        } catch (Exception $ex) {
            echo $ex;
        }
    }

    function printBillRecept($patientId, $bill_pays, $bill_paysRet, $userName) {

        try {
            $this->smarty->assign('visitdate', date("Y/m/d"));
            $this->smarty->assign('detection', ' صيدلية   ');
            $this->smarty->assign('user_name', $userName);


            $patient = R::load('patients', $patientId);
            $this->smarty->assign('statusno', $patient->statusno);
            $this->smarty->assign('pat_name', $patient->wifename . ' - ' . $patient->husdandname);

            $this->smarty->assign('bill_pays', $bill_pays);
            $this->smarty->assign('bill_paysRet', $bill_paysRet);
            $this->smarty->display('visits/print_bills.html');
#################################
        } catch (Exception $ex) {
            echo '-1';
        }
    }

    function erpLiveComment($comment) {
        $arr = explode('/', HOST_URL_ERP);
        echo $_SERVER['DOCUMENT_ROOT'] . "" . end($arr) . "/controllers/backup/" . date("Y-m-d") . ".txt";
        $myfile = fopen($_SERVER['DOCUMENT_ROOT'] . "" . end($arr) . "/controllers/backup/" . date("Y-m-d") . ".txt", "a+"); // or die("Unable to open file!");
        $txt = "-- Royal " . date('Y-m-d H:i:s') . ": " . $comment . " -------\r\n";
        fwrite($myfile, $txt);
        fclose($myfile);
    }

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

    public function operationreserves() {

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

        $visitdate = filter_input(INPUT_POST, "visitdate");
        $doctorId = filter_input(INPUT_POST, "doctorId");

        $reservations = '<option value=""></option> ';

        $drReservations = R::findAll('operations_main', ' doctor_id = ?  and the_date = ? ', [$doctorId, $visitdate]);
        foreach ($drReservations as $data) {
            $operation_hours = explode(',', $data->operation_hours);
            $startHour = $operation_hours[0];
            $reservations .= '<option value="' . $data->id . '">' . $startHour . '</option>';
        }

        echo $reservations;
    }

    public function getDetectionsByReserve() {

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

        $reserveId = filter_input(INPUT_POST, "reserveId");
        $reservation = R::getRow('SELECT operation_types_id  FROM operations_main WHERE id ="' . $reserveId . '"');
        echo $reservation['operation_types_id'];
    }

    public function getChilds() {

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

        $patientId = filter_input(INPUT_POST, "patientId");
        $count = 0;

        if ($patientId > 0) {
            $childs = R::findAll('patients_childs', ' deleted = 0 and patientid = ?  ', [$patientId]);
            $count = count($childs);
            $this->smarty->assign('childs', $childs);
        }
        $this->smarty->assign('count', $count);
        $this->smarty->display('visits/childs.html');
    }

    public function addOrgRow() {

//check login
        autho::checkautho($this->hosturl);
//check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
//prepar wife data insert
        $tableName = filter_input(INPUT_POST, 'tableName');
        $notAll = filter_input(INPUT_POST, "notAll");
        $itr = filter_input(INPUT_POST, 'itr');


        $ogj = R::xdispense($tableName);
        $ogj->deleted = 0;

        try {

            $ogj->id = R::store($ogj);
            $this->smarty->assign('mydata', $ogj);
            $this->smarty->assign('tableName', $tableName);
            $this->smarty->assign('i', $itr);
            $this->smarty->assign('notAll', $notAll);
            $this->smarty->display('visits/neworg.html');
        } catch (Exception $ex) {
            echo -1;
        }
    }

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

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

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

        $id = filter_input(INPUT_POST, 'id');
        $orgDiscountType = filter_input(INPUT_POST, 'orgDiscountType');
        $detectionid = filter_input(INPUT_POST, 'detectionid');
        $detect_cat = 1;
        $par_discount = 0;

        if ($orgDiscountType == 3) {
//            R::debug(true, 2);
            $visitOrg = R::load('organizations', $id);
            $org_discount = R::findOne('organization_discount', ' list_id = ? and detect_id = ?    and detect_cat = ?
                   and offer_id = 0   and deleted = ?  ', [$visitOrg->list_id, $detectionid, $detect_cat, 0]);
            if ($org_discount && $org_discount->contract_price > 0) {
                if ($org_discount->discount_type == 1) {
                    $org_discount->patient_hold = ($org_discount->discount_type * $org_discount->patient_hold ) / 100;
                }
                $par_discount = $org_discount->contract_price - $org_discount->patient_hold;
            }
            $result = array(
                "contract_price" => $org_discount->contract_price,
                "patient_hold" => $org_discount->patient_hold,
                "discount_type" => $org_discount->discount_type,
                "discountRatio" => $par_discount,
                "discountRatioType" => $org_discount->discount_type
            );
        } else {

            $org = R::getRow('SELECT COALESCE(center_discount ,0)   as center_discount  ,
                COALESCE(organization_discount ,0)   as organization_discount  , discount_type
                FROM organizations WHERE id = ? ', [$id]);

            $par_discount = $org['organization_discount'] - $org['center_discount'];

            $result = array(
                "discountRatio" => $par_discount,
                "discountRatioType" => $org['discount_type']
            );
        }



        echo json_encode($result);
    }

    public function getStatus() {

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

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

        if ($patientId > 0) {
            $obj = R::load('patients', $patientId);
            echo $obj->statusno;
        } else {
            echo '';
        }
    }
    
    
        public function getSaudi() {

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

        $patientId = filter_input(INPUT_POST, "patientId");
        $labSetting = R::findOne('programesettinglab');

        if ($patientId > 0 && $labSetting->saudi == 1) {
            $obj = R::load('patients', $patientId);
            echo $obj->saudi;
        } else {
            echo 0;
        }
    }

    public function getPhoneNo() {

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

        $patientId = filter_input(INPUT_POST, "patientId");
        $programesetting = R::findOne('programesetting');

        if ($patientId > 0 && $programesetting->visit_phones == 1) {
            $obj = R::load('patients', $patientId);
            echo ' Phones : ' . $obj->phone . ' - ' . $obj->mobile;
        } else {
            echo ' ';
        }
    }

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

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

        $visitId = filter_input(INPUT_POST, "mVisitId");
        $unitsConsumed = filter_input(INPUT_POST, 'unitsConsumed');

        $visit = R::load('visits', $visitId);
        $detection = R::load('detections', $visit->detectionid);

        $unitVisits = R::getRow('SELECT COALESCE(SUM(units),0)   as units_attend
                                    FROM visits   where  patientid = ?
                               and deleted != ? and detectionid = -88 and visitid = ?   ', [$visit->patientid, 1, $visitId]);


        if ($unitsConsumed > ($detection->units - $visit->units - $unitVisits['units_attend'])) {
            echo -3;
        } else {

            $visitDate = filter_input(INPUT_POST, 'visitdate');
            $for_department = filter_input(INPUT_POST, 'fordepartment');
            $for_doctor = filter_input(INPUT_POST, 'for_doctor');
            $notes = filter_input(INPUT_POST, 'notes');

            $doctor_percent = 0;
            if ($for_doctor > 0) {
                $doctorIn = R::getRow('select * from awusers where user_id = ?', [$for_doctor]);
                switch ($detection->type) {
                    case 1:
                        $doctor_percent = $doctorIn['pulse_per'];
                        break;

                    case 2:
                        $doctor_percent = $doctorIn['session_per'];
                        break;
                }
            }

            $insertDataVisits = R::dispense('visits');
            $insertDataVisits->patientid = $visit->patientid;
            $insertDataVisits->visitdate = $visitDate;
            $insertDataVisits->visittime = date("H:i:s");
            $insertDataVisits->detectionid = -88;
            $insertDataVisits->units = $unitsConsumed;
            $insertDataVisits->for_department = $for_department;
            $insertDataVisits->for_doctor = $for_doctor;
            $insertDataVisits->user_id = $_SESSION['user_id'];
            $insertDataVisits->visitid = $visitId;
            $insertDataVisits->create_date = date('Y-m-d H:i:s'); //$this->today;
            $insertDataVisits->refer_doctor = $visit->refer_doctor;
            $insertDataVisits->refer_doctor_tb = $visit->refer_doctor_tb;
            $insertDataVisits->rfc = $visit->rfc;
            $insertDataVisits->notes = $notes;
            $insertDataVisits->doctor_percent = $doctor_percent;

            if ($_SESSION['role_id'] == 19) {
                $insertDataVisits->customer_add = 1;
            } else {
                $insertDataVisits->customer_add = 0;
            }

            try {

                $insert = R::store($insertDataVisits);
            } catch (Exception $ex) {
                echo $ex;
            }
        }
    }

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

        $visitId = filter_input(INPUT_POST, "visitId");
        $visit = R::load('visits', $visitId);
        $detection = R::load('detections', $visit->detectionid);

        $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  patientid = ?
                               and deleted != ? and detectionid = 999 and visitid = ?   ', [$visit->patientid, 1, $visitId]);


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



        $visits = R::getRow('SELECT  COALESCE(SUM(units),0)   as units_attend
                                    FROM visits   where  patientid = ?
                               and deleted != ? and detectionid = -88 and visitid = ?   ', [$visit->patientid, 1, $visitId]);

        $visitsNo = $visits['units_attend'] + $visit->units;

        if ($visitsNo >= $detection->max_session && $rest > 0) {

            switch ($detection->type) {
                case 1:
                    $msg = ' تم تجاوز عدد النبضات  المسموحة  (   ';
                    break;

                case 2:
                    $msg = ' تم تجاوز عدد الجلسات  المسموحة  (   ';
                    break;

                default:
                    $msg = ' تم تجاوز عدد الوحدات المسموحة  (   ';
                    break;
            }


            $msg .= $detection->max_session;
            $msg .= ' )  يرجى سداد باقى المبلغ  . ';
            echo $msg;
        } else {
            echo '';
        }
    }

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

    public function arrange_visits() {
        $dates = R::getAll('SELECT  distinct  visitdate  as  visitdate
                                    FROM visits   where  visitdate  >  "2023-02-12" order by visitdate desc    ');

        $departs = $this->getOrderDepts(1);
        R::exec('update visits set visit_order = 0  where visitdate  >  "2023-02-12"   ');

        foreach ($dates as $date) {

            $doctors = R::getAll(' select distinct   for_doctor  as userId   from visits
                          where visits.deleted != 1 and   visits.visitdate  =  "' . $date['visitdate'] . '"
                                     and visits.detectionid not in (999 ,  9999 , -88   ) and for_doctor > 0  ');


            foreach ($doctors as $doctor) {
                $sql = ' select visits.id as visitId
                          from     visits
                          where visits.deleted != 1 and   visits.visitdate  =  "' . $date['visitdate'] . '"
                                and   visits.for_department   in (' . $departs . '  )
                                and   visits.for_doctor  = ' . $doctor['userId'] . '
                                and visits.detectionid not in (999 ,  9999 , -88 )
                               order  by   visits.visitdate   asc , visits.id asc    ';


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

                $i = 1;

                foreach ($visits as $visit) {
                    R::exec('update visits set visit_order = ' . $i . ' where id = ' . $visit['visitId']);
                    $i++;
                }
            }
        }
    }

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

    public function testPDF() {
        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 = '<h1>HTML Example</h1>
Some special characters: &lt; € &euro; &#8364; &amp; è &egrave; &copy; &gt; \\slash \\\\double-slash \\\\\\triple-slash
<h2>List</h2>
List example:
<ol>
    <li><img src="images/logo_example.png" alt="test alt attribute" width="30" height="30" border="0" /> test image</li>
    <li><b>bold text</b></li>
    <li><i>italic text</i></li>
    <li><u>underlined text</u></li>
    <li><b>b<i>bi<u>biu</u>bi</i>b</b></li>
    <li><a href="http://www.tecnick.com" dir="ltr">link to http://www.tecnick.com</a></li>
    <li>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.<br />Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</li>
    <li>SUBLIST
        <ol>
            <li>row one
                <ul>
                    <li>sublist</li>
                </ul>
            </li>
            <li>row two</li>
        </ol>
    </li>
    <li><b>T</b>E<i>S</i><u>T</u> <del>line through</del></li>
    <li><font size="+3">font + 3</font></li>
    <li><small>small text</small> normal <small>small text</small> normal <sub>subscript</sub> normal <sup>superscript</sup> normal</li>
</ol>
<dl>
    <dt>Coffee</dt>
    <dd>Black hot drink</dd>
    <dt>Milk</dt>
    <dd>White cold drink</dd>
</dl>
<div style="text-align:center">IMAGES<br />
</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_009.pdf', 'F');

//============================================================+
// END OF FILE
//============================================================+
    }

    function sendPdf() {

        $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-01-22'
            , 'printed_date' => '2022-01-23'
            , 'test_pdf' => new CURLFile(__DIR__ . '\\..\\..\\upload\\lab_pdf\\xxxx.pdf', 'application/pdf')
            , 'plus_file' => ''
            , 'visit_id' => 1
            , 'invest_id' => 8
            , '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,
            'AuthorizationKey: 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 calcBalanceAll() {
        //check login
        autho::checkautho($this->hosturl);

        calcBalance();
    }

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

    public function editlabvisit() {

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

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

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


        if (count($visit) > 0) {

            $invRes = $this->loadVisitInvestsEdit($visitId);

            $name = '';
            if ($patient->wifename != null) {
                $name .= $patient->wifename;
            }

            if ($patient->husdandname != null) {
                $name .= " -  " . $patient->husdandname;
            }

            $refer_doctor = $this->referSelectData($visit->refer_doctor, $visit->refer_doctor_tb);

            $result = array(
                "name" => $name,
                "operation_main_id" => $visit->operation_main_id,
                "unitsConsumed" => $visit->units,
                "visitdate" => date("Y/m/d", strtotime($visit->visitdate)),
                "visit_time" => $visit->visit_time,
                "patientid" => $visit->patientid,
                "detectionid" => $visit->detectionid,
                "detectionvalue_visa" => $visit->detectionvalue_visa,
                "detectionvalue_cash" => $visit->detectionvalue_cash,
                "totaldetectionvalue" => $visit->totaldetectionvalue,
                "discount" => $visit->discount,
                "restdetectionvalue" => $visit->restdetectionvalue,
                "for_department" => $visit->for_department,
                "operation_time" => $visit->operation_time,
                "for_doctor" => $visit->for_doctor,
                "notes" => $visit->notes,
                "selectedInvs" => $invRes['invRes'],
                "externals" => $invRes['externals'],
                "child" => $visit->child,
                "organization_id" => $visit->organization_id,
                "discountRatio" => $visit->organization_discount - $visit->center_discount,
                "discountRatioType" => $visit->org_discount_type,
                "refer_doctor" => $refer_doctor,
                "for_husband" => $visit->for_husband
                , "branch_id" => $visit->branch_id
                , "vat_value" => $visit->vat_value
                , "saudi" => $patient->saudi
                 , "lab_detection_price" => $visit->lab_detection_price
            );

            echo json_encode($result);
        } else {
            echo -1;
        }
    }

    function loadVisitInvestsEdit($visitId) {
        $invRes = '';
        $externals = array();
        $totalPrice = 0;
        $invests = R::findAll('investigationresults', ' visitid  = ? and deleted = 0 ', [$visitId]);

        $i = 1;
        foreach ($invests as $investResult) {
            if ($i > 1) {
                $invRes .= ',';
            }

            if ($investResult->offer_id > 0) {
                $offerDetail = R::findone('invofferdetails', ' invoffer_id = ? and  inv_id = ? and del != 1  '
                                , [$investResult->offer_id, $investResult->investid]);

                $id = 'offer_' . $offerDetail->id;
            } else {
                $id = $investResult->investid;
            }

            $invRes .= $id;

            if ($investResult->external_lab > 0) {
                $ext = array(
                    "id" => 'exLabs' . $id,
                    "val" => $investResult->external_lab
                );
                array_push($externals, $ext);
            }

            $i++;
        }

        $result = array(
            "invRes" => $invRes,
            "externals" => $externals
        );

        return $result;
    }

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

        $patientId = filter_input(INPUT_POST, 'patientid');
        if (!($patientId > 0)) {
            $patientId = $this->newPatient();
        }
        $visitId = filter_input(INPUT_POST, "mVisitId");
        $visitDate = filter_input(INPUT_POST, 'visitdate');
         //$detectionID = 4;
         $detectionID = (filter_input(INPUT_POST, 'detectionidLab') > 0) ? filter_input(INPUT_POST, 'detectionidLab') : 0;
        $labDetectionPrice = (filter_input(INPUT_POST, 'labDetectionPrice') > 0) ? filter_input(INPUT_POST, 'labDetectionPrice') : 0;
        $detectionValue_cash = filter_input(INPUT_POST, 'detectionvalue_cash');
        $detectionValue_visa = filter_input(INPUT_POST, 'detectionvalue_visa');
        $totaldetectionvalue = filter_input(INPUT_POST, 'totaldetectionvalue');
        $branch_id = filter_input(INPUT_POST, 'branch_id');
        $restdetectionvalue = filter_input(INPUT_POST, 'restdetectionvalue');

        $for_department = 12;
        $for_doctor = filter_input(INPUT_POST, 'for_doctor');
        $gender = filter_input(INPUT_POST, 'gender');
        $for_husband = filter_input(INPUT_POST, 'for_husband');
        $child = filter_input(INPUT_POST, 'child');
        $notes = filter_input(INPUT_POST, 'notes');
        $refer_doctor = filter_input(INPUT_POST, 'refer_doctor');
        $vat_value = filter_input(INPUT_POST, 'vat_value');
        $new_date = date('Y/m/d', strtotime($visitDate));

        $discountType = filter_input(INPUT_POST, 'discountType');
        if ($discountType == 1) {
            $discountRatio = filter_input(INPUT_POST, 'discount');
            $discount = $totaldetectionvalue * ($discountRatio / 100 );
        } else {
            $discount = filter_input(INPUT_POST, 'discount');
            $discountType = 0;
            $discountRatio = 0;
        }


        if ($visitId > 0) {

            $insertDataVisits = R::load('visits', $visitId);
            $visitOld = R::load('visits', $visitId);
            $insertDataVisits->patientid = $patientId;
            $insertDataVisits->visitdate = $new_date;
            $insertDataVisits->visittime = date("H:i:s");
           $insertDataVisits->detectionid = $detectionID;
        $insertDataVisits->lab_detection_price = $labDetectionPrice;
            $insertDataVisits->detectionvalue_cash = $detectionValue_cash;
            $insertDataVisits->detectionvalue_visa = $detectionValue_visa;
            $insertDataVisits->totaldetectionvalue = $totaldetectionvalue;
            $insertDataVisits->discount = $discount;
            $insertDataVisits->restdetectionvalue = $restdetectionvalue;
            $insertDataVisits->for_department = $for_department;
            $insertDataVisits->for_doctor = $for_doctor;
            $insertDataVisits->for_husband = $for_husband;
            if ($for_husband == 2) {
                $insertDataVisits->child = $child;
            } else {
                $insertDataVisits->child = 0;
            }
            $insertDataVisits->operation_time = '';
            $insertDataVisits->notes = $notes;
            //  $insertDataVisits->user_id = $_SESSION['user_id'];

            $insertDataVisits->discount_type = $discountType;
            $insertDataVisits->discount_ratio = $discountRatio;
            $insertDataVisits->branch_id = $branch_id;

            if ($_SESSION['role_id'] == 19) {
                $insertDataVisits->customer_add = 1;
            } else {
                $insertDataVisits->customer_add = 0;
            }


            if ($_SESSION['role_id'] != 16) {
                $insertDataVisits->user_id = $_SESSION['user_id'];
            }

            $programesetting = R::findOne('programesetting');
            $patient = R::load('patients', $patientId);

            $labSetting = R::findOne('programesettinglab');
            if ($labSetting->vat > 0 && $patient->saudi == 1) {
                $amount = $totaldetectionvalue - $discount;
                $insertDataVisits->vat = $labSetting->vat;
                $vat_value = ($amount * $labSetting->vat) / 100;
                $insertDataVisits->vat_value = $vat_value;
            } else {
                $insertDataVisits->vat = 0;
                $insertDataVisits->vat_value = 0;
            }


            if ($programesetting->refer_doctor == 1) {
                $insertDataVisits->refer_doctor_tb = 0;
                if ($refer_doctor[0] == "*") {
                    $refer_doctor = ltrim($refer_doctor, '*');
                    $insertDataVisits->refer_doctor_tb = 1;
                }
                $insertDataVisits->refer_doctor = $refer_doctor;
            } else {
                if ($for_husband == 1) {
                    $insertDataVisits->refer_doctor = $patient->h_refer_doctor;
                    $insertDataVisits->refer_doctor_tb = $patient->h_refer_doctor_tb;
                } else {
                    $insertDataVisits->refer_doctor = $patient->refer_doctor;
                    $insertDataVisits->refer_doctor_tb = $patient->refer_doctor_tb;
                }
            }

            if ($for_husband == 1) {
                $insertDataVisits->rfc = $patient->rfc;
            } else {
                $insertDataVisits->rfc = $patient->wrfc;
            }


            if ($for_husband == 2) {
                $insertDataVisits->child = $child;
            }

            $insertDataVisits->notes = $notes;

            $this->updateLabInvs($patientId, $visitId, $for_husband);

            R::store($insertDataVisits);
            $this->billPdf($visitId);
            $this->loadSampleIdForInv($visitId);
            $visit = R::load('visits', $visitId);

            calcBalance($visit->patientid);

            $invstDataForERP = $_POST["invstDataForERP"];
            $this->erpSellbillUpdate($visit, $invstDataForERP);

            echo $visitId;

            $this->reserveOldVisit($visitOld);
        }
    }

    private function updateLabInvs($patientId, $visitId, $for_husband, $orgType) {
        $invType = filter_input(INPUT_POST, 'invType');
        $organizationId = filter_input(INPUT_POST, 'organizations');

        if ($invType != 1) {
            $invType = 0;
        }

        R::exec('update investigationresults set deleted = 1 where visitid = ?   ', [$visitId]);

        if ($organizationId > 0 && $orgType == 3) {
            $this->updateLabInvsOrg($patientId, $visitId, $for_husband, $invType, $organizationId);
        } else {
            $this->updateLabInvsNotOrg($patientId, $visitId, $for_husband, $invType);
        }
    }

    private function updateLabInvsOrg($patientId, $visitId, $for_husband, $invType, $orgId) {
        $visitOrg = R::load('organizations', $orgId);
        foreach ($_POST['labInvests'] as $choosen) {
            $externalLab = filter_input(INPUT_POST, 'exLabs' . $choosen);
            $xx = explode('_', $choosen);

            if ($xx[0] == 'offer') {
                $offerDetailId = $xx[1];

                $offerDetail = R::load('invofferdetails', $offerDetailId);

                $investId = $offerDetail->inv_id;
                $price = $offerDetail->price;
                $offerId = $offerDetail->invoffer_id;
                $original_price = $offerDetail->price;

                $org_discount = R::findOne('organization_discount', ' list_id = ? and detect_id = ?
                and detect_cat = ? and offer_id = ?   and deleted = ?  ', [$visitOrg->list_id, $offerDetailId, 4, $offerId, 0]);
                if ($org_discount) {
                    $organ_discount_type = $org_discount->discount_type;
                    $contract_price = $org_discount->contract_price;
                    $patient_hold = $org_discount->patient_hold;
                }
            } else {
                $investId = $choosen;
                $org_discount = R::findOne('organization_discount', ' list_id = ? and detect_id = ?
                and detect_cat = ?  and deleted = ? and offer_id = 0   ', [$visitOrg->list_id, $investId, 2, 0]);
                $invest = R::load('invests', $investId);
                $original_price = $invest->price;
                if ($org_discount) {
                    $organ_discount_type = $org_discount->discount_type;
                    $contract_price = $org_discount->contract_price;
                    $patient_hold = $org_discount->patient_hold;
                }
                $offerId = 0;
                $price = $invest->price;
            }

            $exist = R::findOne('investigationresults', ' investid  = ?   and  visitid = ? and  offer_id = ?   order by id desc
                         ', [$investId, $visitId, $offerId]);

            if (count($exist) > 0) {
                $exist->deleted = 0;
                $exist->patientid = $patientId;
                $exist->forhusband = $for_husband;
                $exist->external_lab = $externalLab;
                R::store($exist);
            } else {
                $this->saveLabInvest($investId, $price, $offerId, $invType, $visitId
                        , $patientId, $for_husband, 0, '', $externalLab, $organ_discount_type, $contract_price
                        , $patient_hold, $original_price);
            }
        }
    }

    private function updateLabInvsNotOrg($patientId, $visitId, $for_husband, $invType) {
        foreach ($_POST['labInvests'] as $choosen) {
            $externalLab = filter_input(INPUT_POST, 'exLabs' . $choosen);
            $xx = explode('_', $choosen);

            if ($xx[0] == 'offer') {
                $offerDetailId = $xx[1];
                $offerDetail = R::load('invofferdetails', $offerDetailId);
                $investId = $offerDetail->inv_id;
                $price = $offerDetail->price;
                $offerId = $offerDetail->invoffer_id;
            } else {
                $investId = $choosen;
                $invest = R::load('invests', $investId);
                $price = $invest->price;
                $offerId = 0;
            }


            $exist = R::findOne('investigationresults', ' investid  = ?   and  visitid = ? and  offer_id = ?   order by id desc
                         ', [$investId, $visitId, $offerId]);

            if (count($exist) > 0) {
                $exist->deleted = 0;
                $exist->patientid = $patientId;
                $exist->forhusband = $for_husband;
                $exist->external_lab = $externalLab;
                R::store($exist);
            } else {
                $this->saveLabInvest($investId, $price, $offerId, $invType, $visitId
                        , $patientId, $for_husband, 0, '', $externalLab, 0, 0
                        , 0, $price);
            }
        }
    }

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

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

        $nextVisitDate = filter_input(INPUT_POST, "nextVisitDate");
        //   $nextVisitTime = filter_input(INPUT_POST, 'nextVisitTime');
        $nextVisitService = filter_input(INPUT_POST, "nextVisitService");
        $nextVisitNotes = filter_input(INPUT_POST, 'nextVisitNotes');
        $patientId = filter_input(INPUT_POST, 'patientId');


        $doctor_percent = 0;
        $for_department = $_SESSION['role_id'];

        try {
            $doctorIn = R::getRow('select * from awusers where user_id = ?', [$_SESSION['user_id']]);
            $detection = R::load('detections', $nextVisitService);
            switch ($detection->type) {
                case 1:
                    $doctor_percent = $doctorIn['pulse_per'];
                    break;

                case 2:
                    $doctor_percent = $doctorIn['session_per'];
                    break;
            }

            $redirectTo = implode(', ', $_POST['redirectTo']);

            $insertDataVisits = R::dispense('visits');
            $insertDataVisits->patientid = $patientId;
            $insertDataVisits->visitdate = $nextVisitDate;
            $insertDataVisits->visittime = date("H:i:s");
            $insertDataVisits->visit_time = date("H:i:s");
            $insertDataVisits->detectionid = $nextVisitService;
            $insertDataVisits->detectionvalue_cash = 0;
            $insertDataVisits->detectionvalue_visa = 0;
            $insertDataVisits->totaldetectionvalue = 0;
            $insertDataVisits->discount = 0;
            $insertDataVisits->restdetectionvalue = 0;
            $insertDataVisits->for_department = $for_department;
            $insertDataVisits->for_doctor = $_SESSION['user_id'];
            $insertDataVisits->for_husband = 0;
            $insertDataVisits->units = 0;
            $insertDataVisits->doctor_percent = $doctor_percent;

            $insertDataVisits->operation_time = '';
            $insertDataVisits->operation_main_id = 0;
            $insertDataVisits->notes = '';
            $insertDataVisits->is_redirect = 1;
            $insertDataVisits->redirect_note = $nextVisitNotes;
            $insertDataVisits->redirect_to = $redirectTo;
            $insertDataVisits->user_id = $_SESSION['user_id'];
            $insertDataVisits->create_date = date('Y-m-d H:i:s'); //$this->today;

            $insertDataVisits->discount_type = 0;
            $insertDataVisits->discount_ratio = 0;

            $insertDataVisits->room_no = '';
            $insertDataVisits->enterance = '';
            $insertDataVisits->p_exit = '';

            $insertDataVisits->res_room_no = '';
            $insertDataVisits->res_enterance = '';

            $insertDataVisits->recep_p_exit = '';

            if ($_SESSION['role_id'] == 19) {
                $insertDataVisits->customer_add = 1;
                $insertDataVisits->recep_p_exit = '';
            } else {
                $insertDataVisits->customer_add = 0;
                $insertDataVisits->recep_p_exit = date("H:i");
            }

            $insertDataVisits->printserial = 0;



            $patient = R::load('patients', $patientId);
            $insertDataVisits->refer_doctor = $patient->refer_doctor;
            $insertDataVisits->refer_doctor_tb = $patient->refer_doctor_tb;
            $insertDataVisits->rfc = $patient->wrfc;

            $visitId = R::store($insertDataVisits);

            $this->loadNextVisits($_SESSION['user_id']);
            $this->smarty->display('visits/next_visits.html');
        } catch (Exception $ex) {
            echo -1;
        }
    }

    function loadNextVisits($doctorId) {
        $nextVisits = R::getAll('SELECT  visits.visitdate ,   detections.title as serviceName
                                            , visits.redirect_note   ,   visits.redirect_to
                                                  FROM visits
                         left  join detections    on detections.id  =  visits.detectionid

               where  visits.user_id = ?   and visits.for_doctor  = ?        and visits.deleted != 1
               and   visits.is_redirect = 1
                order by visits.visitdate desc , visits.id desc  ', [$doctorId, $doctorId]);

        $i = 0;
        foreach ($nextVisits as $nextVisit) {
            $redirectToText = '';
            $redirectTo = explode(',', $nextVisit['redirect_to']);

            $x = 1;
            foreach ($redirectTo as $redirect) {
                if ($redirect > 0) {
                    $doctor = R::getRow('select name  from awusers where user_id = ?', [$redirect]);
                    if ($x > 1) {
                        $redirectToText .= ' - ';
                    }
                    $redirectToText .= $doctor['name'];
                    $x++;
                }
            }

            $nextVisits[$i]['redirectTo'] = $redirectToText;
            $i++;
        }

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

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

    public function archiveRequestAdd($patientId, $visitId, $doctorId, $visitDate, $branch_id) {
        if ($patientId > 0) {

//            $exist = R::count('archive_request', ' patient_id = ? and ready_userid = 0  ', [$patientId]);
//            if ($exist > 0) {
//                echo -2;
//            } else {
            $obj = R::xdispense('archive_request');
            $obj->patient_id = $patientId;
            $obj->request_userid = $_SESSION['user_id'];
            $obj->request_date = date($visitDate . ' H:i:s');
            $obj->doctor_id = $doctorId;
            $obj->visit_id = $visitId;
            $obj->branch_id = $branch_id;
            $obj->create_date = date('Y-m-d H:i:s');

            R::store($obj);
            // echo 1;
//            }
        }
    }

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

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


        $name = filter_input(INPUT_GET, "term");

        $allDocs = R::getAll('SELECT awusers.user_id as id  , awusers.name    FROM awusers
                                                join  awrole     on awrole.id =  awusers.role_id
                                                WHERE awusers.deleted = 0  and awrole.doctor_show = 1
                                                and awusers.name  LIKE "%' . $name . '%"    limit 0,50  ');
//        echo $name . ' - ';
        echo json_encode($allDocs);
    }

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

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

        $dateFrom = filter_input(INPUT_POST, "date_from");
        $dateTo = filter_input(INPUT_POST, "date_to");

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

        if ($dateFrom != '00-00-0000' && !empty($dateFrom)) {
            $dateFrom = date('Y/m/d', strtotime($dateFrom));
        } else {
            $dateFrom = '0000-00-00';
        }

        if ($dateTo != '00-00-0000' && !empty($dateTo)) {
            $dateTo = date('Y/m/d', strtotime($dateTo));
        } else {
            $dateTo = date('Y/m/d');
        }

        $allvisit = R::find('visits', ' deleted = ?    and  visitdate  between ? and ?
                ORDER BY visitdate asc ,  id asc', [0, $dateFrom, $dateTo]);


        foreach ($allvisit as $visit) {
            sendSms($visit->id, 2);
        }
    }

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

    function SMSMobileSampleHadad1() {
        //  sendSms(1, 1);
        //sendSms(530, 2);

        $mobile = '01115271925';

        // send to Egypt only
        $recipient = ltrim($mobile, "2");
        $recipient = ltrim($recipient, "+2");
        $recipient = ltrim($recipient, "02");
        $recipient = ltrim($recipient, "002");
        $recipient = ltrim($recipient, "0");
        $recipientWithCode = "20" . ($recipient);
        $message = 'نسعد بتقديم أفضل الخدمات لعملائنا الكرام';
        $query = [
            'environment' => 1, //1 For Live , 2 For Test,
            'username' => 'oUc7NXwC',
            'password' => '36e1da61469532f112a3adce9711c01d02514a5f0e757a31008f944903102113',
            'language' => 2, //1 For English , 2 For Arabic , 3 For Unicode
            'sender' => 'c9574236504eb5120e0bda1baeb8911675ea3c722b10f8e31095eb4846fdc15f',
            'mobile' => $recipientWithCode,
            'message' => $message
        ];
        $buildQuery = http_build_query($query);
        $requestUrl = "https://smsmisr.com/api/SMS/?" . $buildQuery;

        $curl = curl_init();
        print_r($curl);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt_array($curl, array(
            CURLOPT_URL => $requestUrl,
            CURLOPT_HEADER => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_HTTPHEADER => array('Content-Type:application/json', 'Content-Length:0')
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        echo $response;
    }

    function testCusSms() {
        sendSms(529, 3);
    }

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

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

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

        if ($visitId > 0) {
            $visit = R::getRow('select visits.id  ,  awusers.name as  visitDoctor
                                                , visits.visitdate ,   detections.title as visitDetect
                                                 ,   awrole.name as visitDept  ,   regions.name as visitRegion
                                                 ,   sub_regions.name as visitSubRegion
                from   visits  
                join     detections             on  detections.id = visits.detectionid  
                left  join  awrole               on awrole.id =   visits.for_department
                left join     awusers           on  awusers.user_id = visits.for_doctor  
                 left join     sub_regions           on  sub_regions.id = visits.sub_region_id  
                left  join  regions                on regions.id =   sub_regions.region_id
                where visits.id = ?  ', [$visitId]);


            $user = R::getRow('SELECT user_id , name  FROM awusers 
                    WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);


            $visits_follows = R::getAll('select visits_follows.id  ,  awusers.name as  userName
                , date(visits_follows.create_date) as followDate  , visits_follows.comment
                 , visits_follows.comment_from , visits_follows.user_id   
                 , TIME_FORMAT(time(visits_follows.create_date), "%h:%i %p")  as followTime
                from   visits_follows  
                join     awusers           on  awusers.user_id = visits_follows.user_id  
                where visits_follows.visit_id = ?  order by id asc   ', [$visitId]);



//            $this->smarty->assign('date', date('Y-m-d'));
//            $this->smarty->assign('time', date('H:i:s'));
            $this->smarty->assign('visit', $visit);
            $this->smarty->assign('user', $user);
            $this->smarty->assign('visits_follows', $visits_follows);
        }


//Html files

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        patientdata::patientdatashow($this->smarty, $this->hosturl);
        $this->smarty->display('visits/follows.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

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

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

        $data = R::xdispense('visits_follows');
        $data->visit_id = $visitId;
        $data->create_date = date('Y-m-d H:i:s');
        $data->user_id = $_SESSION['user_id'];

        try {
            $data->id = R::store($data);

            $visits_follow = R::getRow('select visits_follows.id  ,  awusers.name as  userName
                , date(visits_follows.create_date) as followDate  , visits_follows.comment
                 , visits_follows.comment_from 
                 , TIME_FORMAT(time(visits_follows.create_date), "%h:%i %p")  as followTime
                from   visits_follows  
                join     awusers           on  awusers.user_id = visits_follows.user_id  
                where visits_follows.id = ?   ', [$data->id]);


            $this->smarty->assign('data', $visits_follow);
            $this->smarty->display('visits/follow.html');
        } catch (Exception $e) {
            echo -1;
        }
    }

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

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

        $patId = filter_input(INPUT_POST, "patId");
        $mobile = filter_input(INPUT_POST, "mobile");
        $orgPatNo = filter_input(INPUT_POST, "orgPatNo");
        if ($orgPatNo != '') {
            $allPatients = $this->patByOrgPatNo($orgPatNo);
        } else {
            $allPatients = $this->patByPatInfo($patId, $mobile);
        }

        echo json_encode($allPatients);
    }

    function patByPatInfo($patId, $mobile) {
        $colExt = '   ';
        if ($patId != '') {
            $colExt .= '  and   wifenationalid =  "' . $patId . '"  ';
        }

        if ($mobile != '') {
            $colExt .= '  and  ( phone =  "' . $mobile . '" or    mobile = "' . $mobile . '"  )   ';
        }


        $allPatients = R::getRow('SELECT id , CONCAT(statusno , " -  ", COALESCE(wifename,""), " -  ", COALESCE(husdandname,"")) AS name
                 , saudi FROM patients    WHERE deleted = ? and done = ?  ' . $colExt . '         limit 0,50  ', [0, 1]);

        return $allPatients;
    }
    
    
        function patByOrgPatNo($orgPatNo) {
        $orgPatNos = R::findOne('organizations_patient_no', ' deleted = 0 and patient_no = ?  ', [$orgPatNo]);
        $colExt .= '  and   id = ' . $orgPatNos->patient_id;
        $allPatients = R::getRow('SELECT id , CONCAT(statusno , " -  ", COALESCE(wifename,""), " -  ", COALESCE(husdandname,"")) AS name
                 , 1 as saudi FROM patients    WHERE deleted = ? and done = ?  ' . $colExt . '         limit 0,50  ', [0, 1]);

        return $allPatients;
    }

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

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

        R::selectDatabase('default');
        $paid_cash = filter_input(INPUT_POST, "paid_cash");
        $paid_visa = filter_input(INPUT_POST, "paid_visa");
        $patientId = filter_input(INPUT_POST, "patientId");
        $branch_id = filter_input(INPUT_POST, "branch_id");
        $notes = filter_input(INPUT_POST, "advanceNotes");

        $this->addAdvancePay($patientId, $paid_cash, $paid_visa, $branch_id, $notes, 1);
    }

    public function addAdvancePay($patientId, $paid_cash, $paid_visa, $branch_id, $notes, $printReceipt) {
//check login
        autho::checkautho($this->hosturl);

        R::selectDatabase('default');

        $insert = R::xdispense('advance_payment');
        $insert->patient_id = $patientId;
        $insert->detectionvalue_cash = $paid_cash;
        $insert->detectionvalue_visa = $paid_visa;
        $insert->user_id = $_SESSION['user_id'];
        $insert->type = 0;              ## 0 pay , 1 refund
        $insert->paymentfrom = 0;              ## 0 royal , 1 erp
        $insert->pay_date = date("Y/m/d");
        $insert->branch_id = $branch_id;
        $insert->notes = $notes;

        if ($paid_cash > 0) {
            $insert->printserial = $this->printSerial('last_serial');
        } else {
            $insert->printserial = 0;
        }

        $insert->create_date = date('Y-m-d H:i:s'); //$this->today;

        $insertId = R::store($insert);

        ##erp fatma
        if ($paid_cash > 0 || $paid_visa > 0) {
            calcBalance($patientId);
            //$this->erpSellbillUpdate($visit);
            $_POST['clientIdForERP'] = $patientId;
            $_POST['billsItr'] = 1;
            $_POST['visitid1'] = 0;
            $_POST['payVisitId1'] = 0;
            $_POST['cashPay1'] = $paid_cash;
            $_POST['visaPay1'] = $paid_visa;
            $_POST['billDis1'] = 0;
            $_POST['notBillPay'] = 1;
            $this->payERPBills();
            }

        if ($insertId > 0) {
            if ($paid_cash > 0 && $printReceipt == 1) {
                $this->printAdvanceRecept($insertId);
            }
        } else {
            echo -1;
        }
    }

    public function printAdvanceRecept($advancePaymentId) {
        try {
            $advancePayment = R::load('advance_payment', $advancePaymentId);
            $this->smarty->assign('printserial', $advancePayment->printserial);

            $user = R::findOne('awusers', 'user_id = ?', [$advancePayment->user_id]);
            $this->smarty->assign('user_name', $user->name);

            $patient = R::load('patients', $advancePayment->patient_id);
            $pat_name = $patient->wifename . ' - ' . $patient->husdandname;
            $this->smarty->assign('pat_name', $pat_name);

            $detection_name = ' دفعة مقدمة ';

            $this->smarty->assign('notes', $advancePayment->notes);
            $this->smarty->assign('detection', $detection_name);
            $this->smarty->assign('visitdate', date("Y/m/d", strtotime($advancePayment->pay_date)));
            $this->smarty->assign('detectionvalue_cash', $advancePayment->detectionvalue_cash);
            $this->smarty->assign('detectionvalue_visa', $advancePayment->detectionvalue_visa);

            $this->smarty->display('visits/print.html');
#################################
        } catch (Exception $ex) {
            echo '-1';
        }
    }

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

        $patientId = filter_input(INPUT_POST, "patientId");
        if ($patientId > 0) {
            try {
                $lastAdvanceAll = $this->getlastAdvanceObj($patientId);
                if (count($lastAdvanceAll) > 0) {
                    $lastVisits = $this->getlastAdvanceObj($patientId, " limit 0,3 ");
                    $this->getlastAdvanceCommon($patientId, $lastVisits, count($lastAdvanceAll));
                }
            } catch (Exception $ex) {
                echo -1;
            }
            $this->smarty->display('visits/advance_payment.html');
        }
    }

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

        $patientId = filter_input(INPUT_POST, "patientId");
        if ($patientId > 0) {
            try {
                $lastAdvances = $this->getlastAdvanceObj($patientId);

                if (count($lastAdvances) > 0) {
                    $this->getlastAdvanceCommon($patientId, $lastAdvances);
                }
            } catch (Exception $ex) {
                echo -1;
            }
            $this->smarty->display('visits/advance_payment.html');
        }
    }

    function getlastAdvanceObj($patientId, $limitSql = "") {
//        r::debug(true, 2);

        $lastVisits = R::getAll('SELECT  advance_payment.id as advanceId   , advance_payment.pay_date
                                                   , advance_payment.detectionvalue_cash   , advance_payment.detectionvalue_visa
                                                     , advance_payment.notes as visitNote  , advance_payment.branch_id
                                                      , advance_payment.printserial
                                                  FROM advance_payment
               where  advance_payment.patient_id = ?  and    advance_payment.deleted != ?   
                order by advance_payment.pay_date desc , advance_payment.id desc  ' . $limitSql, [$patientId, 1]);
//        r::debug(false);
        return $lastVisits;
    }

    function getlastAdvanceCommon($patientId, $lastVisits, $all = 0) {
        $programesetting = R::findOne('programesetting');
        $this->smarty->assign('system_type', $programesetting->system_type);
        $this->smarty->assign('branchesActivate', $programesetting->branches);

        $i = 0;
        foreach ($lastVisits as $data) {

            if ($programesetting->branches == 1) {
                $branch = R::load('branches', $data['branch_id']);
                $lastVisits[$i]['branch_name'] = $branch->name;
            }
            $i++;
        }

        if ($all > 3) {
            $this->smarty->assign('lastAdvAll', $all);
            $this->smarty->assign('patientId', $patientId);
        }

        $this->smarty->assign('advancePays', $lastVisits);
        $this->smarty->assign('advancePaysCount', count($lastVisits));
    }

    public function printAdvReceipt() {
        $advancePaymentId = filter_input(INPUT_POST, "id");
        $this->printAdvanceRecept($advancePaymentId);
    }

    ##############################################################
    
        function printJobOrder() {
        //check login
        autho::checkautho($this->hosturl);
        $visitId = filter_input(INPUT_POST, "visitId");

        $visit = R::load('visits', $visitId);
        $this->smarty->assign('printserial', $visit->printserial);

        $patient = R::load('patients', $visit->patientid);
        $pat_name = $this->patName($visit->for_husband, $patient, $visit->child);
        $this->smarty->assign('pat_name', $pat_name);

        $this->jobOrderPrint($visit, $patient);
        $this->smarty->display('visits/printjoborder.html');
    }

    function jobOrderPrint($visit, $patient) {
        $this->smarty->assign('patient', $patient);
        $this->smarty->assign('visitdate', date("d-m-Y g:ia", strtotime($visit->create_date)));

        $doctorName = $this->labDoctorName($visit->for_doctor, $visit->refer_doctor, $visit->refer_doctor_tb);
        $this->smarty->assign('doctorName', $doctorName);


        $user = R::getRow('SELECT name FROM awusers 
                    WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);
        $this->smarty->assign('doneBy', $user['name']);

        $this->visitTests($visit->id);


//        $this->visitTests($visit->id);
//        $this->smarty->assign('visit', $visit);
//        if (!file_exists('../../upload/job_order/' . $patient->statusno . '.png')) {
//            $this->patientLinkQr($patient);
//        }
    }

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

    function billPdf($visitId) {
        $visit = R::load('visits', $visitId);
        $patient = R::load('patients', $visit->patientid);
        if ($visit->bill_pdf != 1) {
            $fileName = 'xxx';
            $htmlHead = $this->billPdfHeader();
            $htmlFoot = $this->billPdfFooter();
            $htmlBody = $this->billPdfBody($visit, $patient);
            $html = $htmlHead . ' ' . $htmlBody . ' ' . $htmlFoot;
            generatePdf($html, 'bills_pdf', $visitId);
            $url = 'http://api.naslab.gt4it.com/api/visit';
            $realpath = realpath('../../upload/bills_pdf/' . $visitId . '.pdf');
            $data = array(
                'visit_id' => $visitId
                , 'patient_id' => $visit->patientid
                , 'bill_file' => new CURLFile($realpath, 'application/pdf')
            );
            $res = sendFileWithData($data, $url);
            if ($res == 1) {
                r::exec(' update visits set bill_pdf = ? where id = ? ', [1, $visitId]);
            }
        }
    }

    function billPdfHeader() {
        $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;
        }
        
    .bold { font-weight: bold;}
    .h1 { font-weight: 900; font-size: 28px;}
    .h2 { font-weight: 700; font-size: 26px;}
    @media print {
        #patient_profile_print {
            transform: scale(.9);
        }
        .bold { font-weight: bold;}
        .h1 { font-weight: 900; font-size: 28px;}
        .h2 { font-weight: 700; font-size: 26px;}
        .table>thead>tr>th{
            background: #DDD !important;
            border: 1px solid #DDD !important;
        }
        .table>tbody>tr>td, .table>thead>tr>td{
            border: 1px solid #DDD !important;
        }
    }
           </style> </head>   <body>  ';

        $htmlHead .= ' 
            <div class="row col-md-12" style="background: #f1f3fa url(' . $this->hosturl . '/views/obgy/_assets/custom/images/nas.png) no-repeat top center !important;
     background-position: center;
     background-border: none !important; ;
     background-blend-mode: lighten;
     background-size: 100% !important;">
    ';

        return $htmlHead;
    }

    function billPdfFooter() {
        $htmlFoot = '
                 
                 </div>';

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

    function billPdfBody($visit, $patient) {
        $dataArray = getPatientDataArr($patient);
        $labSetting = R::findOne('programesettinglab');
        $setting = R::findOne('programesetting');
        $htmlBody = '';
        $htmlBody .= $this->billPdfData($visit, $patient);
        $htmlBody .= $this->billPdfData1($visit, $patient, $dataArray);
        $htmlBody .= $this->billPdfData2($visit, $labSetting);
        $htmlBody .= $this->billPdfData3($visit, $labSetting, $setting);
        return $htmlBody;
    }

    function billPdfData($visit, $patient) {

        $visit->visitdate = date("d-m-Y g:ia", strtotime($visit->create_date));
        $visit->totalAmount = $visit->totaldetectionvalue - $visit->discount + $visit->vat_value;

        $htmlBody = '
        <div class="col-md-12">
        <table style="width: 98%;" class="noborder">
            <tr>
                <td class="enfnt bold txtc wds30" >
                    <h4 class="enfnt txtc" >
                       <img  style="width:  125px ;height: 125px;"   src="' . $this->hosturl . '/../upload/linkqrcodes/' . $patient->statusno . '.png">
                    </h4>
                    <h4 class="enfnt txtc bold" >
                        <span>   Invoice </span>
                    </h4>
                </td>
                <td class="arbfnt bold txtc" >
                          <h3  class="arbfnt bold txtc" >Invoice Tax  - ضريبية فاتورة     </h3> 
                    <h4  class="enfnt bold txtc" >Invoice No. ' . $visit->printserial . ' </h4>     
                    <h4  class="enfnt bold txtc" >Invoice Date : ' . $visit->visitdate . ' </h4>         
                    <h4  class="enfnt bold txtc" > Payment Method :  ' . $this->payingMethod($visit) . ' </h4> 
                </td>
                <td class="enfnt bold txtc wds30" >
                    <h4 class="enfnt txtc" >
                        <img  style="width:  125px ;height: 125px;"   src="' . $this->hosturl . '/../upload/linkqrcodes/' . $patient->statusno . '.png">
                    </h4>
                    <h4 class="enfnt txtc bold" >
                        <span>   My Results  </span>
                    </h4>
                </td>
            </tr>
        </table>
    </div>
    <hr style="border: 1px solid black;">   
';

        return $htmlBody;
    }

    function billPdfData1($visit, $patient, $dataArray) {
        switch ($patient->saudi) {
            case 1:
                $nationality = 'Non Saudi';
                break;

            default:
                $nationality = 'Saudi';
                break;
        }

        $doctorName = $this->labDoctorName($visit->for_doctor, $visit->refer_doctor, $visit->refer_doctor_tb);
        $visit->totalAmount = $visit->totaldetectionvalue - $visit->discount + $visit->vat_value;

        $htmlBody = '
    <div class="col-md-12">
        <table style="width: 98%;" class="noborder">

            <tr>
                <td class="enfnt bold txtl" >Patient Name</td>
                <td class="enfnt  txtc" >' . $dataArray['name'] . '</td>
                <td class="arbfnt bold txtr" >اسم المريض </td>
            </tr>

            <tr>
                <td class="enfnt bold txtl" >Patient No</td>
                <td class="enfnt  txtc" >' . $patient->statusno . '</td>
                <td class="arbfnt bold txtr" >كود  المريض </td>
            </tr>


            <tr>
                <td class="enfnt bold txtl" >Patient ID</td>
                <td class="enfnt  txtc" >' . $patient->wifenationalid . '</td>
                <td class="arbfnt bold txtr" >رقم الهوية    </td>
            </tr>

            <tr>
                <td class="enfnt bold txtl" >Nationality</td>
                <td class="enfnt  txtc" >' . $nationality . '</td>
                <td class="arbfnt bold txtr" >الجنسية    </td>
            </tr>

            <tr>
                <td class="enfnt bold txtl" >Age</td>
                <td class="enfnt  txtc" >' . $dataArray['ageAll'] . '</td>
                <td class="arbfnt bold txtr" >العمر   </td>
            </tr>
            <tr>
                <td class="enfnt bold txtl" >Gender</td>
                <td class="enfnt  txtc" >' . $dataArray['sexTxt'] . '</td>
                <td class="arbfnt bold txtr" >النوع   </td>
            </tr>

            <tr>
                <td class="enfnt bold txtl" >Doctor</td>
                <td class="enfnt  txtc" >' . $doctorName . '</td>
                <td class="arbfnt bold txtr" >الطبيب   </td>
            </tr>

        </table>
    </div>
    
';

        return $htmlBody;
    }

    function billPdfData2($visit, $labSetting) {
        $htmlBody = '
         <div class="col-md-12">
        <table style="width: 98%;" class="table" >
            <thead>
                <tr>
                     <th class="arbfnt bold txtc">Test Name - الاختبار اسم    </th>>
                    <th class="arbfnt bold txtc" >Price - السعر </th>
                </tr>
            </thead>
            <tbody>   
';

        $visitOffers = $this->visitOffers($visit->id);
        $visitTests = $this->visitTestsWithoutOffers($visit->id);

        foreach ($visitOffers as $offer) {
            $htmlBody .= '
                <tr>
                    <td class="enfnt  txtc" >' . $offer['name'] . '</td>
                    <td class="enfnt  txtc" > ' . $offer['price'] . '  ' . $labSetting->currency . '</td>
                </tr>          
';
        }

        foreach ($visitTests as $test) {
            $htmlBody .= '
                <tr>
                    <td class="enfnt  txtc" >' . $test['name'] . '</td>
                    <td class="enfnt  txtc" >' . $test['price'] . ' ' . $labSetting->currency . ' </td>
                </tr>            
';
        }




        $htmlBody .= '
            </tbody>
        </table>
    </div>

    <hr style="border: 1px solid black;">
';

        return $htmlBody;
    }

    function billPdfData3($visit, $labSetting, $setting) {

        $visit->totalAmount = $visit->totaldetectionvalue - $visit->discount + $visit->vat_value;

        $htmlBody = '
        <div class="col-md-12">
        <table style="width: 98%;" class="noborder">

            <tr>
                <td class="enfnt bold txtl" >Total (Excluding VAT)</td>
                <td class="enfnt  txtc" > ' . $visit->totaldetectionvalue . '  ' . $labSetting->currency . '</td>
                <td class="arbfnt bold txtr" >( الإجمالي (غير شامل القيمة المضافة  </td>
            </tr>

            <tr>
                <td class="enfnt bold txtl" >Total VAT</td>
                <td class="enfnt  txtc" >   ' . $visit->vat_value . '  ' . $labSetting->currency . '</td>
                <td class="arbfnt bold txtr" >  مجموع ضريبة القيمة المضافة </td>
            </tr>

            <tr>
                <td class="enfnt bold txtl" >Discount Total</td>
                <td class="enfnt  txtc" >   ' . $visit->discount . '  ' . $labSetting->currency . '</td>
                <td class="arbfnt bold txtr" >مجموع الخصومات    </td>
            </tr>

            <tr>
                <td class="enfnt bold txtl" >Total Amount Due</td>
                <td class="enfnt  txtc" > ' . $visit->totalAmount . '  ' . $labSetting->currency . '</td>
                <td class="arbfnt bold txtr" >اجمالي المبلغ المستحق   </td>
            </tr>

        </table>
    </div>
    <hr style="border: 1px solid black;">
    <div class="col-md-12">
        <table style="width: 98%;" class="noborder">

            <tr>
                <td class="enfnt bold txtl" ></td>
                <td class="arbfnt bold txtr" >Phone :    ' . $setting->phone . '</td>
            </tr>

        </table>
    </div>
';

        return $htmlBody;
    }

    function payingMethod($visit) {
        $payingMethod = '';
        if ($visit->detectionvalue_cash > 0) {
            $payingMethod .= ' cashe';
        }
        if ($visit->detectionvalue_visa > 0) {
            if ($visit->detectionvalue_cash > 0) {
                $payingMethod .= ' and ';
            }
            $payingMethod .= ' visa';
        }
        $this->smarty->assign('payingMethod', $payingMethod);
        return $payingMethod;
    }

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

    public function visitPeriodEdit() {

        $alldata = R::getAll(' select *  from  visit_periods   where deleted  != 1 ');

        $this->smarty->assign('alldata', $alldata);
        $this->smarty->display('visits/periodeditmodel.html');
    }

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

        $periodId = filter_input(INPUT_POST, "periodId");
        $visitDate = filter_input(INPUT_POST, 'visitdate');
        $branchId = filter_input(INPUT_POST, 'branchId');

        $visits = R::count('visits', 'deleted = 0 and visit_period = ? and branch_id = ? 
                         and visitdate = ?  ', [$periodId, $branchId, $visitDate]);

        echo $visits;
    }

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

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

        ### insert into table
        $newtable = R::xdispense($tableName);
        $newtable->$colName = "";

        $insertid = R::store($newtable);

        echo $insertid;
    }

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

    public function payForVisit() {
//check login
        autho::checkautho($this->hosturl);
        $visitId = filter_input(INPUT_POST, "visitId");
        try {
            if ($visitId > 0) {
                $visit = R::load('visits', $visitId);
                $visitDept = visitDept($visitId);
                if ($visitDept > 0) {
                    $this->payvalCommon($visitId, $visitDept, 0, $visit->patientid, 0, '', $visit->branch_id);
                } else {
                    echo -2;
                }
            }
        } catch (Exception $ex) {
            echo -1;
        }
    }

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

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

        $orgId = filter_input(INPUT_POST, 'id');
        $orgDiscountType = filter_input(INPUT_POST, 'discountType');

        if ($orgDiscountType == 3) {
            $this->orgLabCompleteDiscount($orgId);
        } elseif ($orgDiscountType == 2) {
            $this->orgLabSimpleDiscount($orgId);
        }
    }

    function orgLabSimpleDiscount($orgId) {
        $org = R::getRow('SELECT COALESCE(center_discount ,0)   as center_discount  ,
                COALESCE(organization_discount ,0)   as organization_discount  , discount_type
                FROM organizations WHERE id = ? ', [$orgId]);

        $par_discount = $org['organization_discount'] - $org['center_discount'];
        if (!($org['discount_type'] >= 0)) {
            $org['discount_type'] = 0;
        }

        $result = array(
            "discountRatio" => $par_discount,
            "discountRatioType" => $org['discount_type']
        );

        echo json_encode($result);
    }

    function orgLabCompleteDiscount($orgId) {

        $this->Invests($orgId);
        $this->offers($orgId);

        $this->smarty->display('visits/invest_select.html');
    }

    function Invests($orgId) {
        $visitOrg = R::load('organizations', $orgId);
        $invests = R::getAll('select invests.id , invests.name , invests.price , invests.type as external
                                            , 0 as discount   , invests.price as  hold , invests.price as originalPrice
                                                    from invests
                                                   join  investcats      on    investcats.id = invests.investcatid
                                                 where   invests.deleted = 0 and investcats.deleted = 0
                                                 order by   invests.periority  desc  , invests.name asc ');

        $i = 0;
        foreach ($invests as $invest) {
            $org_discount = R::findOne('organization_discount', ' list_id = ? and detect_id = ?
                and detect_cat = ?  and deleted = ? and offer_id = 0   ', [$visitOrg->list_id, $invest['id'], 2, 0]);
                
            
            
            if ($org_discount && $org_discount->contract_price > 0) {

                if ($org_discount->discount_type == 1) {
                    $org_discount->patient_hold = ($org_discount->discount_type * $org_discount->patient_hold ) / 100;
                }
                $par_discount = $org_discount->contract_price - $org_discount->patient_hold;

                $invests[$i]['price'] = $org_discount->contract_price;
                $invests[$i]['hold'] = $org_discount->patient_hold;
                $invests[$i]['discount'] = $par_discount;
            }
            $i++;
        }
        $this->smarty->assign('invests', $invests);
    }

    function offers($orgId) {
        $visitOrg = R::load('organizations', $orgId);
        $invoffers = R::findall('invoffer', 'active = ? and  del = ? ', [1, 0]);
        foreach ($invoffers as $offer) {
            $offerInvests = R::getAll('select  invofferdetails.id , invests.name , invofferdetails.price
                , invests.type as external    , 0 as discount   , invofferdetails.price as  hold
                , invofferdetails.price as originalPrice
                         from invofferdetails
                           join  invests            on    invests.id = invofferdetails.inv_id
                             where    invofferdetails.invoffer_id = ? and  invofferdetails.del = ?
                               order by  invests.investcatid asc ,   invests.name asc  ', [$offer->id, 0]);

            $i = 0;
            $offer->price = 0;
            $offer->hold = 0;
            foreach ($offerInvests as $offerInv) {
                $org_discount = R::findOne('organization_discount', ' list_id = ? and detect_id = ?
                and detect_cat = ? and offer_id = ?   and deleted = ?  ', [$visitOrg->list_id, $offerInv['id'], 4, $offer->id, 0]);

                if ($org_discount && $org_discount->contract_price > 0) {

                    if ($org_discount->discount_type == 1) {
                        $org_discount->patient_hold = ($org_discount->discount_type * $org_discount->patient_hold ) / 100;
                    }
                    $par_discount = $org_discount->contract_price - $org_discount->patient_hold;
                    $offer->price += $org_discount->contract_price;
                    $offer->hold += $org_discount->patient_hold;
                    $offerInvests[$i]['price'] = $org_discount->contract_price;
                    $offerInvests[$i]['hold'] = $org_discount->patient_hold;
                    $offerInvests[$i]['discount'] = $par_discount;
                }
                $i++;
            }

            $offer->offerInvests = $offerInvests;
        }
        $this->smarty->assign('invoffers', $invoffers);
    }

    function orgDiscountObj($organization_id, $detect_id, $detect_cat, $offerId = 0) {
        $visitOrg = R::load('organizations', $organization_id);
        $org_discount = R::findOne('organization_discount', ' list_id = ? and detect_id = ?
            and detect_cat = ? and offer_id = ?
                and deleted = ?  ', [$visitOrg->list_id, $detect_id, $detect_cat, $offerId, 0]);
        if (!($org_discount)) {
            $org = r::xdispense('organization_discount');
            $org->list_id = $visitOrg->list_id;
            $org->detect_id = $detect_id;
            $org->detect_cat = $detect_cat;
            $org->offer_id = $offerId;
            r::store($org);
            $org_discount = R::findOne('organization_discount', ' list_id = ? and detect_id = ?    and detect_cat = ?
                 and offer_id = ?   and deleted = ?  ', [$visitOrg->list_id, $detect_id, $detect_cat, $offerId, 0]);
        }

        return $org_discount;
    }

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

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

        $id = filter_input(INPUT_POST, 'id');
        $orgDiscountType = filter_input(INPUT_POST, 'orgDiscountType');

        if ($orgDiscountType == 3 || $orgDiscountType == 2) {
            $allRayCats1 = $this->raysCats($id, ' and displayorder  in (1 , 2) ', $orgDiscountType);
            $allRayCats2 = $this->raysCats($id, ' and displayorder  = 3 ', $orgDiscountType);
            $allRayCats3 = $this->raysCats($id, ' and displayorder  in (4 , 5) ', $orgDiscountType);
            $allRayCats4 = $this->raysCats($id, ' and displayorder  between 6 and  11 ', $orgDiscountType);
            $allRayCats5 = $this->raysCats($id, ' and displayorder  > 11 ', $orgDiscountType);
            $otherRays = $this->raysCats($id, ' and displayorder  = 0 ', $orgDiscountType);
            $favoritesRays = $this->raysCats($id, ' and favorite  = 1 ', $orgDiscountType);

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

            $this->smarty->display('visits/rays_prices.html');
        }
    }

    function raysCats($orgId, $ext, $type) {
        $visitOrg = R::load('organizations', $orgId);
        $cats = R::findall('rayscats', 'deleted = ?  ' . $ext . ' order by displayorder ', [0]);
        foreach ($cats as $cat) {
            $rays = R::findall('rays', 'rayscatid = ? and deleted = ?', [$cat->id, 0]);
            foreach ($rays as $ray) {
                $ray = $this->ray($ray, $visitOrg->list_id, $type, $orgId);
            }
            $cat->rays = $rays;
        }

        return $cats;
    }

    function ray($ray, $list_id, $type, $orgId) {
        switch ($type) {
            case 2:
                $ray = $this->raySimple($ray, $orgId);
                break;

            case 3:
                $ray = $this->rayComplete($ray, $list_id);
                break;
        }
        return $ray;
    }

    function raySimple($ray, $orgId) {
        if ($orgId > 0) {

            $org = R::getRow('SELECT COALESCE(center_discount ,0)   as center_discount  ,
                COALESCE(organization_discount ,0)   as organization_discount  , discount_type
                FROM organizations WHERE id = ? ', [$orgId]);

            $par_discount = $org['organization_discount'] - $org['center_discount'];

            if ($org['discount_type'] == 1) {
                $discount = ($ray->price * $par_discount) / 100;
            } else {
                $discount = $par_discount;
            }

            $ray->originalPrice = $ray->price;
            $ray->contract = $ray->price;
            $ray->hold = $ray->price = $ray->price - $discount;
            $ray->discount = $discount;
        }
        return $ray;
    }

    function rayComplete($ray, $list_id) {
        if ($list_id > 0) {
            $org_discount = R::findOne('organization_discount', ' list_id = ? and detect_id = ?
                and detect_cat = ?  and deleted = ? and offer_id = 0   ', [$list_id, $ray->id, 3, 0]);
            if ($org_discount && $org_discount->contract_price > 0) {
                if ($org_discount->discount_type == 1) {
                    $org_discount->patient_hold = ($org_discount->discount_type * $org_discount->patient_hold ) / 100;
                }
                $par_discount = $org_discount->contract_price - $org_discount->patient_hold;
                $ray->originalPrice = $ray->price;
                $ray->price = $org_discount->patient_hold;
                $ray->contract = $org_discount->contract_price;
                $ray->hold = $org_discount->patient_hold;
                $ray->discount = $par_discount;
            } else {
                $ray->originalPrice = $ray->price;
                $ray->contract = $ray->price;
                $ray->hold = $ray->price;
                $ray->discount = 0;
            }
        }
        return $ray;
    }

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

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

}
