<?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 = 'today_list';
        $this->shcontrollname = "Today's List";
        $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] = 'today_list'; //controller name or tab name
        $active[1] = 'today_list'; //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);
        });

        #########################################################
        require_once("visits_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']);

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

        $time = date('H', time());
        $sql = ' and clinic_entered != 1 and detectionid not in (-99 , 9999 , 999 )  and today_list  = 1 and today_list_dept  = 0   ';

        if ($time <= $programesetting->addshours) {
            ## iam now at extra time show yesterday visits  also
            $allvisit = R::findAll('visits', 'visitdate in (? , ? )  and deleted = ?     ' . $sql . '
                                                  ORDER BY id ASC  ', [date('Y-m-d'), date('Y-m-d', strtotime("-1 days")), 0]);
        } else {
            $allvisit = R::findAll('visits', 'visitdate = ?  and deleted = ?    
                             ' . $sql . '      ORDER BY id ASC  ', [date('Y-m-d'), 0]);
        }


        $allvisit = $this->visitsDetails($allvisit);
        $this->smarty->assign('visits', $allvisit);

        $roles = R::findAll('clinic_rooms', 'today_list = 1 order by id ');
        foreach ($roles as $role) {
            $sql = ' and clinic_entered != 1  and detectionid not in (-99 , 9999 , 999 )  and today_list  = 1 
                    and today_list_dept  =  ' . $role->id;
            if ($time <= $programesetting->addshours) {
                ## iam now at extra time show yesterday visits  also
                $allvisit = R::findAll('visits', 'visitdate in (? , ? )  and deleted = ?     ' . $sql . '
                                                  ORDER BY id ASC  ', [date('Y-m-d'), date('Y-m-d', strtotime("-1 days")), 0]);
            } else {
                $allvisit = R::findAll('visits', 'visitdate = ?  and deleted = ?    
                             ' . $sql . '      ORDER BY id ASC  ', [date('Y-m-d'), 0]);
            }

            $role->visits = $this->visitsDetails($allvisit);
            list($doctor_id, $doctor_name) = $this->clinicDoctor($role->id, date('Y-m-d'));
            $role->doctor_name = $doctor_name;
            $role->roleCurrentPatient = $this->current($role->id, date('Y-m-d'));
        }
        $this->smarty->assign('roles', $roles);

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

    function current($roomId, $date) {
        $patientName = '';
        $room_info = R::findOne('visits', 'in_clinic = ? and today_list_dept = ? and   visitdate = "' . $date . '"
                 and deleted = 0 order by id desc', [1, $roomId]);

        if ($room_info) {
            $patient_info = R::findOne('patients', 'id = ?', [$room_info->patientid]);
            $patientName = ($room_info->for_husband == 1) ? $patient_info->husdandname : $patient_info->wifename;
        }

        return $patientName;
    }

    public function visitsDetails($allvisit) {
        foreach ($allvisit as $visit) {
            $patientName = R::findOne('patients', 'id = ? ', [$visit->patientid]);

            if ($visit->for_husband == 1) {
                $visit->patientName = $patientName->husdandname;
            } elseif ($visit->for_husband == 2) {

                $child = R::load('patients_childs', $visit->child);

                if (is_null($child->child_name) || $child->child_name == '') {
                    if ($child->gender == 1) {
                        $visit->patientName = 'الطفل / ' . $patientName->wifename;
                    } else {
                        $visit->patientName = 'الطفلة / ' . $patientName->wifename;
                    }
                } else {
                    $visit->patientName = $child->child_name . '  /  ' . $patientName->wifename;
                }
            } else {
                $visit->patientName = $patientName->wifename;
            }


            $file = '../../upload/patientrecords/' . $visit->patientid . '.wav';
            $file1 = '../../upload/patientrecords/' . $visit->patientid . '.mp3';
            $voiceRecord = 0;
            if (file_exists($file)) {
                $visit->voiceExt = 'wav';
            } elseif (file_exists($file1)) {
                $visit->voiceExt = 'mp3';
            }


            $visit->patientId = $patientName->id;
            $visit->statusno = $patientName->statusno;
            $visit->statusno = $patientName->statusno;
        }

        return $allvisit;
    }

    public function attend_today() {
        $patientNo = filter_input(INPUT_GET, 'patientNo');
        $res = 0;
        if ($patientNo > 0) {
            $patientid = getPatientId($patientNo);
            $visit = R::findOne('visits', ' deleted = 0    and  visitdate = ?  and detectionid not in (-99 , 9999 , 999 )  
                and today_list  = 0 and today_list_dept  = 0  and  patientid = ?  ', [date('Y-m-d'), $patientid]);
            if (count($visit) > 0 && $visit->id > 0) {
                $visit->today_list = 1;
                R::store($visit);
                $res = 1;
            }
        }
        echo $res;
        return $res;
    }

    public function enterClinic() {
        $visitId = filter_input(INPUT_POST, 'visitId');
        if ($visitId > 0) {
            $visit = R::findOne('visits', 'id = ?', [$visitId]);
            R::exec('update visits set  in_clinic = 0     where today_list_dept = ' . $visit->today_list_dept);
            $visit->clinic_entered = 1;
            $visit->in_clinic = 1;
            R::store($visit);

            $patient = R::findOne('patients', 'id = ? ', [$visit->patientid]);
            if ($visit->for_husband == 1) {
                $patientName = $patient->husdandname;
            } elseif ($visit->for_husband == 2) {

                $child = R::load('patients_childs', $visit->child);

                if (is_null($child->child_name) || $child->child_name == '') {
                    if ($child->gender == 1) {
                        $patientName = 'الطفل / ' . $patient->wifename;
                    } else {
                        $patientName = 'الطفلة / ' . $patient->wifename;
                    }
                } else {
                    $patientName = $child->child_name . '  /  ' . $patient->wifename;
                }
            } else {
                $patientName = $patient->wifename;
            }

            $result = array(
                "patientid" => $visit->patientid,
                "visitId" => $visitId,
                "patientName" => $patientName,
                "clinicid" => $visit->today_list_dept
            );

            echo json_encode($result);
        }
    }

    public function exitClinic() {
        $clinicId = filter_input(INPUT_POST, 'clinicId');

        try {
            if ($clinicId > 0) {
                R::exec('update visits set  in_clinic = 0     where today_list_dept = ' . $clinicId);
                echo 1;
            }
        } catch (Exception $ex) {
            echo -1;
        }
    }

    public function sortable() {
        $sortedData = filter_input(INPUT_POST, 'datasorted');
        $deptId = filter_input(INPUT_POST, 'deptId');
        $this->updatearrange($sortedData, $deptId);
    }

    public function updatearrange($data, $deptId) {
        $moved = 0;
        parse_str($data, $str);
        $datasort = $str['item'];
        for ($i = 0; $i < count($datasort); $i++) {
            $visit = R::load('visits', $datasort[$i]);
            $visit->today_list_sort = $i + 1;
            if ($visit->today_list_dept != $deptId) {
                $moved = $visit->id;
            }
            $visit->today_list_dept = $deptId;
            R::store($visit);
        }
        echo $moved;
    }

    function clinicDoctor($roomId, $date) {
        $theHour = date('H') . ':00';
        if ($theHour === '07') {
            $theHour = '7';
        }

        list($weekday, $dayNo) = $this->getTodayNumber($date);

        $clinic_reserve = R::findOne('clinic_reserves', 'room_id = ? and reserve_day_no = ? 
                   and reserve_hour = ?     and is_active = 1
                 and deleted = 0 order by id desc', [$roomId, $dayNo, $theHour]);

        $doctor_name = '  ';
        $doctor_id = 0;

        if ($clinic_reserve) {
            $doctor_info = R::findOne('awusers', 'user_id = ?', [$clinic_reserve->doctor_id]);
            $doctor_name = $doctor_info->name;
            $doctor_id = $doctor_info->doctor_id;
        }

        return array($doctor_id, $doctor_name);
    }

    protected function getTodayNumber($today) {
        $weekday = date('l', strtotime($today));
        switch ($weekday) {
            case 'Sunday':
                $dayNo = 2;
                break;
            case 'Monday':
                $dayNo = 3;
                break;
            case 'Tuesday':
                $dayNo = 4;
                break;
            case 'Wednesday':
                $dayNo = 5;
                break;
            case 'Thursday':
                $dayNo = 6;
                break;
            case 'Friday':
                $dayNo = 7;
                break;
            default:
                $dayNo = 1;
                break;
        }
        return array($weekday, $dayNo);
    }

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

}
