<?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("visits_common.php"); //general functions
//here will call all php pages
        require_once("_header.php");
        require_once("_sidebar.php");
        require_once("_leftsidebar.php");
        require_once("_footer.php");
    }

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

        $this->initialBtns();
        $this->initialVisits();

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

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

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

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

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

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

        $this->initialVisitsLab();

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

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

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $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);
    }

    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,
                "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,
                "refer_doctor" => $refer_doctor,
                "for_husband" => $visit->for_husband
            );

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

        if ($visitId > 0) {

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

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

            if ($organizationId > 0 && $visit->organization_id != $organizationId) {
                $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;
            } else if (!($organizationId > 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');



            $programesetting = R::findOne('programesetting');
            $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;


            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) {
                $detection = R::load('detections', $detectionID);
                $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) {
                //  echo 'xxxxx';
                $this->addVisitOrder($visitId, $new_date, $for_doctor);
            }


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

                updateToSite($data);
            }

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

            $this->erpSellbillUpdate($visit);

            echo $visitId;

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

    function updateArchiveRequest($visitId, $patientID, $visitDate, $for_doctor) {
        $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->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');

        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 = $ray;
                        $in->tableName = 'mainantenentalrays';
                    }

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

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

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

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

                    foreach ($PatientRayByDateWifeAnd as $in) {
                        $ray = R::load('rays', $in->rayid);
                        $in->invname = $ray->name;
                        $in->origin = $ray;
                        $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->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) {
        $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 = ?   ', [$visitDate, $doctorId]);
                $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');

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




        $organizationId = filter_input(INPUT_POST, 'organizations');
        $insertDataVisits->organization_id = $organizationId;
        if ($organizationId > 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 = ? ', [$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;
        }


        $detection = R::load('detections', $detectionID);
        $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;
        }

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



//                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');
        $getprice = R::getRow('SELECT detectionval , min_paid , units FROM detections WHERE id ="' . $dtid . '"');

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

        $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') {
            $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);

        if ($tableName == 'organizations' && $programesetting->organizations != 1) {
            $this->smarty->display('visits/organizations.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');

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

        echo json_encode($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);

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

        if ($visit->for_husband == 1) {
            $name = $patient->husdandname;
            $date = $patient->husbanddateofbirth;
            $gender = 'M';
        }
        ###
        else if ($visit->for_husband == 2) {
            $child = R::load('patients_childs', $visit->child);
            $date = $child->birth_date;

            if ($child->gender == 1) {
                $gender = 'M';
            } else {
                $gender = 'F';
            }

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

        $this->smarty->assign('name', $name);
        $this->smarty->assign('title', $title);
        $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 . 'Y';
        } elseif ($interval->m > 0) {
            $age = $interval->m . 'M';
        } elseif ($interval->d > 0) {
            $age = $interval->d . 'D';
        } else {
            $age = '';
        }

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

        $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
                                                                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;
                $invs = R::getAll('SELECT   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 = ?  ', [0, $visitId, $data['sampletype']]);

                $invests = '';
                $x = 1;
                foreach ($invs as $row) {
                    if ($row['type'] == 1) {
                        $showDocName = 1;
                    }
                    if ($x > 1) {
                        $invests .= ' , ';
                    }
                    $invests .= $row['invName'];
                    $x++;
                }


                $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   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;
        $showDocName = 0;
        foreach ($empty_dates as $row) {
            if ($row['type'] == 1) {
                $showDocName = 1;
            }
            if ($x > 1) {
                $invests .= ' , ';
            }
            $invests .= $row['invName'];
            $x++;
        }



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

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

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

            $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
            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'] .= '
                               <div class="md-checkbox-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> ';

            $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
                                                  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) {
        $i = 0;
        foreach ($lastVisits as $data) {

## 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++;
        }


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

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

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

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

        $insertDataVisits = R::dispense('visits');
        $insertDataVisits->patientid = $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;

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

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

        $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  for_department = ' . $deptId;
            $this->smarty->assign('isLab', 1);
        }

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


        if ($doctorId > 0) {
            $ext .= ' and  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  for_doctor   in  (' . $user['related_dr'] . ' ) ';
        }

//        R::debug(true, 2);
        $allvisit = R::find('visits', ' deleted = ?    ' . $ext . '
                        and  visitdate  between ? and ?
                ORDER BY visitdate asc ,  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->patientName = $patient['wifename'];
            $visit->patientstatusno = $patient['statusno'];
            $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'] . ' )';
                } 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;
            }

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

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

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

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


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

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

        $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 = $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->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');

            $visits = R::count('visits', 'deleted = 0 and for_doctor = ? and visitdate = ?
                      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();
        }

        $visitDate = filter_input(INPUT_POST, 'visitdate');
        $detectionID = 4;
        $detectionValue_cash = filter_input(INPUT_POST, 'detectionvalue_cash');
        $detectionValue_visa = filter_input(INPUT_POST, 'detectionvalue_visa');
        $totaldetectionvalue = filter_input(INPUT_POST, 'totaldetectionvalue');

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

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

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


        if ($detectionValue_cash > 0) {
            $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 ($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;
        }

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

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

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

        $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->gender = $gender;
        } else {
            if ($gender == 1) {
                $patient->husdandname = $wifename;
                $patient->husbandtypeid = $wifetype;
                $patient->doctor1 = -1;
                $patient->h_doctor1 = $for_doctor;
                $patient->husbanddateofbirth = $dateofbirth;
            } else {
                $patient->wifename = $wifename;
                $patient->wiftypeid = $wifetype;
                $patient->doctor1 = $for_doctor;
                $patient->h_doctor1 = -1;
                $patient->dateofbirth = $dateofbirth;
            }
        }


        $patient->refer_doctor = -1;
        $patient->h_refer_doctor = -1;
        $patient->doctor2 = -1;
        $patient->h_doctor2 = -1;

        $patient->done = 1;

        $patient->id = R::store($patient);
        $this->erpClient($patient);

        return $patient->id;
    }

    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) {
        $invType = filter_input(INPUT_POST, 'invType');

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

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

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

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

        R::store($obj);
    }

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

        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);
                }
            }
            $this->billPayingRoyal($bill_pays, array(), 0); //$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);
                }
            }
        }
        R::selectDatabase('default');
    }

    public function delPayERPBills($visit) {

        //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) {
        //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->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->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');
        $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->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');
        $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 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
            );

            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;
        $detectionValue_cash = filter_input(INPUT_POST, 'detectionvalue_cash');
        $detectionValue_visa = filter_input(INPUT_POST, 'detectionvalue_visa');
        $totaldetectionvalue = filter_input(INPUT_POST, 'totaldetectionvalue');

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

            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);
            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);
            $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) {
        $invType = filter_input(INPUT_POST, 'invType');

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

        R::exec('update investigationresults set deleted = 1 where visitid = ?   ', [$visitId]);

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

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

    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) {
        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->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);
    }

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

}
