<?php
/**
 * @package     FILEman
 * @copyright   Copyright (C) 2011 Timble CVBA. (http://www.timble.net)
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.joomlatools.com
 */

defined( '_JEXEC' ) or die;

jimport('joomla.plugin.plugin');

class plgButtonFilelink extends JPlugin
{
    public function __construct(&$subject, $config)
    {
        parent::__construct($subject, $config);
        $this->loadLanguage();
    }

    public function onDisplay($name)
    {
        $button = null;
        $user   = JFactory::getUser();

        if (!($this->params->get('userfolder') && $user->guest))
        {
            $button = new JObject();
            $button->class = 'btn';

            $editor = JFactory::getConfig()->get('editor');

            $is_joomlatools_extension = false;
            $is_joomla4               = version_compare(JVERSION, '4.0', '>=');

            $link = 'index.php?option=com_fileman&amp;view=filelink&amp;e_name='.$name.'&amp;_=' . time();

            try
            {
                if (class_exists('Koowa') && class_exists('KObjectManager')) {
                    $is_joomlatools_extension = (boolean) KObjectManager::getInstance()->isRegistered('dispatcher');
                }
            } catch (Exception $e) {}

            if (!$is_joomlatools_extension)
            {
                // Use Joomla modal
                $button->set('modal', true);
                $button->set('options', "{handler: 'iframe', size: {x: 1000, y: 600}}");
                $button->set('link', $link);
            }
            else
            {
                if ($is_joomla4)
                {
                    $button->set('link', '#');
                    $onclick = 'kQuery.magnificPopup.open({type: "iframe", items: {src: "' . str_replace('&amp;', '&', $link) . '"}, mainClass: "k-editor-modal"})';

                    if ($editor != 'tinymce') {
                        $onclick = htmlspecialchars($onclick); // Editors render the property in the button tag, needs escaping
                    }

                    $button->set('onclick', $onclick);
                }
                else
                {
                    $button->set('class', 'btn k-js-iframe-modal'); // Open using MagnificPopup}
                    $button->set('link', $link);
                }
            }

            if ($is_joomla4)
            {
                $button->icon    = 'picture';
                $button->iconSVG = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -1 10 10">
                                        <path d="M0 0v8h8v-8h-8zm1 1h6v3l-1-1-1 1 2 2v1h-1l-4-4-1 1v-3z" />
                                    </svg>';
            }

            $button->set('text', JText::_('PLG_FILELINK_BUTTON_FILE'));
            $button->set('name', 'picture');

            JHtml::_('stylesheet', 'media/koowa/com_koowa/css/modal-override.css');
        }

        return $button;
    }
}