% include( 'elements/edit.html',
              'name'   => 'Billing event definition',
              'table'  => 'part_event',
              'fields' => [
                            'event',
                            { field   => 'eventtable',
                              type    => 'select',
                              options => [ FS::part_event->eventtables ],
                              labels  => $eventtable_labels,
                              onchange => 'eventtable_changed',
                            },
                            { field   => 'agentnum',
                              type    => 'select-agent',
                              disable_empty => $disable_empty_agent,
                            },
                            { field   => 'check_freq',
                              type    => 'select',
                              options => [ '1d', '1m' ],
                              labels  => $check_freq_labels,
                            },
                            { field   => 'disabled',
                              type    => 'checkbox',
                              value   => 'Y',
                            },
                            { type    => 'title',
                              value   => 'Event Conditions',
                            },
                            { field   => 'conditionname',
                              type    => 'selectlayers',
                              options => [ keys %all_conditions ],
                              labels  => \%condition_labels,
                              onchange => 'condition_changed(what);',
                              layer_fields => \%condition_fields,
                              layer_values_callback => $condition_layer_values,
                              html_between       => n_a('action'),
                              m2name_table       => 'part_event_condition',
                              m2name_namecol     => 'conditionname',
                              m2name_label       => 'Condition',
                              m2name_new_default => \@implicit_condition_objs,
                              m2name_error_callback  =>
                                $condition_error_callback,
                              m2name_remove_warnings =>
                                \%condition_remove_warnings,
                              m2name_new_js      => 'condition_repop',
                              m2name_remove_js   => 'condition_add',
                            },
                            { type    => 'title',
                              value   => 'Event Action',
                            },
                            { field   => 'action',
                              type     => 'selectlayers',
                              options  => [ keys %all_actions ],
                              labels   => \%action_labels,
                              onchange => 'action_changed(what);',
                              layer_fields => \%action_fields,
                              layer_values_callback => $action_layer_values,
                              html_between => n_a('action'),
                            },
                          ],
              'labels' => {
                            'eventpart'  => 'Event',
                            'event'      => 'Event name',
                            'eventtable' => 'Type',
                            'agentnum'   => 'Agent',
                            'check_freq' => 'Check frequency',
                            'disabled'   => 'Disable event',
                            'conditionname' => 'Add new condition',
                            #'weight',
                            'action'     => 'Action',
                          },
              'viewall_dir' => 'browse',
              'new_callback' => sub { #start empty for new events only
                my( $cgi, $object, $fields_listref ) = @_; 
                unshift @{ $fields_listref->[1]{'options'} }, '';
              },
              'error_callback' => $error_callback,
              'agent_virt'       => 1,
              'agent_null_right' => 'Edit global billing events',
          )
%>
<%once>
#misc (eventtable, check_freq)
my $eventtable_labels = FS::part_event->eventtable_labels;
$eventtable_labels->{''} = '** Select type **';
my $check_freq_labels = FS::part_event->check_freq_labels;
#conditions
tie my %all_conditions, 'Tie::IxHash', 
  '' => { 'description' => '*** Select new condition ***', },
  FS::part_event_condition->conditions();
my %condition_labels = map { $_ => $all_conditions{$_}->{'description'} }
                           keys %all_conditions;
#my %condition_fields = map { $_ => $all_conditions{$_}->{option_fields} } 
#                           keys %all_conditions;
my %condition_fields = map { my $c = $_;
                             tie my %opts, 'Tie::IxHash',
                               @{ $all_conditions{$c}->{'option_fields'} || []};
                             %opts = ( map { ( "$c.$_" => $opts{$_} ); }
                                           keys %opts
                                     );
                             ( $c => [ %opts ] );
                           } 
                           keys %all_conditions;
my @implicit_conditions = sort { $all_conditions{$a}->{'implicit_flag'} <=>
                                 $all_conditions{$b}->{'implicit_flag'}
                               }
                          grep { $all_conditions{$_}->{'implicit_flag'} }
                          keys %all_conditions;
my @implicit_condition_objs = map {
                                    new FS::part_event_condition {
                                      'conditionname' => $_,
                                    };
                                  }
                                  @implicit_conditions;
my %condition_remove_warnings =
  map  { ( $_ => $all_conditions{$_}->{'remove_warning'} ); }
  grep { $all_conditions{$_}->{'remove_warning'} }
  keys %all_conditions;
#actions
tie my %all_actions, 'Tie::IxHash', 
  '' => { 'description' => '*** Select event action ***', },
  FS::part_event->actions();
my %action_labels = map { $_ => $all_actions{$_}->{'description'} }
                        keys %all_actions;
#my %action_fields = map { $_ => $all_actions{$_}->{option_fields} }
#                        keys %all_actions;
my %action_fields = map { my $action = $_;
                          tie my %opts, 'Tie::IxHash',
                            @{ $all_actions{$action}->{option_fields} || [] };
                          %opts = ( map { ( "$action.$_" => $opts{$_} ); }
                                        keys %opts
                                  );
                          ( $action => [ %opts ] );
                        }
                        keys %all_actions;
#subs
sub n_a {
  my $t = shift;
  return sub {
    my $field = shift;
    qq( ).
      "Party Party Join us Join us".
      '';
  };
}
my $action_layer_values = sub {
  my( $cgi, $part_event ) = @_;
  my $action = $cgi->param('action') || $part_event->action;
  return {} unless $action;
  scalar( #force hashref
    {
      #map { $_ => { $part_event->options } }
      #    keys %action_fields
      map { my $action = $_;
            my %fields = @{ $action_fields{$action} };
            my %obj_opts = $part_event->options;
            %obj_opts = map { ( "$action.$_" => $obj_opts{$_} ); }
                            keys %obj_opts;
            my %opts =
              map { #false laziness w/process/part_event.html
                    my $option = $_;
                    my $value = scalar($cgi->param($_)) || $obj_opts{$_};
                    if ( $option =~ /^(.*)\.reasonnum$/ && $value == -1 ) {
                      $value = {
                        'typenum' => scalar( $cgi->param( "new${option}T" ) ),
                        'reason'  => scalar( $cgi->param( "new${option}"  ) ),
                      };
                    }
                    ( $option => $value );
                  }
                  keys %fields;
            ( $action => \%opts );
          }
          keys %action_fields
    }
  );
};
tie my %cgi_conditions, 'Tie::IxHash';
my $error_callback = sub {
  my( $cgi, $object, $fields_listref ) = @_;
  my @cond_params = grep /^conditionname\d+$/, $cgi->param;
  %cgi_conditions = map {
    my $param = $_;
    my $conditionname = $cgi->param($param);
    $conditionname => {
      map { 
        my $cgi_key = $_;
        $cgi_key =~ /^$param\.$conditionname\.(.*)$/ or die 'wtf!';
        my $key = $1;
        #my $value = $cgi->param($_);
        #my $info = $all_conditions->{$conditionname}
        my %cond_opts =
          @{ $all_conditions{$conditionname}->{'option_fields'} || []};
        my $info = $cond_opts{$key};
        my $value;
        #false laziness w/process/part_event.html
        if (      $info->{'type'} =~ /^(select|checkbox)-?multiple$/
               or $info->{'type'} =~ /^select/ && $info->{'multiple'} ) {
          $value = { map { $_ => 1 } $cgi->param($cgi_key) };
        } elsif ( $info->{'type'} eq 'freq' ) {
          $value = $cgi->param($cgi_key). $cgi->param($cgi_key.'_units');
        } else {
          $value = $cgi->param($cgi_key);
        }
        $key => $value;
      } grep /^$param\.$conditionname\./, $cgi->param
    };
  } grep $cgi->param($_), grep /^conditionname\d+$/, $cgi->param;
};
my $condition_error_callback = sub {
  map {
    new FS::part_event_condition { 'conditionname' => $_, };
  } keys %cgi_conditions;
};
my $condition_layer_values = sub {
  #m2name_table option causes this to be
  # part_event_condition instead of part_event
  my ( $cgi, $part_event_condition, $switches ) = @_;
  scalar( #force hashref
    {
      #map { $_ => { $part_event_condition->options } }
      #    keys %condition_fields
      map { my $conditionname = $_;
            my %opts = $switches->{'mode'} eq 'error'
                       ? %{ $cgi_conditions{$conditionname} || {} }
                       : $part_event_condition->options;
            %opts = (
              map { ( "$conditionname.$_" => $opts{$_} ); }
                  keys %opts
            );
            ( $conditionname => \%opts );
          }
          keys %condition_fields
    }
  );
};
%once>
<%init>
my $curuser = $FS::CurrentUser::CurrentUser;
die "access denied"
  unless $curuser->access_right('Edit billing events')
      || $curuser->access_right('Edit global billing events');
my $disable_empty_agent= ! $curuser->access_right('Edit global billing events');
%cgi_conditions = ();
my $use_cgi_conditions = 0;
my $JS_DEBUG = 0;
%init>