<?php
    $GLOBALS['highlight'] = 'userinfo';

    require_once('include/functions/pages.php');        
    require_once('include/functions/closest_word.php');    
    require_once('include/functions/word_wrap_new.php');    
    
    $_user = isset($_GET['u']) ? trim(strval($_GET['u'])) : '';
    
    if ($_user)
    {
        $members = mysqli_query_logged("SELECT * FROM members WHERE id = '" . get_user_id($_user) . "'");
        if ($members_row = mysqli_fetch_array($members))
        {
            $user_id = $members_row['id'];
            $user_name = $members_row['username'];
        }
        else
        {
            show_error_page('Sorry, we do not have any members by that name.');
            die;
        }
    }
    else
    {
        $user_id = '';
        $user_name = '';
    }


    include('include/parts/header.php');

    if ($user_id)
    {
        mysqli_query_logged("DELETE FROM messages_email WHERE user_id = '" . $GLOBALS['auth']['id'] . "' AND link_id = '" . $user_id . "'");
        mysqli_query_logged("UPDATE messages SET viewed = '1' WHERE sender_id = '" . $user_id . "' AND recipiant_id = '" . $GLOBALS['auth']['id'] . "'");
        $image = mysqli_fetch_array(mysqli_query_logged("SELECT main_image_id FROM members WHERE id = '" . $user_id . "'"));
        $user_image_id = $image['main_image_id'];    
        $history_count = mysqli_fetch_array(mysqli_query_logged("SELECT COUNT(id) AS num FROM messages WHERE (sender_id = '" . $user_id . "' AND recipiant_id = '" . $GLOBALS['auth']['id'] . "' AND sender_id NOT IN (SELECT link_id FROM ignored WHERE user_id = '" . $GLOBALS['auth']['id'] . "')) OR (sender_id = '" . $GLOBALS['auth']['id'] . "' AND recipiant_id = '" . $user_id . "' AND recipiant_id NOT IN (SELECT link_id FROM ignored WHERE user_id = '" . $GLOBALS['auth']['id'] . "'))"));
        $history_count = $history_count['num'];
        $pages = '';
        if ($history_count > MESSAGES_PER_PAGE)
        {
            $page_count = ceil($history_count / MESSAGES_PER_PAGE);
            $pages = '<span class="pages">Page: ' . pages('?s=messages&u=' . $_user, $_page, $page_count) . '</span>';
        }
        echo box_outside_top('<a href="?s=messages">Your Conversations</a> - With <a href="?s=profile&u=' . $_user . '">' . $_user . '</a>' . ($pages ? '<br />' . $pages : ''));
        if ($_error)
        {
            echo '<div class="content"><span class="notice_error" style="font-size: 12px; font-weight: bold;">';
            if ($_error == 'body_missing') 
            {
                echo "Sorry, you need to enter a message to send.";
            } 
            elseif ($_error == 'double_post') 
            {
                echo "Sorry, you cannot send the same message twice in a row.";
            } 
            elseif ($_error == 'rapid') 
            {
                echo "Sorry, you must wait more time between sending messages.";
            }
            elseif ($_error == 'security') 
            {
                echo "Sorry, you have entered the incorrect security code.";
            }
            echo '</span></div>';
        }            
        echo '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr>';
        echo '<td width="' . (THUMB_WIDTH) . '" valign="top">';
        echo box_image_top('margin: 0px 5px 0px 0px;');
        echo '<a href="?s=profile&u=' . $_user . '"><img src="?g=thumb&i=' . get_main_image_id(get_user_id($_user)) . '" width="' . THUMB_WIDTH . '" height="' . THUMB_HEIGHT . '" alt="" border="0" style="border: 0px;"></a>';
        echo box_image_bottom();
        echo '</td>';
        echo '<td valign="top" class="inside">';
        echo '<form action="?a=messages&u=' . $_user . '" method="post" class="form">';
        echo '<textarea name="body" class="input_text" style="width: 90%; height: 112px;"></textarea>';
        echo '<div style="padding: 5px 0px 0px 0px;"></div>';
        mysqli_query_logged("DELETE FROM security_code_last WHERE user_id = '" . $GLOBALS['auth']['id'] . "'");
        if ($user_country != 'CA' && $user_country != 'US')
        {
            $length = mt_rand(4, 6);
            $char_arr = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9');
            $code = '';
            for ($i = 0; $i < $length; $i++)
            {
                $char = $char_arr[mt_rand(0, count($char_arr) - 1)];
                $code .= $char;
            }
            mysqli_query_logged("REPLACE INTO security_code_last SET user_id = '" . $GLOBALS['auth']['id'] . "', code = '" . $code . "', posted_on = NOW()");
            echo '<table cellpadding="0" cellspacing="0" border="0"><tr>';
            echo '<td><img src="?s=security_code&rand=' . mt_rand(1, 9999999) . '" style="border: 0px;"></td>';
            echo '<td style="padding-left: 10px;">Security Code: <input type="text" name="security_code" class="input_text" style="width: 100px;"></td>';
            echo '</tr></table>';
            echo '<div style="padding: 5px 0px 0px 0px;"></div>';
        }
        echo '<input type="submit" value="Send Message" class="input_submit">';
        echo '</td>';
        echo '</tr></table>';                
        $historys = mysqli_query_logged("SELECT body, sender_id, posted_on FROM messages WHERE (sender_id = '" . $user_id . "' AND recipiant_id = '" . $GLOBALS['auth']['id'] . "' AND sender_id NOT IN (SELECT link_id FROM ignored WHERE user_id = '" . $GLOBALS['auth']['id'] . "')) OR (sender_id = '" . $GLOBALS['auth']['id'] . "' AND recipiant_id = '" . $user_id . "' AND recipiant_id NOT IN (SELECT link_id FROM ignored WHERE user_id = '" . $GLOBALS['auth']['id'] . "')) ORDER BY id DESC LIMIT " . (($_page - 1) * MESSAGES_PER_PAGE) . "," . MESSAGES_PER_PAGE);
        if ($history_count > 0)
        {        
            while ($history = mysqli_fetch_array($historys))
            {                        
                if ($history['sender_id'] == $GLOBALS['auth']['id'])
                {
                    echo '<div style="padding: 5px 0px 0px 0px;"></div>';
                    echo '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr>';
                    echo '<td valign="top" class="inside">';
                    echo '<span style="font-weight: bold; font-size: 10px;">' . nice_date($history['posted_on'], 'M j Y @ g:ia') . '</span>';
                    echo '<div style="padding: 5px 0px 0px 0px;"></div>';
                    echo nl2br(word_wrap_new(htmlentities($history['body']), 1));
                    echo '</td>';
                    echo '<td width="' . THUMB_WIDTH . '" valign="top">';
                    echo box_image_top('margin: 0px 0px 0px 5px;');
                    echo '<a href="?s=profile&u=' . $GLOBALS['auth']['username'] . '"><img src="?g=thumb&i=' . get_main_image_id(get_user_id($GLOBALS['auth']['username'])) . '" width="' . THUMB_WIDTH . '" height="' . THUMB_HEIGHT . '" border="0" alt="" style="border: 0px;"></a>';
                    echo box_image_bottom();
                    echo '</td>';
                    echo '</tr></table>';
                }
                else
                {
                    echo '<div style="padding: 5px 0px 0px 0px;"></div>';
                    echo '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr>';
                    echo '<td width="' . THUMB_WIDTH . '" valign="top">';
                    echo box_image_top('margin: 0px 5px 0px 0px;');
                    echo '<a href="?s=profile&u=' . $_user . '"><img src="?g=thumb&i=' . get_main_image_id(get_user_id($_user)) . '" width="' . THUMB_WIDTH . '" height="' . THUMB_HEIGHT . '" border="0" alt="" style="border: 0px;"></a>';
                    echo box_image_bottom();
                    echo '</td>';
                    echo '<td valign="top" class="inside">';
                    echo '<span style="font-weight: bold; font-size: 10px;">' . nice_date($history['posted_on'], 'M j Y @ g:ia') . '</span>';
                    echo '<div style="padding: 5px 0px 0px 0px;"></div>';
                    echo nl2br(word_wrap_new(htmlentities($history['body']), 1));
                    echo '</td>';
                    echo '</tr></table>';
                }
            }
        }
        echo box_outside_bottom();
        if ($pages)
        {
            echo make_pages('<a href="?s=messages">Your Conversations</a> - With <a href="?s=profile&u=' . $_user . '">' . $_user . '</a><br />' . $pages);
        }
    }
    else
    {
        $count_row = mysqli_fetch_assoc(mysqli_query_logged("SELECT COUNT(*) AS num FROM messages_index WHERE receiver_id = '" . $GLOBALS['auth']['id'] . "' AND sender_id NOT IN (SELECT link_id FROM ignored WHERE user_id = '" . $GLOBALS['auth']['id'] . "')"));
        $count_page = ceil($count_row['num'] / MAIL_USERS_PER_PAGE);
        $pages = '<span class="pages">Page: ' . pages('?s=messages', $_page, $count_page) . '</span>';
        echo box_outside_top('Your Conversations' . ($count_page ? '<br />' . $pages : ''));
        if ($count_page)
        {
            $i = 0;
            $messages = mysqli_query_logged("SELECT * FROM messages_index WHERE receiver_id = '" . $GLOBALS['auth']['id'] . "' AND sender_id NOT IN (SELECT link_id FROM ignored WHERE user_id = '" . $GLOBALS['auth']['id'] . "') ORDER BY last_received DESC, last_sent DESC, sender_id LIMIT " . (($_page - 1) * MAIL_USERS_PER_PAGE) . ", " . MAIL_USERS_PER_PAGE);
            while ($messages_row = mysqli_fetch_array($messages))
            {
                if ($i++)
                {
                    echo '<div style="padding: 5px 0px 0px 0px;"></div>';
                }
                $username = get_username($messages_row['sender_id']);
                $message_new = mysqli_fetch_array(mysqli_query_logged("SELECT COUNT(id) AS num FROM messages WHERE sender_id = '" . $messages_row['sender_id']. "' AND recipiant_id = '" . $GLOBALS['auth']['id'] . "' AND viewed = '0'"));
                echo '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr>';
                echo '<td width="90" valign="top">';
                echo box_image_top('margin: 0px 5px 0px 0px;');
                echo '<a href="?s=messages&u=' . $username . '"><img src="?g=thumb&i=' . get_main_image_id($messages_row['sender_id']) . '" width="80" height="60" border="0" alt="" style="border: 0px;"></a>';
                echo box_image_bottom();
                echo '</td>';
                echo '<td valign="top" style="font-size: 10px;" class="inside">';
                echo '<span style="font-size: 11px; font-weight: bold;"><a href="?s=messages&u=' . $username . '">' . $username . ' @ ' . ($messages_row['last_received'] == '0000-00-00 00:00:00' ? 'Waiting For Reply' : nice_date($messages_row['last_received'], 'M j Y, g:ia')) . '</a>';
                echo $message_new['num'] > 0 ? ' [NEW]' : '';
                echo '</span><br />';
                $message_info = mysqli_query_logged("SELECT * FROM messages WHERE id = " . sq($messages_row['message_id_received']));
                if ($message_info_row = mysqli_fetch_array($message_info))
                {
                    echo word_wrap_new(htmlentities(closest_word($message_info_row['body'], 400)), 0);
                }
                echo '</td>';
                echo '</table>';
            }    
        }
        else
        {
            echo box_inside_top();
            echo 'You don\'t have any conversations. Why not start one?';
            echo box_inside_bottom();
        }
        echo box_outside_bottom();
        if ($count_page)
        {
            echo make_pages($pages);
        }    
    }

    include('include/parts/footer.php');
?>