<?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_reports';
        $shcontrollname = 'Operations Reports';
        $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();

        $date = filter_input(0, 'choose_date') ?: date('Y-m-d');
        $this->smarty->assign('today', $date);
        $targetFloors = [8, 6];
        $hours = [
            ['id' => 1, 'text' => '07:00 - 08:00', 'start' => '07:00', 'end' => '08:00'],
            ['id' => 2, 'text' => '08:00 - 09:00', 'start' => '08:00', 'end' => '09:00'],
            ['id' => 3, 'text' => '09:00 - 10:00', 'start' => '09:00', 'end' => '10:00'],
            ['id' => 4, 'text' => '10:00 - 11:00', 'start' => '10:00', 'end' => '11:00'],
            ['id' => 5, 'text' => '11:00 - 12:00', 'start' => '11:00', 'end' => '12:00'],
            ['id' => 6, 'text' => '12:00 - 13:00', 'start' => '12:00', 'end' => '13:00'],
            ['id' => 7, 'text' => '13:00 - 14:00', 'start' => '13:00', 'end' => '14:00'],
            ['id' => 8, 'text' => '14:00 - 15:00', 'start' => '14:00', 'end' => '15:00'],
            ['id' => 9, 'text' => '15:00 - 16:00', 'start' => '15:00', 'end' => '16:00'],
            ['id' => 10, 'text' => '16:00 - 17:00', 'start' => '16:00', 'end' => '17:00'],
            ['id' => 11, 'text' => '17:00 - 18:00', 'start' => '17:00', 'end' => '18:00'],
            ['id' => 12, 'text' => '18:00 - 19:00', 'start' => '18:00', 'end' => '19:00'],
            ['id' => 13, 'text' => '19:00 - 20:00', 'start' => '19:00', 'end' => '20:00'],
            ['id' => 14, 'text' => '20:00 - 21:00', 'start' => '20:00', 'end' => '21:00'],
            ['id' => 15, 'text' => '21:00 - 22:00', 'start' => '21:00', 'end' => '22:00'],
            ['id' => 16, 'text' => '22:00 - 23:00', 'start' => '22:00', 'end' => '23:00'],
            ['id' => 17, 'text' => '23:00 - 24:00', 'start' => '23:00', 'end' => '24:00'],
            ['id' => 18, 'text' => '24:00 - 01:00', 'start' => '24:00', 'end' => '01:00'],
            ['id' => 19, 'text' => '01:00 - 02:00', 'start' => '01:00', 'end' => '02:00'],
            ['id' => 20, 'text' => '02:00 - 03:00', 'start' => '02:00', 'end' => '03:00'],
            ['id' => 21, 'text' => '03:00 - 04:00', 'start' => '03:00', 'end' => '04:00'],
            ['id' => 22, 'text' => '04:00 - 05:00', 'start' => '04:00', 'end' => '05:00'],
            ['id' => 23, 'text' => '05:00 - 06:00', 'start' => '05:00', 'end' => '06:00'],
            ['id' => 24, 'text' => '06:00 - 07:00', 'start' => '06:00', 'end' => '07:00'],
        ];
        $floors = [];
        foreach ($targetFloors as $floor) {
            $details = [
                'id' => $floor,
                'text' => $floor === 6 ? 'عمليات السادس' : 'عمليات الثامن'
            ];
            $operationRooms = R::findAll('operations_rooms', 'deleted = 0 and floor_no = ?', [$floor]);
            $details['rooms'] = [];
            $roomIndex = 1;
            foreach ($operationRooms as $room) {

                // get operations for each room and each hour
                $room->operations = [];
                $beforeId = 0;
                foreach ($hours as $hour) {
                    $res = R::getAll(
                        'select * from operations_rooms_cal where room_id = ? and
                                         (start_time >= ? or end_time > ? ) and (end_time < ? or start_time < ?) and date = ?',
                        [$room->id, $hour['start'], $hour['start'], $hour['end'], $hour['end'], $date]
                    );

                    if (count($res) > 0) {
                        foreach ($res as &$re) {
                            $doctor = R::findOne('awusers', ' user_id = ? ', [$re['doctor_id']]);
                            $operationType = R::findOne('detections', ' id = ? ', [$re['operation_type_id']]);

                            if ($beforeId === $re['id']) {
                                $re['doctor'] = 'continue';
                            } else {
                                $re['doctor'] = $doctor ? $doctor->name : 'لا يوجد';
                            }

                            $re['operation_type'] = $operationType ? $operationType->title : 'لا يوجد';
                            $beforeId = $re['id'];
                        }
                        unset($re);
                    }

                    $room->operations[$hour['id']] = $res;
                }

                $details['rooms'][] = [
                    'id' => $room->id,
                    'text' => 'عمليات ' . $roomIndex++,
                    'operations' => $room->operations
                ];
            }
            $floors[] = $details;
        }
        $this->smarty->assign('floors', $floors);
        $this->smarty->assign('hours', $hours);

        $this->smartyHtml('operations_reports/rooms.html.tpl');
    }

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

        $date = filter_input(0, 'choose_date') ?: date('Y-m-d');
        $this->smarty->assign('today', $date);

        $find = ["Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"];
        $replace = ["السبت", "الأحد", "الإثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة"];
        $arDayFormat = date('D', strtotime($date)); // The Current Day
        $arDay = str_replace($find, $replace, $arDayFormat);
        $this->smarty->assign('arDay', $arDay);

        // get operation group by operation_type_id
        $operations = R::getAll(
            'select operation_type_id, operations_rooms_cal.id,detections.sort,
            operations_rooms_cal.doctor_id,operations_rooms_cal.for_husband
            from operations_rooms_cal inner join detections on operations_rooms_cal.operation_type_id = detections.id
            where date = ? and operations_rooms_cal.for_husband= 0
            group by operation_type_id,operations_rooms_cal.id,detections.sort,operations_rooms_cal.doctor_id,
            operations_rooms_cal.for_husband
            order by -detections.sort DESC ,operations_rooms_cal.doctor_id',
            [$date]
        );

        foreach ($operations as &$operation) {
            $operation['operation_info'] = R::findOne('operations_rooms_cal', ' id = ? ', [$operation['id']]);
            $operation['doctor'] = R::findOne('awusers', ' user_id = ? ', [$operation['doctor_id']]);
            $operation['operation_type'] = R::findOne('detections', ' id = ? ', [$operation['operation_type_id']]);
            $operation['patient'] = R::findOne('patients', ' id = ? ', [$operation['operation_info']->patient_id]);
            $operation['room'] = R::findOne('operations_rooms', ' id = ? ', [$operation['operation_info']->room_id]);
            // check if their operation is for husband
            $for_husband_ops = R::findOne(
                'operations_rooms_cal',
                ' where date = ? and for_husband = ? and patient_id = ?',
                [$date, 1, $operation['operation_info']->patient_id]
            );
            $for_husband_ops->doctor = R::findOne('awusers', ' user_id = ? ', [$for_husband_ops->doctor_id]);
            $for_husband_ops->operation_type = R::findOne('detections', ' id = ? ', [$for_husband_ops->operation_type_id]);
            $for_husband_ops->patient = R::findOne('patients', ' id = ? ', [$for_husband_ops->patient_id]);
            $for_husband_ops->room = R::findOne('operations_rooms', ' id = ? ', [$for_husband_ops->room_id]);

            $operation['for_husband_ops'] = $for_husband_ops;
        }
        unset($operation);

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

        $this->smartyHtml('operations_reports/list.html.tpl');
    }

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

        $date = filter_input(0, 'choose_date') ?: date('Y-m-d');
        $this->smarty->assign('today', $date);

        // get operation group by operation_type_id
        $operations = R::findAll('operations_rooms_cal', 'date = ?', [$date]);

        foreach ($operations as $operation) {
            $operation->doctor = R::findOne('awusers', ' user_id = ? ', [$operation->doctor_id]);
            $operation->operation_type = R::findOne('detections', ' id = ? ', [$operation->operation_type_id]);
            $operation->patient = R::findOne('patients', ' id = ? ', [$operation->patient_id]);
            $operation->room = R::findOne('operations_rooms', ' id = ? ', [$operation->room_id]);
            $operation->contacted_user = R::findOne('awusers', ' user_id = ? ', [$operation->contacted_user_id]);
        }

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

        $this->smartyHtml('operations_reports/support.html.tpl');
    }

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

        $id = filter_input(0, 'id');
        $value = filter_input(0, 'value');
        $operation = R::findOne('operations_rooms_cal', ' id = ? ', [$id]);
        if ($operation) {
            $operation->contacted_patient = $value;
            $operation->contacted_user_id = $_SESSION['user_id'];
            R::store($operation);

            $contactedUser = R::findOne('awusers', ' user_id = ? ', [$operation->contacted_user_id]);

            echo json_encode(['status' => 'success', 'name' => $contactedUser->name]);
        } else {
            echo json_encode(['status' => 'error', 'name' => '']);
        }
    }

    public function updateCol()
    {
        $this->authChecking(true, false);
        $id = filter_input(0, 'id');
        $value = filter_input(0, 'value');
        $col = filter_input(0, 'col');
        $table = filter_input(0, 'table');
        $operation = R::findOne($table, ' id = ? ', [$id]);
        if ($operation) {
            $operation->$col = $value;
            R::store($operation);
            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'error']);
        }
    }

    public function sendSms()
    {
        $this->authChecking(true, false);
        $id = filter_input(0, 'id');
        $operation = R::findOne('operations_rooms_cal', ' id = ? ', [$id]);
        if ($operation) {
            $patient = R::findOne('patients', ' id = ? ', [$operation->patient_id]);
            $this->sendSmsMisr($patient->phone, $operation->sms_message);
            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'error']);
        }
    }

    private function sendSmsMisr($phone, $message)
    {
        $recipient = ltrim($phone, "2");
        $recipient = ltrim($recipient, "+2");
        $recipient = ltrim($recipient, "02");
        $recipient = ltrim($recipient, "002");
        $recipient = ltrim($recipient, "0");
        $recipientWithCode = "20" . ($recipient);

        $curl = curl_init();

        $connectionId = "aQ6zaWdY";
        $password = "f7fb1028f0e64cb06fb6c2d9e5109c9e1845767182b0629eb4dbb9c347c1be60";
        $sender = "Royal";
        $language = "2";

        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://smsmisr.com/api/webapi/" .
                "?Username=" . $connectionId .
                "&password=" . $password .
                "&sender=" . $sender .
                "&language=" . $language .
                "&Mobile=" . $recipientWithCode .
                "&message=" . urlencode($message),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HEADER => false,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => []
        ));

        curl_exec($curl);
        curl_error($curl);

        curl_close($curl);


    }

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

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

        $date = filter_input(0, 'choose_date') ?: date('Y-m-d');
        $this->smarty->assign('today', $date);

        $doctorId = filter_input(0, 'doctor_id');
        $this->smarty->assign('doctor_id', $doctorId);

        $reportType = filter_input(0, 'report_type');
        $this->smarty->assign('report_type', $reportType);

        $find = ["Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"];
        $replace = ["السبت", "الأحد", "الإثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة"];
        $arDayFormat = date('D', strtotime($date)); // The Current Day
        $arDay = str_replace($find, $replace, $arDayFormat);
        $this->smarty->assign('arDay', $arDay);

        $query = ' and operations_rooms_cal.for_husband = 0 ';
        if ($doctorId) {
            $query .= ' and (operations_rooms_cal.doctor_id = ' . $doctorId . ' or operations_rooms_cal.assistant_id = ' . $doctorId . ') ';
        }

        if ((int)$reportType === 5) {
            // filter with custom detections
            $detectionsFilters = '55,152,217,228';
            $query .= ' and detections.id in (' . $detectionsFilters . ')';
        }

        // get operation group by operation_type_id
        $operations = R::getAll(
            'select operation_type_id, operations_rooms_cal.id, operations_rooms_cal.assistant_id,detections.sort,
            operations_rooms_cal.doctor_id,operations_rooms_cal.for_husband
            from operations_rooms_cal inner join detections on operations_rooms_cal.operation_type_id = detections.id
            where date = ? ' . $query . '
            group by operation_type_id,operations_rooms_cal.id,detections.sort,operations_rooms_cal.doctor_id,
            operations_rooms_cal.for_husband
            order by -detections.sort DESC ,operations_rooms_cal.doctor_id',
            [$date]
        );

        foreach ($operations as &$operation) {
            $operation['operation_info'] = R::findOne('operations_rooms_cal', ' id = ? ', [$operation['id']]);
            $operation['doctor'] = R::findOne('awusers', ' user_id = ? ', [$operation['doctor_id']]);
            $operation['assistant'] = R::findOne('awusers', ' user_id = ? ', [$operation['assistant_id']]);
            $operation['operation_type'] = R::findOne('detections', ' id = ? ', [$operation['operation_type_id']]);
            $operation['patient'] = R::findOne('patients', ' id = ? ', [$operation['operation_info']->patient_id]);
            $operation['room'] = R::findOne('residence_rooms', ' id = ? ', [$operation['operation_info']->res_room_id]);
            // check if their operation is for husband
            $forHusbandOPS = R::findOne(
                'operations_rooms_cal',
                ' where date = ? and for_husband = ? and patient_id = ?',
                [$date, 1, $operation['operation_info']->patient_id]
            );
            $operation['for_husband_ops'] = '';
            if ($forHusbandOPS) {
                $forHusbandOPS->doctor = R::findOne('awusers', ' user_id = ? ', [$forHusbandOPS->doctor_id]);
                $forHusbandOPS->operation_type = R::findOne('detections', ' id = ? ', [$forHusbandOPS->operation_type_id]);
                $forHusbandOPS->patient = R::findOne('patients', ' id = ? ', [$forHusbandOPS->patient_id]);
                $forHusbandOPS->room = R::findOne('residence_rooms', ' id = ? ', [$forHusbandOPS->res_room_id]);

                $operation['for_husband_ops'] = $forHusbandOPS;
            }

        }
        unset($operation);

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

        $this->smartyHtml('operations_reports/opReport.html.tpl');
    }

    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']);
    }

}
