<?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 structure of file
 */

use RedBeanPHP\RedException;

require_once("imp/_imp.php");

/**
 * @class operations_calendar
 */
class Controllers
{

    //public vars
    public $smarty;
    public $host_url;
    public $controlName;
    public $active;

    /**
     * @throws RedException
     */
    public function __construct()
    {
        require_once("../public/aw_config.php");
        require_once("imp/_autho.php"); //general functions
        /** @var $smarty
         * @var $hosturl
         */
        $this->smarty = $smarty;
        $this->host_url = $hosturl;

        require_once("../../_library/plugins/Breadcrumbs/Breadcrumbs.php");
        $action = filter_input(INPUT_GET, 'ac');
        $bc = new breadcrumbs($hosturl, '', '', $action);
        $bc->crumbs();
        $breadcrumbs = $bc->breadcrumbs;
        $smarty->assign('breadcrumbs', $breadcrumbs);

        $this->controlName = 'operations_calendar';
        $shcontrollname = 'Operations Calendar';
        $this->smarty->assign('controllname', $this->controlName);
        $this->smarty->assign('shcontrollname', $shcontrollname);

        R::ext('xdispense', static function ($type) {
            return R::getRedBean()->dispense($type);
        });

        $active[0] = 'operations';
        $active[1] = $this->controlName;
        $active[2] = 'show';
        $this->active = $active;

        require_once("_header.php");
        require_once("_sidebar.php");
        require_once("_leftsidebar.php");
        require_once("_footer.php");
    }

    public function index()
    {
        $this->authChecking();

        $this->preData();

        $this->smartyHtml('operations_calendar/show.html.tpl');
    }

    public function rooms()
    {
        $this->authChecking(true, false);

        $operationRooms = R::findAll('operations_rooms', 'deleted = 0 order by floor_no');
        $rooms = [];
        // rooms list
        foreach ($operationRooms as $room) {
            $rooms[] = [
                'id' => $room->id,
                'title' => $room->name,
                'sort' => (int)$room->id,
                'floor_no' => (int)$room->floor_no
            ];
        }
        echo json_encode($rooms);
    }

    public function residenceRooms()
    {
        $this->authChecking(true, false);

        $residenceRooms = R::findAll('residence_rooms', 'deleted = 0 order by floor_no');
        $rooms = [];
        // rooms list
        foreach ($residenceRooms as $room) {
            $rooms[] = [
                'id' => $room->id,
                'title' => $room->name,
                'sort' => (int)$room->id,
                'floor_no' => (int)$room->floor_no
            ];
        }
        echo json_encode($rooms);
    }

    public function events()
    {
        $this->authChecking(true, false);
        $residenceCal = filter_input(INPUT_POST, 'residence_cal');
        $startDate = filter_input(INPUT_POST, 'start');
        $endDate = filter_input(INPUT_POST, 'end');
        $doctorId = filter_input(INPUT_POST, 'doctor_id');
        $operationTypeId = filter_input(INPUT_POST, 'operation_type');
        $events = [];
        $where = ' date >= ? and date < ?  ';
        if ($doctorId) {
            $where .= ' and doctor_id = ' . $doctorId;
        }
        if ($operationTypeId) {
            $where .= ' and operation_type_id = ' . $operationTypeId;
        }
        $operationRoomsCal = R::findAll('operations_rooms_cal', $where, [$startDate, $endDate]);
        foreach ($operationRoomsCal as $event) {

            if ((int)$residenceCal === 1) {

                // check for floor no
                $residenceRoomsInfo = R::findOne('residence_rooms', 'id = ? and deleted = 0', [$event->res_room_id]);
                if ($residenceRoomsInfo && (int)$residenceRoomsInfo->floor_no === 6) {
                    $color = '#ffcaa7';
                } elseif ($residenceRoomsInfo && (int)$residenceRoomsInfo->floor_no === 7) {
                    $color = '#a7ffba';
                } else {
                    $color = '#a7b9ff';
                }

                if ((int)$event->vip === 1) {
                    $color = '#fefe5d';
                }

                // check if any event intersect with this event
                $intersect = R::findOne(
                    'operations_rooms_cal',
                    ' date = ? and res_start_time < ? and res_end_time > ? and res_room_id = ? and id != ? ',
                    [$event->date, $event->res_end_time, $event->res_start_time, $event->res_room_id, $event->id]
                );
                if ($intersect) {
                    // if intersect color red
                    $color = '#dd4b39';
                }
            } else {
                //calculate diff between start and end time
                /*$startTime = strtotime($event->start_time);
                $endTime = strtotime($event->end_time);
                $diff = $endTime - $startTime;
                $diff /= 60;

                if ($diff < 60) {
                    // less than 1 hour color green
                    $color = '#5cffb4';
                } else {
                    // more than 1 hour color blue
                    $color = '#7ff7ff';
                }*/

                // check for floor no
                $operationRoomsInfo = R::findOne('operations_rooms', 'id = ? and deleted = 0', [$event->room_id]);
                if ($operationRoomsInfo && (int)$operationRoomsInfo->floor_no === 6) {
                    $color = '#ffcaa7';
                } else {
                    $color = '#a7b9ff';
                }

                if ((int)$event->vip === 1) {
                    $color = '#fefe5d';
                }

                // check if any event intersect with this event
                $intersect = R::findOne(
                    'operations_rooms_cal',
                    ' date = ? and start_time < ? and end_time > ? and room_id = ? and id != ? ',
                    [$event->date, $event->end_time, $event->start_time, $event->room_id, $event->id]
                );
                if ($intersect) {
                    // if intersect color red
                    $color = '#dd4b39';
                }
            }

            $patient = R::findOne('patients', ' id = ? ', [$event->patient_id]);
            $doctor = R::findOne('awusers', ' user_id = ? ', [$event->doctor_id]);
            $operationType = R::findOne('detections', ' id = ? ', [$event->operation_type_id]);
            $user = R::findOne('awusers', ' user_id = ? ', [$event->created_by]);

            if ((int)$residenceCal === 1) {
                $startDateTime = $event->date . ' ' . $event->res_start_time;
                $endDateTime = $event->date . ' ' . $event->res_end_time;
                $roomId = $event->res_room_id;
            } else {
                $startDateTime = $event->date . ' ' . $event->start_time;
                $endDateTime = $event->date . ' ' . $event->end_time;
                $roomId = $event->room_id;
            }

            // check if there name for patient
            if ($patient) {
                $patientName = $event->for_husband == 1 ? $patient->husdandname : $patient->wifename;
            } else {
                $patientName = 'لا يوجد';
                // check if there patient_name
                if ($event->patient_name) {
                    $patientName = $event->patient_name;
                }
            }

            $events[] = [
                'id' => $event->id,
                'title' => $patientName,
                'doctor' => $doctor ? $doctor->name : 'لا يوجد',
                'operation_type' => $operationType ? $operationType->title : 'لا يوجد',
                'user' => $user ? $user->name : 'لا يوجد',
                'start' => $startDateTime,
                'end' => $endDateTime,
                'color' => $color,
                'resourceId' => $roomId,
                'desc' => 'hello',
            ];
        }
        echo json_encode($events);
    }

    public function searchPatients()
    {
        $this->authChecking(true, false);
        $search = filter_input(INPUT_POST, 'search_text');
        $patients = R::getAll(
            'select * from patients where deleted = 0 and ( wifename like :search or husdandname like :search or patients.statusno like :search )',
            [':search' => '%' . $search . '%']
        );
        $results = [];
        foreach ($patients as $patient) {
            $results[] = [
                'id' => $patient['id'],
                'text' => $patient['wifename'] . ' - ' . $patient['husdandname'] . ' - ' . $patient['statusno'],
            ];
        }
        echo json_encode($results);
    }

    public function saveOperation()
    {
        $this->authChecking(true, false);

        try {
            $operationRoomCal = R::xdispense('operations_rooms_cal');
            $operationRoomCal->room_id = filter_input(INPUT_POST, 'room_id');
            $operationRoomCal->patient_id = filter_input(INPUT_POST, 'patient_id') ?: 0;
            $operationRoomCal->patient_name = filter_input(INPUT_POST, 'patient_name');
            $operationRoomCal->doctor_id = filter_input(INPUT_POST, 'doctor_id');
            $operationRoomCal->assistant_id = filter_input(INPUT_POST, 'assistant_id') ?: 0;
            $operationRoomCal->operation_type_id = filter_input(INPUT_POST, 'operation_type_id');
            $operationRoomCal->start_time = date('H:i', strtotime(filter_input(INPUT_POST, 'start_time')));
            $operationRoomCal->end_time = date('H:i', strtotime(filter_input(INPUT_POST, 'end_time')));
            $operationRoomCal->date = filter_input(INPUT_POST, 'date');
            $operationRoomCal->created_at = date('Y-m-d H:i:s');
            $operationRoomCal->created_by = $_SESSION['user_id'];
            $operationRoomCal->updated_at = date('Y-m-d H:i:s');
            $operationRoomCal->cost = filter_input(INPUT_POST, 'cost');
            $operationRoomCal->cost_details = filter_input(INPUT_POST, 'cost_details');
            $operationRoomCal->instructions = filter_input(INPUT_POST, 'instructions');
            $operationRoomCal->for_husband = filter_input(INPUT_POST, 'for_husband');
            $operationRoomCal->notes = filter_input(INPUT_POST, 'notes');
            $operationRoomCal->vip = filter_input(INPUT_POST, 'vip');
            $operationRoomCal->res_room_id = filter_input(INPUT_POST, 'res_room_id');
            $operationRoomCal->res_start_time = date('H:i', strtotime(filter_input(INPUT_POST, 'res_start_time')));
            $operationRoomCal->res_end_time = date('H:i', strtotime(filter_input(INPUT_POST, 'res_end_time')));
            $result = R::store($operationRoomCal);
            if ($result) {
                echo json_encode(['status' => 'success', 'message' => 'تم الحفظ بنجاح']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'حدث خطأ ما']);
            }
        } catch (Exception $e) {
            echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

    public function removeOperation()
    {
        $this->authChecking(true, false);
        $id = filter_input(INPUT_POST, 'event_id');
        $operationRoomCal = R::findOne('operations_rooms_cal', ' id = ? ', [$id]);
        if ($operationRoomCal) {
            R::trash($operationRoomCal);
            echo json_encode(['status' => 'success', 'message' => 'تم الحذف بنجاح']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'حدث خطأ ما']);
        }
    }

    public function getOperationTime()
    {
        $this->authChecking(true, false);
        $operationTypeId = filter_input(INPUT_POST, 'operation_type_id');
        $operationType = R::findOne('detections', ' id = ? ', [$operationTypeId]);
        if ($operationType) {
            echo json_encode([
                'status' => 'success',
                'time' => $operationType->operation_time,
                'res_time' => $operationType->residence_time,
                'cost' => $operationType->detectionval,
                'cost_details' => $operationType->cost_details,
                'instructions' => $operationType->instructions
            ]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'حدث خطأ ما']);
        }
    }

    public function getOperation()
    {
        $this->authChecking(true, false);

        $id = filter_input(INPUT_POST, 'operation_id');
        $bean = R::findOne('operations_rooms_cal', ' id = ? ', [$id]);
        $this->smarty->assign('operation', $bean);
        $this->preData();

        $operationType = R::findOne('detections', ' id = ? ', [$bean->operation_type_id]);
        $plusTime = [
            'time' => $operationType->operation_time,
            'res_time' => $operationType->residence_time,
        ];
        $this->smarty->assign('plusTime', $plusTime);

        $html = $this->smarty->fetch('operations_calendar/operation.html.tpl');
        $patient = R::findOne('patients', ' id = ? ', [$bean ? $bean->patient_id : 0]);

        $result = [
            'patient' =>
                [
                    'id' => $patient ? $bean->patient_id : 0,
                    'name' => $patient ? $patient->wifename . ' - ' . $patient->husdandname . ' - ' . $patient->statusno : 'لا يوجد',
                ],
            'html' => $html
        ];
        echo json_encode($result);
    }

    public function updateOperation()
    {
        $this->authChecking(true, false);

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

        try {
            $bean = R::load('operations_rooms_cal', $id);
            $bean->updated_at = date('Y-m-d H:i:s');
            $bean->updated_by = $_SESSION['user_id'];
            $bean->room_id = filter_input(INPUT_POST, 'room_id');
            $bean->patient_id = filter_input(INPUT_POST, 'patient_id') ?: 0;
            $bean->doctor_id = filter_input(INPUT_POST, 'doctor_id');
            $bean->assistant_id = filter_input(INPUT_POST, 'assistant_id') ?: 0;
            $bean->operation_type_id = filter_input(INPUT_POST, 'operation_type_id');
            $bean->start_time = date('H:i', strtotime(filter_input(INPUT_POST, 'start_time')));
            $bean->end_time = date('H:i', strtotime(filter_input(INPUT_POST, 'end_time')));
            $bean->cost = filter_input(INPUT_POST, 'cost');
            $bean->cost_details = filter_input(INPUT_POST, 'cost_details');
            $bean->instructions = filter_input(INPUT_POST, 'instructions');
            $bean->for_husband = filter_input(INPUT_POST, 'for_husband');
            $bean->notes = filter_input(INPUT_POST, 'notes');
            $bean->vip = filter_input(INPUT_POST, 'vip');
            $bean->res_room_id = filter_input(INPUT_POST, 'res_room_id');
            $bean->res_start_time = date('H:i', strtotime(filter_input(INPUT_POST, 'res_start_time')));
            $bean->res_end_time = date('H:i', strtotime(filter_input(INPUT_POST, 'res_end_time')));
            $result = R::store($bean);
            if ($result) {
                echo json_encode(['status' => 'success', 'message' => 'تم التحديث بنجاح']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'حدث خطأ ما']);
            }
        } catch (Exception $e) {
            echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

    public function __destruct()
    {
        R::close();
    }

    /**
     * @return void
     */
    protected function smartyHtml($filePath)
    {
        header::headershow($this->smarty, $this->host_url);
        sidebar::sidebarshow($this->smarty, $this->host_url, $this->active);
        $this->smarty->display($filePath);
        leftsidebar::leftsidebarshow($this->smarty, $this->host_url);
        footer::footershow($this->smarty, $this->host_url);
    }

    /**
     * @return void
     */
    protected function authChecking($loginCheck = true, $permissionCheck = true)
    {
        !$loginCheck ?: autho::checkautho($this->host_url);
        !$permissionCheck ?: autho::checkauthoize($this->controlName, $this->host_url, $_SESSION['role_id']);
    }

    /**
     * @return void
     */
    protected function preData()
    {
        $operationRooms = R::findAll('operations_rooms', 'deleted = 0');
        $this->smarty->assign('operation_rooms', $operationRooms);

        $residenceRooms = R::findAll('residence_rooms', 'deleted = 0');
        $this->smarty->assign('residenceRooms', $residenceRooms);

        $operationTypes = R::findAll('detections', ' del != 1 and for_operation = 1');
        $this->smarty->assign('operation_types', $operationTypes);

        $role = R::findOne('awrole', ' id  = 13');
        if ($role) {
            $doctors = R::getAll(
                'select * from awusers where deleted != 1 and role_id in ( ' . $role->related_dr_depts . '  ) '
            );
            $this->smarty->assign('doctors', $doctors);
        }
    }

}
