<?php
    require_once('include/functions/ip_encode.php');

    $_back = isset($_GET['b']) ? str_replace('@', '&', trim(strval($_GET['b']))) : '';
    $_id = isset($_GET['i']) ? intval($_GET['i']) : 0;
    $_body  = isset($_POST['body']) ? trim(strval($_POST['body'])) : '';

    $community_messages = mysqli_query_logged("SELECT * FROM community_messages, community_threads, community_forums, community_sections, community WHERE community_messages.message_id = " . sq($_id) . " AND community_messages.thread_id = community_threads.thread_id AND community_threads.forum_id = community_forums.forum_id AND community_forums.section_id = community_sections.section_id AND community_sections.community_id = community.community_id");
    if (!$community_messages_row = mysqli_fetch_assoc($community_messages))    
    {
        header('Location: ./?s=communities');
        die;        
    }
    
    require_once('include/functions/community_banned.php');
    community_banned($community_messages_row['community_id']);
    require_once('include/functions/community_permissions.php');
    community_permissions($community_messages_row['community_id']);

    require_once('include/functions/community_update_valid.php');
    if ($_error = community_update_valid($_body))    
    {
        show_error_page($_error);
        die;        
    }
    
    $community_messages = mysqli_query_logged("SELECT * FROM community_messages WHERE message_id = " . sq($_id));
    if ($community_messages_row = mysqli_fetch_array($community_messages))
    {
        if ($community_messages_row['message_user_id'] == $GLOBALS['auth']['id'] || $GLOBALS['auth']['community']['message_update'])
        {
            mysqli_query_logged("INSERT INTO community_messages_updates SET message_id = " . sq($_id) . ", update_user_id = '" . $GLOBALS['auth']['id'] . "', update_body = " . sq($_body) . ", update_posted_on = NOW(), update_ip = '" . encode_ip($_SERVER['REMOTE_ADDR']) . "'");
        }
    }

    $previous_count = mysqli_fetch_array(mysqli_query_logged("SELECT COUNT(*) AS count FROM community_messages WHERE thread_id = '" . $community_messages_row['thread_id'] . "' AND message_id < '" . $community_messages_row['message_id'] . "' ORDER BY message_id"));
    $page = ceil(($previous_count['count'] + 1) / COMMUNITY_REPLIES_PER_PAGE);
        
    header('Location: ./?' . ($_back ? $_back : 's=community_thread&i=' . $community_messages_row['thread_id']));
?>