<?php

/*
 * awframework from aw.inc present aw controller
 * it will help you develop easy and fast with secure tools
 * you can edit and add what you feel right
 * don't change in strucure of file
 */

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 = 'cashtransferdectorreport';
        $this->shcontrollname = 'Home';
        $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] = 'cashtransferdectorreport'; //controller name or tab name
        $this->active = $active;


        //here will call all php pages
        require_once("erp_common.php");  ## added by heba 
        require_once("branch_common.php");
        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']);
        //here will load the menu show
        //R::debug(true);

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

        $this->smarty->assign('role_id', $_SESSION['role_id']);


        if ($_SESSION['role_id'] == 12) {
            $py_all_departs = R::findAll('awrole', 'visit_show = 1 and id = 12');
        } else {
            $py_all_departs = R::findAll('awrole', 'visit_show = 1 ');
        }
        $this->smarty->assign('py_all_departs', $py_all_departs);

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

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

        //$this->commonSearch($today, $today);

        $doctors = R::getAll('select user_id , name  from awusers 
                where deleted != 1 and    role_id in ( select id from awrole where visit_show = 1   )');
        $this->smarty->assign('doctors', $doctors);

        $recep_users = R::getAll('select * from awusers where deleted != 1 and    cashtransferdoctor_user   = 1 ');
        $this->smarty->assign('recep_users', $recep_users);

        $this->smarty->assign('login_role', $_SESSION['role_id']);

        $offers = R::findall('invoffer', 'active = ? and  del = ? ', [1, 0]);
        $this->smarty->assign('offers', $offers);

        $detections = R::getAll('select  id , title from detections where del = 0');
        $this->smarty->assign('detections', $detections);

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

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

    function branchSql($branchesActivate, $branch_id)
    {
        $branchSql = ' ';
        if ($branchesActivate == 1 && ($branch_id == -1 || $branch_id > 0)) {
            $branchSql = '  and visits.branch_id  =   ' . $branch_id . '   ';
        }

        $this->smarty->assign('selectedBranch', $branch_id);
        $this->smarty->assign('branchesActivate', $branchesActivate);
        return $branchSql;
    }

    function billBranchSql($branchesActivate, $branch_id)
    {
        $branchSql = ' ';
        if ($branchesActivate == 1 && ($branch_id == -1 || $branch_id > 0)) {
            $branchSql = '  and bill_paying.branch_id  =   ' . $branch_id . '   ';
        }
        return $branchSql;
    }

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

        if ($_SESSION['role_id'] == 12) {
            $fordepartment = 12;
        } else {
            $fordepartment = filter_input(INPUT_POST, 'fordepartment');
        }

        $fdate = filter_input(INPUT_POST, 'fdate');
        $todate = filter_input(INPUT_POST, 'todate');
        $referDrId = filter_input(INPUT_POST, 'referDrId');
        $this->commonSearch($fdate, $todate, $referDrId);

        $this->smarty->assign('login_role', $_SESSION['role_id']);
        $this->smarty->display('reports/cashtransferdoctorsearch.html');
    }

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

        $fdate = filter_input(INPUT_POST, 'fdate');
        $todate = filter_input(INPUT_POST, 'todate');
        $referDrId = filter_input(INPUT_POST, 'referDrId');
        $this->commonSearch(
            $fdate,
            $todate,
            $referDrId
        );

        $this->smarty->assign('login_role', $_SESSION['role_id']);
        $this->smarty->display('reports/cashtransferdoctorprint.html');
    }

    public function commonSearch($fdate, $todate, $referDrId = 0)
    {
        $billShow = 1;
        $ext = '';

        $role = R::load('awrole', $_SESSION['role_id']);
        switch ($role->financial_visits) {
            case 1:
                $billShow = 0;
                $ext .= ' and visits.for_department =   ' . $_SESSION['role_id'];
                break;
            case 2:
                $billShow = 0;
                $ext .= ' and visits.for_doctor =   ' . $_SESSION['user_id'];
                break;
        }

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

        if (!empty($referDrId) && ($referDrId > 0 || $referDrId[0] == "*" || $referDrId == -1)) {
            $refer_doctor_tb = 0;

            if ($referDrId[0] == "*") {
                $referDrId = ltrim($referDrId, '*');
                $refer_doctor_tb = 1;
            }

            $ext .= ' and  visits.refer_doctor =   ' . $referDrId . '  and visits.refer_doctor_tb =  ' . $refer_doctor_tb;
        }
        // $ext .= 'group by visits.branch_id';
        $billsSql = $this->billsPayingSql($fdate, $todate, $billShow);
        if (!empty($billsSql) && $billsSql != '') {
            $billsSql = '  union all    ' . $billsSql;
        }
        $sql = $this->visitSql($fdate, $todate, $ext, $billsSql);

        $allData = R::getAll($sql);
        $this->common($allData);
    }

    function billsPayingSql($fdate, $todate, $billShow, $patientId = 0, $hPatientId = 0, $userId = 0, $billBranchSql = '')
    {
        $ext = '';
        $billsSql = '';

        if ($billShow == 1) {

            if (!empty($userId) && $userId > 0) {
                $ext .= ' and bill_paying.user_id =   ' . $userId;
            }

            if (!empty($patientId) && $patientId > 0) {
                $ext .= ' and bill_paying.patient_id = ' . $patientId;
            } elseif (!empty($hPatientId) && $hPatientId > 0) {
                $ext .= ' and bill_paying.patient_id = ' . $hPatientId;
            }

            $billsSql = ' 
                       SELECT    0 AS visitId , bill_paying.branch_id ,  ""  as branch_name , 
                    detectionvalue_visa , 
                    detectionvalue_cash,
                    totaldetectionvalue,
                      0 as restdetectionvalue,
                     0 as detectionid,
                    "صيدلية " AS type,
                    bill_paying.type  as billType  , 
                    patient_id as patientid,
                    bill_paying.user_id , 
                   "الصيدلية"  AS deptName,
                    discount,
                    ""  AS for_husband,
                    patients.wifename,
                    patients.husdandname,
                     patients.wifenationalid,
                    patients.husbandnationalid,
                    patients.address,
                    ""  AS   dept,
                    patients.statusno,
                    pay_date as visitdate , 
                     bill_paying.notes  COLLATE utf8mb4_unicode_ci     AS   vnotes ,
                    0 AS original_visitid,
                   ""  AS rfc,
                    cu.name AS doctor,
                    hcu.name AS h_doctor,
                    "" AS visitDoctor,
                    0 AS refund,
                    printserial,
                    0 as customer_add,
                    "" AS child,
                    "" AS visitHour,
                    0  as drFees ,
                    "" AS refer_doctor,
                    "" AS  refer_doctor_tb , 
                  0 AS contract_price
                  
                    FROM   bill_paying
                        JOIN patients                        ON        bill_paying.patient_id = patients.id
                        LEFT JOIN awusers cu       ON        cu.user_id = patients.doctor1
                        LEFT JOIN awusers hcu     ON        hcu.user_id = patients.h_doctor1
 
                        WHERE
                         pay_date >= "' . $fdate . '" AND pay_date <= "' . $todate . '"   ' . $ext . '    ' . $billBranchSql . '    ' . $billsSql;
        }
        return $billsSql;
    }

    public function visitSql($fdate, $todate, $ext, $billsSql)
    {
        $sql = 'SELECT DISTINCT
                    visits.id AS visitId,
                    visits.branch_id  ,  ""  as branch_name , 
                    detectionvalue_visa,
                    detectionvalue_cash,
                    totaldetectionvalue,
                    restdetectionvalue,
                    detectionid,
                    detections.title AS type,
                    0  as billType , 
                    visits.patientid,
                    visits.user_id,
                    awrole.name AS deptName,
                    visits.discount,
                    visits.for_husband,
                    patients.wifename,
                    patients.husdandname,
                     patients.wifenationalid,
                    patients.husbandnationalid,
                    patients.address,
                    visits.for_department AS dept,
                    patients.statusno,
                    visits.visitdate,
                    visits.notes AS vnotes,
                    visits.visitid AS original_visitid,
                    IF(visits.rfc = 1, "Yes", "No") AS rfc,
                    cu.name AS doctor,
                    hcu.name AS h_doctor,
                    vu.name AS visitDoctor,
                    0 AS refund,
                    visits.printserial,
                    visits.customer_add,
                    visits.child,
                    "" AS visitHour,
                    visits.dr_salary  as drFees ,
                    visits.refer_doctor,
                    visits.refer_doctor_tb ,        
                  visits.contract_price

                    FROM
                        visits
                        JOIN patients ON visits.patientid = patients.id
                        LEFT JOIN awrole ON visits.for_department = awrole.id
                        LEFT JOIN detections ON visits.detectionid = detections.id
                        LEFT JOIN awusers vu ON vu.user_id = visits.for_doctor
                        LEFT JOIN awusers cu ON cu.user_id = patients.doctor1
                        LEFT JOIN awusers hcu ON hcu.user_id = patients.h_doctor1
                 		LEFT JOIN investigationresults ON visits.id = investigationresults.visitid
                    WHERE
                        visits.deleted = 0 AND visits.customer_add != 1      
                        AND visitdate >= "' . $fdate . '" AND visitdate <= "' . $todate . '" ' . $ext . '  ' . $billsSql;

        return $sql;
    }

    function searchForId($id, $array, $string = 'id')
    {
        foreach ($array as $key => $val) {
            if ($val[$string] === $id) {
                return $key;
            }
        }
        return null;
    }

    function searchForIds($id, $array, $string = 'id')
    {
        $keys = [];
        foreach ($array as $key => $val) {
            if ($val[$string] === $id) {
                $keys[] = $key;
            }
        }
        return $keys;
    }

    private function common($allData)
    {
        $totalCost = 0;
        $totalCash = 0;
        $totalVisa = 0;
        $totalDept = 0;
        $totalDiscount = 0;

        $totalPaid = 0;

        $totalOldCash = 0;
        $totalOldVisa = 0;
        $totalOld = 0;

        $totalRefundCash = 0;
        $totalRefundVisa = 0;

        $total = 0;
        $totalC = 0;
        $totalV = 0;
        $totalDrFees = 0;

        $new_allData = array();
        $i = 0;
        // get all ids
        list($refer_doctors, $refers, $insert_users, $visits_ids, $original_visitId) = [[], [], [], [], []];
        foreach ($allData as $datum) {
            if ($datum['refer_doctor'] > 0) {
                if ($datum['refer_doctor_tb'] === '1') {
                    $refer_doctors[] = $datum['refer_doctor'];
                } else {
                    $refers[] = $datum['refer_doctor'];
                }
            }
            //    print_r($datum['user_id'] . ' - ');
            $insert_users[] = $datum['user_id'];
            $visits_ids[] = $datum['visitId'];
            if ($datum['original_visitid'] > 0) {
                $original_visitId[] = $datum['original_visitid'];
            }
        }
        !empty($refer_doctors) ?: $refer_doctors = [0];
        !empty($refers) ?: $refers = [0];
        !empty($insert_users) ?: $insert_users = [0];
        !empty($visits_ids) ?: $visits_ids = [0];
        !empty($original_visitId) ?: $original_visitId = [0];


        // queries
        $refer_doctors_data = R::getAll('select user_id,name from awusers where user_id in (' . implode(',', $refer_doctors) . ')');
        $refers_data = R::getAll('select id,name from refer where id in (' . implode(',', $refers) . ')');
        $insert_users_data = R::getAll('select user_id,name from awusers where user_id in (' . implode(',', array_unique($insert_users)) . ')');
        $cal_refund_data = R::getAll('SELECT COALESCE(SUM(detectionvalue_cash),0) as refund_cash , COALESCE(SUM(detectionvalue_visa),0) as refund_visa,visitid FROM visits where deleted != 1 and detectionid = 9999 and visitid in (' . implode(',', $visits_ids) . ') GROUP BY visitid');
        $original_visits_data = R::getAll('SELECT id,detectionid FROM visits where id in (' . implode(',', $original_visitId) . ')');
        $invest_details_data = R::getAll('SELECT invests.name,investigationresults.visitid FROM invests JOIN investigationresults ON invests.id = investigationresults.investid JOIN visits ON visits.id = investigationresults.visitid WHERE investigationresults.deleted = 0 AND investigationresults.visitid in (' . implode(',', $visits_ids) . ')');
        $ray_details_data = R::getAll('SELECT rays.name,raysresults.visitid FROM rays JOIN raysresults ON rays.id = raysresults.rayid JOIN visits ON visits.id = raysresults.visitid WHERE raysresults.deleted = 0 AND raysresults.visitid in (' . implode(',', $visits_ids) . ')');
        $reserves_data = R::getAll('SELECT * FROM visit_hours where visit_id in (' . implode(',', $visits_ids) . ') and deleted = 0');


        // get all ids level 2
        $detections_ids = [];
        foreach ($original_visits_data as $datum) {
            $detections_ids[] = $datum['detectionid'];
        }
        !empty($detections_ids) ?: $detections_ids = [0];
        $detections_data = R::getAll('SELECT id,title FROM detections where id in (' . implode(',', array_unique($detections_ids)) . ')');


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

        $showBranchCol = showBranchCol($programesetting->branches);
        $this->smarty->assign('showBranchCol', $showBranchCol);


        foreach ($allData as $data) {

            ### new way
            if ($data['refer_doctor'] > 0) {
                if ($data['refer_doctor_tb'] === '1') {
                    $refer_index = $this->searchForId($data['refer_doctor'], $refer_doctors_data, 'user_id');
                    if ($refer_index !== null) {
                        $data['refer'] = $refer_doctors_data[$refer_index]['name'];
                    }
                } else {
                    $refer_index = $this->searchForId($data['refer_doctor'], $refers_data);
                    if ($refer_index !== null) {
                        $data['refer'] = $refers_data[$refer_index]['name'];
                    }
                }
            } else {
                $data['refer'] = "لا يوجد ";
            }

            $totalCost += $data['totaldetectionvalue'];
            $totalDept += $data['restdetectionvalue'];
            $totalDiscount += $data['discount'];
            $totalDrFees += $data['drFees'];

            ### new way
            $insert_user_index = $this->searchForId($data['user_id'], $insert_users_data, 'user_id');
            if ($insert_user_index !== null) {
                $data['insert_user'] = $insert_users_data[$insert_user_index]['name'];
            }

            if ($data['detectionid'] === '999') {
                ### new way
                $original_visit_index = $this->searchForId($data['original_visitid'], $original_visits_data);
                if ($original_visit_index !== null) {
                    $detection_id = $original_visits_data[$original_visit_index]['detectionid'];
                }
                ### new way
                $detection_index = $this->searchForId($detection_id, $detections_data);
                $title = '';
                if ($detection_index !== null) {
                    $title = $detections_data[$detection_index]['title'];
                }
                $data['type'] = 'دفع متبقي ';
                $data['type'] .= ' ( ' . $title . ' ) ';


                $totalOldVisa += $data['detectionvalue_visa'];
                $totalOldCash += $data['detectionvalue_cash'];

                $totalOld += $data['detectionvalue_visa'];
                $totalOld += $data['detectionvalue_cash'];
            } elseif ($data['detectionid'] === '9999') {

                ### new way
                $original_visit_index = $this->searchForId($data['original_visitid'], $original_visits_data);
                if ($original_visit_index !== null) {
                    $detection_id = $original_visits_data[$original_visit_index]['detectionid'];
                }

                ### new way
                $detection_index = $this->searchForId($detection_id, $detections_data);
                $title = '';
                if ($detection_index !== null) {
                    $title = $detections_data[$detection_index]['title'];
                }

                $data['type'] = 'مرتجع العملاء  ';
                $data['type'] .= ' ( ' . $title . ' ) ';


                $totalRefundVisa += $data['detectionvalue_visa'];
                $totalRefundCash += $data['detectionvalue_cash'];
            } else {

                $totalVisa += $data['detectionvalue_visa'];
                $totalCash += $data['detectionvalue_cash'];

                $totalPaid += $data['detectionvalue_visa'];
                $totalPaid += $data['detectionvalue_cash'];

                ### new way
                $refund_index = $this->searchForId($data['visitId'], $cal_refund_data, 'visitid');
                if ($refund_index !== null) {
                    $refund = $cal_refund_data[$refund_index]['refund_cash'] + $cal_refund_data[$refund_index]['refund_visa'];
                    $data['refund'] = $refund;
                }
            }

            ## 12  investigations dept     ,  5   rays dept
            if ($data['dept'] === '5' && $data['detectionid'] !== '999' && $data['detectionid'] !== '9999') {
                ### new way
                $ray_details_indexes = $this->searchForIds($data['visitId'], $ray_details_data, 'visitid');
                $type = $this->raysDetailsNew($ray_details_indexes, $ray_details_data);
                $data['type'] = $type;
            }

            if ($data['dept'] === '12' && $data['detectionid'] !== '999' && $data['detectionid'] !== '9999') {
                ### new way
                $invest_details_indexes = $this->searchForIds($data['visitId'], $invest_details_data, 'visitid');
                $type = $this->investDetailsNew($invest_details_indexes, $invest_details_data);
                $data['type'] = $type;
            }

            if ($data['billType'] == 1) {
                $data['type'] = 'مرتجع العملاء  ';
                $data['type'] .= ' ( صيدلية) ';

                $totalRefundVisa += $data['detectionvalue_visa'];
                $totalRefundCash += $data['detectionvalue_cash'];

                $totalVisa -= $data['detectionvalue_visa'];
                $totalCash -= $data['detectionvalue_cash'];

                $totalPaid -= $data['detectionvalue_visa'];
                $totalPaid -= $data['detectionvalue_cash'];
            }

            ### new way
            $reserve_index = $this->searchForId($data['visitId'], $reserves_data, 'visit_id');
            if ($reserve_index !== null) {
                $data['visitHour'] = date('h:i A', strtotime($reserves_data[$reserve_index]['visit_hour']));
            }

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

            $new_allData[] = $data;
            $i++;
        }
        $allDataArr = [];
        $detections_no = 0;
        $patients_no = 0;
        $totalCash = 0;
        $totalServices = 0;
        $totalPaid = 0;
        $detectionIds = $patientIds = '';
        foreach ($new_allData as $data) {
            // var_dump($data);
            if (!key_exists($data['branch_id'], $allDataArr)) {
                $branch = R::load('branches', $data['branch_id']);
                $data['branch_name'] = $branch['name'];
                $detectionIds = $data['detectionid'];
                $patientIds = $data['patientid'];
                $detections_no = 1;
                $patients_no = 1;
                $totalCash  = $data['detectionvalue_cash'];
                $totalPaid = $data['detectionvalue_cash'] + $data['detectionvalue_visa'];
                $totalServices = $data['totaldetectionvalue'] - $data['discount'];
                $allDataArr[$data['branch_id']][$data['refer']] = ['branch_name' => $data['branch_name'], 'detections_no' => $detections_no, 'detectionIds' => $detectionIds, 'patients_no' => $patients_no, 'patientIds' => $patientIds, 'cash' => $totalCash, 'services' => $totalServices, 'paid' => $totalPaid];
            } else {
                if (!key_exists($data['refer'], $allDataArr[$data['branch_id']])) {
                    $branch = R::load('branches', $data['branch_id']);
                    $data['branch_name'] = $branch['name'];
                    $detectionIds = $data['detectionid'];
                    $patientIds = $data['patientid'];
                    $detections_no = 1;
                    $patients_no = 1;
                    $totalCash  = $data['detectionvalue_cash'];
                    $totalPaid = $data['detectionvalue_cash'] + $data['detectionvalue_visa'];
                    $totalServices = $data['totaldetectionvalue'] - $data['discount'];
                    $allDataArr[$data['branch_id']][$data['refer']] = ['branch_name' => $data['branch_name'], 'detections_no' => $detections_no, 'detectionIds' => $detectionIds, 'patients_no' => $patients_no, 'patientIds' => $patientIds, 'cash' => $totalCash, 'services' => $totalServices, 'paid' => $totalPaid];
                } else {
                    if (!in_array($data['detectionid'], explode(',', $allDataArr[$data['branch_id']][$data['refer']]['detectionIds']))) {
                        $detections_no = $allDataArr[$data['branch_id']][$data['refer']]['detections_no'] + 1;
                        $detectionIds = $allDataArr[$data['branch_id']][$data['refer']]['detectionIds'] . ',' . $data['detectionid'];
                    }
                    if (!in_array($data['patientid'], explode(',', $allDataArr[$data['branch_id']][$data['refer']]['patientIds']))) {
                        $patients_no = $allDataArr[$data['branch_id']][$data['refer']]['patients_no'] + 1;
                        $patientIds = $allDataArr[$data['branch_id']][$data['refer']]['patientIds'] . ',' . $data['patientid'];
                    }

                    $totalCash  = $allDataArr[$data['branch_id']][$data['refer']]['cash'] + $data['detectionvalue_cash'];
                    $totalPaid = $allDataArr[$data['branch_id']][$data['refer']]['paid'] + $data['detectionvalue_cash'] + $data['detectionvalue_visa'];
                    $totalServices = $allDataArr[$data['branch_id']][$data['refer']]['services'] + $data['totaldetectionvalue'] - $data['discount'];

                    $allDataArr[$data['branch_id']][$data['refer']]['detections_no'] = $detections_no;
                    $allDataArr[$data['branch_id']][$data['refer']]['detectionIds'] = $detectionIds;
                    $allDataArr[$data['branch_id']][$data['refer']]['patients_no'] = $patients_no;
                    $allDataArr[$data['branch_id']][$data['refer']]['patientIds'] = $patientIds;
                    $allDataArr[$data['branch_id']][$data['refer']]['cash'] = $totalCash;
                    $allDataArr[$data['branch_id']][$data['refer']]['services'] = $totalServices;
                    $allDataArr[$data['branch_id']][$data['refer']]['paid'] = $totalPaid;
                }
            }
            // var_dump($allDataArr);
        }
        $total = $totalPaid + $totalOld;
        $totalC = $totalCash + $totalOldCash - $totalRefundCash;
        $totalV = $totalVisa + $totalOldVisa - $totalRefundVisa;

        $this->smarty->assign('totalC', $totalC);
        $this->smarty->assign('totalV', $totalV);
        $this->smarty->assign('totalCost', $totalCost);
        $this->smarty->assign('totalCash', $totalCash);
        $this->smarty->assign('totalVisa', $totalVisa);
        $this->smarty->assign('totalDept', $totalDept);
        $this->smarty->assign('totalPaid', $totalPaid);
        $this->smarty->assign('totalOldCash', $totalOldCash);
        $this->smarty->assign('totalOldVisa', $totalOldVisa);
        $this->smarty->assign('totalOld', $totalOld);
        $this->smarty->assign('totalDiscount', $totalDiscount);
        $this->smarty->assign('totalRefundVisa', $totalRefundVisa);
        $this->smarty->assign('totalRefundCash', $totalRefundCash);
        $this->smarty->assign('total', $total);
        $this->smarty->assign('totalDrFees', $totalDrFees);

        $this->smarty->assign('share', $programesetting->system_type);
        $this->smarty->assign('referDrShow', $programesetting->refer_doctor);

        $this->smarty->assign('drDeptName', $programesetting->fin_doc_dept);
        $this->smarty->assign('organizations', $programesetting->organizations);

        // $this->smarty->assign('allData', $new_allData);
        $this->smarty->assign('allData', $allDataArr);
    }

    private function investDetailsNew($keys, $source)
    {

        $details = '<ul style="margin: 0 ; padding: 0;"> ';
        $x = 1;
        foreach ($keys as $key) {
            $data = $source[$key];
            $details .= '<li>';
            if ($x != 1) {
                $details .= ' , ';
            }
            $details .= ' ' . $data['name'] . ' </li>';
            $x++;
        }
        $details .= ' </ul> ';
        return $details;
    }

    private function raysDetailsNew($keys, $source)
    {
        $details = ' <ul style="margin: 0 ; padding: 0;"> ';
        foreach ($keys as $key) {
            $data = $source[$key];
            $details .= '<li>' . $data['name'] . ' </li>';
        }
        $details .= ' </ul> ';
        return $details;
    }

    function invsDetails($visitId)
    {

        $details = '';

        $sql = 'select   invests.name   from invests  
                               join  investigationresults                  on  invests.id = investigationresults.investid  
                                join  visits                                       on  visits.id = investigationresults.visitid 

                                where 
                                   investigationresults.deleted = 0 and  investigationresults.visitid =  ' . $visitId;

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

        if (count($result) > 0) {

            $details = ' <ul style="margin: 0 ; padding: 0;"> ';

            $x = 1;
            foreach ($result as $data) {
                $details .= '<li>';
                if ($x != 1) {
                    $details .= ' , ';
                }
                $details .= ' ' . $data['name'] . ' </li>';
                $x++;
            }

            $details .= ' </ul> ';
        }


        return $details;
    }

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

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