#!/usr/local/bin/perl
# Periodic payments web interface
#

use Abon;
use Fees;

my $Abon = Abon->new($db, $admin, \%conf);
my $fees = Fees->new($db, $admin, \%conf);
my @PERIODS = ($_DAY, $_MONTH, $_QUARTER, $_SIX_MONTH, $_YEAR);

#*******************************************************************
# Delete user from module
# abon_user_del()
#*******************************************************************
sub abon_user_del {
  my ($uid, $attr) = @_;

  $Abon->{UID} = $uid;
  $Abon->del({ UID => $uid });

  return 0;
}

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

  my $message = '';
  if ($FORM{change} || $FORM{add}) {
    $FORM{QUICK} = 1;
    load_module('Docs', $html);

    $users->pi({ UID => $users->{UID} || $FORM{UID} || $LIST_PARAMS{UID} });
    my @new_arr  = ();
    my @ids_arr  = split(/, /, $FORM{IDS});
    my %ids_hash = ();
    my @add_arr  = ();
    my @del_arr  = ();

    foreach my $k (@ids_arr) {
      $ids_hash{$k} = 1;
    }

    my $list = $Abon->user_tariff_list($FORM{UID});

    foreach my $line (@$list) {
      if ($ids_hash{ $line->[0] } && $line->[5]) {
        delete $ids_hash{ $line->[0] };
      }
      elsif ($line->[5]) {
        push @del_arr, $line->[0];
      }
    }

    @new_arr = keys %ids_hash;
    if ($#new_arr > -1) {
      my $list = $Abon->tariff_list({ IDS => join(', ', @new_arr) });
      foreach my $line (@$list) {
        my ($Y, $M, $D) = split(/-/, $FORM{ 'DATE_' . $line->[7] }, 3);
        my $seltime = POSIX::mktime(0, 0, 0, $D, ($M - 1), ($Y - 1900));

        if (($users->{CREDIT} + $users->{DEPOSIT}) > $line->[1] || $line->[3] || time() < $seltime) {
          $Abon->{TP_INFO}->{PERIOD_ALIGNMENT} = $line->[5] || 0;
          $Abon->{TP_INFO}->{MONTH_FEE}        = $line->[1];
          $Abon->{TP_INFO}->{TP_ID}            = $line->[7];
          $Abon->{TP_INFO}->{NAME}             = $line->[0];
          $Abon->{COMMENTS}                    = $FORM{ 'COMMENTS_' . $line->[7] };
          $Abon->{TP_INFO}->{FEES_TYPE}        = $line->[8] || 1;
          $Abon->{TP_INFO}->{CREATE_ACCOUNT}   = $line->[9];
          $ext_cmd                             = $line->[10];
          $activate_notification               = $line->[11];
          $Abon->{TP_INFO}->{DISCOUNT}         = $line->[13];

          if ($FORM{ 'DATE_' . $Abon->{TP_INFO}->{TP_ID} } && $FORM{ 'DATE_' . $Abon->{TP_INFO}->{TP_ID} } ne '0000-00-00') {
            $FORM{ 'PERIOD_' . $Abon->{TP_INFO}->{TP_ID} } = $line->[2];
            push @add_arr, $line->[7];
            next;
          }

          my %PARAMS = (
            DESCRIBE => "$_ABON: ($line->[7]) " . (($FORM{ 'COMMENTS_' . $line->[7] }) ? $FORM{ 'COMMENTS_' . $line->[7] } : "$line->[0]"),
            METHOD => $Abon->{TP_INFO}->{FEES_TYPE}
          );

          if ($FORM{ 'DISCOUNT_' . $Abon->{TP_INFO}->{TP_ID} }) {
            $Abon->{TP_INFO}->{MONTH_FEE} = $Abon->{TP_INFO}->{MONTH_FEE} * ((100 - $FORM{ 'DISCOUNT_' . $Abon->{TP_INFO}->{TP_ID} }) / 100);
          }
          elsif ($Abon->{TP_INFO}->{DISCOUNT} && $users->{REDUCTION} > 0) {
            $Abon->{TP_INFO}->{MONTH_FEE} = $Abon->{TP_INFO}->{MONTH_FEE} * ((100 - $users->{REDUCTION}) / 100);
          }

          if (time() < $seltime) {

          }
          elsif ($line->[2] == 1 && $Abon->{TP_INFO}->{PERIOD_ALIGNMENT} == 1) {
            $Abon->{ACTIVATE} = $users->{ACTIVATE};
            $message .= abon_get_month_fee($Abon);
          }
          elsif ($FORM{ 'DISCOUNT_' . $Abon->{TP_INFO}->{TP_ID} } < 100) {
            $fees->take($users, $Abon->{TP_INFO}->{MONTH_FEE}, {%PARAMS});
            if ($fees->{errno}) {
              $html->message('err', "$_FEES : $_ERROR", "-[$fees->{errno}] $fees->{errstr}");
            }
            else {
              $message .= "$_ABON: $Abon->{TP_INFO}->{MONTH_FEE} ($Abon->{TP_INFO}->{TP_ID})\n";
            }
          }

          if ($ext_cmd) {
            my $cmd = $ext_cmd;
            $cmd .= " ACTION=ALERT UID=$user{UID} TP_ID=$tp_id COMMENTS=\"$comment\" SUM=$sum";
            $ret = system($cmd);
          }

          if ($Abon->{TP_INFO}->{CREATE_ACCOUNT} && $FORM{ 'CREATE_DOCS_' . $Abon->{TP_INFO}->{TP_ID} }) {

            #$LIST_PARAMS{UID}= $users->{UID};
            delete($FORM{IDS});
            $FORM{SUM}        = $Abon->{TP_INFO}->{MONTH_FEE};
            $FORM{UID}        = $users->{UID};
            $FORM{create}     = 1;
            $FORM{CUSTOMER}   = '-';
            $FORM{ORDER}      = "[$Abon->{TP_INFO}->{TP_ID}] $Abon->{TP_INFO}->{NAME} $Abon->{COMMENTS}";
            $FORM{SEND_EMAIL} = $FORM{ 'SEND_DOCS_' . $Abon->{TP_INFO}->{TP_ID} } || undef;
            docs_invoice({ QUITE => 1 });
          }

          if ($activate_notification) {
            my $message = $html->tpl_show(_include('abon_notification3', 'Abon'), $Abon, { OUTPUT2RETURN => 1 });
            sendmail("$conf{ADMIN_MAIL}", "$email", "$conf{WEB_TITLE} - $Abon->{TP_INFO}->{NAME} $Abon->{COMMENTS}", "$message", "$conf{MAIL_CHARSET}", '', {});
          }

          #$Abon->user_tariff_update({ UID   => "$users->{UID}",
          #                            TP_ID => "$line->[6]",
          #                            DATE  => $DATE,
          #                          });

          push @add_arr, $line->[7];
        }
        else {
          $html->message('err', "$_ABON : $_ERROR", "$_TARIF_PLAN: [$line->[7]] $line->[0]\n$ERR_SMALL_DEPOSIT");
          $FORM{ 'error_' . $line->[7] }          = 1;
          $FORM{ 'error_comments_' . $line->[7] } = $ERR_SMALL_DEPOSIT;
          if ($attr->{REGISTRATION}) {
            return 1;
          }
        }
      }
    }

    delete $FORM{IDS};
    $Abon->user_tariff_change(
      {
        %FORM,
        IDS => join(', ', @add_arr),
        DEL => join(', ', @del_arr)
      }
    );

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

    $html->message('info', $_ABON, $message) if ($message);
    return 0 if ($attr->{QUITE} || $attr->{REGISTRATION});
  }

  my $list  = $Abon->user_tariff_list($FORM{UID});
  my $table = $html->table(
    {
      width   => '100%',
      caption => "$_ABON",
      title   => [ '-', $_NAME, $_COMMENTS, $_SUM, $_PERIOD, $_LAST_ABON, $_NEXT_ABON, "$_REDUCTION (%)", "$_CREATE $_DOCS", "$_SEND_NOTIFICATION" ],
      cols_align => [ 'left', 'left', 'left', 'right', 'left', 'right', 'right' ],
      qs         => $pages_qs,
      ID         => 'USER_ABON',
      class      => 'form'
    }
  );

  my @ids = ();
  if ($FORM{step}) {
    @ids = split(/, /, $FORM{IDS});
  }

  foreach my $line (@$list) {
    my $describe = $line->[2] || $FORM{ 'COMMENTS_' . $line->[0] };
    my $state = ($#ids > -1) ? in_array($line->[0], \@ids) : $line->[8];

    if ($FORM{ 'error_' . $line->[0] }) {
      $table->{rowcolor} = 'red';
    }
    else {
      $table->{rowcolor} = undef;
    }

    $table->addrow(
      $line->[0]
      . $html->form_input(
        'IDS',
        "$line->[0]",
        {
          TYPE  => 'CHECKBOX',
          STATE => ($state == 1) ? 1 : undef
        }
      ),
      ($permissions{5}) ? $html->button($line->[1], "index=" . get_function_index('abon_tariffs') . '&ABON_ID=' . $line->[0]) : "$line->[1]",
      $html->form_input('COMMENTS_' . $line->[0], $describe || $FORM{ 'error_comments_' . $line->[0] }, { SIZE => 40 }),
      "$line->[3]",
      $PERIODS[ $line->[4] ],
      "$line->[5]",
      ($line->[6]) ? "$line->[6]" : $html->date_fld2('DATE_' . $line->[0], { FORM_NAME => 'ABON_USER_TPS', WEEK_DAYS => \@WEEKDAYS, MONTHES => \@MONTHES, DATE => '0000-00-00' }),
      $html->form_input('DISCOUNT_' . $line->[0], "$line->[7]", { SIZE => '8' }),
      $html->form_input(
        'CREATE_DOCS_' . $line->[0],
        "1",
        {
          TYPE  => 'CHECKBOX',
          STATE => ($line->[12]) ? 1 : undef
        }
      ),
      $html->form_input(
        'SEND_DOCS_' . $line->[0],
        "1",
        {
          TYPE  => 'CHECKBOX',
          STATE => ($line->[13]) ? 1 : undef
        }
      )
    );
  }

  my $action = "";
  if ($attr->{ACTION}) {
    $action = $html->br() . $html->form_input('finish', "$_REGISTRATION_COMPLETE", { TYPE => 'submit' }) . ' ' . $html->form_input('back', "$_BACK", { TYPE => 'submit' }) . ' ' . $html->form_input('next', "$_NEXT", { TYPE => 'submit' });
  }
  else {
    $action = $html->form_input('change', "$_CHANGE", { TYPE => 'submit' });
  }

  $table->{extra}    = 'colspan=10 align=center';
  $table->{rowcolor} = 'even';
  $table->addrow($action);

  print $html->form_main(
    {
      CONTENT => $table->show(),
      HIDDEN  => {
        index => "$index",
        UID   => $FORM{UID},
        step  => $FORM{step}
      },
      NAME => 'ABON_USER_TPS',

      #SUBMIT  => \%ACTION
    }
  );

}

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

  if ($attr->{ABON_ID}) {
    $LIST_PARAMS{ABON_ID} = $FORM{ABON_ID};
  }
  elsif ($FORM{ABON_ID}) {
    $FORM{subf} = $index;
    abon_tariffs();
    return 0;
  }

  $LIST_PARAMS{COMPANY_ID} = $FORM{COMPANY_ID} if ($FORM{COMPANY_ID});

  my $list  = $Abon->user_list({%LIST_PARAMS});
  my $table = $html->table(
    {
      width   => '100%',
      caption => "$_ABON - $_USERS",
      title   => [ $_LOGIN, $_FIO, $_TARIF_PLAN, "$_COMMENTS", $_SUM, $_PERIOD, $_LAST_ABON, $_NEXT_ABON ],
      cols_align => [ 'left', 'right', 'left', 'right' ],
      qs         => $pages_qs,
      pages      => $Abon->{TOTAL},
      ID         => "ABON_USERS"
    }
  );

  my $delete = '';
  foreach my $line (@$list) {
    $table->addrow(user_ext_menu($line->[8], $line->[0]), "$line->[1]", $line->[2], $line->[3], $line->[4], $PERIODS[ $line->[5] ], $line->[6], $line->[7]);
  }
  print $table->show();

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

}

#*******************************************************************
# Change user variant form
# abon_tariffs()
#*******************************************************************
sub abon_tariffs {

  $Abon->{ACTION}     = 'add';
  $Abon->{ACTION_LNG} = $_ADD;
  my @Payment_Types = ($_PREPAID, $_POSTPAID);

  if ($FORM{add}) {
    if (!$FORM{SUM} || $FORM{SUM} < 0) {
      $html->message('err', $_ERROR, "$ERR_WRONG_SUM");
    }
    else {
      $Abon->tariff_add({%FORM});
      if (!$Abon->{errno}) {
        $html->message('info', $_INFO, "$_ADDED");
      }
    }
  }
  elsif ($FORM{ABON_ID}) {
    $Abon = $Abon->tariff_info($FORM{ABON_ID});

    if (!$Abon->{errno}) {

      #$html->message('info', $_INFO, "$_CHANGING");
      $FORM{PERIOD} = $Abon->{PERIOD} if (!defined($FORM{PERIOD}));
      $Abon->{ACTION}     = 'change';
      $Abon->{ACTION_LNG} = $_CHANGE;
    }

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

    $pages_qs .= "&ABON_ID=$FORM{ABON_ID}";
    $LIST_PARAMS{ABON_ID} = $FORM{ABON_ID};
    my %F_ARGS = (ABON_ID => $Abon);

    $Abon->{NAME_SEL} = $html->form_main(
      {
        CONTENT => $html->form_select(
          'ABON_ID',
          {
            SELECTED => $Abon->{ID} || $FORM{ABON_ID},
            SEL_MULTI_ARRAY   => $Abon->tariff_list(),
            MULTI_ARRAY_KEY   => 7,
            MULTI_ARRAY_VALUE => 0,

            #NO_ID             => 1
          }
        ),
        HIDDEN => { index => "$index" },
        SUBMIT => { show  => "$_SHOW" }
      }
    );

    func_menu(
      {
        'ID'   => $Abon->{ID},
        $_NAME => $Abon->{NAME_SEL}
      },
      {},
      { f_args => {%F_ARGS} }
    );

    if ($FORM{subf}) {
      return 0;
    }
    elsif ($FORM{change}) {
      $Abon->tariff_change({%FORM});
      if (!$Abon->{errno}) {
        $html->message('info', $_INFO, "$_CHANGED");
      }
    }
  }
  elsif (defined($FORM{del}) && $FORM{is_js_confirmed}) {
    $Abon->tariff_del($FORM{del});
    if (!$Abon->{errno}) {
      $html->message('info', $_INFO, "$_DELETED");
    }
  }

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

  $Abon->{PERIOD_SEL} = $html->form_select(
    'PERIOD',
    {
      SELECTED     => $FORM{PERIOD},
      SEL_ARRAY    => \@PERIODS,
      ARRAY_NUM_ID => 1

    }
  );

  $Abon->{PAYMENT_TYPE_SEL} = $html->form_select(
    'PAYMENT_TYPE',
    {
      SELECTED => $Abon->{PAYMENT_TYPE} || $FORM{PAYMENT_TYPE},
      SEL_ARRAY    => [ $_PREPAID, $_POSTPAID ],
      ARRAY_NUM_ID => 1
    }
  );

  $Abon->{PRIORITY} = $html->form_select(
    'PRIORITY',
    {
      SELECTED => $Abon->{PRIORITY} || 0,
      SEL_ARRAY    => [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 13, 14, 15 ],
      ARRAY_NUM_ID => 1
    }
  );

  my @ACCOUNT_PRIORITY = ($_MAIN, "$_EXTRA $_BILL", "$_MAIN, $_EXTRA $_BILL");

  $Abon->{ACCOUNT_SEL} = $html->form_select(
    'ACCOUNT',
    {
      SELECTED => $Abon->{ACCOUNT} || 0,
      SEL_ARRAY    => \@ACCOUNT_PRIORITY,
      ARRAY_NUM_ID => 1
    }
  );

  $Abon->{PERIOD_ALIGNMENT} = ($Abon->{PERIOD_ALIGNMENT}) ? 'checked' : '';
  $Abon->{NONFIX_PERIOD}    = ($Abon->{NONFIX_PERIOD})    ? 'checked' : '';

  if ($conf{EXT_BILL_ACCOUNT}) {
    my $checked = ($Abon->{EXT_BILL_ACCOUNT}) ? ' checked' : '';
    $Abon->{EXT_BILL_ACCOUNT} = "<tr><td>$_EXTRA $_BILL:</td><td><input type='checkbox' name='EXT_BILL_ACCOUNT' value='1' $checked></td></tr>\n";
  }
  else {
    $Abon->{EXT_BILL_ACCOUNT} = '';
  }

  push @FEES_METHODS, @EX_FEES_METHODS if (@EX_FEES_METHODS);

  my %FEES_METHODS = %{ get_fees_types({}) };

  $Abon->{FEES_TYPES_SEL} = $html->form_select(
    'FEES_TYPE',
    {
      SELECTED => $Abon->{FEES_TYPE},
      SEL_HASH => { '' => '', %FEES_METHODS },
      NO_ID    => 1,
      SORT_KEY => 1
    }
  );

  $Abon->{FEES_TYPE}             = ($Abon->{FEES_TYPE})             ? 'checked' : '';
  $Abon->{NOTIFICATION_ACCOUNT}  = ($Abon->{NOTIFICATION_ACCOUNT})  ? 'checked' : '';
  $Abon->{ALERT}                 = ($Abon->{ALERT})                 ? 'checked' : '';
  $Abon->{ALERT_ACCOUNT}         = ($Abon->{ALERT_ACCOUNT})         ? 'checked' : '';
  $Abon->{CREATE_ACCOUNT}        = ($Abon->{CREATE_ACCOUNT})        ? 'checked' : '';
  $Abon->{ACTIVATE_NOTIFICATION} = ($Abon->{ACTIVATE_NOTIFICATION}) ? 'checked' : '';
  $Abon->{VAT}                   = ($Abon->{VAT})                   ? 'checked' : '';
  $Abon->{DISCOUNT}              = ($Abon->{DISCOUNT})              ? 'checked' : '';

  $html->tpl_show(_include('abon_tp', 'Abon'), $Abon);

  my $list  = $Abon->tariff_list({%LIST_PARAMS});
  my $table = $html->table(
    {
      width   => '100%',
      caption => "$_ABON",
      title   => [ $_NAME, $_SUM, $_PERIOD, $_PAYMENT_TYPE, $_PRIORITY, $_USERS, '-', '-' ],
      cols_align => [ 'left', 'right', 'left', 'right', 'right', 'center', 'center' ],
      qs         => $pages_qs,
      ID         => 'ABON_TARIFFS'
    }
  );

  my $delete = '';
  foreach my $line (@$list) {
    if ($permissions{4}{1}) {
      $delete = $html->button($_DEL, "index=$index&del=$line->[7]", { MESSAGE => "$_DEL $line->[0]?", CLASS => 'del' });
    }
    $table->{rowcolor} = ($FORM{ABON_ID} == $line->[7]) ? $_COLORS[0] : undef;
    $table->addrow(
      $html->button("$line->[0]", "index=$index&ABON_ID=$line->[7]"),
      "$line->[1]",
      $PERIODS[ $line->[2] ],
      $Payment_Types[ $line->[3] ],
      $line->[4],
      $html->button("$line->[6]", "index=" . get_function_index('abon_user_list') . "&ABON_ID=$line->[7]"),
      $html->button("$_CHANGE", "index=$index&ABON_ID=$line->[7]", { CLASS => 'change' }), $delete
    );
  }

  print $table->show();
}

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

  my $debug = $attr->{DEBUG} || 0;
  my $debug_output = '';
  $debug_output .= "ABON: Periodic payments\n" if ($debug > 1);

  $LIST_PARAMS{LOGIN} = $attr->{LOGIN} if ($attr->{LOGIN});
  $LIST_PARAMS{TP_ID} = $attr->{TP_ID} if ($attr->{TP_ID});

  #if (in_array('Docs', \@MODULES) ) {
  $FORM{QUICK} = 1;
  require "Abills/modules/Docs/webinterface";

  # }

  $Abon->{debug} = 1 if ($debug > 7);
  my $list = $Abon->periodic_list({ %LIST_PARAMS, 
  	                                DELETED => 0,
  	                                LOGIN_STATUS => 0 
  	                              });

  my ($y, $m, $d) = split(/-/, $ADMIN_REPORT{DATE}, 3);
  $m--;

  foreach my $line (@$list) {
    my %info = (
      PERIOD    => $line->[0],
      SUM       => $line->[1],
      UID       => $line->[2],
      LOGIN     => $line->[4],
      TP_NAME   => $line->[6],
      DEPOSIT   => $line->[7],
      CREDIT    => $line->[8],
      TP_ID     => $line->[10],
      COMMENT   => $line->[12],
      ABON_DATE => $line->[14],
      BILL_ID   => ($line->[15]) ? $line->[16] : $line->[3],
      FEES_TYPE => $line->[18] || 1,
      CREATE_ACCOUNT => $line->[19],
      EMAIL          => $line->[25],
      ALERT          => $line->[23],
      DATETIME       => "$ADMIN_REPORT{DATE} $TIME",
      NEXT_ABON_FEES => $line->[30],
      DISCOUNT       => $line->[31],
      CREATE_DOCS    => $line->[32],
      SEND_DOCS      => $line->[33],
    );

    my $notification1            = $line->[20];
    my $notification2            = $line->[21];
    my $notification_account     = $line->[22];
    my $alert_account            = $line->[24];
    my $email                    = $line->[25];
    my $notification1_account_id = $line->[26];
    my $ext_cmd                  = $line->[27];
    my $activate_notification    = $line->[28];
    my $vat                      = $line->[29];

    if ($debug > 5) {
      $debug_output .= "UID: $info{UID} TP_ID: $info{TP_ID} SUM: $info{SUM} DEPOSIT: " . (($info{DEPOSIT}) ? $info{DEPOSIT} : 'Undefined') . " NOT1: $notification1 NOT2: $notification2 ABON: $info{ABON_DATE}\n";
    }

    if (defined($info{DEPOSIT})) {
      my %user = (
        UID     => $info{UID},
        BILL_ID => $info{BILL_ID}
      );

      my %PARAMS = (
        DESCRIBE => "$_ABON: ($info{TP_ID}) $info{TP_NAME}",
        METHOD   => $info{FEES_TYPE},
        DATE     => $ADMIN_REPORT{DATE}
      );

      $line->[8] = 0 if (!$line->[8]);
      $PARAMS{DESCRIBE} = "$_ABON: $info{TP_NAME}. $info{COMMENT}" if ($info{COMMENT});
      $abon_date = $ADMIN_REPORT{DATE} if (!$abon_date && $line->[0] == 1 && $d == 1);
      $info{SUM} = $info{SUM} * (100 - $info{DISCOUNT}) / 100 if ($info{DISCOUNT} > 0);

      #Get abon
      if ($ADMIN_REPORT{DATE} eq $info{ABON_DATE} || $info{PERIOD} == 0) {
        if ($line->[8] && ($info{DEPOSIT} + $info{CREDIT} > 0 || $line->[11] == 1) && $line->[9] == 0) {

          $fees->take(\%user, $info{SUM}, {%PARAMS}) if ($info{DISCOUNT} < 100);
          $Abon->user_tariff_update(
            {
              UID   => "$info{UID}",
              DATE  => $ADMIN_REPORT{DATE},
              TP_ID => "$info{TP_ID}"
            }
          );

          if ($info{CREATE_ACCOUNT} && $info{CREATE_DOCS}) {
            $FORM{SUM}        = $info{SUM};
            $FORM{UID}        = $user{UID};
            $FORM{create}     = 1;
            $FORM{CUSTOMER}   = '-';
            $FORM{ORDER}      = "$info{TP_NAME} $info{COMMENT}";
            $FORM{SEND_EMAIL} = $info{SEND_DOCS} || 0;
            docs_invoice({ QUITE => 1 });
          }

          if ($ext_cmd) {
            my $cmd = $ext_cmd;
            $cmd .= " ACTION=ACTIVE UID=$user{UID} TP_ID=$info{TP_ID} COMMENTS=\"$info{COMMENT}\" SUM=$info{SUM}";
            $ret = system($cmd);
          }

          if ($activate_notification && $info{SEND_DOCS}) {
            my $message = $html->tpl_show(_include('abon_notification3', 'Abon'), { %$Abon, %info }, { OUTPUT2RETURN => 1 });
            sendmail("$conf{ADMIN_MAIL}", "$email", "$conf{WEB_TITLE} - $info{TP_NAME} $info{COMMENT}", "$message", "$conf{MAIL_CHARSET}", '', {});
          }

          $debug_output .= "$user{UID} TP_ID: $info{TP_ID} SUM: $info{SUM} ACCOUNT: " . (($info{CREATE_ACCOUNT}) ? "ACCOUNT SEND_EMAIL: $email" : '') . (($activate_notification) ? "NOTIFICATION: $email" : '') . "\n" if ($debug > 0);
        }

        #Send Alert
        elsif ($ADMIN_REPORT{DATE} eq $info{ABON_DATE} && $info{SEND_DOCS}) {
          $debug_output .= "$user{UID} SUM: TP_ID: $info{TP_ID} $info{SUM} ACCOUNT: $info{CREATE_ACCOUNT} Alert EMAIL: $email\n" if ($debug > 0);

          my $message = $html->tpl_show(_include('abon_alert', 'Abon'), { %$Abon, %info }, { OUTPUT2RETURN => 1 });
          my $attach;
          if ($alert_account && $info{CREATE_DOCS}) {
            $FORM{SUM}      = $info{SUM};
            $FORM{UID}      = $user{UID};
            $FORM{create}   = 1;
            $FORM{CUSTOMER} = '-';
            $FORM{ORDER}    = "$info{TP_NAME} $info{COMMENT}";
            my $content = docs_invoice({ QUITE => 1, OUTPUT2RETURN => 1 });

            if ($info{SEND_DOCS}) {
              $attach = [
                {
                  CONTENT      => $content,
                  CONTENT_TYPE => 'Content-type: application/pdf',
                  FILENAME     => 'invoice.pdf'
                }
              ];
            }

            $Abon->user_tariff_update(
              {
                UID                     => "$user{UID}",
                NOTIFICATION            => 1,
                DATE                    => $ADMIN_REPORT{DATE},
                NOTIFICATION_ACCOUNT_ID => $FORM{ACCOUN_ID},
                TP_ID                   => "$info{TP_ID}"
              }
            );
          }

          sendmail("$conf{ADMIN_MAIL}", "$email", "$conf{WEB_TITLE} - $info{TP_NAME} $info{COMMENT}", "$message", "$conf{MAIL_CHARSET}", '', { ATTACHMENTS => $attach });

          if ($ext_cmd) {
            my $cmd = $ext_cmd;
            $cmd .= " ACTION=ALERT UID=$user{UID} TP_ID=$info{TP_ID} COMMENTS=\"$info{COMMENT}\" SUM=$info{SUM}";
            $ret = system($cmd);
          }
        }
      }

      #Notification Section
      elsif ($notification1 eq $ADMIN_REPORT{DATE}) {
        my $message = $html->tpl_show(_include('abon_notification1', 'Abon'), { %$Abon, %info }, { OUTPUT2RETURN => 1 });
        my $attach;
        $debug_output .= "$user{UID} TP_ID: $info{TP_ID} SUM: $info{SUM} ACCOUNT: $info{CREATE_ACCOUNT} Notification 1 EMAIL: $email\n" if ($debug > 0);

        if ($notification_account && $info{CREATE_DOCS}) {
          $LIST_PARAMS{UID} = $user{UID};
          $FORM{SUM}        = $info{SUM};
          $FORM{UID}        = $user{UID};
          $FORM{create}     = 1;
          $FORM{CUSTOMER}   = '-';
          $FORM{ORDER}      = "$info{TP_NAME} $info{COMMENT}";
          $FORM{SEND_EMAIL} = $info{SEND_DOCS} || undef;
          $FORM{pdf}        = $conf{DOCS_PDF_PRINT};
          my $content = docs_invoice({ QUITE => 1, OUTPUT2RETURN => 1 });
          $attach = [
            {
              CONTENT      => $content,
              CONTENT_TYPE => 'Content-type: application/pdf',
              FILENAME     => 'invoice.pdf'
            }
          ];

        }

        $Abon->user_tariff_update(
          {
            UID                     => "$user{UID}",
            NOTIFICATION            => 1,
            DATE                    => $ADMIN_REPORT{DATE},
            NOTIFICATION_ACCOUNT_ID => $FORM{ACCOUNT_ID},
            TP_ID                   => "$info{TP_ID}"
          }
        );

        if ($info{SEND_DOCS}) {
          sendmail("$conf{ADMIN_MAIL}", "$email", "$conf{WEB_TITLE} - $info{TP_NAME} $info{COMMENT}", "$message", "$conf{MAIL_CHARSET}", '', { ATTACHMENTS => $attach });
        }
      }
      elsif ($notification2 eq $ADMIN_REPORT{DATE}) {
        $debug_output .= "$user{UID} TP_ID: $info{TP_ID} SUM: $info{SUM} ACCOUNT: $notification1_account_id Notification 2 EMAIL: $email\n" if ($debug > 0);

        my $message = $html->tpl_show(_include('abon_notification2', 'Abon'), { %$Abon, %info }, { OUTPUT2RETURN => 1 });
        my $attach;

        if ($notification1_account_id && $info{CREATE_DOCS}) {
          $FORM{print}            = $notification1_account_id;
          $FORM{CHECK_PEYMENT_ID} = 1;
          $FORM{pdf}              = $conf{DOCS_PDF_PRINT};
          my $content = docs_invoice({ QUITE => 1, OUTPUT2RETURN => 1 });
          if ($content) {
            $attach = [
              {
                CONTENT      => $content,
                CONTENT_TYPE => 'Content-type: application/pdf',
                FILENAME     => 'invoice.pdf'
              }
            ];
          }
        }

        $Abon->user_tariff_update(
          {
            UID          => "$user{UID}",
            NOTIFICATION => 2,
            DATE         => $ADMIN_REPORT{DATE},
            TP_ID        => "$line->[10]"
          }
        );
        if ($info{SEND_DOCS}) {
          sendmail("$conf{ADMIN_MAIL}", "$email", "$conf{WEB_TITLE} - $info{TP_NAME} $info{COMMENT}", "$message", "$conf{MAIL_CHARSET}", '', { ATTACHMENTS => $attach });
        }
      }

    }
    else {
      print "[ $line->[2] ] $line->[4] - Don't have money account\n";
    }
  }

  $DEBUG .= $debug_output;
  return $debug_output;
}

#**********************************************************
#
#**********************************************************
sub abon_get_month_fee {
  my ($Abon, $attr) = @_;

  my $result_sum = 0;

  my $message = '';

  #Get month fee
  if ($Abon->{TP_INFO}->{MONTH_FEE} > 0) {
    my $sum  = $Abon->{TP_INFO}->{MONTH_FEE};
    my $user = $users->info($Abon->{UID});

    #Current Month
    my ($y,        $m,        $d)        = split(/-/, $DATE,             3);
    my ($active_y, $active_m, $active_d) = split(/-/, $Abon->{ACTIVATE}, 3);
    if (int("$y$m$d") < int("$active_y$active_m$active_d")) {
      return;
    }

    if ($Abon->{TP_INFO}->{PERIOD_ALIGNMENT}) {
      $message = ", $_PERIOD_ALIGNMENT\n";
      my $days_in_month = ($m != 2 ? (($m % 2) ^ ($m > 7)) + 30 : (!($y % 400) || !($y % 4) && ($y % 25) ? 29 : 28));

      if ($Abon->{ACTIVATE} && $Abon->{ACTIVATE} ne '0000-00-00') {
        $days_in_month = ($active_m != 2 ? (($active_m % 2) ^ ($active_m > 7)) + 30 : (!($active_y % 400) || !($active_y % 4) && ($active_y % 25) ? 29 : 28));
        $d = $active_d;
      }

      $conf{START_PERIOD_DAY} = 1 if (!$conf{START_PERIOD_DAY});
      $sum = sprintf("%.2f", $sum / $days_in_month * ($days_in_month - $d + $conf{START_PERIOD_DAY}));
    }

    return 0 if ($sum == 0);

    my $periods = 0;
    if ($active_m > 0 && $active_m < $m) {
      $periods = $m - $active_m;
    }
    elsif ($active_m > 0 && ($active_m >= $m && $active_y < $y)) {
      $periods = 12 - $active_m + $m;
    }

    $message = "$_ABON: " . (($Abon->{COMMENTS}) ? " $Abon->{TP_INFO}->{NAME} $Abon->{COMMENTS}" : " [$Abon->{TP_INFO}->{TP_ID}] $Abon->{TP_INFO}->{NAME} ") . $message . "\n";

    for (my $i = 0 ; $i <= $periods ; $i++) {
      if ($active_m + $i > 12) {
        $active_m = 0;
        $active_y = $active_y + 1;
      }

      $m = sprintf("%.2d", $active_m + $i);

      if ($i > 0) {
        $sum     = $Abon->{TP_INFO}->{MONTH_FEE};
        $message = "$_ABON: $sum ($Abon->{TP_INFO}->{TP_ID})\n";
        $DATE    = "$active_y-$m-01";
        $TIME    = "00:00:00";
      }
      elsif ($Abon->{ACTIVATE} && $Abon->{ACTIVATE} ne '0000-00-00') {
        $DATE = "$active_y-$m-$active_d";
        $TIME = "00:00:00";

        #if ($Abon->{TP_INFO}->{PERIOD_ALIGNMENT}) {
        #  $users->change($Abon->{UID}, { ACTIVATE => '0000-00-00',
        #  UID      => $Abon->{UID} });
        # }
      }

      if ($Abon->{COMMENTS}) {
        $message .= $Abon->{COMMENTS};
      }

      $fees->take(
        $users, $sum,
        {
          DESCRIBE => $message,
          METHOD   => $Abon->{TP_INFO}->{FEES_TYPE},
          DATE     => "$DATE $TIME"
        }
      );

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

  return $message;
}

#**********************************************************
# get services for invoice
#**********************************************************
sub abon_docs {
  my ($attr) = @_;

  my @services = ();
  my $UID      = $FORM{UID} || $attr->{UID};
  my $list     = $Abon->user_tariff_list($UID);
  
  return \@services if ($Abon->{TOTAL} == 0);
  
  foreach my $line (@$list) {
    if ($line->[5]) {
      if ($line->[7] > 0) {
        $line->[3] = $line->[3] * ((100 - $line->[7]) / 100);
      }

      # NAME| ID | SUM
      push @services, "$_ABON: ($line->[0]) " . "$line->[1]" . "|$line->[2]|$line->[3]";
    }
  }

  return \@services;
}

1
