<?php

require_once("imp/_imp.php");

class Controllers {

//public vars
    public $smarty;
    public $hosturl;
    public $controllname;
    public $shcontrollname;
    public $active;
    public $time;
    public $today;

// 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 = 'customer_service';
        $this->shcontrollname = 'customer_service';
        $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] = 'customer_service'; //controller name or tab name
        $active[1] = 'customer_service'; //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("_patientdata.php");
        require_once("_sidebar.php");
        require_once("_leftsidebar.php");
        require_once("_footer.php");

        //find loading time
        $this->time = microtime(true);
        $this->today = date('Y-m-d');
    }

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

        #################################################################### Heba : ## get all rays category ##############################################################################

        $sql = ' select   title , detectionval           from    detections   
                                where del != 1       order by title asc ';
        $detections = R::getAll($sql);

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

        $sql = ' select   invests.name , invests.price  ,   investcats.name  as catName
                                from    invests   
                                join  investcats                     on investcats.id   = invests.investcatid 
                                where  invests.deleted != 1       order by  invests.investcatid asc ,   invests.name asc  ';
        $invests = R::getAll($sql);

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

        $sql = ' select   rays.name , rays.price  ,   rayscats.name  as catName
                                from    rays   
                                join  rayscats                       on rayscats.id   = rays.rayscatid 
                                where  rays.deleted != 1       order by  rays.rayscatid asc ,   rays.name asc  ';
        $rays = R::getAll($sql);

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


        ################################################################################################################################################################################
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('customer_service/prices.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

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

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

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

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

        $sql = ' select   id  , name           from    awrole     where doctor_visit_show = 1       order by id asc ';
        $departs = R::getAll($sql);
        $this->smarty->assign('departs', $departs);

        #############################################
        $doctorSearch = $this->relatedDrEx(0);
        $sql = 'select awusers.* from awusers    
                                            join awrole     on awrole.id = awusers.role_id
                                           where awrole.doctor_visit_show = 1 ' . $doctorSearch;

        $users = R::getAll($sql);
        $this->smarty->assign('users', $users);

        ################################################################################################################################################################################
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('customer_service/visits.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function usersbydept() {
        $doctorSearch = $this->relatedDrEx(0);

        $deptId = filter_input(INPUT_POST, "visit_dept_id");
        if ($deptId > 0) {
            $users = R::getAll('select awusers.user_id , awusers.name  
                    from awusers 
                    where awusers.role_id  =  ?  ' . $doctorSearch, [$deptId]);
        } else {
            $users = R::getAll('select awusers.user_id , awusers.name  
                     from awusers 
                         join awrole     on awrole.id = awusers.role_id  
                    where awrole.doctor_visit_show = 1  ' . $doctorSearch);
        }

        $this->smarty->assign('users', $users);
        $this->smarty->display('customer_service/doctors.html');
    }

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

        $date_from = filter_input(INPUT_POST, "date_from");
        $date_to = filter_input(INPUT_POST, "date_to");
        $deptId = filter_input(INPUT_POST, "deptId");
        $doctorId = filter_input(INPUT_POST, "doctorId");
        $rfc = filter_input(INPUT_POST, "rfc");

        $departs = $this->getOrderDepts(1);

        $visit_doctors = array();
        $rfcSearch = '  ';
        if ($rfc > 0) {
            $rfcSearch .= '   and   visits.rfc  =  ' . $rfc;
        }

        if ($doctorId > 0) {
            $sql = ' select count(visits.id) as visitCount  , awusers.name  as doctorName  , awusers.user_id  as userId
                               ,    0 as confirmed      ,    0 as attended
                            from  visits           
                               join awrole                  on awrole.id = visits.for_department
                               join   awusers               on awusers.user_id  = visits.for_doctor
                          where   awrole.doctor_visit_show = 1    ' . $rfcSearch . '    
                                and visits.deleted != 1 and   visits.visitdate  between "' . $date_from . '"  AND  "' . $date_to . '" 
                               and visits.detectionid not in (999 ,  9999 , -88   )  
                                 and   visits.for_department   in (' . $departs . '  )    and   visits.for_doctor  = ' . $doctorId;

            $visit = R::getRow($sql);

            $sql = ' select count(visits.id) as visitCount  
                            from  visits         
                                  join awrole                  on awrole.id = visits.for_department
                          where    awrole.doctor_visit_show = 1      ' . $rfcSearch . '    
                                and visits.deleted != 1 and   visits.visitdate  between "' . $date_from . '"  AND  "' . $date_to . '" 
                               and visits.detectionid not in (999 ,  9999 , -88   )  and   visits.customer_add  != 1   
                                 and   visits.for_department   in (' . $departs . '  )   and   visits.for_doctor  = ' . $doctorId;

            $confirmed = R::getRow($sql);

            $sql = ' select count(visits.id) as visitCount  
                            from  visits         
                                  join awrole                  on awrole.id = visits.for_department
                          where    awrole.doctor_visit_show = 1       ' . $rfcSearch . '    
                                and visits.deleted != 1 and   visits.visitdate  between "' . $date_from . '"  AND  "' . $date_to . '" 
                               and visits.detectionid not in (999 ,  9999 , -88   )  and   visits.customer_add  != 1   and   visits.view  = 1     
                                 and   visits.for_department   in (' . $departs . '  )    and   visits.for_doctor  = ' . $doctorId;

            $attended = R::getRow($sql);

            //   print_r($attended);

            $visit['confirmed'] = $confirmed['visitCount'];
            $visit['attended'] = $attended['visitCount'];

            if ($visit['visitCount'] == 0) {
                $doctor = R::getRow('select name from awusers where user_id = ?', [$doctorId]);
                $visit['doctorName'] = $doctor['name'];
                $visit['userId'] = $doctorId;
            }

            array_push($visit_doctors, $visit);

            ##
        } elseif ($deptId > 0 && !($doctorId > 0)) {
            $doctorSearch = $this->relatedDrEx(1);

            $sql = ' select distinct   for_doctor   as  userId    
                            from visits 
                          where visits.deleted != 1       ' . $rfcSearch . '   and   visits.visitdate  between "' . $date_from . '"  AND  "' . $date_to . '"      
                                       and visits.detectionid not in (999 ,  9999 , -88   )   ' . $doctorSearch . ' 
                          and   visits.for_department  = ' . $deptId;

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

            foreach ($doctors as $data) {
                $sql = ' select count(visits.id) as visitCount  , awusers.name  as doctorName  , awusers.user_id  as userId
                            from     visits     
                          join       awusers                                           on awusers.user_id  = visits.for_doctor
                                join awrole                  on awrole.id = awusers.role_id
                          where    awrole.doctor_visit_show = 1       ' . $rfcSearch . '    
                                and visits.deleted != 1 and   visits.visitdate  between "' . $date_from . '"  AND  "' . $date_to . '"      
                                       and visits.detectionid not in (999 ,  9999 , -88   )    
                                and   visits.for_department   in (' . $departs . '  )  and   visits.for_doctor  = ' . $data['userId'];

                $visit = R::getRow($sql);

                $sql = ' select count(visits.id) as visitCount  
                            from  visits         
                                  join awrole                  on awrole.id = visits.for_department
                          where    awrole.doctor_visit_show = 1      ' . $rfcSearch . '    
                                and visits.deleted != 1 and   visits.visitdate  between "' . $date_from . '"  AND  "' . $date_to . '" 
                               and visits.detectionid not in (999 ,  9999 , -88   )  and   visits.customer_add  != 1   
                                 and   visits.for_department   in (' . $departs . '  )    and   visits.for_doctor  = ' . $data['userId'];

                $confirmed = R::getRow($sql);

                $sql = ' select count(visits.id) as visitCount  
                            from  visits      
                                  join awrole                  on awrole.id = visits.for_department
                          where    awrole.doctor_visit_show = 1       ' . $rfcSearch . '      
                                and visits.deleted != 1 and   visits.visitdate  between "' . $date_from . '"  AND  "' . $date_to . '" 
                               and visits.detectionid not in (999 ,  9999 , -88   )  and   visits.customer_add  != 1   and   visits.view  = 1     
                                 and   visits.for_department   in (' . $departs . '  )    and   visits.for_doctor  = ' . $data['userId'];

                $attended = R::getRow($sql);

                $visit['confirmed'] = $confirmed['visitCount'];
                $visit['attended'] = $attended['visitCount'];

                array_push($visit_doctors, $visit);
            }
        }

        $this->smarty->assign('rfc', $rfc);
        $this->smarty->assign('visits', $visit_doctors);
        $this->smarty->assign('visitsCount', count($visit_doctors));

        $this->smarty->display('customer_service/search_visits.html');
    }

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

        $date_from = filter_input(INPUT_POST, "date_from");
        $date_to = filter_input(INPUT_POST, "date_to");
        $doctorId = filter_input(INPUT_POST, "doctorId");
        $confirmed = filter_input(INPUT_POST, "confirmed");
        $attended = filter_input(INPUT_POST, "attended");
        $rfc = filter_input(INPUT_POST, "rfc");

        $departs = $this->getOrderDepts(1);

        $sqlExt = ' ';
        if ($confirmed == 1) {
            $sqlExt .= '   and   visits.customer_add  != 1     ';
        }

        if ($attended == 1) {
            $sqlExt .= '   and   visits.view  = 1     ';
        }

        if ($rfc > 0) {
            $sqlExt .= '   and   visits.rfc  =  ' . $rfc;
        }

        $doctor = R::getRow('select name from awusers where user_id = ?', [$doctorId]);
        $this->smarty->assign('doctorName', $doctor['name']);

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

        $sql = ' select visits.id as visitId   ,   patients.wifename as patientName ,   visits.visitdate
                                ,   patients.husdandname as husbandName   ,   patients.statusno  
                                 ,   patients.phone   ,   patients.mobile ,   visits.recep_p_exit  ,   visits.kashf_enterance 
                                 ,   visits.for_husband ,  detections.title as detectionName  , visits.arrived_time
                                   , CASE    WHEN visits.rfc = 1  THEN "Yes"     ELSE "No"    END as rfc  
                                 ,  awrole.name as deptName  ,   visits.visit_order ,   visits.visit_time
                                 ,   visits.arrived_userid   , DATE_FORMAT(visits.arrived_time, "%h:%i %p") as  arrivedTime 
                          from     visits     
                          join patients           on patients.id  =  visits.patientid
                          left   join detections           on detections.id  =  visits.detectionid 
                          left   join awrole                on awrole.id  =  visits.for_department
                          where  awrole.doctor_visit_show = 1  
                           and visits.deleted != 1 and   visits.visitdate  between "' . $date_from . '"  AND  "' . $date_to . '"  
                                and   visits.for_department   in (' . $departs . '  )  and   visits.for_doctor  = ' . $doctorId . '       
                                       and visits.detectionid not in (999 ,  9999 , -88   )     ' . $sqlExt . '         
                                       order  by   visits.visitdate   asc , visits.visit_order asc  , visits.id asc    ';


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

        $waitingMinutes = 0;
        $i = 0;
        foreach ($visits as $visit) {
            if ($visit['arrived_time'] == '0000-00-00' || is_null($visit['arrived_time']) || $visit['arrived_time'] == '') {
                $visits[$i]['waiting'] = '';
            } else {
                $dateWife = new DateTime($visit['arrived_time']);
                $today1 = new DateTime($visit['kashf_enterance']);
                $interval = $today1->diff($dateWife);
                $visits[$i]['waiting'] = $interval->h . ' h -  ' . $interval->i . ' m ';
                $waitingMinutes = $waitingMinutes + 60 * $interval->h + $interval->i;
            }
            $i++;
        }

        $waitingAvgMin = $waitingMinutes / count($visits);
        $waitingAvgHr = floor($waitingAvgMin / 60);
        $waitingAvgMin = $waitingAvgMin - (60 * $waitingAvgHr);
        $waitingAvg = $waitingAvgHr . ' h -  ' . $waitingAvgMin . ' m ';

        $this->smarty->assign('visits', $visits);
        $this->smarty->assign('confirmed', $confirmed);
        $this->smarty->assign('attended', $attended);
        $this->smarty->assign('waitingAvg', $waitingAvg);

        $this->smarty->display('customer_service/doctor_visits.html');
    }

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

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

        if ($id > 0) {
            try {
                $inv = R::load('visits', $id);
                $inv->arrived_userid = $_SESSION['user_id'];
                $inv->arrived_time = date('Y-m-d H:i:s'); //$this->today;
                r::store($inv);

                echo date('h:i A');

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

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

        $doctorSearch = '';
        $user = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);
        if ($user['role_id'] == 19 && $user['related_dr'] != 0 && !empty($user['related_dr']) &&
                $user['related_dr'] != "" && !( is_null($user['related_dr']))) {

            switch ($fromTable) {
                case 1:   // visits
                    $doctorSearch = ' and visits.for_doctor in  (' . $user['related_dr'] . ' ) ';
                    break;

                default:    //  awusers
                    $doctorSearch = ' and awusers.user_id in  (' . $user['related_dr'] . ' ) ';
                    break;
            }
        }

        return $doctorSearch;
    }

    function getOrderDepts($text = 0) {
        $departs = array();
        $departsText = '';
        $sql = ' select   id      from    awrole     where doctor_visit_show = 1       order by id asc ';
        $depts = R::getAll($sql);

        $i = 0;
        foreach ($depts as $dept) {
            array_push($departs, $dept['id']);
            if ($i > 0) {
                $departsText .= ' , ';
            }
            $departsText .= $dept['id'];
            $i++;
        }
        if ($text == 1) {
            return $departsText;
        } else {
            return $departs;
        }
    }

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

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

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

        $patients = R::getAll('select id , wifename , husdandname from patients where deleted = ? and done = ?', [0, 1]);
        $this->smarty->assign('patients', $patients);

        ################################################################################################################################################################################
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('customer_service/complaint.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

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

        #############################################
//        $complaints = R::findAll('patients_complaints', 'deleted = ? and call_date_time like "' . date('Y-m-d') . '%" ', [0]);

        $sql = ' select patients_complaints.id as id   ,   patients.wifename as patientName  , patients_complaints.call_date_time
                                ,   patients.husdandname as husbandName   ,   patients.statusno  , awusers.name as userName 
                          from     patients_complaints     
                          join patients                        on patients.id  =  patients_complaints.patientid 
                          join  awusers                               on awusers.user_id   = patients_complaints.user_id 
                                where patients_complaints.deleted != 1 ';

        $complaints = R::getAll($sql);
        $this->smarty->assign('complaints', $complaints);

        $btnEdit = R::findOne('awrolebtn', ' role_id = ? and btn_id = 5  ', [$_SESSION['role_id']]);
        $btnDelete = R::findOne('awrolebtn', ' role_id = ? and btn_id = 6  ', [$_SESSION['role_id']]);

        $this->smarty->assign('btnEdit', $btnEdit->checkval);
        $this->smarty->assign('btnDelete', $btnDelete->checkval);

        ################################################################################################################################################################################
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('customer_service/complaint_show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function complaint_delete() {

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

        $id = filter_input(INPUT_POST, 'id');
        try {
            R::exec('UPDATE patients_complaints SET deleted = 1 WHERE id = ' . $id);
            echo 1;
        } catch (Exception $e) {
            
        }
    }

    public function complaint_add() {

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

        //vars here
        $patientid = filter_input(INPUT_POST, 'patientid');
        $reply = filter_input(INPUT_POST, 'reply');
        $complaiv = filter_input(INPUT_POST, 'complaiv');

        //here the add
        $complaint = R::xdispense('patients_complaints');

        $complaint->patientid = $patientid;
        $complaint->complaiv = $complaiv;
        $complaint->reply = $reply;
        $complaint->call_date_time = date('Y-m-d h:i:s');
        $complaint->user_id = $_SESSION['user_id'];
        $complaint->deleted = 0;


        try {
            $id = R::store($complaint);
            header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=complaint_show');
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notadd/' . $this->controllname);
        }
    }

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

        #############################################
        $complainId = filter_input(INPUT_GET, 'id');

        $complaint = R::load('patients_complaints', $complainId);
        $this->smarty->assign('complaint', $complaint);

        $patients = R::getAll('select id , wifename , husdandname from patients where deleted = ? and done = ?', [0, 1]);
        $this->smarty->assign('patients', $patients);

        ################################################################################################################################################################################
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('customer_service/complaint_edit.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function complaint_update() {

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

        //vars here
        $complainId = filter_input(INPUT_POST, 'complaint_id');
        $patientid = filter_input(INPUT_POST, 'patientid');
        $reply = filter_input(INPUT_POST, 'reply');
        $complaiv = filter_input(INPUT_POST, 'complaiv');

        //here the add
        $complaint = R::load('patients_complaints', $complainId);

        $complaint->patientid = $patientid;
        $complaint->complaiv = $complaiv;
        $complaint->reply = $reply;
//        $complaint->call_date_time = date('Y-m-d h:i:s');
//        $complaint->user_id = $_SESSION['user_id'];
//        $complaint->deleted = 0;


        try {
            $id = R::store($complaint);
            header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=complaint_show');
        } catch (Exception $e) {
            header('Location:' . $this->hosturl . '/error/notupdate/' . $this->controllname);
        }
    }

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

        #############################################
        $complainId = filter_input(INPUT_GET, 'id');

        $sql = ' select   patients_complaints.id   ,   patients_complaints.complaiv   , patients_complaints.reply
                                 , patients.wifename  , patients.husdandname  , "" as patientName   , patients.statusno 
                                  , awusers.name as userName 
                                
                                from    patients_complaints      
                                join  patients                               on patients.id   = patients_complaints.patientid 
                                join  awusers                               on awusers.user_id   = patients_complaints.user_id 
                                where  
                                patients_complaints.deleted != 1       and patients_complaints.id =  ' . $complainId;

        $complaint = R::getRow($sql);
        $complaint['patientName'] = $complaint['wifename'] . ' - ' . $complaint['husdandname'];
        $this->smarty->assign('complaint', $complaint);

        ################################################################################################################################################################################
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('customer_service/complaint_details.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

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

        #############################################
        $complainId = filter_input(INPUT_GET, 'id');
        $complaint = R::load('patients_complaints', $complainId);
        $patient = R::load('patients', $complaint->patientid);

        $sql = ' select      patients_complaints.complaiv   , patients_complaints.reply  , awusers.name as userName   
                                         ,  TIME_FORMAT(patients_complaints.call_date_time, "%h:%i %p") as  call_time
                                         , DATE_FORMAT(patients_complaints.call_date_time, "%Y-%c-%d") as  call_date 
                                from    patients_complaints      
                                join  awusers                               on awusers.user_id   = patients_complaints.user_id 
                                where  
                                patients_complaints.deleted != 1       
                                and patients_complaints.patientid =  ' . $complaint->patientid . ' order by call_date_time desc ';

        $complaints = R::getAll($sql);
        $this->smarty->assign('complaints', $complaints);
        $this->smarty->assign('patient', $patient);
        ################################################################################################################################################################################
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('customer_service/complaint_details_all.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

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

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

        $date_from = filter_input(INPUT_POST, "date_from");
        $date_to = filter_input(INPUT_POST, "date_to");
        $deptId = filter_input(INPUT_POST, "deptId");
        $doctorId = filter_input(INPUT_POST, "doctorId");
        $confirmed = filter_input(INPUT_POST, "confirmed");
        $attended = filter_input(INPUT_POST, "attended");
        $rfc = filter_input(INPUT_POST, "rfc");

        $result = array();

        $begin = new DateTime($date_from);
        $end = new DateTime($date_to . ' +1 day');

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

        foreach ($period as $dt) {
            $day = array();
            $dayDate = $dt->format("Y-m-d");
            $dayName = $this->getDayNameFnAr($dayDate);
            $dayDoctors = $this->dayDoctors($dayDate, $deptId, $doctorId, $confirmed, $attended, $rfc);

            $day['dayDate'] = $dayDate;
            $day['dayName'] = $dayName;
            $day['dayDoctors'] = $dayDoctors;
            array_push($result, $day);
        }

        $this->smarty->assign('days', $result);
        $this->smarty->assign('resultCount', count($result));
        $this->smarty->assign('confirmed', $confirmed);
        $this->smarty->assign('attended', $attended);

        $this->smarty->display('customer_service/visits_print.html');
    }

    function dayDoctors($dayDate, $deptId, $doctorId, $confirmed, $attended, $rfc) {
        $sqlExt = ' ';
        if ($confirmed == 1) {
            $sqlExt .= '   and   visits.customer_add  != 1     ';
        }

        if ($attended == 1) {
            $sqlExt .= '   and   visits.view  = 1     ';
        }

        if ($rfc > 0) {
            $sqlExt .= '   and   visits.rfc  =  ' . $rfc;
        }

        $doctors = array();

        if ($doctorId > 0) {
            $doctor = array();
            $doctor['doctorId'] = $doctorId;
            array_push($doctors, $doctor);
        }
        ##
        elseif ($deptId > 0 && !($doctorId > 0)) {
            $doctorSearch = $this->relatedDrEx(1);

            $sql = ' select distinct   for_doctor   as  doctorId    
                            from visits 
                          where visits.deleted != 1 and   visits.visitdate  = "' . $dayDate . '"       
                        and visits.detectionid not in (999 ,  9999 , -88   )   ' . $sqlExt . '      ' . $doctorSearch . '     
                          and   visits.for_department  = ' . $deptId;

            $doctors = R::getAll($sql);
        }

        $doctors = $this->doctorVisits($doctors, $dayDate, $sqlExt);
        return $doctors;
    }

    function doctorVisits($doctors, $dayDate, $sqlExt) {
        $x = 0;
        foreach ($doctors as $doctor) {

            $doc = R::getRow('select name from awusers where user_id = ?', [$doctor['doctorId']]);
            $doctors[$x]['doctorName'] = $doc['name'];
            $departs = $this->getOrderDepts(1);

            $sql = ' select visits.id as visitId   ,   patients.wifename as patientName ,   visits.visitdate
                                ,   patients.husdandname as husbandName   ,   patients.statusno  
                                 ,   patients.phone   ,   patients.mobile ,   visits.recep_p_exit  ,   visits.kashf_enterance 
                                 ,   visits.for_husband ,  detections.title as detectionName  , visits.arrived_time
                                  , CASE    WHEN visits.rfc = 1  THEN "Yes"     ELSE "No"    END as rfc 
                                 ,  awrole.name as deptName   ,   visits.notes  ,   visits.visit_order ,   visits.visit_time 
                                   ,   visits.arrived_userid   , DATE_FORMAT(visits.arrived_time, "%h:%i %p") as  arrivedTime 
                          from     visits     
                          join patients           on patients.id  =  visits.patientid
                          left   join detections           on detections.id  =  visits.detectionid 
                          left   join awrole                on awrole.id  =  visits.for_department
                          where awrole.doctor_visit_show = 1  
                           and  visits.deleted != 1 and   visits.visitdate  = "' . $dayDate . '"  
                                and   visits.for_department  in (' . $departs . '  )       ' . $sqlExt . '          
                                       and visits.detectionid not in (999 ,  9999 , -88   )   
                                and   visits.for_doctor  = ' . $doctor['doctorId'] . '   
                                    order  by     visits.visitdate   asc , visits.visit_order asc  , visits.id asc    ';


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

            $waitingMinutes = 0;
            $i = 0;
            foreach ($visits as $visit) {
                if ($visit['arrived_time'] == '0000-00-00' || is_null($visit['arrived_time']) || $visit['arrived_time'] == '') {
                    $visits[$i]['waiting'] = '';
                } else {
                    $dateWife = new DateTime($visit['arrived_time']);
                    $today1 = new DateTime($visit['kashf_enterance']);
                    $interval = $today1->diff($dateWife);
                    $visits[$i]['waiting'] = $interval->h . ' h -  ' . $interval->i . ' m ';
                    $waitingMinutes = $waitingMinutes + 60 * $interval->h + $interval->i;
                }
                $i++;
            }

            $waitingAvgMin = $waitingMinutes / count($visits);
            $waitingAvgHr = floor($waitingAvgMin / 60);
            $waitingAvgMin = $waitingAvgMin - (60 * $waitingAvgHr);
            $waitingAvg = $waitingAvgHr . ' h -  ' . $waitingAvgMin . ' m ';

            $doctors[$x]['doctorVisits'] = $visits;
            $doctors[$x]['doctorVisitsCount'] = count($visits);
            $doctors[$x]['waitingAvg'] = $waitingAvg;
            $x++;
        }

        return $doctors;
    }

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

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

        if ($id > 0) {

            $patient = R::load('patients', $id);

            $result = array(
                "address" => $patient->address,
                "phone" => $patient->phone,
                "mobile" => $patient->mobile
            );

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

// at the end of class call

    public function __destruct() {
        //echo "Time Elapsed: ".(microtime(true) - $this->time)."s";
//close connection
        R::close();
    }

}
