%# 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 }}}
<%args>
$Ticket
$ShowRelatedTickets => 10
$HTMXLoad => 0
</%args>
<%init>
my $target_assets = $Ticket->Links("Base")->Clone;
$target_assets->Limit(
    FIELD    => "Target",
    OPERATOR => "STARTSWITH",
    VALUE    => RT::URI::asset->LocalURIPrefix,
);
my $base_assets = $Ticket->Links("Target")->Clone;
$base_assets->Limit(
    FIELD    => "Base",
    OPERATOR => "STARTSWITH",
    VALUE    => RT::URI::asset->LocalURIPrefix,
);

my @linked_assets;
push @linked_assets, grep { defined } map { $_->TargetURI->IsLocal }
    @{ $target_assets->ItemsArrayRef };
push @linked_assets, grep { defined } map { $_->BaseURI->IsLocal }
    @{ $base_assets->ItemsArrayRef };

my $asset_queue;
if (RT->Config->Get('AssetQueues')) {
    $asset_queue = 1 if grep {$_ eq $Ticket->QueueObj->__Value('Name')} @{RT->Config->Get('AssetQueues')}
} else {
    $asset_queue = 0;
}
return unless @linked_assets or ($Ticket->CurrentUserHasRight("ModifyTicket")
                                     and $asset_queue);

my $assets = RT::Assets->new( $session{CurrentUser} );
$assets->OrderBy( FIELD => "Name", ORDER => "ASC" );
if ( @linked_assets ) {
    $assets->Limit(
        FIELD       => "id",
        OPERATOR    => "IN",
        VALUE       => \@linked_assets,
    );
}

my $Format = RT->Config->Get("AssetSummaryFormat") || q[
    '<a href="__WebHomePath__/Asset/Display.html?id=__id__">__Name__</a>/TITLE:Name',
    Description,
    Status,
    Catalog,
];

$m->callback(
    CallbackName    => 'ModifyCollection',
    Ticket          => $Ticket,
    Assets          => $assets,
    Format          => \$Format,
);


</%init>
<&| /Widgets/TitleBox,
    title => loc('Assets'),
    class => 'ticket-assets',
    title_class => "inverse",
    htmx_load => $HTMXLoad,
    content_body_class => 'pt-0',
    &>

<form hx-post="<% RT->Config->Get("WebPath") %>/Helpers/TicketUpdate" hx-swap="none" enctype="multipart/form-data">
  <input type="hidden" name="id" value="<% $Ticket->id %>">

% $m->callback( CallbackName => "Start", Ticket => $Ticket, Assets => $assets );

  <div id="assets-accordion" class="rt-accordion accordion accordion-flush">
% my $display_path = $session{'CurrentUser'}->Privileged ? 'Asset' : 'SelfService/Asset';

% while (my $asset = $assets->Next) {
    <div class="accordion-item">
      <span class="accordion-title" id="accordion-asset-<% $asset->id %>-title">
        <a href="<% RT->Config->Get('WebPath') %>/<% $display_path %>/Display.html?id=<% $asset->id %>"><&|/l, $asset->id, $asset->Name &>#[_1]: [_2]</&></a>

%# show asset actions menu
% my $request_path = $HTML::Mason::Commands::r->path_info;
% $request_path =~ s!/{2,}!/!g;
% my $page = RT::Interface::Web::Menu->new();
% require RT::Interface::Web::MenuBuilder;
% RT::Interface::Web::MenuBuilder::_BuildAssetMenuActionSubmenu( $request_path, PageWidgets(), $page, Asset => $asset, Ticket => $Ticket );
% $m->callback( CallbackName => "ActionsMenu", Ticket => $Ticket, Asset => $asset, Menu => $page );

        <span class="accordion-actions">
          <& /Elements/Menu, menu => $page, id => 'asset-'.$asset->id.'-actions-menu', parent_id => 'asset-'.$asset->id &>
          <span class="accordion-toggle toggle border rounded collapsed" data-bs-toggle="collapse" data-bs-target="#accordion-asset-<% $asset->id %>" aria-expanded="false" aria-controls="accordion-asset-<% $asset->id %>"></span>
        </span>
      </span>
      <div id="accordion-asset-<% $asset->id %>" class="accordion-content collapse" aria-labelledby="accordion-asset-<% $asset->id %>-title">
        <& /Elements/ShowRecord,
            Object      => $asset,
            Format      => $Format,
            TrustFormat => 1,
            &>
% $m->callback( CallbackName => "BeforeTickets", Ticket => $Ticket, Asset => $asset );
<%perl>
if ($ShowRelatedTickets) {
    my %search = (
        Query   => "id != '@{[$Ticket->id]}' AND LinkedTo = 'asset:@{[$asset->id]}'",
        OrderBy => "LastUpdated",
        Order   => "DESC",
    );
    my $url = RT->Config->Get("WebPath")
            . "/Search/Results.html?"
            . $m->comp("/Elements/QueryString", %search);
</%perl>

        <div class="related-tickets mt-2">
          <div class="label mb-1 fw-medium">
            <a class="text-primary" href="<% $url %>">
              <&|/l, $ShowRelatedTickets &>[_1] most recently updated related tickets</&>
            </a>
          </div>
          <& /Elements/CollectionList,
              %search,
              Class             => "RT::Tickets",
              Format            => RT->Config->Get("AssetSummaryRelatedTicketsFormat"),
              Rows              => $ShowRelatedTickets,
              ShowHeader        => 0,
              AllowSorting      => 0,
              ShowNavigation    => 0,
              InlineEdit        => 0,
          &>
        </div>
% }

% $m->callback( CallbackName => "PerAsset", Ticket => $Ticket, Asset => $asset );

      </div>
    </div>
% }
  </div>

% if ($Ticket->CurrentUserHasRight("ModifyTicket")) {
  <&| /Elements/LabeledValue, Label => loc('Add an asset to this ticket'), ReadOnly => 0 &>
    <div class="d-flex gap-2">
      <div class="flex-grow-1">
        <input data-autocomplete="Assets" class="form-control" size="10" name="<% $Ticket->id %>-RefersTo" data-autocomplete-exclude="<% join(',', @linked_assets) |n %>" type="text">
      </div>
      <button type="submit" name="AddAsset" value="Add" class="btn btn-primary"><% loc('Add') %></button>
    </div>
  </&>
% }

% $m->callback( CallbackName => "End", Ticket => $Ticket, Assets => $assets );

</form>

</&>

<%attr>
directly_accessible => 1
</%attr>
