<?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 = 'reserve_clinic';
        $this->shcontrollname = 'reserve_clinic';
        $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] = 'Reserve Clinic'; //controller name or tab name
        $active[1] = 'Reserve Clinic'; //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 index() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        ####################################################################
        $departs = R::findAll('awrole', 'visit_show = 1 ');
        $this->smarty->assign('departs', $departs);

        $this->drawRoomReservation();
        $this->drawWeekTable();

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

        ####################################################################
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $programesetting = R::findOne('programesetting');

        if ($programesetting->rooms == 1) {
            $this->smarty->display('reserve_clinic/add_v.html');
        } else {
            $this->smarty->display('reserve_clinic/add_h.html');
        }
        //  $this->smarty->display('reserve_clinic/add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function getDeptClinics() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        ####################################################################
        $this->drawRoomReservation();
        $this->drawWeekTable();
        ####################################################################
        //call other class with other content
        if ($programesetting->rooms == 1) {
            $this->smarty->display('reserve_clinic/dept_clinics_v.html');
        } else {
            $this->smarty->display('reserve_clinic/dept_clinics_h.html');
        }
        //   $this->smarty->display('reserve_clinic/dept_clinics.html');
    }

    public function displayDeptClinics() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        ####################################################################
        $clinics = r::getAll('select id , name , today_list  , clinic_no , 0 as  voiceRecord  from clinic_rooms where 
                                   deleted != 1 and is_active = 1 ');

        $i = 0;
        foreach ($clinics as $clinic) {
            $file = '../../upload/clinicrecords/' . $clinic['id'] . '.wav';

            if (file_exists($file)) {
                $clinics[$i]['voiceRecord'] = 1;
            }
            $i++;
        }

        $this->smarty->assign('clinics', $clinics);
        ####################################################################
        //call other class with other content
        $this->smarty->display('reserve_clinic/clinics.html');
    }

    function drawRoomReservation() {
        $rooms = r::getAll('select id , name from clinic_rooms where 
                                   deleted != 1 and is_active = 1 ');

        $x = 0;
        foreach ($rooms as $room) {
            for ($i = 1; $i <= 7; $i++) {
                $res = array();
                $resName = array();
                $reservedHours = r::getAll('select clinic_reserves.reserve_hour  ,    awusers.name as doctorName
                                        from clinic_reserves 
                                         join    awusers    on   awusers.user_id  =  clinic_reserves.doctor_id
                                        where clinic_reserves.room_id = ?  and clinic_reserves.reserve_day_no = ? 
                                  and clinic_reserves.deleted != 1 and clinic_reserves.is_active = 1 ', [$room['id'], $i]);

                foreach ($reservedHours as $value) {
                    array_push($res, $value['reserve_hour']);
                    array_push($resName, $value['doctorName']);
                }


                $rooms[$x]['resHours' . $i] = $res;
                $rooms[$x]['resNames' . $i] = $resName;
//                $this->smarty->assign('resHours' . $i . '_' . $room['id'], $reservedHours);
            }
            $x++;
        }
        $this->smarty->assign('rooms', $rooms);
    }

    function drawWeekTable($dayNo = '') {
        $programesetting = R::findOne('programesetting');
        $start_hour = $programesetting->start_hour;
        $end_hour = $programesetting->end_hour;
        ####################################################################
        if ($dayNo > 0) {
            $days = $this->addDayPerDay($start_hour, $end_hour, $dayNo);
            $this->smarty->assign('day', $days);
        } else {
            $days = $this->addDay($start_hour, $end_hour);
            $this->smarty->assign('days', $days);
        }

//        print_r($days);
    }

    function addDay($start_hour, $end_hour) {
        $hours = $this->addHour($start_hour, $end_hour);


        $days = array();
        for ($i = 0; $i <= 6; $i++) {
            $no = $i + 1;
            $day = array('no' => $no, 'hours' => $hours);
            array_push($days, $day);
        }
        return $days;
    }

    function addHour($start_hour, $end_hour) {
        $hours = array();
        array_push($hours, $start_hour);

        $hours = $this->addHourEx($hours, $start_hour, $end_hour);

        return $hours;
    }

    function addHourEx($hours, $hour, $end_hour) {

        $st_time = strtotime($hour);
        $end_time = strtotime($end_hour);

        if ($st_time == $end_time) {
            
        } else {
            $new_hour = date('H:i', strtotime($hour . '+1 hour'));
            array_push($hours, $new_hour);
            $hours = $this->addHourEx($hours, $new_hour, $end_hour);
        }
        return $hours;
    }

    private function getDayN0($date) {
        $timestamp = strtotime($date);
        $day = date('w', $timestamp);

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

        $res = array('dayNo' => $no, 'dayName' => $name);

        return $res;
    }

    public function del() {

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

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

        try {
            $table_obj = R::load($tableName, $id);
            $table_obj->deleted = 1;
            R::store($table_obj);

            echo 1;
        } catch (Exception $e) {
            echo -1;
        }
    }

    public function update() {

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

        $id = filter_input(INPUT_POST, "id");
        $tableName = filter_input(INPUT_POST, "tableName");
        $colName = filter_input(INPUT_POST, "colName");
        $value = filter_input(INPUT_POST, "value");

        try {
            $table_obj = R::load($tableName, $id);
            $table_obj->$colName = $value;
            R::store($table_obj);

            echo 1;
        } catch (Exception $e) {
            echo -1;
        }
    }

    public function reserveClinic() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        ####################################################################
        $doctorId = filter_input(INPUT_POST, "doctorId");
        $start_date = filter_input(INPUT_POST, "start_date");
        $selectedHours = json_decode(stripslashes(filter_input(INPUT_POST, 'jsonString')));

        try {
            foreach ($selectedHours as $data) {

                $reserve = R::xdispense('clinic_reserves');

                $reserve->room_id = $data[2];
                $reserve->doctor_id = $doctorId;
                $reserve->reserve_day_no = $data[0];
                $reserve->reserve_hour = $data[1];
                $reserve->start_date = $start_date;
                $reserve->user_id = $_SESSION['user_id'];
                $reserve->sys_date = date('Y-m-d h:i:s');
                $reserve->is_active = 1;
                $reserve->deleted = 0;

                R::store($reserve);
            }

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

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

        $room = R::xdispense('clinic_rooms');

        $room->dept_id = 0;
        $room->is_active = 1;
        $room->deleted = 0;

        R::store($room);

        $clinics = r::getAll('select id , name  , today_list  , clinic_no  from clinic_rooms where 
                                   deleted != 1 and is_active = 1 ');

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

        $this->smarty->display('reserve_clinic/rooms.html');
    }

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

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

        $doctors = r::getAll('select distinct   clinic_reserves.doctor_id  ,    awusers.name as doctorName
                                        from clinic_reserves 
                                         join    awusers    on   awusers.user_id  =  clinic_reserves.doctor_id
                                        where  deleted != 1 and is_active = 1 ');


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

    public function cancel() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        ####################################################################
        $canceledHour = json_decode(stripslashes(filter_input(INPUT_POST, 'jsonString')));

        try {
            foreach ($canceledHour as $data) {
//                r::debug(true, 2);
                $reserve = R::findOne('clinic_reserves', '  reserve_day_no  = ? and reserve_hour = ?  
                                   and   room_id = ? and is_active = 1 and deleted = 0    ', [$data[0], $data[1], $data[2]]);

                $reserve->cancel_date = date('Y-m-d');
                $reserve->is_active = 0;
                $reserve->deleted = 1;

                R::store($reserve);
            }

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

    public function printDay() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        //autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        ####################################################################
        $dayNo = filter_input(INPUT_POST, "dayNo");

        $this->drawRoomReservationPerDay($dayNo);
        $this->drawWeekTable($dayNo);

        $dayName = $this->getDayName($dayNo);
        $this->smarty->assign('dayName', $dayName);

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

        if ($programesetting->rooms == 1) {
            $this->smarty->display('reserve_clinic/print_v.html');
        } else {
            $this->smarty->display('reserve_clinic/print_h.html');
        }
    }

    function drawRoomReservationPerDay($dayNo) {
        $rooms = r::getAll('select id , name from clinic_rooms where 
                                   deleted != 1 and is_active = 1 ');


        $x = 0;
        foreach ($rooms as $room) {
            $res = array();
            $resName = array();
            $reservedHours = r::getAll('select clinic_reserves.reserve_hour  ,    awusers.name as doctorName
                                        from clinic_reserves 
                                         join    awusers    on   awusers.user_id  =  clinic_reserves.doctor_id
                                        where room_id = ?  and reserve_day_no = ? 
                                  and clinic_reserves.deleted != 1 and clinic_reserves.is_active = 1 ', [$room['id'], $dayNo]);

            foreach ($reservedHours as $value) {
                array_push($res, $value['reserve_hour']);
                array_push($resName, $value['doctorName']);
            }


            $rooms[$x]['resHours'] = $res;
            $rooms[$x]['resNames'] = $resName;
            $x++;
        }
        $this->smarty->assign('rooms', $rooms);
    }

    function addDayPerDay($start_hour, $end_hour, $dayNo) {
        $hours = $this->addHour($start_hour, $end_hour);
        $day = array('no' => $dayNo, 'hours' => $hours);
        return $day;
    }

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

        return $name;
    }

// at the end of class call

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

}
