<?php
/**
 * Created by PhpStorm.
 * User: jaskokoyn
 * Date: 2/18/2015
 * Time: 12:13 PM
 */

require('../../inc/db.php');
include('../../inc/functions.php');
include('../../inc/JBBCode/Parser.php');
include('../../inc/YoutubeEmbed.php');

$params                         =   getParams();
$output                         =   array('status' => 1);

if( !isReady( $params["opts"], array("fontFamily", "color", "message") ) || $settings['guests_chat'] == 2){
    dj($output);
}

// Check Last Message Sent
if(isset($_SESSION['last_message_sent'])){
    if($_SESSION['last_message_sent'] + 3 > time()){
        dj($output);
    }

    $_SESSION['last_message_sent'] = time();
}else{
    $_SESSION['last_message_sent'] = time();
}

$cid                            =   intval($params['cid']);
$chatQuery                      =   $db->prepare("SELECT * FROM chats WHERE id = :cid");
$chatQuery->execute(array( ":cid" => $cid ));
$chatRow                        =   $chatQuery->fetch();
$profile_img                    =   (isset($_SESSION['loggedin'])) ? $user['profile_img'] : "default.png";
$parser                         =   new JBBCode\Parser();
$message                        =   substr(secure($params['opts']['message']),0,500);
$isMod                          =   false;

// Check if banned
$checkBanQuery                  =   $db->prepare("SELECT * FROM chat_bans WHERE username = :u AND cid = :cid");
$checkBanQuery->execute(array(
    ":u"                        =>  $_SESSION['username'],
    ":cid"                      =>  $cid
));
if($checkBanQuery->rowCount() > 0){
    dj($output);
}

// Check if chat mod
$checkModQuery                  =   $db->prepare("SELECT * FROM chat_mods WHERE username = :u AND cid = :cid");
$checkModQuery->execute(array(
    ":u"                        =>  $_SESSION['username'],
    ":cid"                      =>  $cid
));
if($checkModQuery->rowCount() > 0){
    $isMod                      =   true;
}


// Process Commands
if( isset($_SESSION['loggedin']) &&
    (
        $user['mem_level'] == 2 || $user['mem_level'] == 3 ||
        $chatRow['owner'] == $_SESSION['username'] || $isMod
    )){
    if(substr($message,0,1) === "!"){
        $messageArr             =   explode(" ", $message);
        $command                =   $messageArr[0];
        $output['status']       =   2;

        if($command === "!ban"){
            $cmd_user           =   $messageArr[1];

            if($cmd_user == $chatRow['owner']){
                dj($output);
            }

            $insertBanQuery     =   $db->prepare("INSERT INTO chat_bans(username,cid) VALUES(:u,:cid)");
            $insertBanQuery->execute(array(
                ":u"            =>  $cmd_user,
                ":cid"          =>  $cid
            ));
            $insertMessageQuery =   $db->prepare("INSERT INTO messages(message,m_type,submitted_by,time_submitted,cid,profile_img)
                                                  VALUES( :m, :t, :u, :s, :cid, :pi )");
            $insertMessageQuery->execute(array(
                ":m"                        =>  "The user <strong>" . $cmd_user . "</strong> has been banned.",
                ":t"                        =>  1,
                ":u"                        =>  "Owl Bot",
                ":s"                        =>  time(),
                ":cid"                      =>  $cid,
                ":pi"                       =>  "system.png"
            ));
            dj($output);
        }
        else if($command == "!unban"){
            $cmd_user           =   $messageArr[1];

            if($cmd_user == $chatRow['owner']){
                dj($output);
            }

            $deleteBanQuery     =   $db->prepare("DELETE FROM chat_bans WHERE username = :u AND cid = :cid");
            $deleteBanQuery->execute(array(
                ":u"            =>  $cmd_user,
                ":cid"          =>  $cid
            ));
            $insertMessageQuery =   $db->prepare("INSERT INTO messages(message,m_type,submitted_by,time_submitted,cid,profile_img)
                                                  VALUES( :m, :t, :u, :s, :cid, :pi )");
            $insertMessageQuery->execute(array(
                ":m"                        =>  "The user <strong>" . $cmd_user . "</strong> has been unbanned.",
                ":t"                        =>  1,
                ":u"                        =>  "Owl Bot",
                ":s"                        =>  time(),
                ":cid"                      =>  $cid,
                ":pi"                       =>  "system.png"
            ));
            dj($output);
        }
        else if($command == "!addmod"){
            $cmd_user           =   $messageArr[1];

            if($_SESSION['username'] !== $chatRow['owner'] || ($user['mem_level'] != 2 && $user['mem_level'] != 3) ){
                dj($output);
            }

            $insertModQuery     =   $db->prepare("INSERT INTO chat_mods(username,cid) VALUES( :u, :cid )");
            $insertModQuery->execute(array(
                ":u"            =>  $cmd_user,
                ":cid"          =>  $cid
            ));
            $insertMessageQuery =   $db->prepare("INSERT INTO messages(message,m_type,submitted_by,time_submitted,cid,profile_img)
                                                  VALUES( :m, :t, :u, :s, :cid, :pi )");
            $insertMessageQuery->execute(array(
                ":m"                        =>  "The user <strong>" . $cmd_user . "</strong> has been promoted to chat mod.",
                ":t"                        =>  1,
                ":u"                        =>  "Owl Bot",
                ":s"                        =>  time(),
                ":cid"                      =>  $cid,
                ":pi"                       =>  "system.png"
            ));
            dj($output);
        }
        else if($command == "!removemod"){
            $cmd_user           =   $messageArr[1];

            if($_SESSION['username'] !== $chatRow['owner'] || ($user['mem_level'] != 2 && $user['mem_level'] != 3) ){
                dj($output);
            }

            $deleteModQuery     =   $db->prepare("DELETE FROM chat_mods WHERE username = :u AND cid = :cid");
            $deleteModQuery->execute(array(
                ":u"            =>  $cmd_user,
                ":cid"          =>  $cid
            ));
            $insertMessageQuery =   $db->prepare("INSERT INTO messages(message,m_type,submitted_by,time_submitted,cid,profile_img)
                                                  VALUES( :m, :t, :u, :s, :cid, :pi )");
            $insertMessageQuery->execute(array(
                ":m"                        =>  "The user <strong>" . $cmd_user . "</strong> has been demoted from chat mod.",
                ":t"                        =>  1,
                ":u"                        =>  "Owl Bot",
                ":s"                        =>  time(),
                ":cid"                      =>  $cid,
                ":pi"                       =>  "system.png"
            ));
            dj($output);
        }
    }
}

// Process Emotes
$emotesQuery                    =   $db->prepare("SELECT `img`,`e_cmd` FROM emotes");
$emotesQuery->execute();
while($emotesRow                =   $emotesQuery->fetch()){
    $message                    =   str_replace( $emotesRow['e_cmd'], '<img src="assets/emotes/' . $emotesRow['img'] . '" width="18" height="18">', $message);
}

// Process BBCodes
if(($settings['images_btn'] != 2 && $chatRow['images_enabled'] != 4) ||
    ( isset($user) && ($user['mem_level'] == 2 || $user['mem_level'] == 3) ) ){
    if($chatRow['images_enabled'] == 1){
        $img_html               =   '<img src="{param}" class="img-responsive">';
    }else if($chatRow['images_enabled'] == 2){
        $img_html               =   '<a href="{param}" class="btn btn-violet btn-xs" data-lightbox="image"><i class="fa fa-eye"></i> View Image</a>';
    }else{
        $img_html               =   '<a href="{param}" target="_blank">{param}</a>';
    }

    $img_builder                = new JBBCode\CodeDefinitionBuilder('img', $img_html);
    $parser->addCodeDefinition($img_builder->build());
}
if(($settings['url_btn'] != 2 && $chatRow['links_enabled'] != 2)  ||
    ( isset($user) && ($user['mem_level'] == 2 || $user['mem_level'] == 3) )){
    $link_builder               = new JBBCode\CodeDefinitionBuilder('url', '<a href="{param}" target="_blank">{param}</a>');
    $parser->addCodeDefinition($link_builder->build());
}
if(($settings['youtube_btn'] != 2  && $chatRow['youtube_enabled'] != 2)  ||
    ( isset($user) && ($user['mem_level'] == 2 || $user['mem_level'] == 3) )){
    $youtubeEmbed               = new YoutubeEmbed();
    $parser->addCodeDefinition($youtubeEmbed);
}

$parser->parse($message);
$parsed_message                 =   $parser->getAsHtml();

// Process Bad Words
$badWords                       =   array_merge( explode(",", $chatRow['bad_words']), explode(",", $settings['bad_words']));
$parsed_message                 =   str_replace( $badWords, '<span class="label inverse">****</span>', $parsed_message);

// Process Formatting
$font                           =   in_array($params['opts']['fontFamily'], $fontFamilyArr) ? "font-family: '" . secure($params['opts']['fontFamily']) . "';": "font-samily: 'Noto Sans';";
$size                           =   intval($params['opts']['fontSize']);
$size                           =   $size > 20 || $size < 10 ? "font-size: 12px;" : "font-size: " . $size . "px;";
$color                          =   checkHex($params['opts']['color']) ? "color: " . secure($params['opts']['color']) . ";" : "color: #33;";
$bold                           =   $params['opts']['bold'] ? "font-weight: bold;" : "";
$italic                         =   $params['opts']['italic'] ? "font-style: italic;" : "";
$messageCtr                     =   '<span style="' . $font . $size . $color . $bold . $italic . '">';
$messageCtr                    .=   $parsed_message . '</span>';

// Insert Into DB
$insertMessageQuery             =   $db->prepare("INSERT INTO messages(message,m_type,submitted_by,time_submitted,cid,profile_img)
                                                  VALUES( :m, :t, :u, :s, :cid, :pi )");
$insertMessageQuery->execute(array(
    ":m"                        =>  $messageCtr,
    ":t"                        =>  1,
    ":u"                        =>  $_SESSION['username'],
    ":s"                        =>  time(),
    ":cid"                      =>  $cid,
    ":pi"                       =>  $profile_img
));

$output['status']               =   2;
dj($output);