<?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 $hosturl_ERP;
    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;
        $this->hosturl_ERP = $hosturl_ERP;

        //here name of controll to known
        $this->controllname = 'patientdebt';
        $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] = 'patientdebt'; //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']);

        if ($_SESSION['role_id'] == 12) {
            $fordepartment = 12;
        }

        $this->commonSearch();

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

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

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

        $billsSql = $this->billsPayingSql($billShow);
        if (!empty($billsSql) && $billsSql != '') {
            $billsSql = '  union all    ' . $billsSql;
        }
        $sql = $this->visitSql($ext, $billsSql);

        //print_r($sql);

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

    function billsPayingSql($billShow)
    {
        $ext = '';
        $billsSql = '';

        if ($billShow == 1) {
            $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  bill_paying.deleted = 0 ' . $ext . '  ' . $billsSql;
        }
        return $billsSql;
    }

    public function visitSql($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 patients.deleted = 0 ' . $ext . '  ' . $billsSql;
        return $sql;
    }


    private function common($allData)
    {
        $totalDebt = 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'];
                }
            }
            $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');
        //     var_dump(2222);
        // die();
        // get all ids level 2
        $programesetting = R::findOne('programesetting');

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

        foreach ($allData as $data) {
            if ($data['statusno'] == 576) {
                var_dump($data);
                $totalDebt += $data['restdetectionvalue'];
            }
            $new_allData[] = $data;
            $i++;
        }

        $patientsArr = [];
        foreach ($new_allData as $data) {
            if (!array_key_exists($data['patientid'], $patientsArr)) {
                $patientsArr[$data['patientid']] = $data;
                $patientsArr[$data['patientid']]['totaldebt'] = $data['restdetectionvalue'];
            } else {
                $patientsArr[$data['patientid']]['totaldebt'] += $data['restdetectionvalue'];
            }
        }
        var_dump($totalDebt);
        $this->smarty->assign('totalDebt', $totalDebt);
        $this->smarty->assign('allData', $patientsArr);
    }



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

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

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