#/usr/bin/perl
# Voip web functions

require "Voip.pm";
Voip->import();
my $Voip = Voip->new($db, $admin, \%conf);

use Voip_Sessions;
my  $sessions = Voip_Sessions->new($db, \%conf);




my $MODULE = (defined($module{$index})) ? $module{$index} : 'Voip';




#*******************************************************************
# Change user variant form
# form_chg_vid()
#*******************************************************************
sub voip_chg_tp {
 my ($attr) = @_;

 my $user;

 if(defined($attr->{USER})) {
   $user = $attr->{USER};
   $user = $Voip->user_info($user->{UID});
   if($user->{TOTAL} < 1) {
 	   $html->message('info', $_INFO, $_NOT_ACTIVE);
 	   return 0;
    }
  }
 else {
 	 $html->message('err', $_ERROR, "$_USER_NOT_EXIST");
 	 return 0;
  }

 my $period = $FORM{period} || 0;

 use Shedule;
 $shedule = Shedule->new($db, $admin);

if ($FORM{set}) {
  if ($period == 1) {
    $FORM{date_M}++;
    $shedule->add( {UID => $user->{UID},
                   TYPE => 'tp',
                   ACTION => $FORM{TP_ID},
    	             D => $FORM{date_D},
                   M => $FORM{date_M},
                   Y => $FORM{date_Y},
                   DESCRIBE => "$message<br>
                   $_FROM: '$FORM{date_Y}-$FORM{date_M}-$FORM{date_D}'",
                   MODULE => 'Voip'
                    });

    if ($shedule->{errno}) {
      $html->message('err', $_ERROR, "[$shedule->{errno}] $err_strs{$shedule->{errno}}");	
     }
    else {
      $html->message('info', $_CHANGED, "$_CHANGED");
      $user->user_info($user->{UID});
    }
   }
  else {
    $user->user_change({ %FORM });

    if ($users->{errno}) {
      $html->message('err', $_ERROR, "[$users->{errno}] $err_strs{$users->{errno}}");	
     }
    else {
      $html->message('info', $_CHANGED, "$_CHANGED");
      $user->user_info($user->{UID});
    }

  }
}
elsif($FORM{del}) {
  $shedule->del( { UID => $user->{UID},
   	               ID  => $FORM{SHEDULE_ID}  } 
   	            );

  $html->message('info', $_DELETED, "$_DELETED [$FORM{SHEDULE_ID}]");
}

my $tariffs;



  $shedule->info( {UID     => $user->{UID},
                   TYPE    => 'tp',
                   MODULE  => 'Voip'
                   });


  if ($shedule->{TOTAL} > 0) {
  	$table = $html->table( { width   => '100%',
  		                       caption => "$_SHEDULE",
                             cols_align => ['left', 'left'],
                             rows => [ [ "$_TARIF_PLAN:", "$shedule->{ACTION}"   ],
                                       [ "$_DATE:",   "$shedule->{D}-$shedule->{M}-$shedule->{Y}" ],
                                       [ "$_ADMIN:",  "$shedule->{ADMIN_NAME}" ],
                                       [ "$_ADDED:",  "$shedule->{DATE}"     ],
                                       [ "ID:",       "$shedule->{SHEDULE_ID}"   ]  
                                      ]
                               } );
  	$tariffs->{TARIF_PLAN_SEL} = $table->show(). $html->form_input('SHEDULE_ID', "$shedule->{SHEDULE_ID}", {TYPE => 'HIDDEN' });
  	$tariffs->{ACTION}='del';
  	$tariffs->{LNG_ACTION}=$_DEL;
  }
 else {
   $tariffs->{TARIF_PLAN_SEL}=$html->form_select('TP_ID', 
                                          { 
 	                                          SELECTED  => $user->{TP_ID},
 	                                          SEL_MULTI_ARRAY   => $Voip->tp_list(),
 	                                          MULTI_ARRAY_KEY   => 0,
 	                                          MULTI_ARRAY_VALUE => 1,
 	                                        });

   $tariffs->{PARAMS} .= form_period($period);	
   $tariffs->{ACTION}='set';
   $tariffs->{LNG_ACTION}=$_CHANGE;
  }

 

my $tp_index = $index + 4;

$tariffs->{UID}=$attr->{USER}->{UID};
$tariffs->{m}=$m;
$tariffs->{TP_ID} = $user->{TP_ID};
$tariffs->{TP_NAME} = "$user->{TP_ID}:$user->{TP_NAME} [". $html->button("$_VARIANTS", "index=$tp_index&TP_ID=$user->{TP_ID}", { TITLE => "$_TP" } ). "]";


print $html->tpl_show(templates('chg_tp'), $tariffs);

}









#**********************************************************
# user_voip
#**********************************************************
sub voip_users_list {



 if($FORM{TP_ID}) {
   $LIST_PARAMS{TP_ID} = $FORM{TP_ID};
   $pages_qs .= "&TP_ID=$FORM{TP_ID}";
  }


  form_search({ SEARCH_FORM =>  	
  	"<tr><td colspan=2><hr></td></tr>
     <tr><td>IP (>,<)</td><td><input type=text name=IP value='%IP%'></td></tr>
     <tr><td>CID</td><td><input type=text name=CID value='%CID%'></td></tr>
     <tr><td>NAMBER (>,<):</td><td><input type=text name=NUMBER value='%NUMBER%'></td></tr>\n"
   });
 

 print $html->letters_list({ pages_qs => $pages_qs  }); 

 if ($FORM{letter}) {
   $LIST_PARAMS{FIRST_LETTER} = $FORM{letter};
   $pages_qs .= "&letter=$FORM{letter}";
  } 


#use Users;
#my $users = Users->new($db, $admin, \%conf); 

my $list = $Voip->user_list( { %LIST_PARAMS } );

if ($Voip->{errno}) {
  $html->message('err', $_ERROR, "[$Voip->{errno}] $err_strs{$Voip->{errno}}");	
  return 0;
 }
elsif ($Voip->{TOTAL} == 1) {
	form_users({  USER => user_info($list->[0]->[7]) });
	return 0;
}




my $table = $html->table( { width => '100%',
                                   border => 1,
                                   title => [$_LOGIN, $_FIO, $_DEPOSIT, $_CREDIT, $_TARIF_PLANS, $_STATUS, $_NUMBER, '-'],
                                   cols_align => ['left', 'left', 'right', 'right', 'left', 'center', 'left', 'center', 'center', 'center'],
                                   qs => $pages_qs,
                                   pages => $Voip->{TOTAL}
                                  } );

foreach my $line (@$list) {
  my $payments = ($permissions{1}) ?  $html->button($_PAYMENTS, "index=2&UID=$line->[7]") : ''; 

  $table->addrow($html->button($line->[0], "index=11&UID=$line->[7]"), "$line->[1]",
   "$line->[2]", "$line->[3]", "$line->[4]", "$status[$line->[5]]", 
   "$line->[6]",
   $payments);
}
print $table->show();

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

  return 0;
}


#**********************************************************
# user_dv
#**********************************************************
sub voip_user {
 	$Voip->{UID}=$FORM{UID};	  
  
  if ($FORM{add}) {
    $Voip->user_add({ %FORM });
    if (! $Voip->{errno}) {
      $html->message('info', $_INFO, "$_ADDED");	
     }
   }
	elsif($FORM{set}) {
    $Voip->user_change({ %FORM });
    if (! $Voip->{errno}) {
      $html->message('info', $_INFO, "$_CHANGED");	
     }
   }
	elsif($FORM{del}) {
    $Voip->user_del();
    if (! $Voip->{errno}) {
      $html->message('info', $_INFO, "$_CHANGED");	
     }
	 }

  my $user = $Voip->user_info($FORM{UID});

  if($user->{TOTAL} < 1) {
	  $html->message('info', $_INFO, $_NOT_ACTIVE);
	  $user = $Voip->defaults();
	  $user->{ACTION}='add';
	  $user->{LNG_ACTION}=$_ACTIVATE;
	 }
	else {
	  $user->{ACTION}='set';
	  $user->{LNG_ACTION}=$_CHANGE;
	} 

  $user->{DISABLE} = ($user->{DISABLE} == 1) ?  ' checked' : '';
  $user->{ALLOW_ANSWER}=' checked' if($user->{ALLOW_ANSWER} == 1);
  $user->{ALLOW_CALLS}=' checked' if($user->{ALLOW_CALLS} == 1);
  
  $html->tpl_show(_include('voip_user', 'Voip'), $user);
}



#**********************************************************
# Time intervals
# form_intervals()
#**********************************************************
sub voip_nas {
  $FORM{subf}=18;
  voip_tp();
}


#**********************************************************
# Time intervals
# form_intervals()
#**********************************************************
sub voip_tp_routes {
	my ($attr) = @_;

my $Voip_tp;
if (defined($attr->{TP})) {
	$Voip_tp = $attr->{TP};

	if ($FORM{change}) {
		 $Voip->rp_add({ %FORM });
     if (! $Voip->{errno}) {
      $html->message('info', $_INFO, "$_ADDED");
     }

	 }
	elsif($FORM{clear}) {
		
 	 }
}
else {
 	voip_tp({ f => 'voip_tp_routes' });
 	return 0;
}
  
  
#  my $Voip_tp = $Voip->tp_info( $FORM{TP_ID} );
  my $list = $Voip_tp->ti_list({ %LIST_PARAMS });
  my @caption = ('PREFIX', $_ROUTES, "$_STATUS");
  my @aligns = ('left', 'left', 'center');
  my @interval_ids = ();
  my $intervals=0;
  foreach my $line (@$list) {
     push @caption, "$line->[1] / $line->[2]-$line->[3]";
     push @aligns,  'center';
     push @interval_ids, $line->[0];
   }
  $intervals = $Voip_tp->{TOTAL};


  form_search({ 
     SIMPLE        => {$_PREFIX   => "ROUTE_PREFIX",
                       $_NAME     => "ROUTE_NAME",
                       $_DISABLE  => "DISABLE",
                       $_DESCRIBE => "DESCRIBE",
                       $_GATEWAY  => "GATEWAY_SEL",
                       $_SUM      => "PRICE"},

     HIDDEN_FIELDS => { TP_ID      => $FORM{TP_ID} }
   });



$list = $Voip->rp_list({ %LIST_PARAMS });
my %prices = ();
foreach my $line (@$list) {
  #print "-- $line->[0] / $line->[1] / $line->[2] / $line->[3] <br>\n";  
  $prices{"$line->[0]"}{"$line->[1]"}=$line->[3];

}



$list = $Voip->routes_list({ %LIST_PARAMS });	
my $table = $html->table( { width      => '100%',
                            border     => 1,
                            title      => \@caption,
                            cols_align => \@aligns,
                            qs         => $pages_qs,
                            pages      => $Voip->{TOTAL}
                         } );

my ($delete, $change);
my $price = 0;
foreach my $line (@$list) {
  my @l=();
  for(my $i = 0; $i<$intervals; $i++) { 
  	  if (defined($prices{"$interval_ids[$i]"}{"$line->[5]"})) {
        $price = $prices{$interval_ids[$i]}{$line->[5]};
  	    }
      else {
        $price = "N/P $interval_ids[$i] $line->[5] -0";
       }
      push @l, $html->form_input("p_$line->[5]". '_' . "$interval_ids[$i]", "$price", {SIZE => 10 });

      #"<input type='text' name='p_$line->[5]". '_' . "$interval_ids[$i]' value='$price' size=10>"; 
    }
  $table->addrow("$line->[0]",  "$line->[1]", $status[$line->[2]], @l);
}




###
#my  %new_hash = ();
#my  %phone_prefix = ();
#
#
#foreach my $line (@$list) {
#  $new_hash{$line->[5]}{$line->[0]}="$line->[2]";
#  $route_info{$line->[0]}="$line->[1]:$line->[3]";
#}
#
#my $h = $new_hash{0};
#my @last_array = ();
#
#my @menu_sorted = sort {
#   $h->{$b} <=> $h->{$a}
#     ||
#   length($a) <=> length($b)
#     ||
#   $a cmp $b
#} keys %$h;
#
#
#
#foreach my $parent (@menu_sorted) { 
#  
#  my @l=();
#  for(my $i = 0; $i<$intervals; $i++) { 
#      push @l, "<input type=text name='p_$parent". '_' . "$interval_ids[$i]' value='$parent". '_' . "$interval_ids[$i]' size=5>"; 
#    }
#  
#  my $val = $h->{$parent};
#  my $level = 0;
#  my $prefix = '';
#  my ($phone_prefix, $enable) = split(/:/, $route_info{$parent}, 2);
#  
#  $table->addrow("$phone_prefix",  "$val", @l);
#
#  if (defined($new_hash{$parent})) {
#    $level++;
#    $prefix .= "&nbsp;&nbsp;&nbsp;";
#    label:
#      my $mi = $new_hash{$parent};
#
#      while(my($k, $val)=each %$mi) {
#       
#      my @l=();
#      for(my $i = 0; $i<$intervals; $i++) { 
#         push @l, "<input type=text name='p_$k" .'_'. "$interval_ids[$i]' value='$k". "_" . "$interval_ids[$i]' size=5>"; 
#       }
#
#        my ($phone_prefix, $enable) = split(/:/, $route_info{$k}, 2);
#        $table->addrow("$prefix $phone_prefix", "$prefix $val", @l);
#
#        if (defined($new_hash{$k})) {
#      	   $mi = $new_hash{$k};
#      	   $level++;
#           $prefix .= "&nbsp;&nbsp;&nbsp;";
#           push @last_array, $parent;
#           $parent = $k;
#         }
#        delete($new_hash{$parent}{$k});
#      }
#    
#    if ($#last_array > -1) {
#      $parent = pop @last_array;	
##      print "POP/$#last_array/$parent/<br>\n";
#      $level--;
#      
#      $prefix = substr($prefix, 0, $level * 6 * 3);
#      goto label;
#    }
#    delete($new_hash{0}{$parent});
#   }
#}




print $html->form_main({ CONTENT => $table->show(),
	                       HIDDEN  => { TP_ID   => "$FORM{TP_ID}",
	                                    index   => "$index",
	                                    routes  => "$FORM{ROUTES}"   },
	                       SUBMIT  => { change  => "$_CHANGE" }
	                      
	                      });

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

	
}

#**********************************************************
# Time intervals
# form_intervals()
#**********************************************************
sub voip_intervals {
  my ($attr) = @_;

  @DAY_NAMES = ("$_ALL", 'Sun', 'Mon', 'Tue', 'Wen', 'The', 'Fri', 'Sat', "$_HOLIDAYS");
  my %visual_view = ();
  my $tarif_plan;

  

if(defined($attr->{TP})) {
  $tarif_plan = $attr->{TP};
 	$tarif_plan->{ACTION}='add';
 	$tarif_plan->{LNG_ACTION}=$_ADD;

  if($FORM{routes}) {
  	voip_tp_routes({ TP => $attr->{TP} });
   } 
  elsif ($FORM{add}) {
    $tarif_plan->ti_add( { %FORM });
    if (! $tarif_plan->{errno}) {
      $html->message('info', $_INFO, "$_INTERVALS $_ADDED");
     }
   }
  elsif($FORM{change}) {
    $tarif_plan->ti_change( $FORM{TI_ID}, { %FORM } );

    if (! $tarif_plan->{errno}) {
      $html->message('info', $_INFO, "$_INTERVALS $_CHANGED [$tarif_plan->{TI_ID}]");
     }
   }
  elsif(defined($FORM{chg})) {
  	$tarif_plan->ti_info( $FORM{chg} );
    if (! $tarif_plan->{errno}) {
      $html->message('info', $_INFO, "$_INTERVALS $_CHANGE [$FORM{chg}]");
     }

 	 	$tarif_plan->{ACTION}='change';
 	 	$tarif_plan->{LNG_ACTION}=$_CHANGE;
   }
  elsif($FORM{del} && $FORM{is_js_confirmed}) {
    $tarif_plan->ti_del($FORM{del});
    if (! $tarif_plan->{errno}) {
      $html->message('info', $_DELETED, "$_DELETED $FORM{del}");
     }
   }
  else {
 	 	$tarif_plan->ti_defaults();
   }

  my $list = $tarif_plan->ti_list({ %LIST_PARAMS });
  my $table = $html->table( { width      => '100%',
                              border     => 1,
                              title      => ['#', $_DAYS, $_BEGIN, $_END, $_HOUR_TARIF, '-', '-', '-',  '-'],
                              cols_align => ['left', 'left', 'right', 'right', 'right', 'right', 'center', 'center', 'center', 'center'],
                              qs         => $pages_qs,
                              caption    => $_INTERVALS
                                  } );

  my $color="AAA000";
  foreach my $line (@$list) {

    my $delete = $html->button($_DEL, "index=$index$pages_qs&del=$line->[0]", { MESSAGE =>  "$_DEL [$line->[0]] ?" }); 
    $color = sprintf("%06x", hex('0x'. $color) + 7000);
     
    #day, $hour|$end = color
    my ($h_b, $m_b, $s_b)=split(/:/, $line->[2], 3);
    my ($h_e, $m_e, $s_e)=split(/:/, $line->[3], 3);

     push ( @{$visual_view{$line->[1]}}, "$h_b|$h_e|$color|$line->[0]")  ;

    if (($FORM{tt} eq $line->[0]) || ($FORM{chg} eq $line->[0])) {
       $table->{rowcolor}=$_COLORS[0];      
     }
    else {
    	 undef($table->{rowcolor});
     }
    
    $table->addtd(
                  $table->td($line->[0], { rowspan => ($line->[5] > 0) ? 2 : 1 } ), 
                  $table->td("<b>$DAY_NAMES[$line->[1]]</b>"), 
                  $table->td($line->[2]), 
                  $table->td($line->[3]), 
                  $table->td($line->[4]), 
                  $table->td($html->button("$_ROUTES", "index=$index$pages_qs&routes=$line->[0]")),
                  $table->td($html->button("$_CHANGE", "index=$index$pages_qs&chg=$line->[0]")),
                  $table->td($delete),
                  $table->td("&nbsp;", { bgcolor => '#'. $color, rowspan => ($line->[5] > 0) ? 2 : 1 })
     );

     
   };
  print $table->show();
  
 }
elsif (defined($FORM{TP_ID})) {
  $FORM{subf}=$index;
  voip_tp();
  return 0;
 }




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



$table = $html->table( { width       => '100%',
	                       title_plain => [$_DAYS, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,14,15,16,17,18, 19, 20, 21, 22, 23],
                         caption     => "$_INTERVALS",
                         rowcolor    => $_COLORS[1]
                      } );



for(my $i=0; $i<9; $i++) {
  my @hours = ();

  my ($h_b, $h_e, $color, $p);
  my $link = "&nbsp;";
  for(my $h=0; $h<24; $h++) {

  	 if(defined($visual_view{$i})) {
  	   $day_periods = $visual_view{$i};
       #print "<br>";
       foreach my $line (@$day_periods) {
     	   #print "$i -- $line    <br>\n";
     	   ($h_b, $h_e, $color, $p)=split(/\|/, $line, 4);
     	   if (($h >= $h_b) && ($h < $h_e)) {
#     	   	 print "$i // $h => $h_b && $h <= $h_e // $color <br> \n";
  	   	   $tdcolor = '#'.$color;
  	 	     $link = $html->button('#', "index=$index&TP_ID=$FORM{TP_ID}&subf=$FORM{subf}&chg=$p");
  	 	     last;
  	 	    }
  	     else {
  	 	     $link = "&nbsp;";
  	 	     $tdcolor = $_COLORS[1];
  	      }
       }
     }
  	 else {
  	 	 $link = "&nbsp;";
  	 	 $tdcolor = $_COLORS[1];
  	  }
     
     
  	 push(@hours, $table->td("$link", { align => 'center', bgcolor => $tdcolor }) );
    }
  
  
  $table->addtd("<td>$DAY_NAMES[$i]</td>", @hours);
}


print $table->show();

  $tarif_plan->{SEL_DAYS} = $html->form_select('TI_DAY', 
                                { SELECTED   => $day_id,
 	                                SEL_ARRAY  => \@DAY_NAMES,
 	                                ARRAY_NUM_ID  => 'y'
 	                               });

  $html->tpl_show(templates('ti'), $tarif_plan);
}

#**********************************************************
# Tarif plans
# form_tp
#**********************************************************
sub voip_tp {
 my ($attr) = @_;
 my @Payment_Types    = ($_PREPAID, $_POSTPAID); 

 $Voip_tp = $Voip->tp_defaults();
 $Voip_tp->{LNG_ACTION}=$_ADD;
 $Voip_tp->{ACTION}='ADD_TP';

if($FORM{ADD_TP}) {
  $FORM{TP_ID} = $FORM{CHG_TP_ID};
  $Voip->tp_add({ %FORM });
  if (! $Voip->{errno}) {
    $html->message('info', $_ADDED, "$_ADDED $Voip->{TP_ID}");
   }
 }
elsif (defined($FORM{TP_ID})) {
  $Voip_tp = $Voip->tp_info( $FORM{TP_ID} );

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

  $pages_qs .= "&TP_ID=$FORM{TP_ID}&subf=$FORM{subf}";
  $LIST_PARAMS{TP} = $FORM{TP_ID};
  %F_ARGS = ( TP => $Voip_tp );
  
  func_menu({ 
  	         'ID' =>   $Voip_tp->{TP_ID}, 
  	         $_NAME => $Voip_tp->{NAME}
  	       }, 
  	{ 
#  	 $_INFO          => ":TP_ID=$Voip_tp->{TP_ID}",
#     $_USERS         => "11:TP_ID=$Voip_tp->{TP_ID}",
#     $_INTERVALS     => "73:TP_ID=$Voip_tp->{TP_ID}",
#     $_NAS           => "18:TP_ID=$Voip_tp->{TP_ID}"
  	 },
  	{
  		f_args => { %F_ARGS }
  	 });

#  if($attr->{f}) {
#     $attr->{f}->({ TP => $Voip_tp });
#     return 0;
#   }
#  els
  if ($FORM{subf}) {
  	return 0;
   }
  elsif($FORM{change}) {
    $Voip->tp_change( $FORM{TP_ID}, { %FORM  } );  
    if (! $Voip->{errno}) {
       $html->message('info', $_CHANGED, "$_CHANGED $Voip->{TP_ID}");
     }
   }

  #$Voip_tp = $Voip;
  $Voip_tp->{LNG_ACTION}=$_CHANGE;
  $Voip_tp->{ACTION}='change';

 }
elsif(defined($FORM{del}) && $FORM{is_js_confirmed}) {
  $Voip->tp_del($FORM{del});

  if (! $Voip->{errno}) {
    $html->message('info', $_DELETE, "$_DELETED $FORM{del}");
   }
}


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




$Voip_tp->{PAYMENT_TYPE_SEL} = $html->form_select('PAYMENT_TYPE', 
                                { SELECTED      => $Voip_tp->{PAYMENT_TYPE},
 	                                SEL_ARRAY     => \@Payment_Types,
 	                                ARRAY_NUM_ID  => 'y'
 	                               });

#$Voip_tp = $Voip;

$html->tpl_show(_include('voip_tp', 'Voip'), $Voip_tp);



my $list = $Voip->tp_list({ %LIST_PARAMS });	
# Time tariff Name Begin END Day fee Month fee Simultaneously - - - 
my $table = $html->table( { width      => '100%',
                            border     => 1,
                            title      => ['#', $_NAME,  $_HOUR_TARIF, $_PAYMENT_TYPE, $_DAY_FEE, $_MONTH_FEE, $_SIMULTANEOUSLY, $_AGE,
                                     '-', '-', '-'],
                            cols_align => ['right', 'left', 'center', 'center', 'right', 'right', 'right', 'right', 'right', 'right', 'center', 'center', 'center'],
                                   
                                   
                                  } );

my ($delete, $change);
foreach my $line (@$list) {
  if ($permissions{4}{1}) {
    $delete = $html->button($_DEL, "index=$index&del=$line->[0]",  { MESSAGE => "$_DEL ?" }); 
    $change = $html->button($_INFO, "index=$index&TP_ID=$line->[0]");
   }
  
  if($FORM{TP_ID} eq $line->[0]) {
  	$table->{rowcolor}=$_COLORS[4];
   }
  else {
  	undef($table->{rowcolor});
   }
  
  $table->addrow("<b>$line->[0]</b>", 
  $html->button("$line->[1]", "index=$index&TP_ID=$line->[0]"), 
   $bool_vals[$line->[2]], $Payment_Types[$line->[3]], $line->[4], 
   $line->[5], $line->[6], $line->[7],
   $html->button($_INTERVALS, "index=". ($index+2) ."&subf=73&TP_ID=$line->[0]"),
   $change,
   $delete);
}
print $table->show();

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

	
}



#**********************************************************
# Tarif plans
# voip_routes
#**********************************************************
sub voip_routes {
 
  $Voip->{ACTION}='add';
  $Voip->{LNG_ACTION}=$_ADD;
  $Voip->{PARENT_ID}=0;
 
if($FORM{add}) {
  $Voip->route_add( { %FORM });
  if (! $Voip->{errno}) {
    $html->message('info', $_ADDED, "$_ADDED $Voip->{ROUTE_ID}");
   }
 }
elsif($FORM{change}) {
  $Voip->route_change({ %FORM });
  if (! $Voip->{errno}) {
    $html->message('info', $_INFO, "$_CHANGED");	
   }
 }
if($FORM{add_route}) {
	my $list = $Voip->routes_list();

  my %route_items = ();
  foreach my $line (@$list) {
    $route_items{$line->[0]}{$line->[5]}=$line->[1];
   }

   my $root_index = $FORM{add_route};	
   my $h = $route_items{$root_index};
   $Voip->{PARENT_ID} = $root_index;
   
   
    while(my ($par_key, $name) = each ( %$h )) {
      $menu_navigator =  $html->button("$name", "index=$index&ROUTE_ID=$root_index") . $menu_navigator;
      $tree{$root_index}='y';
      if ($par_key > 0) {
        $root_index = $par_key;
        $h = $route_items{$par_key};
       }
    }
  
  $Voip->{PARENT} = $menu_navigator;
  

 }
elsif($FORM{ROUTE_ID}) {
  $Voip->route_info($FORM{ROUTE_ID}, { %FORM });
  if (! $Voip->{errno}) {
    $html->message('info', $_INFO, "$_CHANGING");	
   }

  $Voip->{ACTION}='change';
  $Voip->{LNG_ACTION}=$_CHANGE;
 }
elsif(defined($FORM{del}) && $FORM{is_js_confirmed}) {
  $Voip->route_del($FORM{del});
  if (! $tariffs->{errno}) {
    $html->message('info', $_DELETE, "$_DELETED $FORM{del}");
   }
}

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







$Voip->{DISABLE}=' checked' if($Voip->{DISABLE} == 1);
$html->tpl_show(_include('voip_route', 'Voip'), $Voip);






  my %SEARCH_FIELDS = ($_PREFIX   => "ROUTE_PREFIX",
                       $_NAME     => "ROUTE_NAME",
                       $_DISABLE  => "DISABLE",
                       $_DESCRIBE => "DESCRIBE",
                       $_GATEWAY  => "GATEWAY_SEL");

  form_search({ 
     SIMPLE => \%SEARCH_FIELDS
   });


##
my  %new_hash = ();
my  %phone_prefix = ();
my $list = $Voip->routes_list({ %LIST_PARAMS });	



my $table = $html->table( { width      => '100%',
                            border     => 1,
                            title      => [$_PREFIX, $_NAME, $_STATUS, $_DATE, '-', '-'],
                            cols_align => ['left', 'left', 'center', 'right', 'center', 'center'],
                            qs         => $pages_qs,
                            pages      => $Voip->{TOTAL}
                                   
                                  } );

my ($delete, $change);
foreach my $line (@$list) {
   if ($permissions{4}{1}) {
    $delete = $html->button($_DEL, "index=$index&del=$line->[5]", { MESSAGe => "$_DEL '$line->[0]'?" }); 
    $change = $html->button($_CHANGE, "index=$index&ROUTE_ID=$line->[5]");
    #$add   = $html->button($_ADD, "index=$index&add_route=$parent&ROUTE_ID=$parent");
   }

   $table->addrow($line->[0], 
            $line->[1], 
            $status[$line->[2]], 
            $line->[3], 
            $change,
            $delete);

}
print $table->show();

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




#--------------------------------------------------------------------
# Tree View


#
#foreach my $line (@$list) {
#  $new_hash{$line->[5]}{$line->[0]}="$line->[2]";
#  $route_info{$line->[0]}="$line->[1]:$line->[3]";
#}
#
#my $h = $new_hash{0};
#my @last_array = ();
#
#my @menu_sorted = sort {
#   $h->{$b} <=> $h->{$a}
#     ||
#   length($a) <=> length($b)
#     ||
#   $a cmp $b
#} keys %$h;
#
#foreach my $parent (@menu_sorted) { 
#  
#  if ($permissions{4}{1}) {
#    $delete = $html->button($_DEL, "index=$index&del=$parent", "$_DEL ?"); 
#    $change = "<a href='$SELF_URL?index=$index&ROUTE_ID=$parent'>$_CHANGE</a>";
#    $add    = "<a href='$SELF_URL?index=$index&add_route=$parent&ROUTE_ID=$parent'>$_ADD</a>";
#   }
#
#  
#  
#  my $val = $h->{$parent};
#  my $level = 0;
#  my $prefix = '';
#  my ($phone_prefix, $enable) = split(/:/, $route_info{$parent}, 2);
#  
#  $table->addrow("$phone_prefix",  "$val", 
#     $status[$enable],
#     $add,
#     $change,
#     $delete 
#    );
#
#  if (defined($new_hash{$parent})) {
#    $level++;
#    $prefix .= "&nbsp;&nbsp;&nbsp;";
#    label:
#      my $mi = $new_hash{$parent};
#
#      while(my($k, $val)=each %$mi) {
#       
#        if ($permissions{4}{1}) {
#          $delete = $html->button($_DEL, "index=$index&del=$k", "$_DEL ?"); 
#          $change = "<a href='$SELF_URL?index=$index&ROUTE_ID=$k'>$_CHANGE</a>";
#          $add    = "<a href='$SELF_URL?index=$index&add_route=$k'>$_ADD</a>";
#        }
#
#        my ($phone_prefix, $enable) = split(/:/, $route_info{$k}, 2);
#        $table->addrow("$prefix $phone_prefix", "$prefix $val", 
#            $status[$enable],
#            $add,
#            $change,
#            $delete );
#
#        if (defined($new_hash{$k})) {
#      	   $mi = $new_hash{$k};
#      	   $level++;
#           $prefix .= "&nbsp;&nbsp;&nbsp;";
#           push @last_array, $parent;
#           $parent = $k;
#         }
#        delete($new_hash{$parent}{$k});
#      }
#    
#    if ($#last_array > -1) {
#      $parent = pop @last_array;	
##      print "POP/$#last_array/$parent/<br>\n";
#      $level--;
#      
#      $prefix = substr($prefix, 0, $level * 6 * 3);
#      goto label;
#    }
#    delete($new_hash{0}{$parent});
#   }
#}
# print $table->show();





	
}

#*******************************************************************
# online users
#*******************************************************************
sub voip_online {

my $nas = Nas->new($db);


my $message;


if ($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{hangup}) {
  my ($nas_id, $acct_session_id, $user_name) = split(/ /, $FORM{hangup}, 4);
  $nas->info( { NAS_ID => $nas_id, SECRETKEY => $conf{secretkey} });
  
  if ($nas->{errno}) {
    $html->message('err', $_NAS, "$nas->{errstr}");
  	return 0;
   }

  $nas_port_id = 0;
  require "Abills/nas.pl";
  my $ret = hangup($nas, "$nas_port_id", "", "$acct_session_id");
  
  
  if ($ret == 0) {
     my $table = $html->table( { width => '100%',
                                caption => $_HANGUPED,
                                rows => [ [ "$_NAS ID",   $nas_id],
                                          [ "$_NAS IP",   $nas->{NAS_IP} ],
                                          [ "$_PORT",     $nas_port_id   ],
                                          [ "SESSION_ID", $acct_session_id ],
                                          [ "", $ret ] ]
                               } );
     
     $message = $table->show();
     sleep 3;
     
     weblog('hangup', "$user_name");
   }
  elsif ($ret == 1) {
   	$message = 'NAS NOT supported yet';
   }

  $html->message('info', $_INFO, "$message");
 }
elsif($FORM{zap}) {
  my  ($nas_id, $acct_session_id)=split(/ /, $FORM{zap}, 3);
  $sessions->zap($nas_id, $acct_session_id);

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

  $nas->info({NAS_ID => $nas_id, SECRETKEY => $conf{secretkey} });
  $message = "<table width=100%>
     <tr><th colspan=2 align=left>$_CLOSED</th></tr>
     <tr><td>$_NAS:</td><td>$nas->{NAS_IP} / $nas->{NAS_INDENTIFIER}</td></tr>
     <tr><td>$_PORT:</td><td>$nas_port_id</td></tr>
     <tr><td>SESSION_ID:</td><td>$acct_session_id</td></tr>
     </table>\n";

  
 
  $sessions->list({ ACCT_SESSION_ID => $acct_session_id, 
  	                NAS_ID => $nas->{NAS_ID} });  
  
  if ($sessions->{TOTAL} < 1) {
    $message .= "<p align=\"center\">[". $html->button('add to log', "index=$index&tolog=$acct_session_id&nas_id=$nas_id"). "]
        [". $html->button("$_DEL", "index=$index&del=$acct_session_id&nas_id=$nas_id&nas_port_id=$nas_port_id"). "]</p>";
   }
  else {
  	$message = "$_EXIST";
  	$sessions->online_del({ NAS_ID  => $nas_id,
                            ACCT_SESSION_ID => $acct_session_id
                            });

   }

  $html->message('info', $_INFO, $message);
}
elsif($FORM{tolog}) {
  $sessions->{debug}=1;
  my $ACCT_INFO = $sessions->online_info({ NAS_ID          => $FORM{nas_id},
                                           ACCT_SESSION_ID => $FORM{tolog}
                                         });

  if ($ACCT_INFO->{TOTAL} < 1) {
    $html->message('err', $_ERROR, "$_NOT_EXIST");	
    return 0;
   }

  require Voip_aaa;
  $ACCT_INFO->{ACCT_STATUS_TYPE} = 'Stop';
  
  my $nas = Nas->new($db);	
  $nas->info({NAS_ID    => $ACCT_INFO->{NAS_ID},
              SECRETKEY => $conf{secretkey}});

  Voip_aaa->import();
  my $Acct = Voip_aaa->new($db, \%conf);
  my $r = $Acct->accounting($ACCT_INFO, $nas, \%conf);

  if ($Acct->{errno}) {
    $html->message('err', $_ERROR, "[$Acct->{errno}] $Acct->{errstr}");	
   }
  else {
  	my $table = $html->table( { width => '100%'} );
  	while(my($k, $v)=each %$ACCT_INFO) {
 		    $table->addrow($k, $v);
  	  }
  	while(my($k, $v)=each %$Acct) {
 		    $table->addrow($k, $v);
  	  }
  	$html->message('info', $_ADDED, $table->show());	
   }
  
  $sessions->online_del({ NAS_ID          => $ACCT_INFO->{NAS_ID},
                          ACCT_SESSION_ID => $ACCT_INFO->{ACCT_SESSION_ID}
                        });
 }
elsif($FORM{del} || $FORM{dellist}) {
  if ($FORM{dellist}) {
    my @sessions_list = split(/, /, $FORM{dellist});
    $sessions->online_del({ SESSIONS_LIST => \@sessions_list });
    $FORM{del} = $FORM{dellist};
   }
  else {
    $sessions->online_del({
   	            NAS_ID          => $FORM{nas_id},
                ACCT_SESSION_ID => $FORM{del}
                           });
   }

  if (! $sessions->{errno}) {
    my $table = $html->table( { width => '100%',
                                rows => [ [ "NAS_ID",          $FORM{nas_id}     ],
                                          [ "ACCT_SESSION_ID", $FORM{del}        ]
                                        ]
                               } );
    
    $html->message('info', $_DELETED, $table->show());	
   }

}








$form_link = '';
my $cure = '';


if($FORM{ZAPED}) {
	$LIST_PARAMS{ZAPED}='yes';
	$form_link = $html->button('On line', "index=$index");
	$cure = 'Zap';
 } 
else {
 	$sessions->online( { ZAPED => 'yes' } );	
 	$form_link = $html->button($_ZAPED, "index=$index&ZAPED=yes"). " ($sessions->{TOTAL})";
	$cure = 'Online';
}


$sessions->online( { %LIST_PARAMS } );	
my $dub_ports = $sessions->{dub_ports};
my $dub_logins = $sessions->{dub_logins};
 
my $table = $html->table( { caption    => "$cure",
	                          width      => '100%',
                            title      => ["$_USER", "$_FIO", "CALLING_STATION_ID", "CALLING_STATION_ID", "$_DURATION", "CLIENT_IP_ADDRESS",  "-", "-", "-"],
                            cols_align => ['left', 'left', 'right', 'right', 'right', 'right', 'right', 'right', 'right', 'center'],
                            qs         => $pages_qs,
                           });


 
my $bg;
my $online = $sessions->{nas_sorted};

my $nas_list = $nas->list();

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

  $table->{rowcolor}=$_COLORS[0];
  $table->{extra}="colspan=\"9\" class=\"small\"";
  $table->addrow("$nas_row->[0]:<b>$nas_row->[1]</b>:$nas_row->[4]" );



  my $l = $online->{$nas_row->[0]};
  foreach my $line (@$l) {
    undef($table->{rowcolor});
    undef($table->{extra});
    #print "$line->[0]<br>";
    if (defined($dub_logins->{$line->[0]}))                   { $bg='#FFFF00';    }
#    elsif (defined($dub_ports->{$nas_row->[4]}{$line->[2]})) { $bg='#00FF40';    }
    elsif ($line->[9] == 3)                                   { $bg='#FF0000';    }
    else {  $bg = ($bg eq $_COLORS[1]) ? $_COLORS[2] : $_COLORS[1];    }

    my $zap = "(". $html->button('Z', "index=$index&zap=$nas_row->[0]+$line->[9]", { TITLE => 'Zap'}). ")";
    my $hangup = ($FORM{ZAPED}) ? $html->form_input('dellist', "$line->[9]", { TYPE => 'checkbox' } ) : "(". $html->button('H', "index=$index&hangup=$nas_row->[0]+$line->[2]+$line->[9]+$line->[0]", { TITLE => 'Hangup'} ) .")";
    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->[17]\nCONNECT_INFO: $line->[18]";

    $table->addrow($html->button($line->[0], "index=11&UID=$line->[10]", { TITLE => "$user_info"}), 
      $line->[1], $line->[2],  $line->[3],  $line->[4], $line->[5], 
     "(". $html->button('P', "index=$index&ping=$line->[3]", { TITLE => 'Ping'}). ")",
     "$zap",
     "$hangup");
  }
}

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


my $total = $table2->show();
my $output = $total . $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'})  
                                         ],
                          cols_align => ['center:noprint', 'center:noprint'],
                           });

if ($FORM{ZAPED}) {
  $output = $html->form_main({ CONTENT => $output,
	                       HIDDEN  => { index => "$index",
	                       	            ZAPED => 1 },
	                       SUBMIT  => { go    => "$_DEL" },
	                       METHOD  => 'GET'
                        });
 }
else {
  $output .= $html->form_main({ CONTENT => $table->show(),
	                              HIDDEN  => { index =>  "$index" },
	                              METHOD  => 'GET'
                        });

  $output .= $html->button('Zap All', "index=$index&zapall=y", { MESSAGE => "Do you realy want zap all sessions ?" });
 }


print  $output;
		
}



#**********************************************************
# Whow sessions from log
# voip_sessions()
#**********************************************************
sub voip_sessions {
  my ($list) = @_;
#Session List


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


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->{debug}=1;

	$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}}");
 }



return 0 if ($sessions->{TOTAL} < 1);
my $table = $html->table( { width        => '100%',
                            border       => 1,
                            title        => ["$_USER", "$_START", "$_DURATION", "$_TARIF_PLAN", "CALLING_STATION_ID", "CALLED_STATION_ID", 
                                     "NAS", "IP", "$_SUM", "-", "-"],
                            cols_align   => ['left', 'right', 'right', 'RIGHT', 'right', 'right', 'right', 'right', 'right', 'right', 'center'],
                            qs           => $pages_qs,
                            pages        => $sessions->{TOTAL},
                            recs_on_page => $LIST_PARAMS{PAGE_ROWS}
                               } );

my $delete = '';

use Billing;
my $Billing = Billing->new($db);	



foreach my $line (@$list) {
  if ($permissions{3}{1}) {
    #$UID, $session_id, $nas_id, $session_start_date, $session_start_time, $sum, $login
    $delete = $html->button($_DEL, "index=$index$pages_qs&del=$line->[11]+$line->[9]+$line->[6]+$line->[1]+$line->[9]+$line->[0]", { MESSAGE => "$_DEL Session SESSION_ID $line->[9]?" });
   }

  $table->addrow($html->button($line->[0], "index=11&UID=$line->[12]"), 
     $line->[1], $line->[2],  $line->[3],  
     $line->[4], 
     $line->[5], $line->[6],
     $line->[7], 
     "$line->[8] $test", 
     "(". $html->button('D', "index=$index&UID=$line->[12]&SESSION_ID=$line->[11]", { TITLE => 'Session Detail' }) .")", 
     $delete);
}

print $table->show();
}


#**********************************************************
# voip_use_all_monthes();
#**********************************************************
sub voip_use_allmonthes {

  $FORM{allmonthes}='y';
  voip_use();
}


#**********************************************************
# dv_use();
#**********************************************************
sub voip_use {
  reports({ DATE   => $FORM{DATE}, 
  	        REPORT => '' });

my ($tables_sessions, $table_fees);

#Day reposrt
if (defined($FORM{DATE})) {
  #Used Fraffic
  $table_sessions = $html->table( { width      => '100%',
	                                  caption    => "$_SESSIONS", 
                                    title      => ["$_DATE", "$_USERS", "$_SESSIONS", $_DURATION, $_SUM],
                                    cols_align => ['right', 'left', 'right', 'right', 'right'],
                                    qs         => $pages_qs             
                               } );

  my $list = $sessions->reports({ %LIST_PARAMS });
  foreach my $line (@$list) {
    $table_sessions->addrow("<b>$line->[0]</b>", 
      $html->button("$line->[1]", "index=11&subf=22&UID=$line->[5]&DATE=$line->[0]"), 
       $line->[2], $line->[3],  "<b>$line->[4]</b>" );
   }

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


  my $list = $sessions->reports({ %LIST_PARAMS });
  foreach my $line (@$list) {
    $table_sessions->addrow(
    $html->button($line->[0], "index=$index&$type=$line->[0]$pages_qs"), 
       $line->[1], $line->[2], $line->[3], "<b>$line->[4]</b>" );
   }

}



$table = $html->table( { width   => '100%',
                         caption => $_SESSIONS,
                         cols_align => ['right', 'right', 'right', 'right', 'right', 'right'],
                         rows => [ [ "$_USERS: <b>$sessions->{USERS}</b>",
                                            "$_SESSIONS: <b>$sessions->{SESSIONS}</b>", 
                                            "$_DURATION: <b>$sessions->{DURATION}</b>", 
                                            "$_SUM: <b>$sessions->{SUM}</b>" ] ],
                                rowcolor => $_COLORS[2]
                               } );


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

}



#**********************************************************
# dv_error
#**********************************************************
sub voip_error {
	my ($attr) = @_;
  my $PAGE_ROWS = 100;
  $conf{LOGFILE} = "/usr/local/abills/var/log/abills.voip";
  my $login  = ''; 


if ($attr->{USER}) {
  my $user = $attr->{USER};
  $login = $user->{LOGIN};
}
elsif ($FORM{LOGIN_EXPR}) {
  $login = $FORM{LOGIN_EXPR};
  $pages_qs .= "&LOGIN_EXPR=$FORM{LOGIN_EXPR}";
 }
elsif($FORM{UID}) {
  voip_users();
  return 0;
}



if (! -f $conf{LOGFILE}) {
	$html->message('info', $_INFO, "'$conf{LOGFILE}' $_NOT_EXIST");
	return 0;
}


if (defined($FORM{LOG_TYPE})) {
	$pages_qs .= "&LOG_TYPE=$FORM{LOG_TYPE}";
}

my ($list, $types, $totals) = show_log("$login", "$conf{LOGFILE}", { DATE      => $FORM{DATE},
	                                                                   LOG_TYPE  => $FORM{LOG_TYPE},
	                                                                   PG        => $PG,
	                                                                   PAGE_ROWS => $PAGE_ROWS });
	                                                                   

print $html->form_main({ CONTENT => "$_LOGIN: " . $html->form_input('LOGIN_EXPR', "$FORM{LOGIN_EXPR}"),
	                       HIDDEN  => { sid   => "$sid",
	                                    index => "$index",
	                                    UID   => "$UID"   },
	                       SUBMIT  => { show  => "$_SHOW" }
	                      
	                      });
	                                                                   

	                                                                   
my $table = $html->table( { caption => "$_LOG",
	                          width   => '100%',
	                          pages   => $totals,
	                          qs      => $pages_qs
	                         } );

foreach my $line (@$list) {
  if ($line =~ m/LOG_WARNING/i) {
     $line = "<font color='#FF0000'>$line</font>";
   }

#  if ($line =~ m/LOG_WARNING/i) {
#    $table->{rowcolor}='#FF0000';
#   } 
#  else {
#  	$table->{rowcolor}=undef;
#   }  

  $table->addrow($line);
}
print $table->show();


$table = $html->table({ 
                        width      => '100%',
                        cols_align => ['right', 'right'] 
                        });

$table->addrow($html->button("$_TOTAL", "index=$index&$pages_qs"), $totals);
while(my($k,$v)=each %$types) {
  $table->addrow($html->button($k, "index=$index&LOG_TYPE=$k$pages_qs"), $v);
}
print $table->show();

}


#**********************************************************
# stats
#**********************************************************
sub voip_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}";
  	voip_session_detail({ USER => $attr->{USER} });
  	
  	return 0;
  }

}
#elsif($FORM{UID}) {
#	form_users();
#	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 });



if (! defined($sessions->{sum_4})) {
	$html->message('info', $_INFO, "$_NO_RECORD");
	return 0;
}

my $table = $html->table( { width       => '100%',
                            title_plain => ["$_PERIOD", "$_DURATION", "$_SUM"],
                            cols_align  => ['left', 'right', 'right'],
                            rowcolor    => $_COLORS[1]
                         } );


for(my $i = 0; $i < 5; $i++) {
	  $table->addrow($html->button("$PERIODS[$i]", "index=$index&period=$i$pages_qs"), 
	  "$sessions->{'duration_'. $i}",
	  $sessions->{'sum_'. $i});
 }
print $table->show();



$table = $html->table( { width       => '100%',
	                       rowcolor    => $_COLORS[0],
                         title_plain => [ "$_FROM: ",  $html->date_fld('from', { MONTHES => \@MONTHES} ),
                                          "$_TO: ",    $html->date_fld('to', { MONTHES => \@MONTHES } ),
                                          "$_ROWS: ",  $html->form_input('rows', int($conf{list_max_recs}), { SIZE => 4 } ),
                                          $html->form_input('show', $_SHOW,  { TYPE => 'submit' })
                                         ],                                   
                      });

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


voip_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} = int($FORM{period}); 
	$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],
	                       caption     => $_TOTAL,
                         title_plain => ["$_SESSIONS", "$_DURATION", "$_SUM"],
                         cols_align  => ['right', 'right', 'right'],
                         rows        => [ [ $sessions->{TOTAL}, $sessions->{DURATION}, $sessions->{SUM} ] ],
                               } );
print $table->show();
voip_sessions($list, $sessions) if ( $sessions->{TOTAL} > 0);
}


#*******************************************************************
# WHERE period
# base_state($where, $period);
#*******************************************************************
sub voip_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} ],
                                  [ $_SUM,  $sessions->{min_sum}, $sessions->{max_sum}, $sessions->{avg_sum} ]
                                        ]
                               } );
print $table->show();
}

#**********************************************************
# form_stats
#**********************************************************
sub voip_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", "$_SUM"],
                                   cols_align => ['left', 'right', 'right'],
                                   rowcolor => $_COLORS[1]
                                  } );

if (! defined($sessions->{sum_5})) {
	$html->message('info', $_INFO, $_NO_RECORD);
	return 0;
}

for(my $i = 0; $i < 5; $i++) {
	  $table->addrow($html->button("$PERIODS[$i]", "index=$index&period=$i$pages_qs"), "$sessions->{'duration_'. $i}",
	  $sessions->{'sum_'. $i});
 }
print $table->show();


$table = $html->table( { width       => '100%',
	                       rowcolor    => $_COLORS[0],
                         title_plain => [ "$_FROM: ",  $html->date_fld('from', { MONTHES => \@MONTHES} ),
                                          "$_TO: ",    $html->date_fld('to', { MONTHES => \@MONTHES } ),
                                          "$_ROWS: ",  $html->form_input('rows', int($conf{list_max_recs}), { SIZE => 4 } ),
                                          $html->form_input('show', $_SHOW,  { TYPE => 'submit' })
                                         ],                                   
                      });

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

voip_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} = int($FORM{period}); 
	$pages_qs .= "&period=$FORM{period}";
}


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

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


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



sub voip_user_info {
  my $user = $Voip->user_info($LIST_PARAMS{UID});
  
  if ($user->{TOTAL} < 1) {
  	$html->message('info', $_INFO, "$_NOT_ACTIVE");
    return 0;	
  }
  
  $html->tpl_show(_include('voip_user_info', 'Voip'), $Voip);
}




#**********************************************************
# daily_fees
#**********************************************************
sub voip_daily_fees {
 
 require Tariffs;
 Tariffs->import();
 my $tariffs = Tariffs->new($db, $conf);

 require Fees;
 Fees->import();
 my $fees = Fees->new($db, $admin, $conf);

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

 foreach my $line (@$list) {
 	 if ($line->[5] > 0) {
# 	   print "$line->[0] $line->[6]\n";
 	   $LIST_PARAMS{TP}=$line->[0];

 	   my $ulist = $Dv->list({ 
         ACTIVATE => "<=$DATE",
         EXPIRE => ">$DATE",
         DISABLE => '0',
         TP => $line->[0]
 	   	 });

#     .id, u.fio, if(acct.id IS NULL, u.deposit, acct.deposit), u.credit, tp.name, u.disable, 
#      u.uid, u.account_id, u.email, u.tp_id
     foreach my $u (@$ulist) {
        my %user = (
            ACCOUNT_ID => $u->[7],
            UID => $u->[6],
            BILL_ID => $u->[12]  
         );
#          print " $u->[0] $line->[6] $u->[2] $u->[3]\n"; 	

        if($line->[5] > 0
            || $conf{negative_deposit} eq 'yes'
            || $u->[2] + $u->[3] > 0 ) {
          $fees->take(\%user, $line->[5], { DESCRIBE => "$_DAY_FEE" } );  
         }
      }

 	  }
  }




}





#**********************************************************
# monthly_fees
#**********************************************************
sub voip_monthly_fees {
 require Tariffs;
 Tariffs->import();
 my $tariffs = Tariffs->new($db);

 require Fees;
 Fees->import();
 my $fees = Fees->new($db, $admin);

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

 #print "$y, $m, $d\n";

 $m--;
 
my $date_unixtime =  mktime(0, 0, 0, $d, $m, $y - 1900, 0, 0, 0);
 
 foreach my $line (@$list) {
 	 if ($line->[6] > 0) {
# 	   print "$line->[0] $line->[7]\n";
 	   $LIST_PARAMS{TP}=$line->[0];

 	   my $ulist = $users->list({ 
         ACTIVATE => "<=$DATE",
         EXPIRE => ">$DATE",
         DISABLE => '0',
         TP => $line->[0]
 	   	 });
#u.id, u.fio, if(acct.id IS NULL, u.deposit, acct.deposit), u.credit, tp.name, u.disable, 
#      u.uid, u.account_id, u.email, u.tp_id, u.activate, u.expire


     foreach my $u (@$ulist) {
          my %user = (
            ACCOUNT_ID => $u->[7],
            UID => $u->[6],
            BILL_ID => $u->[12]   
           );

        if ($u->[10] eq '0000-00-00' and $d == 1) {
#          print " $u->[0] $line->[6] $u->[2] $u->[3] $u->[10] - $u->[11]\n"; 	
          if($line->[4] > 0 
              || $conf{negative_deposit} eq 'yes'
              || $u->[2] + $u->[3] > 0 ) {
            $fees->take(\%user, $line->[6], { DESCRIBE => "$_MONTH_FEE" } );  
           }
         }
        elsif($u->[10] ne '0000-00-00') {
          my ($activate_y, $activate_m, $activate_d)=split(/-/, $u->[10], 3);
          $activate_m--;
          my $active_unixtime =  mktime(0, 0, 0, $activate_d, $activate_m, $activate_y - 1900, 0, 0, 0);

          if ($date_unixtime - $active_unixtime > 30 * 86400) {
            #my $aa = (strftime "%Y-%m-%d", localtime($active_unixtime));
            $fees->take(\%user, $line->[7], { DESCRIBE => "$_MONTH_FEE" } );
            $users->change($u->[6], { ACTIVATE => $DATE } );
           }
#          print "   $u->[0] $line->[6] $u->[2] $u->[3] $u->[10] - $u->[11]\n"; 	
         }

      }

 	  }
  }
}


#**********************************************************
# user_warnings
# 
#**********************************************************
sub voip_users_warning_messages {

my %LIST_PARAMS = (USERS_WARNINGS => 'y' ) ;
my $list = $Voip->list( { %LIST_PARAMS } );

$ADMIN_REPORT{USERS_WARNINGS} = sprintf("%-14s| %4s|%-20s| %9s| %8s|\n", $_LOGIN, 'TP', $_VARIANT, $_DEPOSIT, $_CREDIT).
   "---------------------------------------------------------------\n";
return 0 if ($Dv->{TOTAL} < 1);
my %USER_INFO = ();

foreach my $line (@$list) {
  #u.id, u.email, u.tp_id, u.credit, u.deposit, tp.name, tp.uplimit

  $USER_INFO{LOGIN}=$line->[0];
  $USER_INFO{TP_NAME}=$line->[5];
  $USER_INFO{TP_ID}=$line->[2];
  $USER_INFO{DEPOSIT}=$line->[4];
  $USER_INFO{CREDIT}=$line->[3];
  
  my $email = ((! defined($line->[1])) || $line->[1] eq '') ? "$line->[0]\@$conf{USERS_MAIL_DOMAIN}" : "$line->[1]";
  
 
  $ADMIN_REPORT{USERS_WARNINGS} .= sprintf ("%-14s| %4d|%-20s| %9.4f| %8.2f|\n", 
  $USER_INFO{LOGIN}, $USER_INFO{TP_ID}, $USER_INFO{TP_NAME},  $USER_INFO{DEPOSIT}, $USER_INFO{CREDIT});
  
  my $message = $html->tpl_show(_include('dv_users_warning_messages', 'Dv'), \%USER_INFO, { notprint => 'yes' });

  sendmail("$conf{ADMIN_MAIL}", "$email", "Попередження сервера статистики.", 
              "$message", "$conf{MAIL_CHARSET}", "2 (High)");
}

$ADMIN_REPORT{USERS_WARNINGS} .= "---------------------------------------------------------------
$_TOTAL: $Dv->{TOTAL}\n";


}


#**********************************************************
# voip_gk_console
#**********************************************************
sub voip_gk_console {

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



my $list = $nas->list({ TYPE => 'gnugk'});
my $table = $html->table({ caption => "$_NAS",
	                         width   => '100%',
                           border  => 1,
                           title   => ["#", "$_NAME", 'NAS-Identifier',  'IP' ],
                           cols_align => ['right', 'left', 'left', 'right'],
                           qs      => $pages_qs
                          });

my ($host, $user, $password);
foreach my $line (@$list) {
    if($line->[0] eq $FORM{NAS_ID}) {
    	$table->{rowcolor}=$_COLORS[4];
     }
    else {
  	  undef($table->{rowcolor});
     }

    $table->addrow($html->button("$line->[0]", "index=$index&NAS_ID=$line->[0]"),  
     $line->[1], 
     $line->[2], 
     $line->[3]);
  }
print $table->show();



if ($FORM{NAS_ID}){

 my %gk_commands = (
  help                   => 'help',
  unregisteralias        => 'unregisteralias',
  PrintAllRegistrations  => 'PrintAllRegistrations, r, ? - Show all registered endpoints',
  PrintAllRegistrationsVerbose => 'PrintAllRegistrationsVerbose, rv, ?? - Show details of all registered endpoints',
  PrintCurrentCalls        => "PrintCurrentCalls, c, ! - Show all current calls using the same ACF syntax as in call establishment. ",
  PrintCurrentCallsVerbose => "PrintCurrentCallsVerbose, cv, !!  - Show details of all current calls.",
  Find                     => "Find, f - Find a registered endpoint by an alias or a prefix. ",
  FindVerbose              => "FindVerbose, fv - Find details of a registered endpoint by an alias or a prefix. ",
  UnregisterIP             => "Forcedly unregister an endpoint by IP and call signalling port. ",
  UnregisterAllEndpoints   => "Forcedly unregister all registered endpoints",


  who                     => 'who',
  statistics              => 'statistics',
  shutdown                => 'shutdown',
  debug                   => 'debug',
  disconnectalias         => 'disconnectalias',
  disconnectcall          => 'disconnectcall',
  disconnectendpoint      => 'disconnectendpoint',
  disconnectip            => 'disconnectip',
  disconnectsession       => 'disconnectsession',
  version                 => 'version',
  reload                  => 'reload',
  
 );


  if(length($FORM{command})>0){
    $nas->info({ NAS_ID => $FORM{NAS_ID}});
    my @commands = ();
 
    require 'Abills/nas.pl';
    push @commands, "login:\t$nas->{NAS_MNG_USER}";
    push @commands, "assword:\t$nas->{NAS_MNG_PASSWORD}";
    push @commands, ";\t$FORM{command}";
    push @commands, ";\tquit";

    my $result = telnet_cmd("$nas->{NAS_MNG_IP_PORT}", \@commands, { debug => 1 });
    my $total=0;
    my @rows = split(/\n/, $result);
    my @registred = ();

    
   if($FORM{command} =~ /\!|CurrentCalls/) {
    	my $table = $html->table({ width      => '100%',
                                 border     => 1,
                                 title      => ['NUMBER', 'ACF', 'Caller_IP:Port', 'Caller_EPID', 'CRV', 'DestinationInfo', 'SrcInfo', 'IsAnswered', '-'],
                                 cols_align => ['right', 'center', 'right', 'left', 'left', 'center'],
                                 qs         => $pages_qs,
                                 caption    => 'Associated'
                                  } );
 
     
     my @rows = split(/\n/, $result);

     foreach my $line (@rows) {

       if($line =~ /Dial/) {
         #print "#      Caller_Aliases|Callee_Aliases|Bandwidth|Connected_Time <r>";
         my @registred = split(/\|/, $line);
         $table->addrow(@registred);
         $total++;
        }
       elsif($line =~ /ACF/) {
         my @registred = split(/\|/, $line);
         #ACF|Caller_IP:Port|Caller_EPID|CRV|DestinationInfo|SrcInfo|IsAnswered;
         #ACF|Callee_IP:Port|Callee_EPID|CRV|DestinationInfo|SrcInfo|IsAnswered;
         $table->addrow('&nbsp;', @registred, 
          "(". $html->button("H", "index=$index&NAS_ID=$FORM{NAS_ID}&command=disconnectcall+$registred[4]", 
             { TITLE => 'Hangup'} ). ')');
        }
      }
     print $table->show();

     $table = $html->table( { caption  => 'Commands',
     	                        width    => '100%',
                              cols_align => ['right', 'right'],
                              rows => [ ["$_TOTAL:", "<b>$total</b>" ] ]
                               } );

     print $table->show();
#CurrentCalls 
#Call No. 1 | CallID 06 20 60 00 00 60 40 10 00 00 00 0a f4 53 db fd | 5 | 175 
#Dial 600:dialedDigits 
#ACF|192.168.101.23:2832|9868_ag1|8354|600:dialedDigits|101:dialedDigits|false; 
#ACF|192.168.101.18:1720|9870_ag1|41122|600:dialedDigits|101:dialedDigits|true; 
#Number of Calls: 1 Active: 0 From Neighbor: 0 From Parent: 0 

     }
    elsif($FORM{command} =~ /\?|PrintAllRegistrations$/) {
    	my $table = $html->table({ width => '100%',
                                 border => 1,
                                 title => ["#", "IP", 'NUMBER',  "$_TYPE", "ID", ''],
                                 cols_align => ['right', 'right', 'left', 'center', 'left', 'center'],
                                 qs => $pages_qs,
                                 caption => 'Associated'
                                  } );
 
     
     foreach my $line (@rows) {
       if($line =~ /RCF/) {
         @registred = split(/\|/, $line);
         push @registred, "(". $html->button('H', "index=$index&NAS_ID=$FORM{NAS_ID}&command=UnregisterIP+$registred[1]", 
           { TITLE => 'Hangup'}). ")";
         $table->addrow(@registred);
        }
      }
     print $table->show();

     $table = $html->table( { width => '100%',
                                cols_align => ['right', 'right'],
                                rows => [ ["$_TOTAL:", "<b>$total</b>" ] ]
                               } );
     print $table->show();
     }
    else {
      $result =~s/\n/<br>/g;
      $html->message('info', $_INFO, "$result");
     }
  }

print  $html->form_main({ CONTENT => $html->form_input('command', "$FORM{command}"),
  	                      HIDDEN  => { index   => "$index",
  	                      	           NAS_ID  => "$FORM{NAS_ID}"  
  	                      	          },
	                        SUBMIT  => { go   => "$_SHOW"} 
	                        });

 $table = $html->table({ caption => 'Commands',
  	                      width => '100%',
                          border => 1,
                          title => ["_COMMAND", "_HELP"],
                          cols_align => ['left', 'left']
                         });
    
  foreach my $k (sort keys %gk_commands) {
     $table->addrow($html->button("$k", "index=$index&NAS_ID=$FORM{NAS_ID}&command=$k"), $gk_commands{$k});
   }
  print $table->show();

}
	
}



#***********************************************************
# voip_sheduler
#***********************************************************
sub voip_sheduler {
	my ($type, $action, $uid)=@_;

  my $user = $Voip->user_info($uid);  	
  if ($type eq 'tp') {
    $Voip->user_change({UID   => $uid, 
    	                  TP_ID => $action });
   }

}



#***********************************************************
# voip_report
#***********************************************************
sub voip_report {
	my ($type, $attr)=@_;
  my $REPORT = "Module: Voip\n";
  
  %LIST_PARAMS = %{$attr->{LIST_PARAMS}} if (defined($attr->{LIST_PARAMS}));

 
  return $REPORT;
}


1

