%# What does it mean if there is no fortune for you?

% unless ($NoUI) {
<& /Work/Elements/104Header, Title => 'New Request', Method => 'POST', Enctype => 'multipart/form-data' &>
% }
<INPUT TYPE=HIDDEN Name="id" VALUE="new">
<INPUT TYPE=HIDDEN NAME=Status Value="new">
<INPUT Name="Requestors" Type="HIDDEN" Value="<% ($ARGS{Requestors}) || $session{CurrentUser}->Id %>">
<INPUT TYPE=HIDDEN NAME="Queue" Value="<% $QueueObj->Id %>">
<INPUT TYPE=HIDDEN NAME="Due" VALUE="<% $ARGS{Due} %>">
% if ($RT::OIN104 or $ARGS{Subject}) {
<INPUT TYPE=HIDDEN Name="Subject" value="<%$ARGS{Subject} || 'Workflow'%>">
% }
% if ($NoUI) {
<table cellpadding=0 cellspacing=0 border=0>
% } else {
<& /Work/Tickets/Elements/ShowQueue, QueueObj => $QueueObj &>
<& /Work/Tickets/Elements/ShowBasics, Ticket => $Ticket, SelectOwner => 1, DefaultOwner => $Owner &>
% }
<tr><td colspan="2" valign="top"> 
% my $CFs = $QueueObj->CustomFields;
% $CFs->LimitAttribute( NAME => 'Pattern', OPERATOR => '!=', VALUE => '' );
% if ($CFs->Count) {
    <div id="MandatoryNotice" name="MandatoryNotice" align="right" style="position: absolute; right: 30px; color: #00659C">
% my $img = "<img src='/img/FillMark_red.png' width='4' height='7' alt='".loc('(required)')."' title='".loc('(required)')."'>";
<&|/l, $img &>* The [_1] symbol denotes a mandatory field.</&>
    </div>
% }
    <table border="0" cellspacing="2" cellpadding="0" width=100%>
<& /Work/Tickets/Elements/EditCustomFields, %ARGS,
    Entries    => $Entries,
    Ticket     => $Ticket,
    ReadOnly   => 0,
    Check      => 'OnCreate',
    NoCF       => $NoCF,
    Loc        => $Loc,
&>
% unless ($RT::SystemQueues{$QueueObj->Id} or $NoCF->{Attachments}) {
<& /Work/Tickets/Elements/AddAttachments, %ARGS &>
% }
% unless ($RT::OIN104 or length($ARGS{Subject}) or $NoCF->{Subject}) {
<& /Work/Tickets/Elements/AddSubject, %ARGS &>
% }
% unless ($NoCF->{Notes} or $NoCF->{Content}) {
<& /Work/Tickets/Elements/AddContent, %ARGS &>
% }

    </table>
</td></tr>
% if ($NoUI) {
            <tr><td align="center">
              <input name="Submit-Create" type="submit" value="<&|/l&>Confirm Submit</&>" onclick="this.disabled = true; document.getElementById('Action-Create').value='1'; this.form.submit();">
              <input type="hidden" id="Action-Create" name="Action-Create" value="">
              <br>
            </td></tr>
            </table>
%    return;
% }

              <tr> 
                <td bgcolor="#333333" height="1" colspan="2"></td>
              </tr>
            </table>
            <div align="center"><br>
              <& /Work/Elements/BackButton &>
              <input type="submit" name="Submit-Create" value="<&|/l&>Confirm Submit</&> &gt;&gt;" onclick="if(chkDescp()){this.disabled = true; document.getElementById('Action-Create').value='1'; this.form.submit();}">
              <input type="hidden" id="Action-Create" name="Action-Create" value="">
              <br>
            </div>
          </td>
        </tr>
      </table>
    </td>
  </tr>
</table>
<%DOC>
% if (!$m->notes('ValidFields')) {
<SCRIPT><!--
alert('<&|/l&>Missing mandatory fields</&>.');
--></SCRIPT>
% }
</%DOC>
<%INIT>
my $QueueObj = new RT::Queue($session{'CurrentUser'});
$QueueObj->Load($Queue) || Abort(loc("Queue could not be loaded."));

my $CustomFields = $QueueObj->CustomFields;
my $UserObj = $session{CurrentUser}->UserObj;
my $Check = 'OnCreate';

my $ValidCFs = $m->comp(
    'Elements/ValidateCustomFields',
    CustomFields => $CustomFields,
    ARGSRef => \%ARGS
);

if ($QueueObj->DefaultDueIn) {
    my $default_due = RT::Date->new($session{'CurrentUser'});
    $default_due->SetToNow();
    $default_due->AddDays($QueueObj->DefaultDueIn);
    $ARGS{'Due'} = $default_due->ISO();
}

# {{{ deal with deleting uploaded attachments
foreach my $key (keys %ARGS) {
    if ($key =~ m/^DeleteAttach-(.+)$/) {
        delete $session{'Attachments'}{$1};
    }
    $session{'Attachments'} = { %{$session{'Attachments'} || {}} };
}

# {{{ store the uploaded attachment in session
if ($ARGS{'Attach'}) {                  # attachment?
    $session{'Attachments'} = {} unless defined $session{'Attachments'};

    my $subject = "$ARGS{'Attach'}";
    # strip leading directories
    $subject =~ s#^.*[\\/]##;

    my $attachment = MakeMIMEEntity(
        Subject             => $subject,
        Body                => "",
        AttachmentFieldName => 'Attach'
    );

    $session{'Attachments'} = { %{$session{'Attachments'} || {}},
                                $ARGS{'Attach'} => $attachment };
}
# }}}

foreach my $key (keys %ARGS) {
    $key =~ /^AddMoreEntry-(.*)$/ or next;
    $ARGS{'AddMoreEntry'} = [ split(/-/, $1) ];
}

$session{'Entries'} = {} unless $ARGS{'AddMoreEntry'} or $ARGS{'id'};
my $Entries = $session{'Entries'} || {};

$m->comp('Elements/ProcessEntryUpdates', Entries => $Entries, %ARGS);

# delete temporary storage entry to make WebUI clean
unless (keys %{$session{'Attachments'}} and $ARGS{'id'} eq 'new') {
    delete $session{'Attachments'};
}

if (keys %{$Entries} and $ARGS{'id'} eq 'new') {
    $ARGS{"CustomField-$_"} = $Entries->{$_} foreach keys %{$Entries};
    $session{'Entries'} = { %{$Entries} };
}
else {
    delete $session{'Entries'};
}

# }}}

# {{{ deal with multi-select CC & AdminCC
foreach my $key (keys %ARGS) {
    if      ($key =~ m/^AddAdminCc/) {
        my @AdminCCs =
            ref($ARGS{$key}) eq 'ARRAY' ? @{$ARGS{$key}} : ($ARGS{$key});
        $ARGS{AdminCc} =
            join ",", $ARGS{AdminCc}, grep { $_ ne "-" } @AdminCCs;
    } elsif ($key =~ m/^AddCc/) {
        my @CCs = ref($ARGS{$key}) eq 'ARRAY' ? @{$ARGS{$key}} : ($ARGS{$key});
        $ARGS{Cc} =
            join ",", $ARGS{Cc}, grep { $_ ne "-" } @CCs;
    }
}
# }}}

if ((!exists $ARGS{'AddMoreAttach'}) && (!exists $ARGS{'AddMoreEntry'}) && ($ARGS{'id'} eq 'new') and $ValidCFs) {
    my $out = $m->scomp('Display.html', %ARGS, CreateOnly => 1);
    if (my $id = $m->notes('NewTicketId')) {
        $m->comp('/Edit/Elements/Redirect', URL => 'Display.html', Args => "?id=$id&Role=requestor&Queue=$Queue");
    }
    else {
        $m->print($out);
    }
    $m->abort;
}

my $users = new RT::Users($session{'CurrentUser'});
$users->LimitToPrivileged();
my @PrivUsers;
while (my $user = $users->Next) {
    push @PrivUsers, $user->Name;
}

my $Owner = $ARGS{Owner};
my $OwnerObj;
if (!$Owner and $OwnerObj = $QueueObj->AdminCc->UserMembersObj->First) {
    $Owner ||= $OwnerObj->Id;
};

$ARGS{Subject} = '' unless exists $ARGS{Subject};

require Test::MockObject;
my $Now = RT::Date->new($session{'CurrentUser'}); $Now->SetToNow;
my $Ticket = Test::MockObject->new;
$Ticket->set_always( Queue => $QueueObj->Id )
       ->set_always( QueueObj => $QueueObj )
       ->set_always( OwnerObj => $OwnerObj || $RT::Nothing )
       ->set_always( CreatedObj => $Now )
       ->set_always( Status => 'new' )
       ->set_always( HasUnresolvedDependencies => 0 )
       ->set_always( Id => undef )
       ->set_always( FirstRequestor => $UserObj )
       ->set_always( Subject => undef );
</%INIT>

<%ARGS>
$DependsOn => undef
$DependedOnBy => undef
$MemberOf => undef
$QuoteTransaction => undef
$Queue => undef
$NoUI => undef
$Loc => undef
$NoCF => {}
$descp=>''
</%ARGS>
