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

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

// all drugs will show in selectbox in add new drugs
        $this->patientdata();

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

        $statusNo = R::getRow('select statusno  from patients where id = ?   ', [$patientid]);
        $this->smarty->assign('statusNo', $statusNo['statusno']);
        $this->smarty->assign('patientid', $patientid);

        $found = 0;
        if (!empty($patientid)) {
            $date = date("Y/m/d");

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

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

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

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

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


//Html files

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

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

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


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

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

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

        $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 desc ', [$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'];

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

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

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


            $result = array(
                "name" => $name,
                "operation_main_id" => $visit->operation_main_id,
                "visitdate" => date("Y/m/d", strtotime($visit->visitdate)),
                "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,
                "for_husband" => $visit->for_husband
            );

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

    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 .= ' </div>  ';

            $i++;
        }

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

        return $invRes;
    }

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

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


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



        $oldReserveId = $visit->operation_main_id;

        if ($reserveId != $oldReserveId) {

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



        if ($detectionValue_cash > 0 && $visit->printserial == 0) {

            $printserial = 1;

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

            if ($programesetting->last_serial < 500) {
                $printserial = $programesetting->last_serial + 1;
            }

            $programesetting->last_serial = $printserial;
            r::store($programesetting);

            $visit->printserial = $printserial;
        }

        $old_for_department = $visit->for_department;

        $visit->patientid = $patientID;
        $visit->visitdate = $new_date;
        $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->notes = $notes;

        if ($reserveId != $oldReserveId) {




            $visit->operation_main_id = $operation_main_id;
            $visit->room_no = $room_no;
            $visit->enterance = $enterance;
            $visit->p_exit = $p_exit;

            $visit->res_room_no = $res_room_no;
            $visit->res_enterance = $res_enterance;
            $visit->res_p_exit = $res_p_exit;
        }

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



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


        R::store($visit);
        $this->erpSellbillUpdate($visit);

        echo $visitId;
    }

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

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

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

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

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

        $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;
        $insertDataVisits->child = $child;
        $insertDataVisits->operation_time = $operation_time;
        $insertDataVisits->operation_main_id = $operation_main_id;
        $insertDataVisits->notes = $notes;
        $insertDataVisits->user_id = $_SESSION['user_id'];

        $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;
        $insertDataVisits->res_p_exit = $res_p_exit;

        $insertDataVisits->recep_p_exit = $recep_p_exit;
        $insertDataVisits->recep_enterance = $recep_enterance;

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


        if ($detectionValue_cash > 0) {

            $printserial = 1;
            $programesetting = R::findOne('programesetting');

            if ($programesetting->last_serial < 500) {
                $printserial = $programesetting->last_serial + 1;
            }

            $programesetting->last_serial = $printserial;
            r::store($programesetting);

            $insertDataVisits->printserial = $printserial;
        } else {
            $insertDataVisits->printserial = 0;
        }


        try {
            if ($insertnew == 1) {
                $insert = R::store($insertDataVisits);
                if ($insertDataVisits->detectionvalue_cash) {//only payed visits make bills in erp
                    $this->erpSellbill($insertDataVisits);
                }

//                if ($detectionValue_cash > 0) {
//                    $this->printrecept($insert);
//                }


                if ($for_department == 5 || $for_department == 12) {
                    $this->sendToDept($patientID, $for_department, $insert, $for_husband);
                }
            } else {
                $insert = 0;
            }
            echo $insert;
        } catch (Exception $ex) {
            echo -1;
        }
    }

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

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

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

        $updatedt = R::load('detections', $id);
        $updatedt->title = $dttitle;
        $updatedt->detectionval = $dtvalue;
        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 FROM detections WHERE id ="' . $dtid . '"');
        echo $getprice['detectionval'];
    }

    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');
        $data = R::getRow("SELECT MAX(enterordered)  FROM `visits`");
        $lastEnter = $data['MAX(enterordered)'];
        $visitview = R::load('visits', $id);
        $visitview->view = 1;
        $visitview->visitorder = 0;
        $visitview->enterordered = $lastEnter + 1;
        try {
            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);
            $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;
                R::store($patientDelete);
                $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);
            $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 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']);
        } else {
            $alldata = R::findAll($tableName, 'del = 0');
        }


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

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

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

        $today = new DateTime(date('d-m-Y'));

        if ($visit->for_husband != 1) {
            $wifetypes = R::load('wifetypes', $patient->wiftypeid);
            $name = $patient->wifename;
            $title = $wifetypes->title;

            if ($patient->dateofbirth != '0000-00-00' && $patient->dateofbirth != '' && $patient->dateofbirth != Null) {
## calculate wife age
                $dateWife = new DateTime($patient->dateofbirth);
                $today1 = new DateTime(date('Y-m-d'));
                $interval = $today1->diff($dateWife);
            }
###
        } else {
            $husbandtypes = R::load('husbandtypes', $patient->husbandtypeid);
            $name = $patient->husdandname;
            $title = $husbandtypes->title;

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

        $this->smarty->assign('name', $name);
        $this->smarty->assign('title', $title);

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

        $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) {
                $invs = R::getAll('SELECT   invests.id as invId , invests.name as invName
                                                                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 ($x > 1) {
                        $invests .= ' , ';
                    }
                    $invests .= $row['invName'];
                    $x++;
                }


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

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



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

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

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

        if ($statusNo > 0) {
            $allPatients = R::getRow('SELECT id , CONCAT(COALESCE(wifename,""), " -  ", COALESCE(husdandname,"")) AS name  
                 , wifename    ,   husdandname
            FROM patients    WHERE deleted = ? and done = ?    and   statusno  = ?     limit 0,50  ', [0, 1, $statusNo]);
        }

        echo json_encode($allPatients);
    }

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


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

        $lastVisits = R::getAll('SELECT  visits.id as visitid ,   detections.title as detect    , awrole.name as department 
                                                , visits.for_doctor , visits.visitdate   , awusers.name as drName 
                                                   , visits.detectionvalue_cash   , visits.detectionvalue_visa    
                                                  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  patientid = ?    and deleted != ?  and visits.detectionid   != 999 and visits.detectionid   != 9999
                order by visits.visitdate desc , visits.id desc  ', [$patientId, 1]);

        if (count($lastVisits) > 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']]);

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

                $i++;
            }



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

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


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

        $visits = array();

        $lastVisit = R::getAll('SELECT id as visitid , restdetectionvalue as rest , visitdate    FROM visits   
                                                    where  patientid = ?   and  restdetectionvalue >0
                                                               and 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'];

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

        $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 ($paid_cash > 0) {
            $printserial = 1;

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

            if ($programesetting->last_serial < 500) {
                $printserial = $programesetting->last_serial + 1;
            }

            $programesetting->last_serial = $printserial;
            r::store($programesetting);

            $insertDataVisits->printserial = $printserial;
        } else {
            $insertDataVisits->printserial = 0;
        }


        $insert = R::store($insertDataVisits);
        $this->erpSellbillUpdate($insertDataVisits);

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


        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 desc', [0, $dateFrom, $dateTo]);

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

            $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 . ' ) ';
            } else {
                $detection = R::load('detections', $visit->detectionid);
                $visit->detection = $detection->title;
            }
        }

        $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 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);
        } else {
            $this->printrecept($visitId);
        }
    }

    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) {
                $this->smarty->assign('detection', 'دفع متبقى');
            } else {
                $detection = R::load('detections', $visit->detectionid);
                $this->smarty->assign('detection', $detection->title);
            }

            $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) {
                $this->smarty->assign('detection', 'دفع متبقى');
            } else {
                $detection = R::load('detections', $visit->detectionid);
                $this->smarty->assign('detection', $detection->title);
            }




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

            try {
                $insert = R::store($insertDataVisits);
                echo 1;
            } catch (Exception $ex) {
                echo $ex;
            }
        }
    }

    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 {

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

                R::store($fundVisit);
                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 {

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

                R::store($visit);
                $this->erpSellbillUpdate($visit);
                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');

            $visits = R::count('visits', 'deleted = 0 and for_doctor = ? and visitdate = ? 
                      and for_department in ( 4 , 8 )  ', [$doctorId, $visitDate]);

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

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

            $printserial = 1;
            $programesetting = R::findOne('programesetting');

            if ($programesetting->last_serial < 500) {
                $printserial = $programesetting->last_serial + 1;
            }

            $programesetting->last_serial = $printserial;
            r::store($programesetting);

            $insertDataVisits->printserial = $printserial;
        } else {
            $insertDataVisits->printserial = 0;
        }


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

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

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

        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);
                $count = 0;
                $start = 0;
                $limit = 30;
                $end = $start + $limit;
                R::selectDatabase('default');
                $detectionsCount = R::getRow('select count(id) as id from detections');
                $count = $detectionsCount["id"];
                for ($i = $start; $i <= $count; $i += $limit) {
                    R::selectDatabase('default');
                    $allDetections = R::findAll("detections", " order by id asc limit $start,$end ");
                    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']);
                            }
                        }
                    } else {
                        throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                    }
                    //
                    $start += $limit;
                    $end += $limit;
                }
                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"
    public function curlAddProduct($detection, $erpDB) {
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'detection_id' => $detection->id,
            'new_cat_id' => 'obygy',
            'level' => 'obygy',
            '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);
    }

    public function curlupdateProduct($detection, $erpDB, $productId) {
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'detection_id' => $detection->id,
            'productId' => $productId,
            'productCatId' => 'obygy',
            'level' => 'obygy',
            '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) {
        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);
                    $productData = R::getRow('select productId from product where obygyDetectionId = ' . $visit->detectionid);
                    $doctorData = R::getRow('select userid from user where obygyDoctorId = ' . (int) $visit->for_doctor);
                } 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');
            }

            // set post fields
            $post = [
                'erpDB' => $programesetting->erpdb,
                'saveid' => $programesetting->erpdbsave,
                'supplier' => $clientData['clientid'],
                'sellerid' => $doctorData['userid'],
                'bn' => $visit->visitdate,
                'totalBill_hidden' => $visit->totaldetectionvalue,
                'discount' => $visit->discount,
                'netBill_hidden' => $visit->totaldetectionvalue - $visit->discount,
                'cash' => $visit->detectionvalue_cash,
                'visa' => $visit->detectionvalue_visa,
                'visaAccount' => $programesetting->erpdbvisaaccount,
                'remain' => $programesetting->restdetectionvalue,
                'productid' => $productData['productId'],
                'visitId' => $visit->id,
            ];
            $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);
        } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
        }
    }

    public function erpSellbillUpdate($visit) {
        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);
                    $sellData = R::getRow('select sellbillid from sellbill where conditions = 0 and obygyVisitId = ' . $visit->id);
                    $productData = R::getRow('select productId from product where obygyDetectionId = ' . $visit->detectionid);
                    $doctorData = R::getRow('select userid from user where obygyDoctorId = ' . (int) $visit->for_doctor);
                } 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');
            }

            // set post fields
            $post = [
                'erpDB' => $programesetting->erpdb,
                'saveid' => $programesetting->erpdbsave,
                'supplier' => $clientData['clientid'],
                'sellerid' => $doctorData['userid'],
                'bn' => $visit->visitdate,
                'totalBill_hidden' => $visit->totaldetectionvalue,
                'discount' => $visit->discount,
                'netBill_hidden' => $visit->totaldetectionvalue - $visit->discount,
                'cash' => $visit->detectionvalue_cash,
                'visa' => $visit->detectionvalue_visa,
                'visaAccount' => $programesetting->erpdbvisaaccount,
                'remain' => $programesetting->restdetectionvalue,
                'productid' => $productData['productId'],
                'visitId' => $visit->id,
                'sellbillId' => $sellData["sellbillid"],
            ];
            $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;
        }
    }

    public function erpSellbillDel($visit) {
        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()) {
                    $sellData = R::getRow('select sellbillid from sellbill where conditions = 0 and obygyVisitId = ' . $visit->id);
                } 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');
            }

            // set post fields
            $post = [
                'erpDB' => $programesetting->erpdb,
                'sellbillId' => $sellData["sellbillid"],
            ];

            $ch = curl_init(HOST_URL_ERP . '/controllers/sellbillController.php?do=delObgyVisit');
            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;
        }
    }

    public function erpClient($patient) {
        $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()) {
                    $clientData = R::getRow('select clientid from client where obygyPatientId = ' . $patient->id);
                    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) {
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'newclientName' => $patient->wifename,
            'clientaddress' => $patient->address,
            'clientphone' => $patient->phone,
            'clientmobile' => $patient->mobile,
            'newclientdebt' => 0,
            'clientdetails' => $patient->importantnote,
            'clientareaid' => 0,
            'clientcode' => '',
            'store_all' => -10,
            'obygyPatientId' => $patient->id,
        ];

        try {
            $ch = curl_init(HOST_URL_ERP . '/controllers/clientControllerAjax.php?do=addclient');
            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 curlUpdateClient($patient, $erpDB, $clientId, $treeId) {
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'id' => $clientId,
            'treeId' => $treeId,
            'newclientName' => $patient->wifename,
            'clientaddress' => $patient->address,
            'clientphone' => $patient->phone,
            'clientmobile' => $patient->mobile,
            'newclientdebt' => 0,
            'clientdetails' => $patient->importantnote,
            'clientareaid' => 0,
            'clientcode' => '',
            'store_all' => 1,
            'obygyPatientId' => $patient->id,
        ];
        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 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'];
    }

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

}
