<?php   
        $thisLink = "/arbour";
        $table = "arbour";
        
        $thisNumber = (isset($_GET['p']) ? abs(intval($_GET['p'])) : 0);

        $accessEdit = (isset($user['id']) ? admin :: getAccess($user,  array('a'=>3,'m_chat'=>1)) : '' );

        $edit = false;
        if(isset($_GET['edit']) && isset($user['id'])){
            $editID = intval($_GET['edit']);
            $messEdit = DB :: $pdo -> queryFetch("SELECT * FROM `{$table}` WHERE `id` = ?", [$editID]);
            if($messEdit['id_user'] == $user['id'] || $accessEdit){ $edit = true; }
        }

    
        $reply = (isset($_GET['reply']) ? intval($_GET['reply']) : 0);
        $replyUser['id'] = 0;
        if($reply > 0) {
            $reply = DB::$pdo->queryFetch("select `id`,`id_user` from `{$table}` where `id` = :id and `id_user` <> :us limit 1;", array(':id'=>$reply, ':us'=>$user['id']));
            if($reply['id'] > 0) {
                $replyUser = profile :: getUser($reply['id_user'],"*",false);
                if(!isset($replyUser['id'])) { $replyUser['id'] = 0; } 
                $reply = $reply['id'];
            } else $reply = 0;
        }


        if(isset($user['id']) && (isset($_POST['cfms']))) {
            $mess = system :: check($_POST['message']);
            $msg_str = system :: utf_strlen($mess);
            $mess = emoji :: Encode($mess);
            if($msg_str >= 1) {
                if($msg_str <= 100000) {
                    $m_db = DB :: $pdo -> querySingle("SELECT COUNT(*) FROM `{$table}` WHERE `id_user` = ? AND `time` > ? AND `message` = ?;", array($user['id'], (time() - 600), $mess));
                    if($m_db == 0) {        
                        $time_m = time();
                        if($edit){

                            DB :: $pdo -> query("UPDATE `{$table}` SET `message` = ? WHERE `id` = ?;", array($mess, $messEdit['id']));
                            if(!empty($thisNumber)){ $thisLink .= "?p={$thisNumber}"; }
                            system :: redirect("Сообщение изменено.", $thisLink);
                        }
                        elseif(DB :: $pdo -> query("INSERT INTO `{$table}` (`id_user`, `time`, `message`, `reply_user`, `reply_msg_id`) VALUES (?, ?, ?,?,?);", array($user['id'], $time_m, $mess,$replyUser['id'],$reply))) {            
                            if((int)$replyUser['id'] > 0 && (int)$replyUser['id'] !== (int)$user['id']) {
                                notif::init()->arbour([
                                    'id_author' => $replyUser['id'],
                                    'id_user' => $user['id'],
                                    'id_post' => $reply,
                                    'text' =>$mess
                                ]);
                            }
                            	if($user['rait'] < '100'){DB::$pdo->query("UPDATE `users` SET `rait_us` ='".($user['rait_us'] + 0.02)."' WHERE `id` = '$user[id]' LIMIT 1");} //Начисления рейтинга


                            system :: redirect("Сообщение отправлено.", $thisLink);
                        } else {
                            $errMsg = "Неизвестная ошибка. Сообщение не отправлено.";
                        }
                    } else { $errMsg = "Сообщение повторяет предыдущее."; }
                } else { $errMsg = "Сообщение превышает 1000 знаков."; }
            } else { $errMsg = "Пустое сообщение."; }
        }
        
        $title = $l = 'Общий чат';
         $lBack = profile :: getLink($user);
        
                
        if(isset($_GET['act']) && $accessEdit) {
            $act = system :: check($_GET['act']);
            if($act == "delete") { require (".inc/del_message.php"); }
        }
        
        require (CORE."head.php");

        
        if(isset($errMsg)){ echo system :: show($errMsg); }
?>

        
        <div class="app-block">
            <?php if(isset($user['id'])) {?>
        
            <form method="post" class="post-add" data-type="arbour" action="<?=$ss?>">
                <textarea name="message" id="emoji-textarea" data-id="emoji-block_1" class="app-textarea" placeholder="Введите сообщение.."><?=($edit ? emoji :: decode($messEdit['message']) : '')?></textarea>
                <div class="list _bg-gray"><div class="_p-rel">             
                <input type="submit" class="main-btn" name="cfms" value="Отправить">
                <?=(isset($replyUser['id']) && $replyUser['id'] > 0 ? '<span style="color: gray;margin: 5px;">
                            Ответ для '.profile :: goPage($replyUser, false).' (<a href="'.$thisLink.'?p='.$thisNumber.'">отменить</a>)
                        </span>' :'')?>
                <?=emoji :: Smiles("emoji-block_1","emoji-textarea")?>
                <?= genStickersButton() ?>
                </div>
                </div>
            </form>
            <?php } else { ?>
            <div class="list _center _gray _font-s">
            Для того, чтобы писать в общем чате сначала <a href="/" class="_bold">войдите</a> или <a href="/signup" class="_bold">зарегистрируйтесь</a>.
            </div>
            <?php } ?>
        
        
<?php


        $query = "SELECT * FROM `{$table}` ORDER by `time` DESC ";
        $total = DB :: $pdo -> querySingle("SELECT COUNT(*) FROM `{$table}`");
        
        if($total > 10) {
            $p = (($_GET['p']) ? intval($_GET['p']) : 1);
            $pagination = new pagination(10, $total, $p);
            $query .= $pagination -> limit;
        }
        
        $q = DB :: $pdo -> query("{$query}");

        $i = 0;
        $in = 0;

        echo '<div class="post-list-all ">';
        while($r = $q -> fetch()) {
            $dataUser = ($r['id_user'] == $user['id'] ? $user : profile :: getUser($r['id_user'],"*",false) );
            unset($rData);
            if($r['reply_user'] > 0) { $rData = ($r['reply_user'] == $user['id'] ? $user : profile :: getUser($r['reply_user'],"*",false) ); }
            ?>
            
        
            
            <?if(isset($_GET['edit']) && $r['id'] == intval($_GET['edit']) && ($r['id_user'] == $user['id'] || $accessEdit)  ){
                $class = " edit_msg";
            }
            else $class = "";
            ?>
            
            <div class="list<?=$class;?>" id="arbour_p<?=$r['id']?>">
                <?php if($r['id_user'] == $user['id'] || $accessEdit){
                    $url = $thisLink.'?p='.$pagination -> page;
                    $actionsLink[] = ['link'=>$url.'&amp;edit='.$r['id'],'text'=>"Редактировать"];
                    $actionsLink[] = ['link'=>$url.'&amp;act=delete&amp;id='.$r['id'].'&amp;access='.ACCESS,'text'=>"Удалить"];
                    echo UI :: toggleMenu($actionsLink);
                    unset($actionsLink);
                } 
                    ?>

            
                <div class="_oh">

<div class="list-flex">
                <div class="post-l emotion-show" data-emotions="<?=system::textOut($dataUser['emotions'])?>">
                    <?=profile :: userAvatar($dataUser, 3)?>
                </div>
                <div class="post-c">
                    <div style="display: block;"><span class="_name"><?=profile :: goPage($dataUser)?> <?=profile :: cake($dataUser)?> </span> <?=(isset($rData['id']) ? ' <span class="_gray _font-m">ответ для '.profile :: goPage($rData,false).'</span>' : '')?><div><span class="_font-m _gray"><?=system :: times($r['time'])?></span></div></div>  
                </div>
                </div>
                </div>
                <div class="_oh">
                    <span style="vertical-align: sub;"><?=emoji :: Text(system :: BBcode(system :: textOut($r['message'])))?></span>
                </div>
            <?php if(isset($user['id']) && $r['id_user'] != $user['id']) : ?>
                     <a href="<?=$thisLink.'?reply='.$r['id'].'&p='.$pagination -> page?>" class="app-touch-bottom post-bottom-menu-h"><i class="fa fa-reply" aria-hidden="true"></i> Ответить</a>
            <?php endif; ?>
<?= like::init()->createButton(like::ARBOUR, [
                    'id_post' => $r['id'],
                    'id_user' => isset($user['id']) ? $user['id'] : -1,
                    'id_author' => $r['id_user']
                ]) ?>
             <!--
                   <span class="_fl-r"> <a href="" class="app-touch-bottom post-bottom-menu-h"><i class="fa fa-heart-o"></i></a></span>
                   
             <span class="_fl-r"> <a href="" class="app-touch-bottom post-bottom-menu-h"><i class="fa fa-heart"></i> 2</a></span>
                   
            -->
            </div>

            
        
            
            
            <?php
        }

        if($total > 10) echo $pagination -> printPages($thisLink."?"); 
        echo '</div>';

    require (CORE."foot.php");
?>