<?

session_start();

header( 'Content-type: text/html; charset=windows-1251' );

if ( !isset( $_SESSION['iduser'] ) ) {
    exit();
}
if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) {
    exit();
} else {
    define( 'ROOT', 'http://'.$_SERVER['HTTP_HOST'] );
    define( 'ROOT_DIR', $_SERVER['DOCUMENT_ROOT'] );
    include_once ROOT_DIR . '/engine/config.php';
    include_once ROOT_DIR . '/engine/function.php';
    include_once ROOT_DIR . '/engine/classes/bbcode.class.php';
    
    /*---Проверка данных на SQL иньекции---*/
    if ( $_REQUEST ) {
        foreach ( $_REQUEST as $v ) {
            if ( init_inj( $v ) ) {
                exit();
            }
        }
    }
    
    $get_messages = mysql_query( "SELECT * FROM messages WHERE m_state = 'inbox' and from_id = '" . ( int ) $_POST['id'] . "' and to_id = '" . $_SESSION['iduser'] . "' and m_type = '0' ORDER BY data DESC" );
    
    if ( mysql_num_rows( $get_messages ) > 0 ) {
        
        while ( $row = mysql_fetch_array( $get_messages ) ) {
            $info_from_id = mysql_fetch_array( mysql_query( "SELECT username, avatar FROM user WHERE id = '" . $row['from_id'] . "' LIMIT 1" ) );
            mysql_query( "UPDATE messages SET m_type = 1 WHERE id = '" . $row['id'] . "' and m_state = 'inbox' and m_type = 0" );
            
            if ( date( 'd.m.Y', $row['data'] ) == date( 'd.m.Y', time() ) ) {
                $data = 'сегодня в ' . date( 'H:i', $row['data'] );
            } else
            if ( date( 'd.m.Y', $row['data'] ) == date( 'd.m.Y', time() - 86400 ) ) {
                $data = 'вчера в ' . date( 'H:i', $row['data'] );
            } else {
                $data = date( 'd.m.Y H:i', $row['data'] );
            }
            
            $array = array( 'id' => $row['id'], 'username' => iconv( 'windows-1251', 'UTF-8', $info_from_id['username'] ), 'avatar' => $info_from_id['avatar'], 'text' => iconv( 'windows-1251', 'UTF-8', $row['text'] ), 'data' => iconv( 'windows-1251', 'UTF-8', $data ) );
            
            $json['mread'][] = $array;
        }
        
        if ( count( $json['mread'] ) ) {
            $json['ok'] = 1;
        }
        print json_encode( $json ); //кодируем в json
    } else {
        
    }
}

?>