<?php

require_once("imp/_imp.php");

class Controllers
{
    public $smarty;
    public $host_url;
    public $control_name;
    public $display_control_name;
    public $active;
    public $time;
    public $today;
    public $patient_id;

    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;

        $this->control_name = 'messages';
        $this->display_control_name = 'messages';
        $this->smarty->assign('control_name', $this->control_name);
        $this->smarty->assign('display_control_name', $this->display_control_name);

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

        $active[0] = $this->control_name;
        $active[1] = $this->control_name;
        if ($acty === '') {
            $active[2] = $this->control_name . 'add';
        } else {
            $active[2] = $this->control_name . 'show';
        }

        $this->active = $active;

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

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

        $this->time = microtime(true);
        $this->today = date('Y-m-d');
    }

    /*
     *  create table in db
create table messages
(
id          int auto_increment
primary key,
message     text     null,
created_at  datetime null,
sender_id   int      not null,
receiver_id int      not null,
constraint messages_id_uindex
unique (id)
);
     */

    public function index()
    {
        autho::checkautho($this->host_url);
        autho::checkauthoize($this->control_name, $this->host_url, $_SESSION['role_id']);

        // all awusers
        $aw_users = R::getAll('select * from awusers where user_id != ? and user_active = 1', [$_SESSION['user_id']]);
        foreach ($aw_users as $key => $value) {
            // get last message from messages tbl
            $last_message = R::getRow('select * from messages where (sender_id = ? and receiver_id = ?) or (sender_id = ? and receiver_id = ?) order by created_at desc limit 1', [$_SESSION['user_id'], $value['user_id'], $value['user_id'], $_SESSION['user_id']]);
            if ($last_message) {
                $aw_users[$key]['last_message'] = $last_message['message'];
                $aw_users[$key]['last_message_date'] = date('d-m-Y h:ia', strtotime($last_message['created_at']));
            } else {
                $aw_users[$key]['last_message'] = '';
                $aw_users[$key]['last_message_date'] = '';
            }

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

        header::headershow($this->smarty, $this->host_url);
        sidebar::sidebarshow($this->smarty, $this->host_url, $this->active);
        $this->smarty->display('messages/show.html.tpl');
        leftsidebar::leftsidebarshow($this->smarty, $this->host_url);
        footer::footershow($this->smarty, $this->host_url);
    }

    public function chat(){
        autho::checkautho($this->host_url);

        $receiver_id = filter_input(INPUT_GET, 'receiver_id');

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

        $receiver = R::getRow('select * from awusers where user_id = ?', [$receiver_id]);
        $this->smarty->assign('receiver', $receiver);

        $messages = R::getAll('select * from messages where (sender_id = ? and receiver_id = ?) or (sender_id = ? and receiver_id = ?) order by created_at', [$_SESSION['user_id'], $receiver_id, $receiver_id, $_SESSION['user_id']]);
        // enhance message datetime to human readable
        foreach ($messages as $key => $value) {
            $messages[$key]['created_at'] = date('d-m-Y h:ia', strtotime($value['created_at']));
        }
        $this->smarty->assign('messages', $messages);


        $this->smarty->display('messages/chat.html.tpl');
    }

    public function send(){
        autho::checkautho($this->host_url);

        $receiver_id = filter_input(INPUT_POST, 'receiver_id');
        $message = filter_input(INPUT_POST, 'message');

        $message_bean = R::xdispense('messages');
        $message_bean->message = $message;
        $message_bean->sender_id = $_SESSION['user_id'];
        $message_bean->receiver_id = $receiver_id;
        $message_bean->created_at = date('Y-m-d H:i:s');
        R::store($message_bean);
    }

    public function discussions(){
        autho::checkautho($this->host_url);

        $receiver_id = filter_input(INPUT_POST, 'receiver_id');
        $this->smarty->assign('receiver_id', $receiver_id);

        $aw_users = R::getAll('select * from awusers where user_id != ? and user_active = 1', [$_SESSION['user_id']]);
        foreach ($aw_users as $key => $value) {
            // get last message from messages tbl
            $last_message = R::getRow('select * from messages where (sender_id = ? and receiver_id = ?) or (sender_id = ? and receiver_id = ?) order by created_at desc limit 1', [$_SESSION['user_id'], $value['user_id'], $value['user_id'], $_SESSION['user_id']]);
            if ($last_message) {
                $aw_users[$key]['last_message'] = $last_message['message'];
                $aw_users[$key]['last_message_date'] = date('d-m-Y h:ia', strtotime($last_message['created_at']));
            } else {
                $aw_users[$key]['last_message'] = '';
                $aw_users[$key]['last_message_date'] = '';
            }

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

        $this->smarty->display('messages/discussions.html.tpl');
    }

    public function notifications(){
        autho::checkautho($this->host_url);

        $notifications = [
//            [
//                'sender_name' => 'John Doe',
//                'message' => 'any thing'
//            ],
//            [
//                'sender_name' => 'Ahmed',
//                'message' => 'any thing2'
//            ]
        ];

        echo json_encode($notifications);
    }

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

}
