#/usr/bin/perl
# IPN web functions



require Ipn;
Ipn->import();
my $Ipn = Ipn->new($db, \%conf);
my @TT_COLORS = ("$_COLORS[1]", "#80FF80", "#FFFF80", "#BFBFFF");

use Dv;
use Dv_Sessions;
use Nas;
use Tariffs;

my $sessions = Dv_Sessions->new($db, $admin, \%conf);
my $tariffs = Tariffs->new($db, \%conf, $admin);
my $users = Users->new($db, $admin, \%conf); 


#**********************************************************
# Whow sessions from log
# ipn_sessions()
#**********************************************************
sub ipn_sessions2 {
  if (! $user->{UID}) {
    $LIST_PARAMS{UID}=$FORM{UID};
    ipn_recalculate();
   }
  else {
  	$LIST_PARAMS{UID}=$user->{UID};
   }

  $pages_qs.="&UID=$LIST_PARAMS{UID}";

 reports({ DATE        => $FORM{DATE}, 
  	       REPORT      => '',
  	       PERIOD_FORM => 1,
  	       NO_GROUP    => 1,
  	       HIDDEN      => { UID => $LIST_PARAMS{UID} }
  	      });

 my %totals = ();

my %DATA_HASH = ( );
my %CHART = ();
my %AVG = (MONEY    => 0,
           TRAFFIC  => 0,
           DURATION => 0);
my @type;

$CHART{SUFFIX}='b';

my $graph_type='';
#Day reposrt
if (defined($FORM{DATE})) {
   $LIST_PARAMS{INTERVAL_TYPE} = 2;
   $graph_type='day_stats';
}
else {
	if ($sessions->prepaid_rest({ UID => $LIST_PARAMS{UID}, INFO_ONLY => 1 })) {
	  #Prepaid: period, traffic_type
  
    
    my $list = $Ipn->prepaid_rest({ UID  => $LIST_PARAMS{UID}, 
  	                                INFO => $sessions->{INFO_LIST} });




    my $table = $html->table( { caption     => "$_PREPAID",
	                          width       => '100%',
                            title_plain => ["$_TRAFF $_TYPE", "$_BEGIN", "$_END", "$_START", "$_TOTAL (MB)", "$_REST (MB)", "$_OVERQUOTA (MB)"],
                            cols_align  => ['left', 'right', 'right', 'right', 'right', 'right', 'right'],
                            rowcolor    => $_COLORS[1]
                           } );
	
 	  foreach my $line  (@$list) {
	     $table->addrow($line->[0], 
         $line->[1], 
         $line->[2], 
         $line->[3], 
         $line->[4],
         ($line->[4] > 0 && $Ipn->{TRAFFIC}->{$line->[0]} && $line->[4] - $Ipn->{TRAFFIC}->{$line->[0]} > 0) ? $line->[4] - $Ipn->{TRAFFIC}->{$line->[0]} : 0,
         ($line->[4] > 0 && $Ipn->{TRAFFIC}->{$line->[0]} && $line->[4] - $Ipn->{TRAFFIC}->{$line->[0]} < 0) ? abs($line->[4] - $Ipn->{TRAFFIC}->{$line->[0]}) : 0
         );
     }
    print $table->show();	 
  }
	
	$graph_type='month_stats';
	
}

#   $Ipn->{debug}=1;
   my $list = $Ipn->reports_users({ %LIST_PARAMS });
   #Used Fraffic
   $table_sessions = $html->table( { width      => '100%',
	                                   caption    => "$_SESSIONS", 
                                     title      => ["$_DATE", "TT", "$_NAME", "IN", "OUT", "$_TOTAL", "$_SUM"],
                                     cols_align => ['right', 'left', 'right', 'right', 'right', 'right', 'right'],
                                     qs         => $pages_qs             
                                 } );


    my %report = ();
    foreach my $line (@$list) {
       push  @{ $report{"$line->[0]"} }, [ @$line ];
     }

    my $num = 0;
    foreach my $k ( sort %report) {  
      my $v=$report{$k};
      
      next if (ref($k) eq 'ARRAY');

      my @stats_array = @$v;
	    $table_sessions->{rowcolor}=$_COLORS[1];
  
      my $user_total_in=0;
      my $user_total_out=0;
      my $user_sum = 0;
      
      my $period = $stats_array[0][0];
      if (! $FORM{DATE}) {
      	$period = $html->button($stats_array[0][0], "index=$index&$type=$stats_array[0][0]$pages_qs");
       }

      $table_sessions->addtd(
                  $table->td($period, { rowspan => ($#stats_array > 0) ? $#stats_array+2 : 2 } ),
                  $table->td($stats_array[0][1], { bgcolor => $TT_COLORS[$stats_array[0][1]] }), 
                  $table->td($stats_array[0][2], { bgcolor => $TT_COLORS[$stats_array[0][1]] }), 
                  $table->td(int2byte($stats_array[0][3]), { bgcolor => $TT_COLORS[$stats_array[0][1]] }), 
                  $table->td(int2byte($stats_array[0][4]), { bgcolor => $TT_COLORS[$stats_array[0][1]] }),
                  $table->td(int2byte($stats_array[0][3]+$stats_array[0][4]), { bgcolor => $TT_COLORS[$stats_array[0][1]] }),
                  $table->td("$stats_array[0][5]", { bgcolor => $TT_COLORS[$stats_array[0][1]] })
      );

      $user_total_in+=$stats_array[0][3];
      $user_total_out+=$stats_array[0][4];
      $user_sum+=$stats_array[0][5];

      $totals{IN}{$stats_array[0][1]}  += $stats_array[0][3];
      $totals{OUT}{$stats_array[0][1]} += $stats_array[0][4];
      $totals{SUM}{$stats_array[0][1]} += $stats_array[0][5];
     
      for($i=1; $i<$#stats_array+1; $i++)  {

        if ($TT_COLORS[$stats_array[$i][2]] ne '') {
          $table_sessions->{rowcolor}=$TT_COLORS[$stats_array[$i][1]] 
         }
        else {
  	      $table_sessions->{rowcolor}=undef;
         } 

        $table_sessions->addrow($stats_array[$i][1], 
          $stats_array[$i][2],
          int2byte($stats_array[$i][3]),
          int2byte($stats_array[$i][4]),
          int2byte($stats_array[$i][3]+$stats_array[$i][4]),
          "$stats_array[$i][5]"
          );


      $totals{IN}{$stats_array[$i][1]}  += $stats_array[$i][3];
      $totals{OUT}{$stats_array[$i][1]} += $stats_array[$i][4];
      $totals{SUM}{$stats_array[$i][1]} += $stats_array[$i][5];

      $user_total_in+=$stats_array[$i][3];
      $user_total_out+=$stats_array[$i][4];
      $user_sum+=$stats_array[$i][5];
     }
     
     #Sub totals
     $table_sessions->{rowcolor}=$_COLORS[3];
     $table_sessions->addtd($table->th($_TOTAL, { colspan => 2 }), 
                            $table->th(int2byte($user_total_in)),
                            $table->th(int2byte($user_total_out)),
                            $table->th(int2byte($user_total_in + $user_total_out)),
                            $table->th($user_sum)
                           );

    if ($FORM{DATE}) {
   
      my($date, $h)=split(/ /, $stats_array[0][0], 2);

      $h++;
      #$AVG{TRAFFIC_IN}   = $user_total_in if ($AVG{TRAFFIC_IN} < $user_total_in);
      #$AVG{TRAFFIC_OUT}  = $user_total_out if ($AVG{TRAFFIC_OUT} < $user_total_out);
 
      $DATA_HASH{TRAFFIC_IN}[$h]=int($user_total_in / 3600) ;
      $DATA_HASH{TRAFFIC_OUT}[$h]=int($user_total_out / 3600) ;
      $DATA_HASH{MONEY}[$h]=$user_sum;
     }
    else {
      #$AVG{TRAFFIC_IN}  = $line->[1] if ($AVG{TRAFFIC_IN} < $line->[1]);
      #$AVG{TRAFFIC_OUT}  = $line->[2] if ($AVG{TRAFFIC_OUT} < $line->[2]);

      if ($stats_array[0][0] =~ /(\d+)-(\d+)-(\d+)/) {
      	 $num = $3;
        }
      elsif ($stats_array[0][0] =~ /(\d+)-(\d+)/) {
      	 $CHART{X_LINE}[$num]=$stats_array[0][0];
      	 $num++;
       }

      $DATA_HASH{TRAFFIC_IN}[$num]=int($user_total_in / (3600 * 24));
      $DATA_HASH{TRAFFIC_OUT}[$num]=int($user_total_out / (3600 * 24));
      $DATA_HASH{MONEY}[$num]=$user_sum;
     }

    $AVG{MONEY}        = $user_sum if ($AVG{TRAFFIC_IN} < $user_sum);
    
 }
 
 @type = ('column', 'column', 'line');
 # @type = ('area', 'area', 'line');
$table = $html->table( { width      => '100%',
	                       caption    => "$_TOTAL",
	                       title      => ['TT', "$_RECV", "$_SENT", "$_TOTAL", "$_SUM" ],
	                       cols_align => ['right', 'right', 'right', 'right', 'right'],
                      } );

  foreach my $tt (  sort keys %{ $totals{IN} } ) {
 	  $table->addrow("$tt", 
 	                 int2byte($totals{IN}{$tt}),
 	                 int2byte($totals{OUT}{$tt}),
 	                 int2byte($totals{OUT}{$tt} + $totals{IN}{$tt}),
 	                 $totals{SUM}{$tt}
 	                );
   }

print $table_sessions->show() . $table->show();



$html->make_charts({  
	 PERIOD => $graph_type,
	 DATA   => \%DATA_HASH,
	 AVG    => \%AVG,
	 TYPE   => \@type,
	 TRANSITION => 1,
	 %CHART
  });



}

#**********************************************************
# Whow sessions from log
# ipn_sessions()
#**********************************************************
sub ipn_sessions {
  my ($list, $sessions) = @_;




if (defined($FORM{show})) {
  $pages_qs .= "&show=y&fromd=$FORM{fromd}&fromm=$FORM{fromm}&fromy=$FORM{fromy}&tod=$FORM{tod}&tom=$FORM{tom}&toy=$FORM{toy}";
  $FORM{fromm}++;
  $FORM{tom}++;
  $FORM{fromm} = sprintf("%.2d", $FORM{fromm}++);
  $FORM{tom} = sprintf("%.2d", $FORM{tom}++);
  $LIST_PARAMS{INTERVAL} = "$FORM{fromy}-$FORM{fromm}-$FORM{fromd}/$FORM{toy}-$FORM{tom}-$FORM{tod}";
 }
elsif (defined($FORM{period})) {
	$LIST_PARAMS{PERIOD} = $FORM{period}+0; 
	$pages_qs .= "&period=$FORM{period}";
}
elsif($FORM{DATE}) {
	$LIST_PARAMS{DATE} = $FORM{DATE}; 
	$pages_qs .= "&DATE=$FORM{DATE}";
}

if (! $list) {
  if (! defined($FORM{sort})) {
	  $LIST_PARAMS{SORT} = 2;
	  $LIST_PARAMS{DESC} = 'DESC';
  }

  my $nas = Nas->new($db);
  my $nas_list = $nas->list({ %LIST_PARAMS });

  my $SEL_NAS = "<select name=NAS_ID>\n";
     $SEL_NAS .= "<option value=''>$_ALL\n";
  foreach my $line (@$nas_list) {
  	$SEL_NAS .= "<option value='$line->[0]'";
	  $SEL_NAS .= ' selected' if ($FORM{NAS_ID} eq $line->[0]);
	  $SEL_NAS .= ">$line->[1] / $line->[4] ($line->[3])\n";
   }
  $SEL_NAS .= "</select>\n";


  form_search({ SEARCH_FORM => $html->tpl_show(_include('ipn_seassion_search', 'Ipn'), 
  	                                  { %$Ipn, %FORM }, 
  	                                  { notprint => 1 }) 
 	
             });

  $list = $Ipn->list({ %LIST_PARAMS, %FORM });	
}


#return 0 if ($ipn->{TOTAL} < 1);



my %GROUPS = (SRC_IP   =>  3,
              SRC_PORT =>  4,
              DST_IP   =>  5,
              DST_PORT =>  6);

my %G  = ();
if (defined($FORM{GROUPS})) {
  my @t = split(/, /, $FORM{GROUPS});
  foreach my $line (@t){
    $G{"$line"}=$line;
    #print "$G{$line} $line/ ";
  }
}




$table = $html->table( { width => '640',
	                                 rowcolor => $_COLORS[0],
                                   rows => [ [ 
                                   "$_FROM: ", $html->date_fld('from', { MONTHES => \@MONTHES} ),
                                   "$_TO: ", $html->date_fld('to', { MONTHES => \@MONTHES } ),
                                   "$_ROWS: ",  "<input type=text name=rows value='$conf{list_max_recs}' size=4>"
                                    ] ],                                   
                                  } );
my $search =  $table->show();





print "<form action='$SELF_URL'>
<input type=hidden name=index value=$index>
<table border=1>
<tr><td>SRC_ADDR:</td><td><input type=text name=SRC_ADDR value='$FORM{SRC_ADDR}'></td><td>SRC_PORT:</td><td><input type=text name=SRC_PORT value='$FORM{SRC_PORT}' size=5></td></tr>
<tr><td>DST_ADDR:</td><td><input type=text name=DST_ADDR value='$FORM{DST_ADDR}'></td><td>DST_PORT:</td><td><input type=text name=DST_PORT value='$FORM{DST_PORT}' size=5></td></tr>
<tr><td colspan=4>
";

my $line = '';
while(my($k, $v)=each %GROUPS ) {
	$line .= " <input type=checkbox name=GROUPS value=$v";
	 if (defined($G{"$v"})) {
	 	 $line .= " checked" ;
	 	}

	$line .= ">$k<br> \n";
}

my $INTERVAL_TYPE_SEL = '';
my @intervals = ('', 'Minute', 'Hours', 'Days', 'Month');
my $i = 0;
foreach my $line (@intervals)  {
  $INTERVAL_TYPE_SEL .= "<option value=$i";
  $INTERVAL_TYPE_SEL .= " selected" if ($FORM{INTERVAL_TYPE} eq $i);
  $INTERVAL_TYPE_SEL .= ">$line\n";
  $i++;
}


print "
$line
</td></tr>
<tr><td colspan=4>
$search
</td></tr>

<tr><td>INTERVAL: <!-- <input type=text name=INTERVAL value='$FORM{INTERVAL}'> --> </td><td colspan=3> 
<select name=INTERVAL_TYPE>
$INTERVAL_TYPE_SEL
</select>
</td></tr>
</table>
<input type=submit name=SHOW value='$_SHOW'>
</form>\n";


my $table = $html->table( { width        => '100%',
                            border       => 1,
                            title        => ["$_TIME", "$_SIZE", "SRC_IP", "SRC_PORT", "DST_IP", "DST_PORT", "$_PROTOCOL", "-"],
                            cols_align   => ['right', 'right', 'RIGHT', 'right', 'right', 'right', 'center'],
                            qs           => $pages_qs,
                            pages        => $sessions->{TOTAL},
                            recs_on_page => $LIST_PARAMS{PAGE_ROWS}
                               } );

my $delete = '';
foreach my $line (@$list) {
  if ($permissions{3}{1}) {
    $delete = $html->button($_DEL, "index=". $index ."&$pages_qs&del=$line->[12]+$line->[11]+$line->[7]+$line->[1]+$line->[9]+$line->[0]", { MESSAGE => "$_DEL Session SESSION_ID $line->[11]?" });
   }

  $table->addrow($line->[0],
     int2byte($line->[1]), 
     $line->[2],  
     $line->[3],  
     $line->[4], 
     $line->[5],
     $line->[6], 
     $html->button("$_HOSTS", "index=$index$pages_qs")
  );
}

print $table->show();




$table = $html->table( { width       => '100%',
	                       rowcolor    => $_COLORS[1],
                         title_plain => ["$_SESSIONS", "$_TRAFFIC"],
                         cols_align  => ['right', 'right', 'right', 'right'],
                         rows        => [ [ $Ipn->{COUNT}, int2byte($Ipn->{SUM}) ] ],
                       } );


print $table->show();
}


#**********************************************************
# ipn_use_all_monthes();
#**********************************************************
sub ipn_use_users_allmonthes {
  $FORM{allmonthes}='y';
  ipn_use_users();
}


#**********************************************************
# ipn_use();
#**********************************************************
sub ipn_use_users {

  reports({ DATE       => $FORM{DATE}, 
  	        REPORT     => '',
  	        SHOW_HOURS => 'Y',
   	        EX_PARAMS  => { HOURS => "$_HOURS",
            	              USERS => "$_USERS" } 
  	       });



my %totals = ();

my %DATA_HASH2= ();
my %DATA_HASH = (  	 	             );
my %CHART = (SUFFIC => '%');
my %AVG = (MONEY    => 0,
           TRAFFIC  => 0,
           DURATION => 0);

my $graph_type='';
my $out = '';
my @type = ();

#Day reposrt

if (defined($FORM{DATE})) {

   $LIST_PARAMS{INTERVAL_TYPE} = 2;
#  $LIST_PARAMS{DATE}="$FORM{DATE}";
#  $pages_qs.="&DATE=$LIST_PARAMS{DATE}";
    my $list = $Ipn->reports_users({ %LIST_PARAMS });
    #Used Fraffic
    $table_sessions = $html->table( { width      => '100%',
	                                    caption    => "$_SESSIONS", 
                                      title      => ["$_DATE", "$_USERS", "TT", "$_NAME", "IN", "OUT", "$_TOTAL", "$_SUM"],
                                      cols_align => ['right', 'left', 'right', 'right', 'right', 'right', 'right'],
                                      qs         => $pages_qs             
                               } );


    my %report = ();
    
    if ($FORM{EX_PARAMS} && $FORM{EX_PARAMS} eq 'HOURS') {
      $graph_type='day_stats';
      
      foreach my $line (@$list) {
         push  @{$report{"$line->[0]"}}, [ @$line ];
       }

      foreach my $k ( sort %report) {  
        my $v=$report{$k};
        next if (ref($k) eq 'ARRAY');


        my @stats_array = @$v;
	      $table_sessions->{rowcolor}=$_COLORS[1];

        my $user_total_in=0;
        my $user_total_out=0;
        my $user_traffic_sum=0;
        my $user_sum=0;
        my $user_count = $stats_array[0][1];
        

        
        $table_sessions->addtd(
                  $table->td($stats_array[0][0], { rowspan => ($#stats_array > 0) ? $#stats_array+2 : 2 } ),
                  $table->td($stats_array[0][1], { rowspan => ($#stats_array > 0) ? $#stats_array+2 : 2 } ),
                  $table->td($stats_array[0][2], { bgcolor => $TT_COLORS[$stats_array[0][2]] }), 
                  $table->td($stats_array[0][3], { bgcolor => $TT_COLORS[$stats_array[0][2]] }), 
                  $table->td(int2byte($stats_array[0][4]), { bgcolor => $TT_COLORS[$stats_array[0][2]] }), 
                  $table->td(int2byte($stats_array[0][5]), { bgcolor => $TT_COLORS[$stats_array[0][2]] }),
                  $table->td(int2byte($stats_array[0][4]+$stats_array[0][5]), { bgcolor => $TT_COLORS[$stats_array[0][2]] }),
                  $table->td($stats_array[0][6], { bgcolor => $TT_COLORS[$stats_array[0][2]] })
         );

        $user_total_in+=$stats_array[0][4];
        $user_total_out+=$stats_array[0][5];
        $user_traffic_sum+=$stats_array[0][4]+$stats_array[0][5];
        $user_sum+=$stats_array[0][6];



        for($i=1; $i<$#stats_array+1; $i++)  {

          if ($TT_COLORS[$stats_array[$i][2]] ne '') {
            $table_sessions->{rowcolor}=$TT_COLORS[$stats_array[$i][2]] 
           }
          else {
  	        $table_sessions->{rowcolor}=undef;
           } 

          $table_sessions->addrow($stats_array[$i][2], 
             $stats_array[$i][3],
             int2byte($stats_array[$i][4]),
             int2byte($stats_array[$i][5]),
             int2byte($stats_array[$i][4]+$stats_array[$i][5]),
             $stats_array[$i][6]
            );
        
          $user_total_in+=$stats_array[$i][4];
          $user_total_out+=$stats_array[$i][5];
          $user_traffic_sum+=$stats_array[$i][4]+$stats_array[$i][5];
          $user_sum+=$stats_array[$i][6];
          
         }

        $table_sessions->{rowcolor}=$_COLORS[3];
        $table_sessions->addtd("<th colspan='2'>$_TOTAL:</th>", 
          "<th>". int2byte($user_total_in) ."</th>",
          "<th>". int2byte($user_total_out) ."</th>",
          "<th>". int2byte($user_traffic_sum). "</th>",
          "<th>". $user_sum . "</th>" );
 

        $totals{SUM}+=$user_sum;
        $totals{TRAFFIC_IN}+=$user_total_in;
        $totals{TRAFFIC_OUT}+=$user_total_out;
#Chart        
        my($date, $h)=split(/ /, $stats_array[0][0], 2);
        $h++;
        $AVG{MONEY}        = $user_sum if ($AVG{TRAFFIC_IN} < $user_sum);
        $DATA_HASH{TRAFFIC_IN}[$h]=int($user_total_in / 3600) ;
        $DATA_HASH{TRAFFIC_OUT}[$h]=int($user_total_out / 3600) ;
        $DATA_HASH2{USERS}[$h]=$user_count;
        $DATA_HASH2{MONEY}[$h]=int($user_sum);
       }	

       $out = $html->make_charts({  
	        PERIOD => $graph_type,
	        DATA   => \%DATA_HASH2,
	        AVG    => \%AVG,
	        TYPE   => ['column', 'line'],
	        TRANSITION => 1,
	        %CHART,
          OUTPUT2RETURN => 1	 
       });

      @type = ('area', 'area', 'line');
     }
#Report by users
    else {
      foreach my $line (@$list) {
        push  @{$report{"$line->[0]$line->[1]"}}, [ @$line ];
       }

      while(my($k, $v)=each %report) {
        my @stats_array = @$v;
	      $table_sessions->{rowcolor}=$_COLORS[1];

        my $user_total_in=0;
        my $user_total_out=0;
        my $user_traffic_sum=0;
        my $user_sum=0;

        $table_sessions->addtd(
                  $table->td($stats_array[0][0], { rowspan => ($#stats_array > 0) ? $#stats_array+2 : 2 } ),
                  $table->td($html->button($stats_array[0][1], "index=11&UID=$stats_array[0][8]"), { rowspan => ($#stats_array > 0) ? $#stats_array+2 : 2 } ),
                  $table->td($stats_array[0][2], { bgcolor => $TT_COLORS[$stats_array[0][2]] }), 
                  $table->td($stats_array[0][3], { bgcolor => $TT_COLORS[$stats_array[0][2]] }), 
                  $table->td(int2byte($stats_array[0][4]), { bgcolor => $TT_COLORS[$stats_array[0][2]] }), 
                  $table->td(int2byte($stats_array[0][5]), { bgcolor => $TT_COLORS[$stats_array[0][2]] }),
                  $table->td(int2byte($stats_array[0][4]+$stats_array[0][5]), { bgcolor => $TT_COLORS[$stats_array[0][2]] }),
                  $table->td($stats_array[0][6], { bgcolor => $TT_COLORS[$stats_array[0][2]] })
         );

        $user_total_in+=$stats_array[0][4];
        $user_total_out+=$stats_array[0][5];
        $user_traffic_sum+=$stats_array[0][4]+$stats_array[0][5];
        $user_sum+=$stats_array[0][6];
     


       for($i=1; $i<$#stats_array+1; $i++)  {

         if ($TT_COLORS[$stats_array[$i][2]] ne '') {
           $table_sessions->{rowcolor}=$TT_COLORS[$stats_array[$i][2]] 
          }
         else {
  	       $table_sessions->{rowcolor}=undef;
          } 

         $table_sessions->addrow($stats_array[$i][2], 
             $stats_array[$i][3],
             int2byte($stats_array[$i][4]),
             int2byte($stats_array[$i][5]),
             int2byte($stats_array[$i][4]+$stats_array[$i][5]),
             $stats_array[$i][6]
            );
        
            $user_total_in+=$stats_array[$i][4];
            $user_total_out+=$stats_array[$i][5];
            $user_traffic_sum+=$stats_array[$i][4]+$stats_array[$i][5];
            $user_sum+=$stats_array[$i][6];
       }

       $table_sessions->{rowcolor}=$_COLORS[3];
       $table_sessions->addtd("<th colspan='2'>$_TOTAL:</th>", 
          "<th>". int2byte($user_total_in) ."</th>",
          "<th>". int2byte($user_total_out) ."</th>",
          "<th>". int2byte($user_traffic_sum). "</th>",
          "<th>". $user_sum . "</th>" );
 

      $totals{SUM}+=$user_sum;
      $totals{TRAFFIC_IN}+=$user_total_in;
      $totals{TRAFFIC_OUT}+=$user_total_out;
   }
}


 }
else {
  #Used Traffic
  $table_sessions = $html->table( { width      => '100%',
	                                  caption    => "$_SESSIONS", 
                                    title      => ["$_DATE", "$_USERS", "IN", "OUT", "$_TOTAL",  $_SUM ],
                                    cols_align => ['right', 'right', 'right', 'right', 'right', 'right'],
                                    qs         => $pages_qs             
                               } );

  $LIST_PARAMS{INTERVAL_TYPE}=3;

  my $list = $Ipn->reports_users({ %LIST_PARAMS });
  $graph_type='month_stats';
  
  my $num = 0;

  foreach my $line (@$list) {
    $table_sessions->addrow($html->button($line->[0], "index=$index&$type=$line->[0]$pages_qs"), 
       $line->[1],   
       int2byte($line->[2]), 
       int2byte($line->[3]),
       int2byte($line->[2]+$line->[3]),
       $line->[4]
      );
   
      $AVG{MONEY}      = $line->[4] if ($AVG{MONEY} < $line->[4]);
      #$AVG{TRAFFIC_IN}  = $line->[2] if ($AVG{TRAFF->[2] if ($AVG{TRAFF->[2] if ($AVG{TRAFF->[2] if ($AVG{TRAFF->[2] if ($AVG{TRAFF->[2] if ($AVG{TRAFF->[2] if ($AVG{TRAFF->[2] if ($AVG{TRAFF->[2] if ($AVG{TRAFFIC_IN} < $line->[2]);
      #$AVG{TRAFFIC_OUT} = $line->[3] if ($AVG{TRAFFIC_OUT} < $line->[3]);
      $AVG{USERS}      = $line->[1] if ($AVG{USERS} < $line->[1]);


      if ($line->[0] =~ /(\d+)-(\d+)-(\d+)/) {
      	 $num = $3;
        }
      elsif ($line->[0] =~ /(\d+)-(\d+)/) {
      	 $CHART{X_LINE}[$num]=$line->[0];
      	 $num++;
       }

      $DATA_HASH2{USERS}[$num]=$line->[1];
      $DATA_HASH2{MONEY}[$num]=$line->[4];
            
      $DATA_HASH{TRAFFIC_OUT}[$num]=$line->[2];
      $DATA_HASH{TRAFFIC_IN}[$num]=$line->[3];


     
     $totals{TRAFFIC_IN}+=$line->[2];
     $totals{TRAFFIC_OUT}+=$line->[3];
     $totals{SUM}+=$line->[4];
   
   }

  $out = $html->make_charts({  
	 PERIOD        => $graph_type,
	 DATA          => \%DATA_HASH2,
	 AVG           => \%AVG,
	 TYPE          => ['column', 'line'],
	 TRANSITION    => 1,
	 %CHART,
   OUTPUT2RETURN => 1	 
  });


 @type = ('area', 'area');

}


$table = $html->table( { width => '100%',
	    cols_align => ['right', 'right', 'right', 'right', 'right'],
	          rows => [ [ "$_USERS: <b>". int2byte($total_tunnel) ."</b>", 
	                      "IN: <b>". int2byte($totals{TRAFFIC_IN}) ."</b>",
                        "OUT: <b>".   int2byte($totals{TRAFFIC_OUT}). "</b>", 
                        "TRAFFIC: <b>". int2byte($totals{TRAFFIC_IN}+$totals{TRAFFIC_OUT}) ."</b>", 
                        "SUM: <b>".   $totals{SUM} ."</b>"
                        ] ],
                        rowcolor => $_COLORS[2]
                               } );


print $table_sessions->show() . $table->show() . $out;




$html->make_charts({  
	 PERIOD => $graph_type,
	 DATA   => \%DATA_HASH,
	 AVG    => \%AVG,
	 TYPE   => \@type,
	 TRANSITION => 1,
	 %CHART
  });



}




#**********************************************************
# ipn_use();
#**********************************************************
sub ipn_use {



      my $list = $Ipn->reports2({ %LIST_PARAMS });

      $table_sessions = $html->table( { width => '100%',
	                                      caption    => "$_FROM", 
                                        title      => ["IP", "PACKEDGE", "$_SUM"],
                                        cols_align => ['left', 'right', 'right'],
                                        qs         => $pages_qs             
                               } );

      foreach my $line (@$list) {
        $table_sessions->addrow("<b>$line->[0]</b>", 
          int2byte($line->[1]), 
          $line->[2]
         );
       }

      print $table_sessions->show();



return 0;


 my @EX_GROUPS = ('Time', 'Hosts', 'Ports');
 my %EX_PARAMS = ();
 my $i = 0;
 foreach my $line (@EX_GROUPS) {
   	$EX_PARAMS{$i}=$line;
    $i++;
  }



  reports({ DATE       => $FORM{DATE}, 
  	        REPORT     => '',
  	        EX_PARAMS  => \%EX_PARAMS,
  	        SHOW_HOURS => 'Y'
  	       });


  my $total_in      = 0;
  my $total_out     = 0;
  my $total_tunnel  = 0;
  my $total_sum     = 0;
  my $total_package = 0;  




#Day reposrt
if (defined($FORM{DATE})) {

   $LIST_PARAMS{INTERVAL_TYPE} = 2;

   if ($FORM{EX_PARAMS} == 1) {
      $LIST_PARAMS{HOSTS}='y';
      $Ipn->reports({ %LIST_PARAMS });

      my $list = $Ipn->{HOSTS_LIST_FROM};
      $table_sessions = $html->table( { width => '100%',
	                              caption => "$_FROM", 
                                title =>["IP", "$_SUM", "PACKEDGE"],
                                cols_align => ['left', 'right', 'right'],
                                qs => $pages_qs             
                               } );

      foreach my $line (@$list) {
        $table_sessions->addrow("<b>$line->[0]</b>", 
          int2byte($line->[1]), 
          $line->[2]
         );
       }

      print $table_sessions->show();
      $list = $Ipn->{HOSTS_LIST_TO};
      $table_sessions = $html->table( { width => '100%',
	                              caption => "$_TO", 
                                title =>["IP", "$_SUM", "PACKEDGE"],
                                cols_align => ['left', 'right', 'right'],
                                qs => $pages_qs             
                               } );

      foreach my $line (@$list) {
        $table_sessions->addrow("<b>$line->[0]</b>", 
          int2byte($line->[1]), 
          $line->[2]
         );
       }
    }

   elsif ($FORM{EX_PARAMS} == 2) {
      $LIST_PARAMS{PORTS}='y';
      $Ipn->reports({ %LIST_PARAMS });

      my $list = $Ipn->{PORTS_LIST_FROM};
      $table_sessions = $html->table( { width => '100%',
	                              caption => "$_FROM", 
                                title =>["IP", "$_SUM", "PACKEDGE"],
                                cols_align => ['left', 'right', 'right'],
                                qs => $pages_qs             
                               } );

      foreach my $line (@$list) {
        $table_sessions->addrow("<b>$line->[0]</b>", 
          int2byte($line->[1]), 
          $line->[2]
         );
       }

      print $table_sessions->show();
      $list = $Ipn->{PORTS_LIST_TO};
      $table_sessions = $html->table( { width => '100%',
	                              caption => "$_TO", 
                                title =>["IP", "$_SUM", "PACKEDGE"],
                                cols_align => ['left', 'right', 'right'],
                                qs => $pages_qs             
                               } );

      foreach my $line (@$list) {
        $table_sessions->addrow("<b>$line->[0]</b>", 
          int2byte($line->[1]), 
          $line->[2]
         );
       }
    }


   else {
#  $LIST_PARAMS{DATE}="$FORM{DATE}";
#  $pages_qs.="&DATE=$LIST_PARAMS{DATE}";
    my $list = $Ipn->reports({ %LIST_PARAMS });
    #Used Fraffic
    $table_sessions = $html->table( { width => '100%',
	                              caption => "$_SESSIONS", 
                                title =>["$_DATE", "IN", "OUT", "TUNELS", "$_SUM", "PACKEDGE", '-'],
                                cols_align => ['right', 'right', 'right', 'right', 'right', 'right', 'center'],
                                qs => $pages_qs             
                               } );


    foreach my $line (@$list) {
      $table_sessions->addrow("<b>$line->[0]</b>", 
        int2byte($line->[1]), 
        int2byte($line->[2]), 
        int2byte($line->[3]),  
        int2byte($line->[4]),  
        $line->[5], 
        $html->button("$_HOSTS", "index=$index&HOUR=$line->[0]$pages_qs&EX_PARAMS=1")
      );

     $total_in      += $line->[1];   
     $total_out     += $line->[2]; 
     $total_tunnel  += $line->[3];
     $total_sum     += $line->[4];
     $total_package += $line->[5];
    }
  }
 }
else {
  #Used Traffic
  $table_sessions = $html->table( { width => '100%',
	                              caption => "$_SESSIONS", 
                                title =>["$_DATE", "IN", "OUT", "TUNNELS", $_SUM, "PACKEDGE", '-', '-'],
                                cols_align => ['right', 'right', 'right', 'right', 'right', 'right', 'center', 'center'],
                                qs => $pages_qs             
                               } );


  $LIST_PARAMS{INTERVAL_TYPE}=3;
  my $list = $Ipn->reports({ %LIST_PARAMS });
  foreach my $line (@$list) {
    $table_sessions->addrow($html->button($line->[0], "index=$index&$type=$line->[0]$pages_qs"), 
       int2byte($line->[1]),   
       int2byte($line->[2]), 
       int2byte($line->[3]),
       int2byte($line->[4]),
       $line->[5],
       $html->button("$_HOURS", "index=$index&$type=$line->[0]$pages_qs"),
       $html->button("$_HOSTS", "index=$index$pages_qs")
       );
   
    $total_in      += $line->[1];   
    $total_out     += $line->[2]; 
    $total_tunnel  += $line->[3];
    $total_sum     += $line->[4];
    $total_package += $line->[5];
   }
}



$table = $html->table( { width => '100%',
	    cols_align => ['right', 'right', 'right', 'right', 'right'],
	    rows => [ [ "IN: <b>". int2byte($total_in) ."</b>",
                                            "OUT: <b>". int2byte($total_out). "</b>", 
                                            "TUNEL: <b>". int2byte($total_tunnel) ."</b>", 
                                            "SUM: <b>". int2byte($total_sum) ."</b>", 
                                            "PACKAGES: <b>$total_package</b>" 
                                           ] ],
                                rowcolor => $_COLORS[2]
                               } );


print $table_sessions->show() . $table->show();


}


#**********************************************************
# stats
#**********************************************************
sub ipn_stats {
	my ($attr) = @_;
 
if (defined($attr->{USER}))	{
	my $user = $attr->{USER};

	$UID = $user->{UID};
	$LIST_PARAMS{UID} = $UID;
	if (! defined($FORM{sort})) {
	  $LIST_PARAMS{SORT}=2;
	  $LIST_PARAMS{DESC}=DESC;
   }

  if (defined($FORM{OP_SID}) and $FORM{OP_SID} eq $COOKIES{OP_SID}) {
 	  $html->message('err', $_ERROR, "$_EXIST $FORM{OP_SID} eq $COOKIES{OP_SID}");
   }
  elsif ($FORM{bm}) {
    use Bills;
    my $Bill = Bills->new($db);
    $Bill->action('add', "$FORM{BILL_ID}", $FORM{sum});
    if($bill->{errno}) {
      $html->message('err', $_ERROR, "[$bill->{errno}] $err_strs{$bill->{errno}}");
     }
    else {
      $html->message('info', $_INFO, "$_ADDED: SUM $FORM{sum}, BILL_ID: $FORM{BILL_ID}");  	
     }
   }
  elsif($FORM{SESSION_ID}) {
  	$pages_qs .= "&SESSION_ID=$FORM{SESSION_ID}";
  	ipn_session_detail({ USER => $attr->{USER} });
  	
  	return 0;
  }

}
#elsif($FORM{UID}) {
#	form_users();
#	return 0;
#}	


if ($FORM{del} && $FORM{is_js_confirmed}) {
	if(! defined($permissions{3}{1})) {
     $html->message('err', $_ERROR, 'ACCESS DENY');
     return 0;
	 } 

	my ($UID, $session_id, $nas_id, $session_start_date, $session_start_time, $sum, $login)=split(/ /, $FORM{del}, 7);
	$sessions->del($UID, $session_id, $nas_id, "$session_start_date $session_start_time");
  if (! $sessions->{errno})	 {
  	$html->message('info', $_DELETED, "$_LOGIN: $login<br> SESSION_ID: $session_id<br> NAS_ID: $nas_id<br> SESSION_START: $session_start_date $session_start_time<br> $_SUM: $sum");
    form_back_money('log', $sum, { UID => $UID }); #
    return 0;
   }
}

if ($sessions->{errno})	 {
	$html->message('err', $_ERROR, "[$sessions->{errno}] $err_strs{$sessions->{errno}}");
 }


if ($FORM{rows}) {
  $LIST_PARAMS{PAGE_ROWS}=$FORM{rows};
  $conf{list_max_recs}=$FORM{rows};
  $pages_qs .= "&rows=$conf{list_max_recs}";
 }


#PEriods totals
my $list = $sessions->periods_totals({ %LIST_PARAMS });
my $table = $html->table( { width => '100%',
                                   title_plain => ["$_PERIOD", "$_DURATION", "$_SEND", "$_RECV", "$_SUM"],
                                   cols_align => ['left', 'right', 'right', 'right', 'right'],
                                   rowcolor => $_COLORS[1]
                                  } );
for(my $i = 0; $i < 5; $i++) {
	  $table->addrow("<a href='$SELF_URL?index=$index&period=$i$pages_qs'>$PERIODS[$i]</a>", "$sessions->{'duration_'. $i}",
	  int2byte($sessions->{'sent_'. $i}), int2byte($sessions->{'recv_'. $i}), int2byte($sessions->{'sum_'. $i}));
 }
print $table->show();


print "<form action=$SELF_URL>
<input type=hidden name=index value='$index'>
<input type=hidden name=UID value='$UID'>\n";

$table = $html->table( { width => '640',
	                                 rowcolor => $_COLORS[0],
                                   title_plain => [ "$_FROM: ", $html->date_fld('from', { MONTHES => \@MONTHES} ),
                                   "$_TO: ", $html->date_fld('to', { MONTHES => \@MONTHES } ),
                                   "$_ROWS: ",  "<input type=text name=rows value='$conf{list_max_recs}' size=4>",
                                   "<input type=submit name=show value=$_SHOW>"
                                    ],                                   
                                  } );
print $table->show();
print "</form>\n";

ipn_stats_calculation($sessions);

if (defined($FORM{show})) {
  $pages_qs .= "&show=y&fromd=$FORM{fromd}&fromm=$FORM{fromm}&fromy=$FORM{fromy}&tod=$FORM{tod}&tom=$FORM{tom}&toy=$FORM{toy}";
  $FORM{fromm}++;
  $FORM{tom}++;
  $FORM{fromm} = sprintf("%.2d", $FORM{fromm}++);
  $FORM{tom} = sprintf("%.2d", $FORM{tom}++);
  $LIST_PARAMS{INTERVAL} = "$FORM{fromy}-$FORM{fromm}-$FORM{fromd}/$FORM{toy}-$FORM{tom}-$FORM{tod}";
 }
elsif (defined($FORM{period})) {
	$LIST_PARAMS{PERIOD} = $FORM{period}+0; 
	$pages_qs .= "&period=$FORM{period}";
}
elsif($FORM{DATE}) {
	$LIST_PARAMS{DATE} = $FORM{DATE}; 
	$pages_qs .= "&DATE=$FORM{DATE}";
}

if (! defined($FORM{sort})) {
  $LIST_PARAMS{SORT}=2;
  $LIST_PARAMS{DESC}=DESC;
 }

#Session List
$list = $sessions->list({ %LIST_PARAMS });	

$table = $html->table( { width => '640',
	                              rowcolor => $_COLORS[1],
                                title_plain => ["$_SESSIONS", "$_DURATION", "$_TRAFFIC", "$_SUM"],
                                cols_align => ['right', 'right', 'right', 'right'],
                                rows => [ [ $sessions->{TOTAL}, $sessions->{DURATION}, int2byte($sessions->{TRAFFIC}), $sessions->{SUM} ] ],
                               } );
print "<p>" . $table->show() . "</p>\n";

ipn_sessions($list, $sessions);
}


#*******************************************************************
# WHERE period
# base_state($where, $period);
#*******************************************************************
sub ipn_stats_calculation  {
 my ($sessions) = @_;

$sessions->calculation({ %LIST_PARAMS }); 


my $table = $html->table( { width       => '640',
	                          rowcolor    => $_COLORS[1],
                            title_plain => ["-", "$_MIN", "$_MAX", "$_AVG"],
                            cols_align  => ['left', 'right', 'right', 'right'],
                            rows        => [ [ $_DURATION,  $sessions->{min_dur}, $sessions->{max_dur}, $sessions->{avg_dur} ],
                                          [ "$_TRAFFIC $_RECV", int2byte($sessions->{min_recv}), int2byte($sessions->{max_recv}), int2byte($sessions->{avg_recv}) ],
                                          [ "$_TRAFFIC $_SENT", int2byte($sessions->{min_sent}), int2byte($sessions->{max_sent}), int2byte($sessions->{avg_sent}) ],
                                          [ "$_TRAFFIC $_SUM",  int2byte($sessions->{min_sum}),  int2byte($sessions->{max_sum}),  int2byte($sessions->{avg_sum}) ]
                                        ]
                               } );
print $table->show();
}

#**********************************************************
# form_stats
#**********************************************************
sub ipn_user_stats {
	#my ($user) = @_;
	#$UID = $user->{UID};
	#$LIST_PARAMS{UID} = $user->{UID};
	if (! defined($FORM{sort})) {
	  $LIST_PARAMS{SORT}=2;
	  $LIST_PARAMS{DESC}=DESC;
   }

if ($sessions->{errno})	 {
	$html->message('err', $_ERROR, "[$sessions->{errno}] $err_strs{$sessions->{errno}}");
 }


if ($FORM{rows}) {
  $LIST_PARAMS{PAGE_ROWS}=$FORM{rows};
  $conf{list_max_recs}=$FORM{rows};
  $pages_qs .= "&rows=$conf{list_max_recs}";
 }


#PEriods totals
my $list = $sessions->periods_totals({ %LIST_PARAMS });
my $table = $html->table( { width       => '100%',
                            title_plain => ["$_PERIOD", "$_DURATION", "$_SEND", "$_RECV", "$_SUM"],
                            cols_align  => ['left', 'right', 'right', 'right', 'right'],
                            rowcolor    => $_COLORS[1]
                        } );

for(my $i = 0; $i < 5; $i++) {
	  $table->addrow("<a href='$SELF_URL?index=$index&period=$i$pages_qs'>$PERIODS[$i]</a>", "$sessions->{'duration_'. $i}",
	  int2byte($sessions->{'sent_'. $i}), int2byte($sessions->{'recv_'. $i}), int2byte($sessions->{'sum_'. $i}));
 }
print $table->show();


print "<form action=$SELF_URL>
<input type=hidden name=sid value='$sid'>
<input type=hidden name=index value='$index'>
<input type=hidden name=UID value='$UID'>\n";

$table = $html->table( { width       => '640',
	                       rowcolor    => $_COLORS[0],
                         title_plain => [ "$_FROM: ", $html->date_fld('from', { MONTHES => \@MONTHES} ),
                                   "$_TO: ", $html->date_fld('to', { MONTHES => \@MONTHES } ),
                                   "$_ROWS: ",  "<input type=text name=rows value='$conf{list_max_recs}' size=4>",
                                   "<input type=submit name=show value=$_SHOW>"
                                    ],                                   
                                  } );
print $table->show();
print "</form>\n";

ipn_stats_calculation($sessions);

if (defined($FORM{show})) {
  $pages_qs .= "&show=y&fromd=$FORM{fromd}&fromm=$FORM{fromm}&fromy=$FORM{fromy}&tod=$FORM{tod}&tom=$FORM{tom}&toy=$FORM{toy}";
  $FORM{fromm}++;
  $FORM{tom}++;
  $FORM{fromm} = sprintf("%.2d", $FORM{fromm}++);
  $FORM{tom} = sprintf("%.2d", $FORM{tom}++);
  $LIST_PARAMS{INTERVAL} = "$FORM{fromy}-$FORM{fromm}-$FORM{fromd}/$FORM{toy}-$FORM{tom}-$FORM{tod}";
 }
elsif ($FORM{period}) {
	$LIST_PARAMS{PERIOD} = $FORM{period}; 
	$pages_qs .= "&period=$FORM{period}";
}

#if (! defined($FORM{sort})) {
#  $LIST_PARAMS{SORT}=2;
#  $LIST_PARAMS{DESC}=DESC;
# }

#Session List
$list = $sessions->list({ %LIST_PARAMS });	

$table = $html->table( { width       => '640',
	                       caption     => '',
	                       rowcolor    => $_COLORS[1],
                         title_plain => ["$_SESSIONS", "$_DURATION", "$_TRAFFIC", "$_SUM"],
                         cols_align  => ['right', 'right', 'right', 'right'],
                         rows        => [ [ $sessions->{TOTAL}, $sessions->{DURATION}, int2byte($sessions->{TRAFFIC}), $sessions->{SUM} ] ],
                     } );
print $table->show();	

ipn_sessions($list, $sessions) if ( $sessions->{TOTAL} > 0);
}



#**********************************************************
# ipn_session_detail
#**********************************************************
sub ipn_session_detail {
	my ($attr) = @_;
  my $user;


 
if (defined($attr->{USER}))	{
	$user = $attr->{USER};
	$LIST_PARAMS{LOGIN}=$user->{LOGIN};
}
elsif($FORM{UID}) {
	ipn_user();
	return 0;
}	



$sessions->session_detail({ %FORM });


$sessions->{_SENT}=int2byte($sessions->{SENT}); 
$sessions->{_RECV}=int2byte($sessions->{RECV}); 
$sessions->{_SENT2}=int2byte($sessions->{SENT2});
$sessions->{_RECV2}=int2byte($sessions->{RECV2});

$html->tpl_show(_include('ipn_session_detail', 'Ipn'), $sessions);

my %ORDERS = (hours    => $_HOURS,
              days     => $_DAYS,
              sessions => $_SESSIONS  );

print "<form action=$SELF_URL>
<input type=hidden name=index value=$index>
<input type=hidden name=UID value=$FORM{UID}>
<input type=hidden name=SESSION_ID value=$FORM{SESSION_ID}>
GROUP: <select name=PERIOD>\n";

while(my($k, $v) = each %ORDERS ) {
  print "<option value=$k";
  print ' selected' if ($k eq $FORM{PERIOD});
  print ">$v\n";
}


print "</select>
<input type=submit name=SHOW value='$_SHOW'>";


my $list = $sessions->detail_list({ %LIST_PARAMS, %FORM });
my $table = $html->table({ width      => '100%',
                           border     => 1,
                           title      => ["LAST_UPDATE", "$_SESSION_ID", "NAS_ID", "SENT", "RECV", "SENT2", "RECV2"],
                           cols_align => ['right', 'right', 'right', 'right', 'right', 'right', 'right'],
                           pages      => $sessions->{TOTAL},
                           qs         => $pages_qs
                        });

 foreach my $line (@$list) {
    $table->addrow($line->[0],  $line->[1], $line->[2], $line->[3],  $line->[4], $line->[5], $line->[6]);
  }
 print $table->show();


$table = $html->table( { width      => '100%',
                         cols_align => ['right', 'right'],
                         rows       => [ ["$_TOTAL:", "<b>$sessions->{TOTAL}</b>" ] ]
                     } );
print $table->show();
}








	
	
sub ipn_form_user {
	
	
	
  $Ipn->{LNG_ACTION}="$_ACTIVATE";
	$Ipn->{ACTION}='Active';

	$html->tpl_show(_include('ipn_form_user', 'Ipn'), $Ipn);
}

	

#**********************************************************
#
#**********************************************************
sub ipn_user_activate {


  my $nas  = Nas->new($db, \%conf);	

  my $ip = '0.0.0.0';
  my $IP_INPUT = '';
  if (! $user->{UID})  {
     $IP_INPUT = $html->form_input('REMOTE_ADDR', "$ENV{REMOTE_ADDR}", { OUTPUT2RETURN => 1});

     $ip = ($FORM{REMOTE_ADDR}) ? $FORM{REMOTE_ADDR} : $ENV{REMOTE_ADDR};
   } 
  else {
    $ip = $ENV{REMOTE_ADDR};
   }


  my $nas_id = 0; 
  if (! $user->{UID} && defined ($FORM{NAS_ID}))  {
    $nas_id=int($FORM{NAS_ID});
   }
  else {
    my $poll_list = $nas->ip_pools_list();
    my $ip_num = unpack("N", pack("C4", split( /\./, $ip))); 
  
    # Get valid NAS
    foreach my $line (@$poll_list) {
    	if ( ($line->[1] <= $ip_num) && ($ip_num <= $line->[2]) ) {
  	  	$nas_id=$line->[7];
  	  	last;
  	   } 
     }
   }

  if ($nas_id < 1) {
  	$html->message('err', $_ERROR, "$_NOT_EXIST IP '$ip'");
  	if (! $user->{UID}) {
      $IP_INPUT .= $html->form_select('NAS_ID', 
                                    { 
 	                                   SELECTED          => $nas_id,
 	                                   SEL_MULTI_ARRAY   => $nas->list(),
 	                                   MULTI_ARRAY_KEY   => 0,
 	                                   MULTI_ARRAY_VALUE => 1,
 	                                  });
  	 }
    else {
    	return 0;
     }
   }


  if ($FORM{ACTIVE}) {
    use Auth;
    if (int($nas_id) < 1) {
      $html->message('err', $_ERROR, "Unknown NAS");  	
     }
    else {
      my $user  = $users->info( $LIST_PARAMS{UID} );
      $nas->info({ NAS_ID => $nas_id });
      my %DATA = (ACCT_STATUS_TYPE  => 1, 
                  USER_NAME         => $user->{LOGIN}, 
                  SESSION_START     => 0, 
                  ACCT_SESSION_ID   => mk_unique_value(10), 
                  FRAMED_IP_ADDRESS => $ip, 
                  CONNECT_INFO      => '', 
                  NAS_ID            => $nas_id,
                  NAS_IP_ADDRESS    => $nas->{NAS_IP},
                  TP                => 0 );

    
    
    
    my $Auth = Auth->new($db, \%conf);
    my ($r, $RAD_PAIRS) = $Auth->dv_auth(\%DATA, $nas, { SECRETKEY => $conf{secretkey}
 	                                      } );

    if ($r == 1) {
       $html->message('err', $_ERROR, "$RAD_PAIRS->{'Reply-Message'}");
    	 return 0;
     }
     
     
     $Ipn->user_status({ %DATA });
     ipn_change_status({ STATUS => 'ONLINE_ENABLE', %DATA });
    }
   }
  elsif ($FORM{LOGOUT}) {
  	 ipn_change_status({ STATUS                => 'HANGUP',
  	 	                   FRAMED_IP_ADDRESS     => $ip,
  	 	                   ACCT_TERMINATE_CAUSE  => 1
  	 	         	 	     });
     $html->message('info', $_INFO, "$_DISABLE");
   }

#  my $nas_list = $html->form_select('NAS_ID', 
#                                    { 
# 	                                   SELECTED  => $FORM{NAS_ID},
# 	                                   SEL_MULTI_ARRAY   => $nas->list(),
# 	                                   MULTI_ARRAY_KEY   => 0,
# 	                                   MULTI_ARRAY_VALUE => 1,
# 	                                  });
#  	   $nas_list. 
#  	   "TP:". $html->form_input('TP_ID', "0") ,


  
  my %ACTION = ( ACTIVE => "$_ACTIVATE" ); 
  my %HIDDEN = ();
#  my $nas = '';


  my $table;
  my $online_session = '';
  
  my $list = $sessions->online( );
  
  if ($sessions->{TOTAL} > 0){




   $table = $html->table( { width       => '100%',
                            caption     => "Online",
                            border      => 1,
                            title_plain => ["$_USER", "$_PORT", "IP", "$_DURATION", "$_RECV", "$_SENT", '-' ],
                            cols_align  => ['left', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'center'],
                            qs          => $pages_qs,
                               } );
  foreach my $line (@$list) {
    my $online_ip = int2ip($line->[3]);
    $online_ips{$ip}=1;

    if ($online_ip eq $ip && $user->{UID}) {
       if ($line->[11] == $LIST_PARAMS{UID}) {
         $ACTION{LOGOUT}= "$_HANGUP";    	
         $HIDDEN{SESSION_ID} = $line->[21];
         delete $ACTION{ACTIVE};
         if ($line->[17] == 11) {
       	   $html->message('err', $_ERROR, "$_DISABLE");
       	   return 0;
          } 
        }       
       else {
       	  $html->message('err', $_ERROR, "THIS IP IS CURRENTLY IN USE");
       	  return 0;
        }
    }

    $table->addrow($line->[0], 
       $line->[2],  
       $online_ip,  
       $line->[4], 
       int2byte($line->[5]), int2byte($line->[6]),
       $html->button("$_HANGUP", "index=$index&UID=$LIST_PARAMS{UID}&LOGOUT=1&SESSION_ID=$line->[21]")
       )  if ($line->[11] == $LIST_PARAMS{UID} );
    }

    $online_session = $table->show();	
   } 
  else {
    $ACTION{ACTIVE}="$_ACTIVATE";    
   }


  $HIDDEN{sid}=$html->{SID} if ($html->{SID});

print $html->form_main({ CONTENT => "IP: $ip $IP_INPUT (". $nas_id .") ", 
                     HIDDEN  => { index   => "$index",
                     	            UID     => $LIST_PARAMS{UID},
                     	            %HIDDEN
                     	           },
	                   SUBMIT  => { %ACTION } 
	                 });

print $online_session;


}



#**********************************************************
# ipn_change_status
#**********************************************************
sub ipn_change_status {
	my ($attr) = @_;

	if ($attr->{FRAMED_IP_ADDRESS} !~ /^(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}$/ ) {
    $html->message('err', $_ERROR, "$ERR_WRONG_DATA");
    return 0;
   }

	my $ip              = $attr->{FRAMED_IP_ADDRESS};
	my $netmask         = 32;
	my $STATUS          = $attr->{STATUS} || '';
  my $USER_NAME       = $attr->{USER_NAME} || '';
  my $ACCT_SESSION_ID = $attr->{ACCT_SESSION_ID} || '';
  #my $PORT            = $attr->{NAS_PORT} || 0;
    
  my $speed_in=0;
  my $speed_out=0;
   

  my @ip_array = split(/\./, $ip, 4);
  my $rule_num = $conf{IPN_FW_FIRST_RULE} + $ip_array[3];
  my $cmd;

	if ($STATUS eq 'ONLINE_ENABLE'){
     $cmd = $conf{IPN_FW_START_RULE};
     $html->message('info', $_INFO, "$_ENABLE IP: $ip");
     $sessions->online_update({ USER_NAME       => $USER_NAME,
                                ACCT_SESSION_ID => $ACCT_SESSION_ID,
                                STATUS          => 10
                               });
     
   }
	elsif($STATUS eq 'ONLINE_DISABLE') {
     $cmd = $conf{IPN_FW_STOP_RULE};

     $html->message('info', $_INFO, "$_DISABLE IP: $ip");     
     $sessions->online_update({ USER_NAME       => $USER_NAME,
                                ACCT_SESSION_ID => $ACCT_SESSION_ID,
                                STATUS          => 11
                               });
	 }
	elsif ($STATUS eq 'HANGUP') {
     my $ACCT_TERMINATE_CAUSE = $attr->{ACCT_TERMINATE_CAUSE} || 6;
     $Ipn->acct_stop({ %FORM, ACCT_TERMINATE_CAUSE => $ACCT_TERMINATE_CAUSE });

     $cmd = $conf{IPN_FW_STOP_RULE};

     my $table = $html->table( { width      => '100%',
                                 caption    => "Hangup",
                                 border     => 1,
                                 rows       => [["IP:" ,      int2ip($Ipn->{FRAMED_IP_ADDRESS}) ],
                                           ["IN:" ,      int2byte($Ipn->{TRAFFIC_IN})      ], 
                                           ["OUT:",      int2byte($Ipn->{TRAFFIC_OUT})     ], 
                                           ["$_TOTAL:",  int2byte($Ipn->{TRAFFIC_IN}+$Ipn->{TRAFFIC_OUT})   ], 
                                           ["DURATION:", sec2time($Ipn->{ACCT_SESSION_TIME}, { str => 1 })   ], 
                                           ["SUM:",      "$Ipn->{SUM}" ]]
                            });

    $html->message('info', $_INFO,  $table->show({ OUTPUT2RETURN => 1 }));
   }

	
  $cmd =~ s/\%IP/$ip/g;
  $cmd =~ s/\%MASK/$netmask/g;
  $cmd =~ s/\%NUM/$rule_num/g;
  $cmd =~ s/\%SPEED_IN/$speed_in/g if ($speed_in > 0);
  $cmd =~ s/\%SPEED_OUT/$speed_out/g if ($speed_out > 0);
  #print "$cmd";

  system($cmd);
}


#**********************************************************
#
#**********************************************************
sub ipn_club_monitor {

  my %status_colors = ( 10  => '#00FF00',
  	                    11  => undef);

  if ($FORM{ACTIVE}){
   	 ipn_change_status({ STATUS            => 'ONLINE_ENABLE',
   	 	                   USER_NAME         => $FORM{ACTIVE},
                         FRAMED_IP_ADDRESS => $FORM{ip},
                         ACCT_SESSION_ID   => $FORM{ACCT_SESSION_ID},
  	 	         	 	     });
   }
	elsif ($FORM{DEACTIVE}) {
   	 ipn_change_status({ STATUS            => 'ONLINE_DISABLE',
   	 	                   FRAMED_IP_ADDRESS => $FORM{ip},
   	 	                   USER_NAME         => $FORM{DEACTIVE},
                         ACCT_SESSION_ID   => $FORM{ACCT_SESSION_ID},
  	 	         	 	     });
	 }
	elsif ($FORM{HANGUP}) {
   	 ipn_change_status({ STATUS                => 'HANGUP',
  	 	                   FRAMED_IP_ADDRESS     => $FORM{HANGUP},
  	 	                   ACCT_TERMINATE_CAUSE  => 6
  	 	         	 	     });
   }
	elsif ($FORM{ping}) {
    if ($FORM{ping} =~ /^(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}$/) {
      my $res = `/sbin/ping -c 5 $FORM{ping}`;
      $html->message('info', $_INFO,  "Ping  $FORM{ping}<br>Result:<br><pre>$res</pre>");
     }
    else {
      $html->message('err', $_ERROR,  "_WRONG_DATA");
     }
   }
	elsif ($FORM{DETAIL}) {
		
    $LIST_PARAMS{SESSION_ID}=$FORM{DETAIL};
    ipn_sessions2();
	 }

$sessions->online( { %LIST_PARAMS, FIELDS => [ 0,1,2,3,4,5,6,14,9,10,15 ] } );	
my $dub_logins = $sessions->{dub_logins};
 
my $table = $html->table( { width      => '100%',
                            caption    => "Online",
                            border     => 1,
                            title      => ["$_USER", "$_FIO", "$_NUM", "IP", "$_DURATION", "$_RECV", "$_SENT",
                                 "$_SUM", "-", "-", '-', '-' ],
                            cols_align => ['left', 'left', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'center'],
                            qs         => $pages_qs,
                               } );


my $nas = Nas->new($db, \%conf); 
my $online = $sessions->{nas_sorted};
my $nas_list = $nas->list({ TYPE => 'ipcad' });

my $graph_type='';
my %DATA_HASH = ();
my %CHART = ();
my %AVG = (MONEY    => 0,
           TRAFFIC  => 0
          );


  my $num = 0;
  my @X_TEXT = ();


foreach my $nas_row (@$nas_list) {
  next if (! defined($online->{$nas_row->[0]}));

  my $l = $online->{$nas_row->[0]};
  my $total = $#{@$l} + 1;  
  $table->{rowcolor}=$_COLORS[0];
  $table->{extra}="colspan='8' class='small'";
  $table->addrow("$nas_row->[0]:<b>$nas_row->[1]</b>:$nas_row->[3]:$_TOTAL: $total" );
  
  foreach my $line (@$l) {
    undef($table->{rowcolor});
    undef($table->{extra});

    my $ip = int2ip($line->[3]);
    my $status = ($line->[10] == 10 || $line->[10] == 3 || $line->[10] == 1) ? "(". $html->button("DEACTIVE", "index=$index&DEACTIVE=$line->[0]&ip=$ip&ACCT_SESSION_ID=$line->[9]", { TITLE => 'Status' }) . ")" : "(". $html->button("$_ACTIVATE", "index=$index&ACTIVE=$line->[0]&ip=$ip&ACCT_SESSION_ID=$line->[9]", { TITLE => 'active users' }) . ")" ;
    my $user_info =  "$_FIO: $line->[1]\n$_PHONE: $line->[12]\n$_VARIANT: $line->[13]\n$_DEPOSIT: $line->[14]\n".
     "$_CREDIT: $line->[15]\n$_SPEED: $line->[16]\nSESSION_ID: $line->[9]\nCID: $line->[24]\nCONNECT_INFO: $line->[18]\nUPDATES: $line->[20]";



    $table->addrow($html->button($line->[0], "index=11&UID=$line->[13]", { TITLE => "$user_info" }), 
      $line->[1], 
      $line->[2],  
      $ip,  
      $line->[4], 
      int2byte($line->[5]), 
      int2byte($line->[6]), 
      $line->[7],
     "$status",
     "(". $html->button("$_DETAIL", "index=$index&DETAIL=$line->[21]", { TITLE => 'Detail' }) .")",
     "(". $html->button('P', "index=$index&ping=$ip", { TITLE => 'ping' }) .")",
     "(". $html->button('H', "index=$index&HANGUP=$ip&SESSION_ID=$line->[9]", { TITLE => 'Hangup' }) .")"
     );


    $num++;
    $DATA_HASH{MONEY}[$num]  = $line->[7];
    #$DATA_HASH{COMPUTERS}[$num]  = $num;
    #$DATA_HASH{DURATION}[$num] = time2sec($line->[4]);
    push @X_TEXT,  "$line->[2]:$line->[0]";



  }
}

print $table->show();	


$table = $html->table( { width       => '100%',
                         title_plain => [ 
                                             "$_REFRESH (sec): ".   $html->form_input('REFRESH', int($FORM{REFRESH}), { SIZE => 4 } ),
                                             $html->form_input('SHOW',  $_SHOW, {  TYPE => 'SUBMIT' })  
                                            ],
                           });

print $html->form_main({ CONTENT => $table->show(),
	                       HIDDEN  => { index =>  "$index" },
	                       METHOD  => 'GET'
                        });


print $html->make_charts({  
	 X_TEXT             => \@X_TEXT,
	 DATA               => \%DATA_HASH,
	 AVG                => \%AVG,
	 TYPE               => ['bar'],
 	 AXIS_CATEGORY_skip => 0,
	 TRANSITION         => 1,
	 CHART_RECT_width   => 400,
	 CHART_RECT_height  => $#X_TEXT * 22,
	 CHART_RECT_x       => 70
  });


}


#**********************************************************
# 
#**********************************************************
sub ipn_comps {

  $Ipn->{ACTION}='add';
	$Ipn->{ACTION_LNG}="$_ADD";

if ($FORM{add}) {
	$Ipn->comps_add({ %FORM });
   if($Ipn->{errno}) {
      $html->message('err', $_ERROR, "[$Ipn->{errno}] $err_strs{$Ipn->{errno}}");
   }
  else {
	  $html->message('info', $_INFO, "$_ADDED");
   }
}
elsif ($FORM{change}) {
	$Ipn->comps_change({ %FORM });

  if($Ipn->{errno}) {
      $html->message('err', $_ERROR, "[$Ipn->{errno}] $err_strs{$Ipn->{errno}}");
   }
  else {
  	$html->message('info', $_INFO, "$_CHANGED");
   }
}
elsif ($FORM{chg}) {
	$Ipn->comps_info($FORM{chg});
	$html->message('info', $_INFO, "$_CHANGING");
	
  $Ipn->{ACTION}='change';
	$Ipn->{ACTION_LNG}=$_CHANGE;
}
elsif ($FORM{del}){
	$Ipn->comps_del( $FORM{del} );
	$html->message('info', $_INFO, "$_DELETED");
}


$html->tpl_show(_include('ipn_comps', 'Ipn'), $Ipn);	

my $list = $Ipn->comps_list({ %LIST_PARAMS });
my $table = $html->table( { width      => '100%',
                            caption    => "Computers",
                            border     => 1,
                            title      => ["$_NUM", "$_NAME", "IP", "MAC", '-', '-' ],
                            cols_align => ['right', 'left', 'right', 'right', 'center', 'center'],
                            qs         => $pages_qs,
                           } );

foreach $line (@$list) {
	$table->addrow(
	 $line->[0],
	 $line->[1],
	 $line->[2],
	 $line->[3],
	 $html->button($_CHANGE, "index=$index&chg=$line->[4]"),
	 $html->button($_DEL, "index=$index&$pages_qs&del=$line->[4]", { MESSAGE => "$_DEL '$line->[1]?" })
	);
}




print $table->show();

}

#**********************************************************
#
#**********************************************************
sub ipn_user_add {
 
 my $list = $Ipn->comps_list({ %LIST_PARAMS });
 my %allow_comps = ();
	 
 foreach my $line (@$list) {
   $allow_comps{$line->[2]}="$line->[0]:$line->[1]";
  }


	
 if ($FORM{add}) {
     my $Dv       = Dv->new($db, $admin, \%conf);
     my $payments = Finance->payments($db, $admin, \%conf);
     my $users    = Users->new($db, $admin, \%conf); 
     my $LOGIN    = mk_unique_value(6, { SYMBOLS => '0123456789'});
     my $PASSWORD = mk_unique_value(8, { SYMBOLS => '0123456789'});
     my $user=$users->add({ LOGIN       => $LOGIN,
    	                      PASSWORD    => "$PASSWORD",
     	                      CREATE_BILL => 1
                         });
 
     if (! $user->{errno}) {
          $UID = $user->{UID};
          $user = $user->info($UID);
      }
     else {
        $html->message('err', $_ERROR, "[$user->{errno}] $err_strs{$user->{errno}}");	
        return 0;
      }

      my $er = $payments->exchange_info($FORM{'5.ER'});
      if ($FORM{SUM}) {
        $payments->add($user, { SUM => $FORM{SUM}, 
                                ER  => $er->{ER_RATE} });  

        if ($payments->{errno}) {
          $html->message('err', $_ERROR, "[$payments->{errno}] $err_strs{$payments->{errno}}");	
         }
       }

   	 $Dv->add({ UID     => $UID, 
   	  	        TP_ID   => int($FORM{TP_ID}),
   	  	        IP      => '0.0.0.0',
   	  	        NETMASK => '255.255.255.255' });

      if ($Dv->{errno}) {
         $html->message('err', $_ERROR, "[$Dv->{errno}] $err_strs{$Dv->{errno}}");	
        }

     my @USER_PARAMS=();
     my $comp_number=0; 
     my $comp_name='';

     ($comp_number, $comp_name)=split(/:/, $allow_comps{$FORM{IP}}) if ($allow_comps{$FORM{IP}});

     if ($FORM{ACTIVATE}) {

       my %DATA = (ACCT_STATUS_TYPE  => 1, 
                   USER_NAME         => $LOGIN, 
                   SESSION_START     => 0, 
                   ACCT_SESSION_ID   => mk_unique_value(10), 
                   FRAMED_IP_ADDRESS => $FORM{IP}, 
                   CONNECT_INFO      => '', 
                   NAS_ID            => $FORM{NAS_ID},
                   TP                => $FORM{TP_ID},
                   NAS_PORT          => $comp_number );
     
       $Ipn->user_status({ %DATA });
       ipn_change_status({ STATUS => 'ONLINE_ENABLE', %DATA });
     }
     
     
     
     my $table = $html->table( { width  => '400',
     		                         class  => 'with_border',
     	                           border => 1,
                                 rows   => [["$_LOGIN:",      "$LOGIN"       ],
                                            ["$_PASSWD:",     "$PASSWORD"    ],
                                            ["IP:",           "$FORM{IP}"    ],
                                            ["$_NUM:",        "$comp_number" ],
                                            ["COMPUTER:",     "$comp_name"   ],
                                            ["$_SUM:",        "$FORM{SUM}"   ],
                                            ["$_TARIF_PLAN:", "$FORM{TP_ID}" ],
                                            ["$_DATE:",       "$DATE $TIME"  ],
                                            ["$_ADMIN:",      "$admin->{A_FIO}"]
                                            ]
                                  } );
     
     $html->message('info', $_ACTIVATED, "$_LOGIN: $LOGIN");
     print $table->show();

     return 0;
  }




 $Ipn->{TP_SEL}=$html->form_select('TP_ID', 
                                          { 
 	                                          SEL_MULTI_ARRAY   => $tariffs->list(),
 	                                          MULTI_ARRAY_KEY   => 0,
 	                                          MULTI_ARRAY_VALUE => 1,
                                         });
 
 my $nas = Nas->new($db);
 my $nas_list = $nas->list({ %LIST_PARAMS });
 $Ipn->{NAS_SEL} = $html->form_select('NAS_ID', 
                                    { 
 	                                   SEL_MULTI_ARRAY   => $nas_list,
 	                                   MULTI_ARRAY_KEY   => 0,
 	                                   MULTI_ARRAY_VALUE => 1,
 	                                  });
 

 
 if ($Ipn->{TOTAL} > 0) {
	 
 	 my $session_list=$sessions->online( { %LIST_PARAMS } );	



   foreach my $line (@$session_list) {
   	  if (defined($allow_comps{int2ip($line->[3])})) {
   	      delete $allow_comps{int2ip($line->[3])};
   	  }
    }


 	 $Ipn->{IP}=$html->form_select('IP', 
                                    { 
 	                                   SEL_HASH   => \%allow_comps
 	                                  });
 	 }
 else {
   $Ipn->{IP}=$html->form_input('IP', '0.0.0.0');
  }
 
 
 
 $Ipn->{ACTIVATE}='checked';
 $html->tpl_show(_include('ipn_form_user_add', 'Ipn'), $Ipn);	
}


#**********************************************************
#
#**********************************************************
sub ipn_ipfw {
	
my $fw = "00010       71       3320 deny log logamount 100 tcp from any to any 25 via rl0
01101       93       9935 deny ip from 192.168.0.101 to any via rl0
01102      270      17456 deny ip from 192.168.0.102 to any via rl0
01103        5        994 deny ip from 192.168.0.103 to any via rl0
01104        0          0 deny ip from 192.168.0.104 to any via rl0
01105       53       3026 deny ip from 192.168.0.105 to any via rl0
01106        6       1092 deny ip from 192.168.0.106 to any via rl0
01107       84       8657 deny ip from 192.168.0.107 to any via rl0
01108        5        994 deny ip from 192.168.0.108 to any via rl0
01109      755      47240 deny ip from 192.168.0.109 to any via rl0
01110        5       1175 deny ip from 192.168.0.110 to any via rl0
01111      443      29484 deny ip from 192.168.0.111 to any via rl0
01112       86       7552 deny ip from 192.168.0.112 to any via rl0
50000    54112   19223594 count ip from any to any in recv tun0
50001    56557    5803097 count ip from any to any out xmit tun0
65535 43820756 9909262975 allow ip from any to any
";

my @rows = split(/\n/, $fw);


$table = $html->table( { width       => '100%',
                            caption     => "ipfw",
                            border      => 1,
                            title       => ["$_NUM", "$_IN", "$_OUT", "$_TYPE", "-"],
                            cols_align  => ['right', 'right', 'center'],
                           });


foreach my $row (@rows) {
	my ($num, $in, $out,  $type, $protocol, $other)=split(/ +/, $row, 6);
	$table->addrow($num, $in, $out,  $type, $protocol, $other);
}

print	 $table->show();
	
}

#**********************************************************
#
#**********************************************************
sub ipn_use_allmonthes  {

}

#**********************************************************
#
#**********************************************************
sub ipn_getnet {

my $ip    =  $FORM{IP}   || '0.0.0.0';
my $port  =  $FORM{PORT} || '0'; 
my $time  =  $FROM{TIME} || $TIME;
my $date  =  $FROM{DATE} || $DATE;
	

my @ARR = ( ["IP / HOST / URL:", $html->form_input('IP', "$ip", { OUTPUT2RETURN => 1 })     ],
            ["$_PORT:", $html->form_input('PORT', "$port", { OUTPUT2RETURN => 1 }) ],
            ["$_DATE:", $html->form_input('DATE', "$date", { OUTPUT2RETURN => 1 }) ],
            ["$_TIME:", $html->form_input('DATE', "$time", { OUTPUT2RETURN => 1 }) ]
          );

	# Resolv if not ip
	if ($ip !~  /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/) {
		if ($ip =~ /^http:\/\/([0-9a-z\-\.]+)\/?/i || $ip =~ /(\S+)\//i) {
      $ip = $1;
		 }
    use Socket;
		use Sys::Hostname;
		if (my $addr = gethostbyname($ip)) {
		  $ip = inet_ntoa(scalar($addr));
		 }
		else {
			 print $html->message('err', $_ERROR, "Can't resolv");
			 $ip = '0.0.0.0';
		 }
		push @ARR, [ 'IP:', $ip ];
	 }



my $table = $html->table( { width       => '400',
                            border      => 1,
                            rows        => \@ARR
                         } );

	
	 
	print $html->form_main({ CONTENT => $table->show({ OUTPUT2RETURN => 1 }),
	                         HIDDEN  => { index => $index,
                                        ID    => "$FORM{chg}",
                                        UID   => "$FORM{UID}"
                                      },
	                         SUBMIT  => { show  => $_SHOW
	                       	            } 
	                       });
	
	
	my $Dv = Dv->new($db, $admin, \%conf);

  if (! $user->{UID}) {
    $LIST_PARAMS{UID}=$FORM{UID};
   }
  else {
  	$LIST_PARAMS{UID}=$user->{UID};
   }

	$Dv->info($LIST_PARAMS{UID});
	
	

	require Billing;
  Billing->import();
  my $Billing = Billing->new($db, \%conf);

  my ($TIME_INTERVALS,
      $INTERVAL_TIME_TARIF,
      $INTERVAL_TRAF_TARIF) = $Billing->time_intervals($Dv->{TP_ID});


  my ($remaining_time, $ret_attr) = $Billing->remaining_time(0, {
          TIME_INTERVALS      => $TIME_INTERVALS,
          INTERVAL_TIME_TARIF => $INTERVAL_TIME_TARIF,
          INTERVAL_TRAF_TARIF => $INTERVAL_TRAF_TARIF,
          #SESSION_START       => $user->{SESSION_START},
          #DAY_BEGIN           => $user->{DAY_BEGIN},
          #DAY_OF_WEEK         => $user->{DAY_OF_WEEK},
          #DAY_OF_YEAR         => $user->{DAY_OF_YEAR},
          REDUCTION           => $user->{REDUCTION},
          POSTPAID            => 1 
         });

       #$tp_interval{$TP_ID} = (defined($ret_attr->{TT}) && $ret_attr->{TT} > 0) ? $ret_attr->{TT} :  0;
       
  my $TP_INTERVAL = $tp_interval{$TP_ID} = ($ret_attr->{FIRST_INTERVAL}) ? $ret_attr->{FIRST_INTERVAL} :  0;

	
#	print "TP: $Dv->{TP_ID} // Interval: $TP_INTERVAL // TIME_INTERVALS: $TIME_INTERVALS,
#      $INTERVAL_TIME_TARIF,
#      $INTERVAL_TRAF_TARIF<br>";
	
	# Get names
  my $list_tt = $tariffs->tt_list({ TI_ID => $TP_INTERVAL });
  my %tt_names = ();
  foreach my $line (@$list_tt) {
    $tt_names{$line->[0]}=$line->[6];
   }

	
	
	$Ipn->get_zone({ TP_INTERVAL => $TP_INTERVAL });


  $table = $html->table( { width       => '100%',
                           caption     => "$_TRAFIC_TARIFS",
                           border      => 1,
                           title_plain => ["ID", "$_TYPE", "IP", "$_PREPAID", "$_IN", "$_OUT",  '-' ],
                           cols_align  => ['left', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'center'],
                           qs          => $pages_qs,
                       } );

	my $zone = -1;

	foreach my $zone_id (@{ $Ipn->{ZONES_IDS} }) {
	  if(ip_in_zone(ip2int($ip), $port, $zone_id, $Ipn->{ZONES})) {
		  $zone = $zone_id;
      last;
	   };
	 }

	foreach my $line ( @{ $Ipn->{ZONES_IDS} }) {
		$last_byte = 0;
		my $networks = '';
		foreach my $address ( @{ $Ipn->{ZONES}{$line}{A} } ){
			my $adr_hash = \%{ $address };

      my $a_ip  = $$adr_hash{'IP'}; 
      my $a_msk = $$adr_hash{'Mask'}; 
      my $a_neg = $$adr_hash{'Neg'}; 
      my $a_ports_ref = \@{$$adr_hash{'Ports'}};

			$networks .= int2ip($a_ip)."/". int2ip($a_msk).'<br>'; # ", $a_neg<br>";
	   }


    $table->{rowcolor} = ($zone == $line) ? $_COLORS[0] : undef;
    $table->addrow($line, 
      $tt_names{$line},
      $networks,
      $Ipn->{ZONES}{$line}{PREPAID_TSUM},
      $Ipn->{ZONES}{$line}{PriceIn},
      $Ipn->{ZONES}{$line}{PriceOut},
      $last_byte);
	}
	
	print $table->show();
	
}



#**********************************************************
#
#**********************************************************
sub ipn_recalculate {


if ($FORM{RECALCULATE}) {
#  $FORM{FROM_M} = sprintf("%.2d", $FORM{FROM_M}+1);
#  $FORM{TO_M} = sprintf("%.2d", $FORM{TO_M}+1);
  $LIST_PARAMS{INTERVAL} = "$FORM{FROM_Y}-". sprintf("%.2d", $FORM{FROM_M}+1) ."-$FORM{FROM_D}/$FORM{TO_Y}-". sprintf("%.2d", $FORM{TO_M}+1) ."-$FORM{TO_D}";

	$Ipn->recalculate({ %LIST_PARAMS });
	
	if ($Ipn->{TOTAL} > 0) {
    my $Dv    = Dv->new($db, $admin, \%conf);    
    my $user  = $users->info( $LIST_PARAMS{UID} );
    $Dv->info($LIST_PARAMS{UID});
    $tariffs->info( $Dv->{TP_ID} );
    $OCTETS_DIRECTION = $tariffs->{OCTETS_DIRECTION};
  
    my $table = $html->table( { caption     => "$_RECALCULATE",
    	                          width       => '100%',
    	                          title       => [ $_START,  "$_TRAFFIC  ID", $_RECV, $_SEND,  'NAS',  'IP', $_INTERVALS, 
    	                          $_SUM, 'SID' ],
    	                          cols_align  => ['right', 'right', 'right', 'right', 'right', 'right', 'right', 'right' ]
                         } );
    my $total_sum = 0;
    my %TIME_INTERVALS = ();
    
    #Get user TP
    
    
    foreach my $line (@{ $Ipn->{list} }) {
    	my $time_interval = $line->[6];
    	my $traffic_class = $line->[1];
    	 if (! defined($TIME_INTERVALS{$line->[6]}) ) {
    	   my $tt_list = $tariffs->tt_list({ TI_ID => $time_interval });

         foreach my $tt_line ( @$tt_list ) {
    	     $TIME_INTERVALS{$time_interval}{$tt_line->[0]}{PRICE_IN}  = $tt_line->[1];
    	     $TIME_INTERVALS{$time_interval}{$tt_line->[0]}{PRICE_OUT} = $tt_line->[2];
    	     $TIME_INTERVALS{$time_interval}{$tt_line->[0]}{PREPAID}   = $tt_line->[3];
          }
    	  }
    	
     my $recalculate_sum  = 0;
     my $price_in  = $TIME_INTERVALS{$time_interval}{$traffic_class}{PRICE_IN};
     my $price_out = $TIME_INTERVALS{$time_interval}{$traffic_class}{PRICE_OUT};
     my $prepaid   = $TIME_INTERVALS{$time_interval}{$traffic_class}{PREPAID};
     my $in        = $line->[2];
     my $out       = $line->[3];
     my $sum_in    = 0;
     my $sum_out   = 0;

     # Work with prepaid traffic
     if ( $prepaid > 0 ) {
     	  my($used_traffic) = $Ipn->traffic_user_get({ UID      => $LIST_PARAMS{UID}, 
     	  	                                           INTERVAL => "0000-00-00/$line->[0]"   
     	  	                                         });
        my $online  = 0;

        if($OCTETS_DIRECTION == 1) {
          $used_traffic->{$traffic_class}{TRAFFIC_SUM}=($used_traffic->{$traffic_class}{TRAFFIC_IN}) ? $used_traffic->{$traffic_class}{TRAFFIC_IN} : 0;
          $online = $in;
         }
        #Sent / Out
        elsif($OCTETS_DIRECTION == 2) {
   	      $used_traffic->{$traffic_class}{TRAFFIC_SUM}=($used_traffic->{$traffic_class}{TRAFFIC_OUT}) ? $used_traffic->{$traffic_class}{TRAFFIC_OUT} : 0;
   	      $online = $out;
         }
        else {
          $used_traffic->{$traffic_class}{TRAFFIC_SUM}=($used_traffic->{$traffic_class}{TRAFFIC_IN}) ? $used_traffic->{$traffic_class}{TRAFFIC_OUT} + $used_traffic->{$traffic_class}{TRAFFIC_IN} : 0;
          $online =  ($in + $out);
         } 

 	  
     	  if ($debug > 1) {
          print "Prepaid traffic: $prepaid CLASS: $traffic_class USED: $used_traffic->{$traffic_class}{TRAFFIC_SUM}\n";
        }
# print "$used_traffic->{$k}{TRAFFIC_OUT} + $used_traffic->{$k}{TRAFFIC_IN} + ($in + $out) / $conf{MB_SIZE}\n";
# print $OCTETS_DIRECTION."\n";
# print "$used_traffic->{$k}{TRAFFIC_SUM} < $prepaid\n";

#print "$used_traffic->{$traffic_class}{TRAFFIC_SUM} < $prepaid<br>";

        if ($used_traffic->{$traffic_class}{TRAFFIC_SUM} < $prepaid) {
           $price_in = 0;
           $price_out = 0;
         }
        elsif ($used_traffic->{$traffic_class}{TRAFFIC_SUM} + $online / $conf{MB_SIZE} > $prepaid 
            && $used_traffic->{$traffic_class}{TRAFFIC_SUM} < $prepaid) {
          my $not_prepaid = ($used_traffic->{$traffic_class}{TRAFFIC_SUM} * $conf{MB_SIZE} + $online ) - $prepaid * $conf{MB_SIZE};

          my $sent = ($OCTETS_DIRECTION == 2) ?  $not_prepaid : $not_prepaid / 2;
          my $recv = ($OCTETS_DIRECTION == 1) ?  $not_prepaid : $not_prepaid / 2;

          $sum_in    = $recv / $conf{MB_SIZE} * $price_in if ($price_in > 0); 
          $sum_out   = $sent / $conf{MB_SIZE} * $price_out if ($price_out > 0);
          $price_in  = 0;
          $price_out = 0;
         }
       #exit;
      }
 
 #print "$price_in / $price_out <br>";
 
 	      $sum_in = $in / $conf{MB_SIZE} * $price_in if ($price_in > 0); 
        $sum_out = $out / $conf{MB_SIZE} * $price_out if ($price_out > 0);

        my $recalculate_sum = $sum_in + $sum_out;

    	 $table->addrow($line->[0], 
    	   $line->[1], 
    	   
    	   $line->[2], 
    	   $line->[3], 

    	   $line->[4], 
    	   $line->[5], 
    	   $line->[6], 
    	   $line->[7], 
    	   $line->[8],

    	   $recalculate_sum
    	   );
       
       if ($FORM{ACTION}) {
          $Ipn->traffic_recalc({ UID           => "$LIST_PARAMS{UID}",
                                  START         => "$line->[0]",
                                  TRAFFIC_CLASS => "$traffic_class",
                                  IN            => "$line->[2]",
                                  OUT           => "$line->[3]",
                                  SESSION_ID    => "$line->[8]",
                                  SUM           => "$recalculate_sum" });
        }
       $total_sum += $line->[7];
       $recalculate_total_sum +=  $recalculate_sum;
     }

      if ($FORM{ACTION}) {
       	my $recalculte = sprintf("%.5f", $total_sum -  $recalculate_total_sum);
       	print "$user->{BILL_ID} // ---- $recalculte";

        if ($recalculte > 0) {
       	  $Ipn->traffic_recalc_bill({ SUM     => $recalculte, 
       		                            BILL_ID => $user->{BILL_ID} });

          print $html->$message('info', $_RECALCULATE, "$_SUM: $recalculte");
         }
       }

      $table->{rowcolor}=$_COLORS[3];
      $table->addtd(
                  $table->td($_TOTAL, { colspan => 3 } ),
                  $table->td($total_sum, { colspan => 2 } ),
                  $table->td($_RECALCULATE, { colspan => 3 } ),
                  $table->td($recalculate_total_sum, { colspan => 2 } )
                  );
      
      print $table->show();
	 }

   

}


$table = $html->table( { width    => '100%',
	                       rowcolor => $_COLORS[0],
                         rows     => [ [  "$_RECALCULATE:",                                   "$_FROM: ", $html->date_fld('FROM_', { MONTHES => \@MONTHES} ),
                                   "$_TO: ", $html->date_fld('TO_', { MONTHES => \@MONTHES } ),
                                   $html->form_select('ACTION', 
                                    { 
 	                                   SELECTED          => $FORM{ACTION} || 0,
 	                                   SEL_ARRAY         => [$_SHOW, $_RECALCULATE],
 	                                   ARRAY_NUM_ID      => 1
 	                                  }),

                                   $html->form_input('RECALCULATE', "$_RECALCULATE",  {  TYPE => 'SUBMIT', OUTPUT2RETURN => 1  })
                                    ] ],                                   
                     } );


print $html->form_main({ CONTENT => $table->show(), 
                         HIDDEN  => { index   => "$index",
                        	            UID     => $LIST_PARAMS{UID},
                     	           }
    	                 });






}


1




