<?php
/*
 * @package AJAX_Chat
 * @author Sebastian Tschan
 * @copyright (c) Sebastian Tschan
 * @license GNU Affero General Public License
 * @link https://blueimp.net/ajax/
 */

class CustomAJAXChat extends AJAXChat {

    // Returns an associative array containing userName, userID and userRole
    // Returns null if login is invalid
    function getValidLoginUserData() {
        if(empty($_COOKIE['msz_auth'])) {
            header('Location: https://flashii.net/auth/login.php');
            exit;
        }

        $userInfo = SockChatAuth::attempt($this->getConfig('flashiiSecret'), (string)filter_input(INPUT_COOKIE, 'msz_auth'));

        if($userInfo->success) {
            // Check if we have a valid registered user:

            $chatUser = [
                'userID' => $userInfo->user_id,
                'userName' => $userInfo->username,
                'userRole' => AJAX_CHAT_GUEST,
            ];

            // sock chat auth doesn't actually return role ids lol
            if($userInfo->colour_raw === 0xEE9400)
                $chatUser['userRole'] = DONATOR;
            elseif($userInfo->colour_raw === 0x0099FF)
                $chatUser['userRole'] = CMOD;
            elseif($userInfo->colour_raw === 0x7353C4)
                $chatUser['userRole'] = PURPLE;
            elseif($userInfo->colour_raw === 0x9E8DA7)
                $chatUser['userRole'] = BOTS;
            elseif($userInfo->rank >= 10)
                $chatUser['userRole'] = AJAX_CHAT_ADMIN;
            elseif($userInfo->rank >= 5)
                $chatUser['userRole'] = AJAX_CHAT_MODERATOR;
            elseif($userInfo->rank >= 1)
                $chatUser['userRole'] = AJAX_CHAT_USER;

            return $chatUser;
        } else {
            // Guest users:
            return $this->getGuestUser();
        }
    }

    // Store the channels the current user has access to
    // Make sure channel names don't contain any whitespace
    function &getChannels() {
        if($this->_channels === null) {
            $this->_channels = array();

            /*$customUsers = $this->getCustomUsers();

            // Get the channels, the user has access to:
            if($this->getUserRole() == AJAX_CHAT_GUEST) {
                $validChannels = $customUsers[0]['channels'];
            } else {
                $validChannels = $customUsers[$this->getUserID()]['channels'];
            }*/

            // Add the valid channels to the channel list (the defaultChannelID is always valid):
            foreach($this->getAllChannels() as $key=>$value) {
                // Check if we have to limit the available channels:
                if($this->getConfig('limitChannelList') && !in_array($value, $this->getConfig('limitChannelList'))) {
                    continue;
                }

                //if(in_array($value, $validChannels) || $value == $this->getConfig('defaultChannelID')) {
                    $this->_channels[$key] = $value;
                //}
            }
        }
        return $this->_channels;
    }

    // Store all existing channels
    // Make sure channel names don't contain any whitespace
    function &getAllChannels() {
        if($this->_allChannels === null) {
            // Get all existing channels:
            $customChannels = $this->getCustomChannels();

            $defaultChannelFound = false;

            foreach($customChannels as $key=>$value) {
                $forumName = $this->trimChannelName($value);

                $this->_allChannels[$forumName] = $key;

                if($key == $this->getConfig('defaultChannelID')) {
                    $defaultChannelFound = true;
                }
            }

            if(!$defaultChannelFound) {
                // Add the default channel as first array element to the channel list:
                $this->_allChannels = array_merge(
                    array(
                        $this->trimChannelName($this->getConfig('defaultChannelName'))=>$this->getConfig('defaultChannelID')
                    ),
                    $this->_allChannels
                );
            }
        }
        return $this->_allChannels;
    }

    /*function &getCustomUsers() {
        global $database;

        $userlist = $database->query("SELECT * FROM `accounts`.`flashii_users` WHERE `userrole` != '0'")->fetch_all(MYSQLI_ASSOC);

        $users = array();

        $users[0] = array();
        $users[0]['userRole'] = AJAX_CHAT_GUEST;
        $users[0]['userName'] = null;
        $users[0]['password'] = null;
        $users[0]['channels'] = array(0,1);

        foreach($userlist as $user) {
            $users[$user['id']]                 = array();
            $users[$user['id']]['userName']     = $user['username'];
            $users[$user['id']]['password']     = $user['password'];

            switch($user['userrole']) {
                // Tenshi
                case 7:
                    $users[$user['id']]['userRole'] = DONATOR;
                    $users[$user['id']]['channels'] = array(0, 1);
                break;

                // Chat Moderators
                case 6:
                    $users[$user['id']]['userRole'] = CMOD;
                    $users[$user['id']]['channels'] = array(0, 1, 2);
                break;

                // Bots
                case 5:
                    $users[$user['id']]['userRole'] = BOTS;
                    $users[$user['id']]['channels'] = array(0, 1, 2);
                break;

                // Developers
                case 4:
                    $users[$user['id']]['userRole'] = PURPLE;
                    $users[$user['id']]['channels'] = array(0, 1, 2);
                break;

                // Administrator
                case 3:
                    $users[$user['id']]['userRole'] = AJAX_CHAT_ADMIN;
                    $users[$user['id']]['channels'] = array(0, 1, 2);
                break;

                // Site Moderators
                case 2:
                    $users[$user['id']]['userRole'] = AJAX_CHAT_MODERATOR;
                    $users[$user['id']]['channels'] = array(0, 1, 2);
                break;

                // Regular Users
                case 1:
                    $users[$user['id']]['userRole'] = AJAX_CHAT_USER;
                    $users[$user['id']]['channels'] = array(0, 1);
                break;

                // Unknown and Deactivated Users
                case 0:
                default:
                    $users[$user['id']]['userRole'] = AJAX_CHAT_GUEST;
                    $users[$user['id']]['channels'] = array(0);
            }
        }

        return $users;
    }*/

    function &getCustomChannels() {
        $channels = [
            0 => 'Public',
        ];
        /*$result = $this->db->sqlQuery("SELECT * FROM ajax_chat_channels")->_result->fetch_all(MYSQLI_ASSOC);

        foreach($result as $channel) {
            $channels[$channel['id']] = $channel['name'];
        }*/

        if($this->isLoggedIn())
            $channels[9001] = 'Secret';

        return $channels;
    }

    function parseCustomCommands($text, $textParts) {
        switch($textParts[0]) {
            case '/afk':
                $this->setUserName('<AFK>_' . $this->getUserName());
                $this->updateOnlineList();
                $this->addInfoMessage($this->getUserName(), 'userName');
                $this->setSessionVar('AwayFromKeyboard', true);
            return true;
            default:
            return false;
        }
    }

    function onNewMessage($text) {
        if($this->getSessionVar('AwayFromKeyboard')) {
            $this->setUserName(substr($this->getUserName(), 6));
            $this->updateOnlineList();
            $this->addInfoMessage($this->getUserName(), 'userName');
            $this->setSessionVar('AwayFromKeyboard', false);
        }
        return true;
    }
}
