%# BEGIN BPS TAGGED BLOCK {{{
%#
%# COPYRIGHT:
%#
%# This software is Copyright (c) 1996-2026 Best Practical Solutions, LLC
%#                                          <sales@bestpractical.com>
%#
%# (Except where explicitly superseded by other copyright notices)
%#
%#
%# LICENSE:
%#
%# This work is made available to you under the terms of Version 2 of
%# the GNU General Public License. A copy of that license should have
%# been provided with this software, but in any event can be snarfed
%# from www.gnu.org.
%#
%# This work is distributed in the hope that it will be useful, but
%# WITHOUT ANY WARRANTY; without even the implied warranty of
%# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
%# General Public License for more details.
%#
%# You should have received a copy of the GNU General Public License
%# along with this program; if not, write to the Free Software
%# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
%# 02110-1301 or visit their web page on the internet at
%# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
%#
%#
%# CONTRIBUTION SUBMISSION POLICY:
%#
%# (The following paragraph is not intended to limit the rights granted
%# to you to modify and distribute this software under the terms of
%# the GNU General Public License and is only of importance to you if
%# you choose to contribute your changes and enhancements to the
%# community by submitting them to Best Practical Solutions, LLC.)
%#
%# By intentionally submitting any modifications, corrections or
%# derivatives to this work, or any other work intended for use with
%# Request Tracker, to Best Practical Solutions, LLC, you confirm that
%# you are the copyright holder for those contributions and you grant
%# Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
%# royalty-free, perpetual, license to use, copy, create derivative
%# works based on those contributions, and sublicense and distribute
%# those contributions and any derivatives thereof.
%#
%# END BPS TAGGED BLOCK }}}
<input type="hidden" name="<% $NamePrefix %>Status" value="<% $ARGS{ $NamePrefix .'Status' } || $QueueObj->LifecycleObj->DefaultOnCreate %>" />

<div class="ticket-create-basics">
<&| /Widgets/TitleBox, title => loc("Basics"), class => 'ticket-info-basics' &>

% if ($Constituency) {
  <div class="form-row">
    <div class="label col-3">
      <% loc('Constituency') %>:
    </div>
    <div class="value col-9">
      <span class="current-value"><% $Constituency %></span>
    </div>
  </div>
% }

  <div class="form-row">
    <div class="label col-3">
      <&|/l&>Queue</&>:
    </div>
    <div class="value col-9">
      <& /RTIR/Elements/SelectRTIRQueue,
          Name => $NamePrefix . 'Queue',
          Default => $QueueObj->Name,
          Lifecycle => $QueueObj->Lifecycle,
          AutoSubmit => 1,
          ShowNullOption => 0,
          ShowAll => 0,
          Constituency => $Constituency
      &>
    </div>
  </div>

% unless ( $SkipField{'Owner'} || $HideField{'Owner'} ) {
  <div class="form-row owner">
    <div class="label col-3">
      <&|/l&>Owner</&>:
    </div>
    <div class="value col-9">
      <& /Elements/SelectOwner,
          Name     => $NamePrefix ."Owner",
          QueueObj => $QueueObj,
          Default  => $value_cb->('Owner') || $session{'CurrentUser'}->Id,
      &>
    </div>
  </div>
% }

% unless ( $SkipField{'TimeFields'} ) {
<div class="form-row">
  <div class="label col-3">
    <&|/l&>Time Worked</&>:
  </div>
  <div class="value col-9">
    <& /Elements/EditTimeValue,
        Name    => $NamePrefix . 'TimeWorked',
        Default => $value_cb->('TimeWorked') || '',
    &>
  </div>
</div>
<div class="form-row">
  <div class="label col-3">
    <&|/l&>Time Left</&>:
  </div>
  <div class="value col-9">
    <& /Elements/EditTimeValue,
        Name    => $NamePrefix . 'TimeLeft',
        Default => $value_cb->('TimeLeft') || '',
    &>
  </div>
</div>
% }

% unless ( $SkipField{'DateFields'} ) {
<&| /Widgets/TitleBox, title => loc("Dates"), class => 'ticket-info-dates' &>

<div class="form-row">
  <div class="label col-3">
    <&|/l&>Starts</&>:
  </div>
  <div class="value col-9">
    <& /Elements/SelectDate,
        Name    => $NamePrefix . 'Starts',
        Default => $value_cb->('Starts') || '',
    &>
  </div>
</div>

<div class="form-row">
  <div class="label col-3">
    <&|/l&>Due</&>:
  </div>
  <div class="value col-9">
    <& /Elements/SelectDate,
        Name    => $NamePrefix . 'Due',
        Default => $value_cb->('Due') || '',
    &>
  </div>
</div>

</&>
% }

% if ( ($QueueObj || $TicketObj) && !$SkipField{'CustomFields'} ) {
<& /RTIR/Elements/EditCustomFields,
    %ARGS,
    TicketObj  => $ticket,
    NamePrefix => $NamePrefix,
    QueueObj   => $QueueObj,
    DefaultsFrom => $TicketObj,
    CFIDPrefix => $NamePrefix,
    CFDefaults => \%CFDefaults,
&>
% }

</&>

% if ( ($QueueObj || $TicketObj) && !$SkipField{'CustomFields'} ) {
<& /Elements/EditCustomFieldCustomGroupings,
    %ARGS,
    %CFDefaults,
    Object => $ticket,
    CustomFieldGenerator => sub { $QueueObj->TicketCustomFields },
    Groupings => [ RT::CustomField->CustomGroupings( 'RTIR::Ticket', $QueueObj->Name ), '' ],
&>
% }

</div>

<div class="ticket-create-details">
<&| /Widgets/TitleBox,
    title => loc("Launch a new investigation"),
    class => 'ticket-info-message',
&>

% unless ( $SkipField{'Requestors'} || $HideField{'Requestors'} ) {
<div class="form-row">
  <div class="label col-2">
    <&|/l&>Correspondents</&>:
  </div>
  <div class="value col-9">
    <& /Elements/EmailInput,
        Name    => $NamePrefix . 'Requestors',
        Default => $value_cb->('Requestors'),
        Size    => undef,
    &>
  </div>
</div>
% $m->callback( CallbackName => 'AfterRequestors', ARGSRef => \%ARGS );
% }

% unless ( $SkipField{'Cc'} || $HideField{'Cc'} ) {
<div class="form-row">
  <div class="label col-2">
    <&|/l&>Cc</&>:
    <span class="far fa-question-circle icon-helper" data-toggle="tooltip" data-placement="top" data-original-title="<&|/l&>Sends a carbon-copy of this update to a comma-delimited list of email addresses. These people will receive future updates.</&>"></span>
  </div>
  <div class="value col-9">
    <& /Elements/EmailInput,
        Name    => $NamePrefix . 'Cc',
        Default => $value_cb->('Cc'),
        Size    => undef,
    &>
  </div>
</div>
% }

% unless ( $SkipField{'AdminCc'} && $HideField{'AdminCc'} ) {
<div class="form-row">
  <div class="label col-2">
    <&|/l&>Admin Cc</&>:
     <span class="far fa-question-circle icon-helper" data-toggle="tooltip" data-placement="top" data-original-title="<&|/l&>Sends a carbon-copy of this update to a comma-delimited list of administrative email addresses. These people will receive future updates.</&>"></span>
  </div>
  <div class="value col-9">
    <& /Elements/EmailInput,
        Name    => $NamePrefix . 'AdminCc',
        Default => $value_cb->('AdminCc'),
        Size    => undef,
    &>
  </div>
</div>
% }

% unless ( $SkipField{'Subject'} || $HideField{'Subject'} ) {
<div class="form-row">
  <div class="label col-2">
    <&|/l&>Subject</&>:
  </div>
  <div class="value col-9">
    <input class="form-control" type="text" name="<% $NamePrefix %>Subject" value="<% $value_cb->('Subject') %>" />
  </div>
</div>
% }

% if ( !$SkipField{'SignEncrypt'} && RT->Config->Get('GnuPG')->{'Enable'} ) {
<div class="form-row">
  <div class="label col-2">
    &nbsp;
  </div>
  <div class="value col-9">
    <div class="form-row">
      <div class="col-auto">
        <& /Widgets/Form/Boolean:InputOnly,
           Name         => $NamePrefix . 'Sign',
           CurrentValue => $ARGS{ $NamePrefix . 'Sign' },
           DefaultLabel => loc( 'Sign' ),
        &>
      </div>
      <div class="col-auto">
        <& /Widgets/Form/Boolean:InputOnly,
           Name         => $NamePrefix . 'Encrypt',
           CurrentValue => $ARGS{ $NamePrefix . 'Encrypt' },
           DefaultLabel => loc( 'Encrypt' ),
        &>
      </div>
    </div>
  </div>
</div>
% }

% unless ( $SkipField{'Content'} || $HideField{'Content'} ) {
% if ( RT->Config->Get('ArticleOnTicketCreate')) {
  <& /Articles/Elements/BeforeMessageBox,
     %ARGS,
     QueueObj       => $QueueObj,
     MessageBoxName => $NamePrefix . 'Content',
  &>
% }
% $m->callback( %ARGS, MessageBoxName => $NamePrefix . 'Content',
%    CallbackPage => '/Ticket/Create.html', CallbackName => 'BeforeMessageBox' );
% my $content = $value_cb->('Content');
  <& /Elements/MessageBox,
      Name             => $NamePrefix . 'Content',
      Default          => $content,
      IncludeSignature => exists $ARGS{'IncludeSignature'} ? $ARGS{'IncludeSignature'} : !$content,
      QuoteTransaction => $value_cb->('QuoteTransaction'),
      FullWidth        => 1,
  &>
% }

</&>

<div class="form-row">
  <div class="col-12">
    <& /Elements/Submit,
        Name => 'CreateWithInvestigation',
        Label => loc("Create Incident and run Investigation"),
        SubmitId => 'create-ticket-with-investigation'
    &>
  </div>
</div>

% $m->callback( CallbackName => 'AfterTable', ARGSRef => \%ARGS, TicketObj  => $ticket,
%    QueueObj   => $QueueObj, DefaultsFrom => $TicketObj );
</div>

<%ARGS>
$NamePrefix => ''
$QueueObj => undef
$TicketObj => undef
%HideField => ()
%SkipField => ()
$Constituency => undef
</%ARGS>
<%INIT>
# this component is only ever called from Incident/Create.html


my %CFDefaults;
my $value_cb = sub {
    my $name = shift;
    my $full_name = $NamePrefix . $name;
    my $value;
    $value = $ARGS{     $full_name };
    $value = $ARGS{     $name } unless defined $value;
    $value = ''                 unless defined $value;
    return $value;
};

unless ( $QueueObj ) {
    if ( my $queue = $value_cb->('Queue') ) {
        $QueueObj = RT::Queue->new( $session{'CurrentUser'} );
        $QueueObj->Load( $queue );
    } else {
        $QueueObj = RT::Queue->new( $session{'CurrentUser'} );
        # XXX TODO DO NOT HARDCODE THIS. THIS IS WRONG
        $QueueObj->Load('Investigations'.($Constituency? ' - '.$Constituency : ''));

    }
}




my $ticket = RT::Ticket->new($session{'CurrentUser'}); # empty ticket object

if ( RT->Config->Get('GnuPG')->{'Enable'} ) {
    foreach ( qw(Sign Encrypt) ) {
        $ARGS{ $NamePrefix . $_ } = $m->comp( '/Widgets/Form/Boolean:Process',
            Name => $NamePrefix . $_,
            DefaultValue => $QueueObj->$_,
            Arguments => \%ARGS,
        );
    }
}

</%INIT>

<%METHOD Process>
<%ARGS>
$NamePrefix => '',
$DefaultsNamePrefix => undef
</%ARGS>
<%INIT>
if ( defined $NamePrefix && length $NamePrefix ) {
    foreach my $k( keys %ARGS ) {
        next unless $k =~ /^\Q$NamePrefix\E(.*)$/;
        if ( defined $ARGS{ $k } && length $ARGS{ $k } ) {
            $ARGS{ $1 } = delete $ARGS{ $k };
        } else {
            delete $ARGS{ $k };
        }
    }
}
if ( $DefaultsNamePrefix && $DefaultsNamePrefix ne $NamePrefix ) {
    foreach my $k( keys %ARGS ) {
        next unless $k =~ /^\Q$DefaultsNamePrefix\E(.*)$/;
        if ( defined $ARGS{ $1 } && length $ARGS{ $1 } ) {
            delete $ARGS{ $k };
        } else {
            $ARGS{ $1 } = delete $ARGS{ $k };
        }
    }
}
delete $ARGS{'DefaultsNamePrefix'};
delete $ARGS{'NamePrefix'};

# deal with custom fields
if ( ($DefaultsNamePrefix||'') ne $NamePrefix ) {
    my $queue = RT::Queue->new( $session{'CurrentUser'} );
    unless ( $queue->Load( $ARGS{'Queue'} ) ) {
        Abort('Queue not found');
    }

    my %cf_map;
    foreach my $k( keys %ARGS ) {
        next unless $k =~ /^(Object-RT::Ticket--CustomField(?::\w+)?-)(\d+)(.*?)$/;
        my ($prefix, $cf_id, $rest) = ($1, $2, $3);

        unless ( exists $cf_map{ $cf_id } ) {
            my $src_cf = $queue->LoadCustomFieldByIdentifier($cf_id);
            unless ( $src_cf->id ) {
                $cf_map{ $cf_id } = 0;
                delete $ARGS{ $k };
                RT->Logger->error("Couldn't load CF #$cf_id");
                next;
            }

            my $dst_cf = do {
                my $cfs = $queue->TicketCustomFields;
                $cfs->Limit( FIELD => 'Name', VALUE => $src_cf->Name, CASESENSITIVE => 0 );
                $cfs->RowsPerPage(1);
                $cfs->First;
            };

            unless ( $dst_cf && $dst_cf->id ) {
                $cf_map{ $cf_id } = 0;
                delete $ARGS{ $k };
                RT->Logger->debug( $src_cf->Name .' is not applied. skipping.' );
                next;
            }
            $cf_map{ $cf_id } = $dst_cf->id;
        }

        if ( $cf_map{ $cf_id }
            && defined $ARGS{ $prefix . $cf_map{ $cf_id } . $rest } 
            && length $ARGS{ $prefix . $cf_map{ $cf_id } . $rest } )
        {
            $ARGS{ $prefix. $cf_map{ $cf_id } . $rest } =
                delete $ARGS{ $k };
        } else {
            delete $ARGS{ $k };
        }
    }
}

my ($Ticket, @results) = CreateTicket( %ARGS);

return ($Ticket, @results);
</%INIT>
</%METHOD>
