<?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);

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

        $programesetting = R::findOne('programesetting');
        if ($programesetting->branches == 1) {
            $this->loadWithBranches();
            $b = '_branch';
        } else {
            $b = '';
            $this->drawRoomReservation();
            $this->drawWeekTable();
        }
        $this->smarty->assign('programesetting', $programesetting);
        ####################################################################
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);

        if ($programesetting->rooms == 1) {
            $this->smarty->display('reserve_clinic/v_version/add_v' . $b . '.html');
        } else {
            $this->smarty->display('reserve_clinic/h_version/add_h' . $b . '.html');
        }

        //  $this->smarty->display('reserve_clinic/add.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    function loadWithBranches() {

        $allBranches = R::findAll('branches');
        foreach ($allBranches as $branch) {
            $branchSql = ' and branch_id =  ' . $branch->id;
            $branch->rooms = $this->drawRoomReservation($branch->id, $branchSql);
            $branch->days = $this->drawWeekTable();
        }

        $this->smarty->assign('allBranches', $allBranches);
    }

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

        $programesetting = R::findOne('programesetting');
        if ($programesetting->branches == 1) {
            $this->loadWithBranches();
            $b = '_branch';
        } else {
            $b = '';
            $this->drawRoomReservation();
            $this->drawWeekTable();
        }

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

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

        if ($programesetting->rooms == 1) {
            $this->smarty->display('reserve_clinic/v_version/dept_clinics_v' . $b . '.html');
        } else {
            $this->smarty->display('reserve_clinic/h_version/dept_clinics_h' . $b . '.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 , branch_id  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);

        $programesetting = R::findOne('programesetting');
        if ($programesetting->branches == 1) {
            $branches = R::findAll('branches');
            $this->smarty->assign('branches', $branches);
            $this->smarty->assign('branchesActivate', $programesetting->branches);
        }

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

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



        $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);
        return $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);
        }

        return $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']);
        ####################################################################
        $programesetting = R::findOne('programesetting');



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

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

        if ($programesetting->branches == 1) {
            $branches = R::findAll('branches');
            $this->smarty->assign('branches', $branches);
            $this->smarty->assign('branchesActivate', $programesetting->branches);

            $room->branch_id = 0;
        }

        R::store($room);

        $clinics = r::getAll('select id , name  , today_list  , clinic_no , branch_id  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");
        $branchId = filter_input(INPUT_POST, "branchId");

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

        $branchSql = ' ';
        if ($branchId > 0 && $programesetting->branches == 1) {
            $branchSql = ' and branch_id =  ' . $branchId;

            $branch = R::load('branches', $branchId);
            $this->smarty->assign('branchName', $branch->name);
        }

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

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

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

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


        $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();
    }

}
