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

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

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

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

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

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

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

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

        if ($programesetting->balance == 1) {
            $this->smarty->assign('balance', 0);
        }

        $visit_periods = R::findAll('visit_periods', 'deleted = 0');
        $this->smarty->assign('visit_periods', $visit_periods);

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

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

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

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

    function loadVisits($dateFrom, $dateTo, $patientId) {
        if ($patientId > 0) {
            $allvisit = $this->visitsFuture($patientId);
        } else {
            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');
            }


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

            if ($extraTime->visit_period == 1) {
                $allvisit = $this->visitsWithPeriod($dateFrom, $dateTo);
            } else {
                $allvisit = $this->visitsWithoutPeriod($dateFrom, $dateTo);
            }
        }
        $this->smarty->assign('withPeriod', $extraTime->visit_period);
        $this->smarty->assign('programview', $extraTime->programview);
        $this->smarty->assign('allvisit', $allvisit);
    }

    function visitsFuture($patientId) {
        $pro = R::findOne('programesetting');
        $date = date('Y/m/d');
        $visits = R::find('visits', '  visitdate  > ?    and deleted = ? and    patientid = ?    
                ORDER BY visittime ASC', [$date, 0, $patientId]);

        $allvisit = $this->visitCommon($visits);
        $this->smarty->assign('showPeriod', $pro->visit_period);
        return $allvisit;
    }

    function visitsWithoutPeriod($dateFrom, $dateTo) {
        $visits = R::find('visits', '  visitdate  between ? and ?    and deleted = ?     
                ORDER BY visittime ASC', [$dateFrom, $dateTo, 0]);
        $allvisit = $this->visitCommon($visits);
        return $allvisit;
    }

    function visitsWithPeriod($dateFrom, $dateTo) {
        $result = array();

        $begin = new DateTime($dateFrom);
        $end = new DateTime($dateTo . ' +1 day');

        $interval = DateInterval::createFromDateString('1 day');
        $period = new DatePeriod($begin, $interval, $end);

        foreach ($period as $dt) {
            $dayDate = $dt->format("Y-m-d");

            $visit_periods = R::findAll('visit_periods', 'deleted = 0');
            $dayVisitCount = R::count('visits', 'visitdate  = ?  and deleted = ?', [$dayDate, 0]);

            $dayName = $this->getDayNameFnAr($dayDate);
            $dayDateAll = $dayName . ' : ' . $dayDate;

            if ($dayVisitCount > 0) {
                foreach ($visit_periods as $period) {
                    $period->periodVisits = '';

                    $visits = R::findAll('visits', ' visitdate  = ?  and deleted = ? and visit_period = ?  
                    ORDER BY visittime ASC', [$dayDate, 0, $period->id]);

                    $allvisit = $this->visitCommon($visits);
                    $period->periodVisits = $allvisit;
//                $period->periodVisitsCount = count($allvisit);
                    $period->dayName = $dayName;
                }

                $result[$dayDateAll] = $visit_periods;
            }
        }

        return $result;
    }

    function visitCommon($visits) {
        foreach ($visits as $visit) {
            $visit->visitdate = date("Y/m/d", strtotime($visit->visitdate));

            if ($visit->approx_time != '' && $visit->approx_time != null && !empty($visit->approx_time)) {
                $visit->approx_time = date("g:i A", strtotime($visit->approx_time));
            }

            $visit->createdate = date("Y/m/d", strtotime($visit->createdate));
            $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'];
            $visit->phone = $patientName['phone'];

            switch ($visit->detectionid) {
                case -99:
                    $visit->detection = 'دفع قسط';
                    break;

                case 9999:
                    $originalVisit = R::load('visits', $visit->visitid);
                    $detection = R::load('detections', $originalVisit->detectionid);
                    $visit->detection = 'مرتجع العملاء';
                    $visit->detection .= ' ( ' . $detection->title . ' ) ';
                    break;

                case 999:
                    $originalVisit = R::load('visits', $visit->visitid);
                    $detection = R::load('detections', $originalVisit->detectionid);
                    $visit->detection = 'دفع متبقى ';
                    $visit->detection .= ' ( ' . $detection->title . ' ) ';
                    break;

                default:
                    $detection = R::getRow('SELECT * FROM detections WHERE id = "' . $visit->detectionid . '"');
                    $visit->detection = $detection['title'];

                    $payVisits = R::getRow('SELECT COALESCE(SUM(detectionvalue_cash),0)   as paid_cash 
                                                                 , COALESCE(SUM(detectionvalue_visa),0)   as paid_visa  
                                                                  , COALESCE(SUM(discount),0)   as paid_discount 
                                                                 , 0 as paid   
                                    FROM visits   where  patientid = ?    
                               and deleted != ? and detectionid = 999 and visitid = ?   ', [$visit->patientid, 1, $visit->id]);


#               ## what pt paid after  creating visit 
                    $payVisits['paid'] = $payVisits['paid_cash'] + $payVisits['paid_visa'];
                    $visit->dept = $visit->restdetectionvalue - $payVisits['paid'] - $payVisits['paid_discount'];

                    break;
            }

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

            $p = R::load('visit_periods', $visit->visit_period);
            $visit->period_name = $p->name;
        }
        return $visits;
    }

    function reloadVisits() {

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

        $dateFrom = filter_input(INPUT_POST, "date_from");
        $dateTo = filter_input(INPUT_POST, "date_to");
        $patientId = filter_input(INPUT_POST, "patientId");

        $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->loadVisits($dateFrom, $dateTo, $patientId);
        $this->smarty->display('visits/visitdiv.html');
    }

    public function editVisit() {
        $visitId = filter_input(INPUT_POST, "visitId");
        $visit = R::load('visits', $visitId);
        $patient = R::load('patients', $visit->patientid);


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

        if ($visit->detectionid == -99) {
            $visit->detectionType = 'دفع قسط';
        } else {
            $detection = R::getRow("SELECT * FROM detections WHERE id = $visit->detectionid");
            $visit->detectionType = $detection['title'];
        }





        $allDetections = R::getAll('select * from detections where del = 0');

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


        $result = array(
            "visitdate" => date("Y/m/d", strtotime($visit->visitdate)),
            "patientid" => $visit->patientid,
            "detectionid" => $visit->detectionid,
            "payedflag" => $visit->payedflag,
            "urgent" => $visit->urgent,
            "visit_period" => $visit->visit_period,
            "patient_edit" => $visit->patient_edit,
            "detectionvalue_visa" => $visit->detectionvalue_visa,
            "detectionvalue_cash" => $visit->detectionvalue_cash,
            "totaldetectionvalue" => $visit->totaldetectionvalue,
            "discount" => $visit->discount,
            "restdetectionvalue" => $visit->restdetectionvalue,
            "setting" => $programesetting->visitsform,
            "notes" => $visit->notes,
            "balancesetting" => $programesetting->balance
        );

        echo json_encode($result);
    }

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

    public function getlastvisit() {

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

        $visit = R::findOne('visits', 'patientid = ? order by visitdate desc', [$patientId]);

        $result = array(
            "detectionId" => $visit->detectionid,
            "detectionValue" => $visit->detectionvalue
        );

        echo json_encode($result);
    }

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


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

        $lastVisits = R::getAll('SELECT  visits.id as visitid ,   detections.title as detect  
                                                    , visits.visitdate       , visits.detectionvalue_cash   , visits.detectionvalue_visa    
                                                  FROM visits  
                                                    left  join detections    on detections.id  =  visits.detectionid 
                                          where  patientid = ?    and deleted != ?      
                                          and visits.detectionid   != -99  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 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');
        $payVisit = (int) filter_input(INPUT_POST, 'payVisit');
        $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');
        $visit_period = filter_input(INPUT_POST, 'visit_period');
        $new_date = date('Y/m/d', strtotime($visitDate));
        $urgent = (int) filter_input(INPUT_POST, 'urgent');
        $patient_edit = filter_input(INPUT_POST, "patient_edit");
        $notes = filter_input(INPUT_POST, "notes");

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

        $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->visit_period = $visit_period;
        $visit->payedflag = $payVisit;
        $visit->urgent = $urgent;
        $visit->patient_edit = $patient_edit;
        $visit->notes = $notes;

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

        echo $visitId;
    }

    public function restorevisit() {
        $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");
        $result = array(
            "husbandName" => $patientName['husdandname'],
            "address" => $patientName['address'],
            "detectionType" => $detection['title']
        );

        echo json_encode($result);
    }

    ##fatma

    public function payvisit() {
        $visitId = filter_input(INPUT_POST, "visitId");
        $visit = R::load('visits', $visitId);
        if ($visit->payedflag != 1) {
            $visit->payedflag = 1;
            R::store($visit);
            //now patient pay make bills in erp
            $this->erpSellbill($visit);
            echo $visit->mobileappvisit;
        }
    }

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

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

        $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');
        $discount = filter_input(INPUT_POST, 'discount');
        $visit_period = filter_input(INPUT_POST, 'visit_period');
        $urgent = (int) filter_input(INPUT_POST, 'urgent');
        $notes = filter_input(INPUT_POST, "notes");
        $approx_time = filter_input(INPUT_POST, "approx_time");

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

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

        $newOrder = 1;
        $data = R::getRow("SELECT MAX(enterordered) as last_order   FROM visits ");
        if ($data['last_order'] >= 1) {
            $newOrder = $data['last_order'] + 1;
        }

        session_start();

        $insertDataVisits = R::dispense('visits');
        $insertDataVisits->patientid = $patientID;
        $insertDataVisits->visitdate = $new_date;
        $insertDataVisits->detectionid = $detectionID;
        $insertDataVisits->detectionvalue_cash = $detectionValue_cash;
        $insertDataVisits->detectionvalue_visa = $detectionValue_visa;
        $insertDataVisits->totaldetectionvalue = $totaldetectionvalue;
        $insertDataVisits->discount = $discount;
        $insertDataVisits->restdetectionvalue = $restdetectionvalue;
        $insertDataVisits->visit_period = $visit_period;
        $insertDataVisits->mobileappvisit = 0;
        $insertDataVisits->payedflag = 1;
        $insertDataVisits->urgent = $urgent;
        $insertDataVisits->enterordered = $newOrder;
        $insertDataVisits->visitorder = 0;
        $insertDataVisits->createdate = date('Y-m-d h:i:s');
        $insertDataVisits->user_id = $_SESSION['user_id'];
        $insertDataVisits->notes = $notes;

        $insertDataVisits->approx_time = $approx_time;             //date("H:i:s");

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

            if ($insert) {
                echo 1;
            } else {
                echo -1;
            }
        } catch (Exception $ex) {
            echo -1;
        }
    }

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

        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() {
        $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);
            $this->erpProduct($updatedt);
        } catch (Exception $ex) {
            
        }
    }

    function loadalldtselected() {
        $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;
        $inserted = 0;
        try {
            $inserted = R::store($insertDataDetection);
            $insertDataDetection->id = $inserted;
            $this->erpProduct($insertDataDetection);
            echo $inserted;
        } catch (Exception $ex) {
            
        }
    }

    public function adddetectionpop() {
        $detectiontype = filter_input(INPUT_POST, 'detectiontype');
        $detectionvalue = filter_input(INPUT_POST, 'detectionvl');
        $addfrmpopdetection = R::dispense('detections');
        $addfrmpopdetection->title = $detectiontype;
        $addfrmpopdetection->detectionval = $detectionvalue;
        $addfrmpopdetection->del = 0;
        $added = 0;
        try {
            $inserted = R::store($addfrmpopdetection);
            $addfrmpopdetection->id = $inserted;
            $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) {
        return $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
    }

    function search() {
        $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.*
                                        FROM `visits`
                                        INNER JOIN patients          ON  visits.patientid  = patients.id
                                        WHERE
                                        patients.deleted = 0
                                        and visits.deleted = 0
                                        $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() {
        $dtid = filter_input(INPUT_POST, 'dtID');
        $getprice = R::getRow('SELECT detectionval FROM detections WHERE id ="' . $dtid . '"');
        echo $getprice['detectionval'];
    }

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

    function visitviewed() {
        $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 = ? ', [$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 = filter_input(INPUT_POST, 'detectionvalue');
        echo $vId;


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

    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 updateWaiting() {
        //check login
        autho::checkautho($this->hosturl);

        $id = filter_input(INPUT_POST, 'id');
        $date = filter_input(INPUT_POST, 'date');

        try {
            $visit = R::load('visits', $id);

            if ($date == 1) {
                $visit->visitdate = date('Y/m/d');
            } else {
                $visit->urgent = 0;
                $visit->deleted = 1;
            }

            R::store($visit);

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

    public function deldetection() {
        $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() {
        $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);
            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");

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

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


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

        $insertDataDetection = R::dispense('detections');
        $insertDataDetection->del = 0;
        $inserted = 0;
        try {
            $inserted = R::store($insertDataDetection);
            $insertDataDetection->id = $inserted;
            $this->erpProduct($insertDataDetection);
            echo $inserted;
        } catch (Exception $ex) {
            
        }
    }

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


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

    ################################# visit control  ################################

    public function gettotalbalance() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        // autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //vars here
        try {
            $patientId = filter_input(INPUT_POST, 'patientId');

            $balance = R::getRow('select sum(balance) as totalbalance  from totalbalance
                where deleted = 0 and  patientid = ' . $patientId);

            $paidBalance = R::getRow('select  
                COALESCE(SUM(detectionvalue_cash),0)   as paid_cash 
               , COALESCE(SUM(detectionvalue_visa),0)   as paid_visa 
                , COALESCE(SUM(discount),0)   as discount    
                from visits
                where deleted = 0 and detectionid = -99 and  patientid = ' . $patientId);

            $rest = $balance['totalbalance'] - $paidBalance['paid_cash'] - $paidBalance['paid_visa'] - $paidBalance['discount'];


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

    public function addbalance() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        // autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //vars here
        try {
            $patientId = filter_input(INPUT_POST, 'patientId');
            $newBalance = filter_input(INPUT_POST, 'newBalance');


            $row = r::dispense('totalbalance');
            $row->patientid = $patientId;
            $row->balance = $newBalance;
            $row->userid = $_SESSION['user_id'];
            $row->adddate = date('Y/m/d');
            $row->deleted = 0;

            r::store($row);


            $balance = R::getRow('select sum(balance) as totalbalance  from totalbalance
                where deleted = 0 and  patientid = ' . $patientId);

            $paidBalance = R::getRow('select  
                COALESCE(SUM(detectionvalue_cash),0)   as paid_cash 
               , COALESCE(SUM(detectionvalue_visa),0)   as paid_visa 
                , COALESCE(SUM(discount),0)   as discount    
                from visits
                where deleted = 0 and detectionid = -99 and  patientid = ' . $patientId);

            $rest = $balance['totalbalance'] - $paidBalance['paid_cash'] - $paidBalance['paid_visa'] - $paidBalance['discount'];

            echo $rest;
        } catch (Exception $ex) {
            echo 0;
        }
    }

    ##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
            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');
            }
            R::selectDatabase('default');
        }
    }

    public function erpProductDel($detection) {//detections
        $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()) {
                $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');
        }
    }

    //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' => $detection->detectionval,
            'new_productbuypricereal' => $detection->detectionval,
            '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,
        ];
        $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);

        // 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' => $detection->detectionval,
            'productbuypricereal' => $detection->detectionval,
            '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,
        ];
        $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);

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

    public function curlDelProduct($erpDB, $productId) {
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'productId' => $productId,
        ];
        $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);

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

    public function erpSellbill($visit) {
        $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);
            } 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'],
            'bn' => $visit->visitdate,
            'totalBill_hidden' => $visit->detectionvalue,
            'netBill_hidden' => $visit->detectionvalue,
            'productid' => $visit->detectionid,
            '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);
    }

    public function erpSellbillUpdate($visit) {
        $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);
            } 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'],
            'bn' => $visit->visitdate,
            'totalBill_hidden' => $visit->detectionvalue,
            'netBill_hidden' => $visit->detectionvalue,
            'productid' => $visit->detectionid,
            '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);
    }

    public function erpSellbillDel($visit) {
        $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);
    }

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

    public function visitPeriodEdit() {

        $alldata = R::getAll(' select *  from  visit_periods   where deleted  != 1 ');

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

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

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

        ### insert into table
        $newtable = R::xdispense($tableName);
        $newtable->$colName = "";

        $insertid = R::store($newtable);

        echo $insertid;
    }

    public function 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 {
            $obj = R::load($tablename, $id);
            $obj->$colname = $value;
            R::store($obj);
            echo 1;
        } catch (Exception $ex) {
            echo -1;
        }
    }

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


        $periodId = filter_input(INPUT_POST, "periodId");
        $visitDate = filter_input(INPUT_POST, 'visitdate');

        $visits = R::count('visits', 'deleted = 0 and visit_period = ? and visitdate = ?  ', [$periodId, $visitDate]);

        echo $visits;
    }

    public function waitingList() {
        $setting = R::findOne('programesetting');
        $today = date('Y/m/d');
        $visits = R::findAll('visits', 'visitdate > ? and deleted = ?  and urgent = ? ', [$today, 0, 1]);
        $allvisit = $this->visitCommon($visits);

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

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

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


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

        $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->user_id = $_SESSION['user_id'];
        $insertDataVisits->visitid = $visitId;
        $insertDataVisits->notes = $restNotes;

        $insert = R::store($insertDataVisits);

        if (count($insert) > 0) {
            echo 1;
        } else {
            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->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 fixOldVisits() {

        $oldVisits = R::findAll('old_visits', ' id > ?  and id  <=  ?  ', [0, 1000]);
        foreach ($oldVisits as $oldVisit) {
            $visit = R::load('visits', $oldVisit->id);
            $visit->totaldetectionvalue = $oldVisit->detectionvalue;
            $visit->detectionvalue_cash = $oldVisit->detectionvalue;
            r::store($visit);
            print_r($visit->id . '  -  ');
        }

        $oldVisits = R::findAll('old_visits', ' id > ?  and id  <=  ?  ', [1000, 2000]);
        foreach ($oldVisits as $oldVisit) {
            $visit = R::load('visits', $oldVisit->id);
            $visit->totaldetectionvalue = $oldVisit->detectionvalue;
            $visit->detectionvalue_cash = $oldVisit->detectionvalue;
            r::store($visit);
            print_r($visit->id . '  -  ');
        }


        $oldVisits = R::findAll('old_visits', ' id > ?  and id  <=  ?  ', [2000, 3000]);
        foreach ($oldVisits as $oldVisit) {
            $visit = R::load('visits', $oldVisit->id);
            $visit->totaldetectionvalue = $oldVisit->detectionvalue;
            $visit->detectionvalue_cash = $oldVisit->detectionvalue;
            r::store($visit);
            print_r($visit->id . '  -  ');
        }


        $oldVisits = R::findAll('old_visits', ' id > ?  and id  <=  ?  ', [3000, 4000]);
        foreach ($oldVisits as $oldVisit) {
            $visit = R::load('visits', $oldVisit->id);
            $visit->totaldetectionvalue = $oldVisit->detectionvalue;
            $visit->detectionvalue_cash = $oldVisit->detectionvalue;
            r::store($visit);
            print_r($visit->id . '  -  ');
        }


        $oldVisits = R::findAll('old_visits', ' id > ?  and id  <=  ?  ', [4000, 5000]);
        foreach ($oldVisits as $oldVisit) {
            $visit = R::load('visits', $oldVisit->id);
            $visit->totaldetectionvalue = $oldVisit->detectionvalue;
            $visit->detectionvalue_cash = $oldVisit->detectionvalue;
            r::store($visit);
            print_r($visit->id . '  -  ');
        }


        $oldVisits = R::findAll('old_visits', ' id > ?  and id  <=  ?  ', [5000, 6000]);
        foreach ($oldVisits as $oldVisit) {
            $visit = R::load('visits', $oldVisit->id);
            $visit->totaldetectionvalue = $oldVisit->detectionvalue;
            $visit->detectionvalue_cash = $oldVisit->detectionvalue;
            r::store($visit);
            print_r($visit->id . '  -  ');
        }


        $oldVisits = R::findAll('old_visits', ' id > ?  and id  <=  ?  ', [6000, 7000]);
        foreach ($oldVisits as $oldVisit) {
            $visit = R::load('visits', $oldVisit->id);
            $visit->totaldetectionvalue = $oldVisit->detectionvalue;
            $visit->detectionvalue_cash = $oldVisit->detectionvalue;
            r::store($visit);
            print_r($visit->id . '  -  ');
        }


        $oldVisits = R::findAll('old_visits', ' id > ?  and id  <=  ?  ', [7000, 8000]);
        foreach ($oldVisits as $oldVisit) {
            $visit = R::load('visits', $oldVisit->id);
            $visit->totaldetectionvalue = $oldVisit->detectionvalue;
            $visit->detectionvalue_cash = $oldVisit->detectionvalue;
            r::store($visit);
            print_r($visit->id . '  -  ');
        }


        $oldVisits = R::findAll('old_visits', ' id > ?  and id  <=  ?  ', [8000, 9092]);
        foreach ($oldVisits as $oldVisit) {
            $visit = R::load('visits', $oldVisit->id);
            $visit->totaldetectionvalue = $oldVisit->detectionvalue;
            $visit->detectionvalue_cash = $oldVisit->detectionvalue;
            r::store($visit);
            print_r($visit->id . '  -  ');
        }
    }

    private function getDayNameFnAr($date) {
        $timestamp = strtotime($date);

        $day = date('w', $timestamp);



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

        return $name;
    }

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

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

}
