<?php
$escape = $this->plugin('escapeHtml');
$allMedia = null;
$thumbnailUrl = null;
if ($attachedItem) {
    $allMedia = $attachedItem->media();
    $primaryMedia = $attachedItem->primaryMedia();
    if ($attachedMedia) {
        $thumbnailUrl = $attachedMedia->thumbnailUrl('square');
        $thumbnailTitle = $attachedMedia->displayTitle();
    } elseif ($primaryMedia) {
        $thumbnailUrl = $primaryMedia->thumbnailUrl('square');
        $thumbnailTitle = $primaryMedia->displayTitle();
    }
}
$changeItemButton = '<button id="attachment-item-select" data-sidebar-content-url="' .
    $escape($site->adminUrl('sidebar-item-select')) .
    '">' . $this->translate('Change item') . '</button>';
?>
<?php if ($attachedItem): ?>
<div class="selected-attachment">
    <?php if ($thumbnailUrl): ?>
    <h3 class="item-title"><?php echo $escape($attachedItem->displayTitle()); ?></h3>
    <span class="media-title"><?php echo $thumbnailTitle; ?></span>
    <img class="item-thumbnail" src="<?php echo $escape($thumbnailUrl); ?>">
    <?php else: ?>
    <h3 class="item-title"><?php echo $escape($attachedItem->displayTitle()); ?></h3>
    <?php endif; ?>
    <?php echo $changeItemButton; ?>
</div>
<?php if ($allMedia): ?>
<div class="select-media option">
    <h3><?php echo $this->translate('Media'); ?></h3><a href="#" class="collapse" aria-label="<?php echo $this->translate('Collapse'); ?>" title="<?php echo $this->translate('Collapse'); ?>"></a>
    <div class="collapsible">
        <ul class="media-list">
            <?php foreach ($allMedia as $media): ?>
            <?php
            $attached = null;
            if (($attachedMedia && ($attachedMedia->id() === $media->id()))
                || (!$attachedMedia && ($primaryMedia->id() === $media->id()))
            ) {
                $attached = 'attached';
            }
            ?>
            <li class="media <?php echo $attached; ?>" data-media-id="<?php echo $escape($media->id()); ?>">
                <img class="media-thumbnail" src="<?php echo $escape($media->thumbnailUrl('square')); ?>" title="<?php echo $escape($media->displayTitle()); ?>">
            </li>
            <?php endforeach; ?>
        </ul>
    </div>
</div>
<?php endif; ?>
<?php else: ?>
<div class="selected-attachment">
    <h3 class="item-title"><?php echo $escape('No Attachment'); ?></h3>
    <p><?php echo $this->translate('No item selected.'); ?></p>
    <?php echo $changeItemButton; ?>
</div>
<?php endif; ?>
