<?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; }
        }



        if(isset($user['id']) && (isset($_POST['cfms']))) {
            $mess = system :: check($_POST['message']);
            //die($mess);
            $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`) VALUES (?, ?, ?);", array($user['id'], $time_m, $mess))) {            
                            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="Отправить">
                <?=emoji :: Smiles("emoji-block_1","emoji-textarea")?>
                </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) );
            ?>
            
        
            
            <?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)?></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>
            </div>

            
        
            
            
            <?php
        }

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

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