<?php

declare(strict_types=1);

/*
 * This file is part of memberfiles bundle.
 *
 * (c) vonRotenberg
 *
 * @license commercial
 */

namespace vonRotenberg\MemberfilesBundle\EventListener\DataContainer;

use Contao\Backend;
use Contao\BackendUser;
use Contao\CoreBundle\ServiceAnnotation\Callback;
use Contao\DataContainer;
use Contao\File;
use Contao\Image;
use Contao\Input;
use Contao\StringUtil;
use Contao\System;
use Contao\Date;
use Contao\Config;
use vonRotenberg\MemberfilesBundle\Model\SecureDownloadsModel;

class MemberListener {

    /**
     * @var BackendUser
     */
    protected $User;

    public function __construct()
    {
        $this->User = BackendUser::getInstance();
    }

    /**
     * @Callback(table="tl_member", target="list.operations.secureDownloads.button"
     */
    public function onListSecureDownloadsOperationCallback(array $row, ?string $href, string $label, string $title, ?string $icon, string $attributes, string $table, array $rootRecordIds, ?array $childRecordIds, bool $circularReference, ?string $previous, ?string $next, DataContainer $dc)
    {
        if (Input::get('popup'))
        {
            return '';
        } else
        {
            $objSecFile = SecureDownloadsModel::findByPk($row['id']);
            $objFile = $objSecFile->getRelated('uuid');
            $title = sprintf($GLOBALS['TL_LANG']['tl_member_secureDownloads']['show'][1], $objFile->name);

            if ($objFile !== null)
            {
                return '<a href="contao/popup.php?src=' . base64_encode($objFile->path) . '" title="' . StringUtil::specialchars($title, false, true) . '"' . $attributes . ' onclick="Backend.openModalIframe({\'width\':600,\'title\':\'' . str_replace("'", "\\'", StringUtil::specialchars($objFile->name, false, true)) . '\',\'url\':this.href,\'height\':300});return false">' . Image::getHtml($icon, $label) . '</a> ';
            } else
            {
                return '';
            }
        }
    }

}