<?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 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 = 'beauty_calendar';
        $shcontrollname = 'Beauty Calendar';
        $this->smarty->assign('controllname', $this->controlName);
        $this->smarty->assign('shcontrollname', $shcontrollname);

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

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

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

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

        $this->preData();

        $user = R::findOne('awusers', ' user_id = ? ', [$_SESSION['user_id']]);
        $roleInfo = R::findOne('awrole', ' id = ? ', [$user ? $user->role_id : 0]);
        $this->smarty->assign('roleInfo', $roleInfo);

        $this->smartyHtml('beauty/calendar/index.html.tpl');
    }

    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 phone like :search )', [':search' => '%' . $search . '%']);
        $results = [];
        foreach ($patients as $patient) {
            $results[] = [
                'id' => $patient['id'],
                'text' => $patient['wifename'] . ' - ' . $patient['phone'],
            ];
        }
        echo json_encode($results);
    }

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

        $user = R::findOne('awusers', ' user_id = ? ', [$_SESSION['user_id']]);
        $roleInfo = R::findOne('awrole', ' id = ? ', [$user ? $user->role_id : 0]);

        if ($roleInfo && $roleInfo->is_doctor === '1') {
            $today = date('Y-m-d');
            $visitsRooms = R::getCol('SELECT room_id from beauty_visits where status != 3 and date >= ? and doctor_id = ? ', [$today, $user->user_id]);
            $operationRooms = R::findAll('operations_rooms', 'deleted = 0 and  branch_id IN (' . $user->branch_id . ') and id IN (' . implode(',', $visitsRooms) . ')');
        } else {
            $operationRooms = R::findAll('operations_rooms', 'deleted = 0 and  branch_id IN (' . $user->branch_id . ')');
        }

        $rooms = [];
        foreach ($operationRooms as $room) {
            $rooms[] = [
                'id' => $room->id,
                'title' => $room->name,
                'sort' => $room->id,
            ];
        }
        echo json_encode($rooms);
    }

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

        $user = R::findOne('awusers', ' user_id = ? ', [$_SESSION['user_id']]);
        $roleInfo = R::findOne('awrole', ' id = ? ', [$user ? $user->role_id : 0]);

        $startDate = filter_input(INPUT_POST, 'start');
        $endDate = filter_input(INPUT_POST, 'end');
        $events = [];
        $where = ' date >= ? and date < ? and status != 3 ';

        if ($roleInfo && $roleInfo->is_doctor === '1') {
            $where .= ' and doctor_id = ' . $user->user_id . ' ';
        }

        $beautyVisits = R::findAll('beauty_visits', $where, [$startDate, $endDate]);
        foreach ($beautyVisits as $event) {
            $color = '#74f753'; // status 4
            $statusText = 'Paid';
            if ($event->status === '1') {
                $color = '#007bff';
                $statusText = 'Reserved';
            } elseif ($event->status === '2') {
                $color = '#c120bc';
                $statusText = 'Confirmed';
            } elseif ($event->status === '4') {
                $color = '#d2d521';
                $statusText = 'Done';
            }

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

            $events = $this->getEvents($event, $color, $statusText, $events);
        }

        echo json_encode($events);
    }

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

//        $service_ids_arr = filter_input(INPUT_POST, 'service_ids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
//        $service_ids = implode(',', $service_ids_arr);

        try {
            $bean = R::xdispense('beauty_visits');
            $bean->doctor_id = filter_input(INPUT_POST, 'doctor_id');
            $bean->service_ids = filter_input(INPUT_POST, 'service_ids'); //$service_ids;
            $bean->user_id = filter_input(INPUT_POST, 'user_id');
            $bean->branch_id = filter_input(INPUT_POST, 'branch_id');
            $bean->status = filter_input(INPUT_POST, 'status');
            $bean->date = filter_input(INPUT_POST, 'date');
            $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->room_id = filter_input(INPUT_POST, 'room_id');
            $bean->patient_id = filter_input(INPUT_POST, 'patient_id') ?: 0;
            $bean->created_at = date('Y-m-d H:i:s');
            $bean->updated_at = date('Y-m-d H:i:s');
            $bean->created_by = $_SESSION['user_id'];
            $bean->visit_id = 0;
            $result = R::store($bean);
            if ($result) {
                $bean->id = $result;
                foreach ($service_ids_arr as $service_id) {
                    $visit_service = R::xdispense('visit_services');
                    $visit_service->visit_id = $result;
                    $visit_service->service_id = $service_id;
                    $visit_service->created_at = date('Y-m-d H:i:s');
                    $visit_service->updated_at = date('Y-m-d H:i:s');
                    R::store($visit_service);
                }
                $this->saveInVisits($bean);
                echo json_encode(['status' => 'success', 'message' => 'تم الحفظ بنجاح']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'حدث خطأ ما']);
            }
        } catch (Exception $e) {
            echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

    function saveInVisits($beautyVisit) {
        switch ($beautyVisit->visit_id) {
            case 0:
                $this->addVisit($beautyVisit);
                break;

            default:
                break;
        }
    }

    function addVisit($beautyVisit) {
        $doctor_percent = 0;
        $for_department = 0;
        if ($beautyVisit->doctor_id > 0) {
            $doctorIn = R::getRow('select * from awusers where user_id = ?', [$beautyVisit->doctor_id]);
            $for_department = $doctorIn['role_id'];
            $detection = R::load('detections', $beautyVisit->service_ids);
            switch ($detection->type) {
                case 1:
                    $doctor_percent = $doctorIn['pulse_per'];
                    break;

                case 2:
                    $doctor_percent = $doctorIn['session_per'];
                    break;
            }
        }

        $insertDataVisits = R::dispense('visits');
        $insertDataVisits->patientid = $beautyVisit->patient_id;
        $insertDataVisits->visitdate = $beautyVisit->date;
        $insertDataVisits->visittime = date("H:i:s");
        $insertDataVisits->visit_time = $beautyVisit->start_time;
        $insertDataVisits->detectionid = $beautyVisit->service_ids;
        $insertDataVisits->detectionvalue_cash = 0;
        $insertDataVisits->detectionvalue_visa = 0;
        $insertDataVisits->totaldetectionvalue = 0;
        $insertDataVisits->discount = 0;
        $insertDataVisits->restdetectionvalue = 0;
        $insertDataVisits->for_department = $for_department;
        $insertDataVisits->for_doctor = $beautyVisit->doctor_id;
        $insertDataVisits->for_husband = 0;
        $insertDataVisits->units = 0;
        $insertDataVisits->doctor_percent = $doctor_percent;

        $insertDataVisits->operation_time = '';
        $insertDataVisits->operation_main_id = 0;
        $insertDataVisits->notes = '';
        $insertDataVisits->user_id = $_SESSION['user_id'];
        $insertDataVisits->create_date = date('Y-m-d H:i:s'); //$this->today;

        $insertDataVisits->discount_type = 0;
        $insertDataVisits->discount_ratio = 0;

        $insertDataVisits->room_no = '';
        $insertDataVisits->enterance = '';
        $insertDataVisits->p_exit = '';

        $insertDataVisits->res_room_no = '';
        $insertDataVisits->res_enterance = '';
        $insertDataVisits->res_p_exit = '';

        $insertDataVisits->recep_p_exit = '';

        if ($_SESSION['role_id'] == 19) {
            $insertDataVisits->customer_add = 1;
            $insertDataVisits->recep_p_exit = '';
        } else {
            $insertDataVisits->customer_add = 0;
            $insertDataVisits->recep_p_exit = date("H:i");
        }

        $insertDataVisits->printserial = 0;



        $patient = R::load('patients', $beautyVisit->patient_id);
        $insertDataVisits->refer_doctor = $patient->refer_doctor;
        $insertDataVisits->refer_doctor_tb = $patient->refer_doctor_tb;
        $insertDataVisits->rfc = $patient->wrfc;

        $visitId = R::store($insertDataVisits);

        if ($visitId > 0) {
            R::exec('update beauty_visits set visit_id = ' . $visitId . '   where id = ' . $beautyVisit->id . ' ');
        }
    }

    public function removeVisit() {
        $this->authChecking(true, false);
        $id = filter_input(INPUT_POST, 'event_id');
        $bean = R::findOne('beauty_visits', ' id = ? ', [$id]);
        if ($bean) {
            $bean->status = 3;
            R::store($bean);
            if ($bean->visit_id > 0) {
                R::exec('update visits set deleted = 1  where id = ' . $bean->visit_id . ' ');
            }
            echo json_encode(['status' => 'success', 'message' => 'تم الحذف بنجاح']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'حدث خطأ ما']);
        }
    }

    public function getVisit() {
        $this->authChecking(true, false);
        $id = filter_input(INPUT_POST, 'visit_id');
        $bean = R::findOne('beauty_visits', ' id = ? ', [$id]);
        $this->smarty->assign('visit', $bean);
        if ($bean) {
            $services = explode(',', $bean->service_ids);
            $this->smarty->assign('services', $services);
        }
        $this->preData();

        $visitServices = R::findAll('visit_services', ' visit_id = ? ', [$id]);
        foreach ($visitServices as $visit_service) {
            $service = R::findOne('detections', ' id = ? ', [$visit_service->service_id]);
            $visit_service->paid_amount = $visit_service->paid_amount ?: 0;
            $visit_service->pulse_no = $visit_service->pulse_no ?: 0;
            $visit_service->service = $service;
        }
        $this->smarty->assign('visit_services', $visitServices);

        $user = R::findOne('awusers', ' user_id = ? ', [$_SESSION['user_id']]);
        $roleInfo = R::findOne('awrole', ' id = ? ', [$user ? $user->role_id : 0]);

        if ($bean->status === '4' || $bean->status === '5') {
            $html = $this->smarty->fetch('beauty/calendar/visit_done.html.tpl');
        } else {
            if ($roleInfo->is_doctor !== '1') {
                $html = $this->smarty->fetch('beauty/calendar/visit.html.tpl');
            } else {
                $html = $this->smarty->fetch('beauty/calendar/visit_done.html.tpl');
            }
        }


        $patient = R::findOne('patients', ' id = ? ', [$bean->patient_id]);

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

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

        $id = filter_input(INPUT_POST, 'id');
        $service_ids_arr = filter_input(INPUT_POST, 'service_ids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
        $service_ids = implode(',', $service_ids_arr);

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

        try {
            $bean = R::load('beauty_visits', $id);
            $bean->updated_at = date('Y-m-d H:i:s');
            $bean->updated_by = $_SESSION['user_id'];
            $bean->status = $status;
            if ($bean->status === '4' || $bean->status === '5') {
                $bean->paid_amount = filter_input(INPUT_POST, 'paid_amount');
                $bean->pulse_no = filter_input(INPUT_POST, 'pulse_no');
                foreach (explode(',', filter_input(INPUT_POST, 'service_ids_hide')) as $service_id) {
                    $visit_service = R::findOne('visit_services', ' visit_id = ? AND service_id = ? ', [$id, $service_id]);
                    if ($visit_service) {
                        $paid_amount = filter_input(INPUT_POST, 'paid_amount_' . $visit_service->id);
                        $pulse_no = filter_input(INPUT_POST, 'pulse_no_' . $visit_service->id);
                        $visit_service->paid_amount = $paid_amount ?: 0;
                        $visit_service->pulse_no = $pulse_no ?: 0;
                        $visit_service->updated_at = date('Y-m-d H:i:s');
                        R::store($visit_service);
                    }
                }
            } else {
                $bean->doctor_id = filter_input(INPUT_POST, 'doctor_id');
                $bean->service_ids = $service_ids;
                $bean->user_id = filter_input(INPUT_POST, 'user_id');
                $bean->branch_id = filter_input(INPUT_POST, 'branch_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->date = filter_input(INPUT_POST, 'date');
                $bean->room_id = filter_input(INPUT_POST, 'room_id');
                $bean->patient_id = filter_input(INPUT_POST, 'patient_id') ?: 0;

                $visit_services = R::findAll('visit_services', ' visit_id = ? ', [$id]);
                foreach ($visit_services as $visit_service) {
                    R::trash($visit_service);
                }
                foreach ($service_ids_arr as $service_id) {
                    $visit_service = R::xdispense('visit_services');
                    $visit_service->visit_id = $id;
                    $visit_service->service_id = $service_id;
                    $visit_service->created_at = date('Y-m-d H:i:s');
                    $visit_service->updated_at = date('Y-m-d H:i:s');
                    R::store($visit_service);
                }
            }

            $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 getServiceTime() {
        $this->authChecking(true, false);
        $service_ids = filter_input(INPUT_POST, 'service_ids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
        $time = 0;
        foreach ($service_ids as $service_id) {
            $bean = R::findOne('detections', ' id = ? ', [$service_id]);
            $time += $bean ? $bean->operation_time : 0;
        }
        echo json_encode(['status' => 'success', 'time' => $time]);
    }

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

    /**
     * @param $event
     * @param $color
     * @param $statusText
     * @param array $events
     * @return array
     */
    protected function getEvents($event, $color, $statusText, array $events) {
        $branch = R::findOne('branches', ' id = ? ', [$event->branch_id]);
        $user = R::findOne('awusers', ' user_id = ? ', [$event->user_id]);
        $patient = R::findOne('patients', ' id = ? ', [$event->patient_id]);
        $doctor = R::findOne('awusers', ' user_id = ? ', [$event->doctor_id]);

        $services = explode(',', $event->service_ids);
        $servicesNames = [];
        foreach ($services as $service_id) {
            $service = R::findOne('detections', ' id = ? ', [$service_id]);
            if ($service) {
                $servicesNames[] = $service->title;
            }
        }

        $events[] = [
            'id' => $event->id,
            'title' => $patient ? $patient->wifename : 'لا يوجد',
            'branch' => $branch ? $branch->name : 'لا يوجد',
            'user' => $user ? $user->name : 'لا يوجد',
            'doctor' => $doctor ? $doctor->name : 'لا يوجد',
            'services' => implode(',', $servicesNames),
            'start' => $event->date . ' ' . $event->start_time,
            'end' => $event->date . ' ' . $event->end_time,
            'the_date' => $event->date,
            'color' => $color,
            'resourceId' => $event->room_id,
            'status' => $event->status,
            'status_text' => $statusText,
        ];
        return $events;
    }

    /**
     * @return void
     */
    protected function preData() {
        $user = R::findOne('awusers', ' user_id = ? ', [$_SESSION['user_id']]);
        $userBranches = $user ? explode(',', $user->branch_id) : [];

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

        $roles = R::getCol('select id from awrole where is_doctor = 1 ');
        list($doctors, $users) = [[], []];
        foreach ($userBranches as $branch) {
            $doctors[] = R::getAll(
                            'select * from awusers where deleted != 1 and role_id in (' . implode(',', $roles) . ') and FIND_IN_SET(?,branch_id)',
                            [$branch]
            );
            $users[] = R::getAll(
                            'select * from awusers where deleted != 1 and role_id = 3 and FIND_IN_SET(?,branch_id)',
                            [$branch]
            );
        }
        $doctors = call_user_func_array('array_merge', $doctors + [[]]);
        $users = call_user_func_array('array_merge', $users + [[]]);
        $this->smarty->assign('doctors', array_unique($doctors, SORT_REGULAR));
        $this->smarty->assign('users', array_unique($users, SORT_REGULAR));

        $operationRooms = R::findAll('operations_rooms', 'deleted = 0 and  branch_id IN (' . $user->branch_id . ')');
        $this->smarty->assign('operation_rooms', $operationRooms);

        $branches = R::findAll('branches', 'id in (' . $user->branch_id . ')');
        $this->smarty->assign('branches', $branches);

        $status = [
            ['id' => 1, 'name' => 'Reserved'],
            ['id' => 2, 'name' => 'Confirmed'],
            //['id' => 3, 'name' => 'Canceled'],
            ['id' => 4, 'name' => 'Done'],
            ['id' => 5, 'name' => 'Paid'],
        ];
        $this->smarty->assign('status', $status);
    }

}
