<?

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_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';
    
	///sleep(2);
	
    /*---Проверка данных на SQL иньекции---*/
    if ( $_REQUEST ) {
        foreach ( $_REQUEST as $v ) {
            if ( init_inj( $v ) ) {
                exit();
            }
        }
    }
	
	$get_messages = mysql_query( "SELECT * FROM chat_mess WHERE data > ". $config_user['chat_view']." AND from_id != '".$_SESSION['iduser']."' ORDER BY data ASC LIMIT 1000" );
    
    if ( mysql_num_rows( $get_messages ) > 0 ) { 
        
        while ( $row = mysql_fetch_array( $get_messages ) ) {
            $info_from_id = mysql_fetch_array( mysql_query( "SELECT * FROM user WHERE id = '" . $row['from_id'] . "' LIMIT 1" ) );
            
			mysql_query( "UPDATE user SET chat_view = '".time()."' WHERE id = '" .  $_SESSION['iduser'] . "' " );
            
            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'] );
            }
			
			if($config_user['account'] == 5 OR $config_user['username'] == 2 ) {
				$adm_chat_status_json = '1';
			} else {
				$adm_chat_status_json = '0';
			}
            
            $array = array( 'adm' => $adm_chat_status_json, '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['chat'][] = $array;
        }
        
        if ( count( $json['chat'] ) ) {
            $json['ok'] = 1;
        }
        print json_encode( $json ); //кодируем в json
    } else {
        
    }
}

?>