{#
/**
 * This file is part of FacturaScripts
 * Copyright (C) 2017-2024 Carlos Garcia Gomez <carlos@facturascripts.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
 */
#}
{% extends "Master/MenuBghTemplate.html.twig" %}
{% import 'Macro/Utils.html.twig' as Utils %}

{% block bodyHeaderOptions %}
    {{ parent() }}
    <div class="container-fluid mb-2">
        <div class="row">
            <div class="col-sm-6">
                <div class="btn-group">
                    <a class="btn btn-sm btn-secondary" href="{{ fsc.url() }}" title="{{ trans('refresh') }}">
                        <i class="fas fa-redo" aria-hidden="true"></i>
                    </a>
                    {% if fsc.getPageData()['name'] == fsc.user.homepage %}
                        <a class="btn btn-sm btn-secondary active" href="{{ fsc.url() }}?defaultPage=FALSE"
                           title="{{ trans('marked-as-homepage') }}">
                            <i class="fas fa-bookmark" aria-hidden="true"></i>
                        </a>
                    {% else %}
                        <a class="btn btn-sm btn-secondary" href="{{ fsc.url() }}?defaultPage=TRUE"
                           title="{{ trans('mark-as-homepage') }}">
                            <i class="far fa-bookmark" aria-hidden="true"></i>
                        </a>
                    {% endif %}
                </div>
                {% if config('disable_add_plugins', false) == false %}
                    <button class="btn btn-spin-action btn-sm btn-success" type="button" data-toggle="modal"
                            data-target="#modalAddPlugin">
                        <i class="fas fa-plus fa-fw" aria-hidden="true"></i>
                        <span class="d-none d-sm-inline-block">{{ trans('add') }}</span>
                    </button>
                {% endif %}
                <div class="btn-group">
                    <a href="{{ fsc.url() }}?action=rebuild&multireqtoken={{ formToken(false) }}"
                       onclick="animateSpinner('add')" class="btn btn-spin-action btn-sm btn-warning">
                        <i class="fas fa-hammer fa-fw" aria-hidden="true"></i>
                        <span class="d-none d-sm-inline-block">{{ trans('rebuild') }}</span>
                    </a>
                </div>
            </div>
            <div class="col-sm text-right">
                <h1 class="h3">
                    {{ trans(fsc.getPageData()['title']) | capitalize }}
                    <i class="{{ fsc.getPageData()['icon'] }}" aria-hidden="true"></i>
                </h1>
            </div>
        </div>
    </div>
    <ul class="nav nav-tabs" role="tablist">
        <li class="nav-item">
            <a class="nav-link active" id="installedPluginsTab" data-toggle="tab" href="#installed" role="tab">
                <i class="fas fa-box-open fa-fw" aria-hidden="true"></i> {{ trans('installed-plugins') }}
                {% if fsc.pluginList | length > 0 %}
                    <span class="badge badge-secondary">{{ fsc.pluginList | length }}</span>
                {% endif %}
            </a>
        </li>
        {% if config('disable_add_plugins', false) == false %}
            <li class="nav-item">
                <a class="nav-link" id="allPluginsTab" data-toggle="tab" href="#all" role="tab">
                    <i class="fas fa-boxes fa-fw" aria-hidden="true"></i>
                    <span class="d-none d-sm-inline-block">{{ trans('more-plugins') }}</span>
                    {% if fsc.remotePluginList | length > 0 %}
                        <span class="badge badge-secondary">{{ fsc.remotePluginList | length }}</span>
                    {% endif %}
                </a>
            </li>
        {% endif %}
    </ul>
{% endblock %}

{% block body %}
    {{ parent() }}
    <div class="tab-content">
        <div class="tab-pane fade show active" id="installed" role="tabpanel">
            {{ _self.showInstalledPlugins(fsc) }}
            {% if fsc.updated == false %}
                <div class="ml-2 mt-3 mr-2 mb-3">
                    {{ Utils.updateInstall() }}
                </div>
            {% elseif fsc.registered == false %}
                <div class="ml-2 mt-3 mr-2 mb-3">
                    {{ Utils.registerInstall() }}
                </div>
            {% endif %}
        </div>
        {% if config('disable_add_plugins', false) == false %}
            <div class="tab-pane fade" id="all" role="tabpanel">
                {{ _self.showAllPlugins(fsc) }}
            </div>
        {% endif %}
    </div>

    {# Modal for add new plugins #}
    {% if config('disable_add_plugins', false) == false %}
        <form action="{{ fsc.url() }}" class="form" enctype="multipart/form-data" id="f_add_plugins" method="post"
              name="upload-plugins" onsubmit="animateSpinner('add')">
            {{ formToken() }}
            <input type="hidden" name="action" value="upload"/>
            <div class="modal fade" id="modalAddPlugin" tabindex="-1" role="dialog" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="fa-solid fa-file-zipper mr-2"></i> {{ trans('add-new-plugin') }}
                            </h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="{{ trans('close') }}">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        {% if fsc.getMaxFileUpload() < 99 %}
                            <div class="alert alert-warning mb-0">
                                {{ trans('help-server-accepts-filesize', {'%size%': fsc.getMaxFileUpload()}) }}
                            </div>
                        {% endif %}
                        <div class="modal-body">
                            <div class="form-group">
                                {{ trans('select-plugin-zip-file') }}<br/>
                                <input type="file" name="plugin[]" accept="application/zip" multiple required/>
                                {% if fsc.getMaxFileUpload() >= 99 %}
                                    <small class="form-text text-muted">
                                        {{ trans('help-server-accepts-filesize', {'%size%': fsc.getMaxFileUpload()}) }}
                                    </small>
                                {% endif %}
                            </div>
                            <div class="text-right mt-5">
                                <button type="button" class="btn btn-spin-action btn-secondary" data-dismiss="modal">
                                    {{ trans('cancel') }}
                                </button>
                                <button type="submit" class="btn btn-spin-action btn-success">
                                    {{ trans('continue') }}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    {% endif %}
{% endblock %}

{% block javascripts %}
    {{ parent() }}
    {% if config('disable_rm_plugins', false) == false %}
        <script>
            function deletePlugin(pluginName) {
                bootbox.confirm({
                    title: "{{ trans('confirm-delete')|raw }}",
                    message: "{{ trans('are-you-sure') }}",
                    closeButton: false,
                    buttons: {
                        cancel: {
                            label: "<i class='fas fa-times'></i> {{ trans('cancel') }}"
                        },
                        confirm: {
                            label: "<i class='fas fa-check'></i> {{ trans('delete') }}",
                            className: 'btn-danger'
                        }
                    },
                    callback: function (result) {
                        if (result) {
                            animateSpinner('add');
                            window.location = "{{ fsc.url() }}?action=remove" + "\u0026" + "plugin=" + pluginName
                                + "\u0026" + "multireqtoken={{ formToken(false) }}";
                        }
                    }
                });
            }

            $(document).ready(function () {
                searchList('#querySearchPlugin', '#all-plugins .card', '.card-title');
                searchList('#querySearchInstalledPlugins', '#installed-plugins .item-plugin', '.plugin-name');

                // si los archivos son demasiado grandes, no se pueden subir
                $("#f_add_plugins").submit(function (e) {
                    let size = 0;
                    let files = document.querySelector('input[type=file]').files;
                    for (let i = 0; i < files.length; i++) {
                        size += files[i].size;
                    }

                    if (size > {{ fsc.getMaxFileUpload() }} * 1024 * 1024) { // MB
                        e.preventDefault();
                        alert('{{ trans('plugin-file-too-big', {'%size%': fsc.getMaxFileUpload()}) }}');
                        animateSpinner('remove');
                    }
                });
            });

            function searchList(querySelectorInput, querySelectorItem, querySelectorPluginName) {
                $(querySelectorInput).on('keyup', function (e) {
                    const query = this.value.toLowerCase().trim();
                    $(querySelectorItem).each(function (index, value) {
                        $(value).toggle($(querySelectorPluginName, value).text().toLowerCase().trim().includes(query));
                    });
                });
            }
        </script>
    {% endif %}
{% endblock %}

{% macro healthStatus(value) %}
    {% if value < 1 %}
        <i class="fas fa-heart-broken"></i>
        <i class="far fa-heart"></i>
        <i class="far fa-heart"></i>
        <i class="far fa-heart"></i>
        <i class="far fa-heart"></i>
    {% elseif value < 2 %}
        <i class="fas fa-heart"></i>
        <i class="far fa-heart"></i>
        <i class="far fa-heart"></i>
        <i class="far fa-heart"></i>
        <i class="far fa-heart"></i>
    {% elseif value < 3 %}
        <i class="fas fa-heart"></i>
        <i class="fas fa-heart"></i>
        <i class="far fa-heart"></i>
        <i class="far fa-heart"></i>
        <i class="far fa-heart"></i>
    {% elseif value < 4 %}
        <i class="fas fa-heart"></i>
        <i class="fas fa-heart"></i>
        <i class="fas fa-heart"></i>
        <i class="far fa-heart"></i>
        <i class="far fa-heart"></i>
    {% elseif value < 5 %}
        <i class="fas fa-heart"></i>
        <i class="fas fa-heart"></i>
        <i class="fas fa-heart"></i>
        <i class="fas fa-heart"></i>
        <i class="far fa-heart"></i>
    {% else %}
        <i class="fas fa-heart"></i>
        <i class="fas fa-heart"></i>
        <i class="fas fa-heart"></i>
        <i class="fas fa-heart"></i>
        <i class="fas fa-heart"></i>
    {% endif %}
{% endmacro %}

{% macro showAllPlugins(fsc) %}
    <div class="p-2">
        <input type="text" class="form-control shadow-sm" id="querySearchPlugin" placeholder="{{ trans('search') }}"/>
    </div>
    <div class="card-columns pl-2 pr-2" id="all-plugins">
        {% for plugin in fsc.remotePluginList %}
            {% set extraClass = plugin.health > 2 ? 'border-success' : plugin.health == 0 ? 'border-danger' : 'border-warning' %}
            <div class="card {{ extraClass }} shadow-sm" id="{{ plugin.idplugin }}">
                <div class="card-body p-2">
                    <h5 class="card-title">{{ plugin.name }} v{{ plugin.version }}</h5>
                    <p class="card-text">{{ plugin.description | slice(0, 300) | nl2br }}</p>
                </div>
                <div class="card-footer p-2">
                    {% set extraBtnClass = plugin.health > 2 ? 'btn-outline-success' : plugin.health == 0 ? 'btn-outline-danger' : 'btn-outline-warning' %}
                    <a href="{{ plugin.url }}" class="btn {{ extraBtnClass }}" target="_blank">{{ trans('add') }}</a>
                    <span class="ml-2 text-danger" title="{{ trans('health') }}">
                        {{ _self.healthStatus(plugin.health) }}
                    </span>
                </div>
            </div>
        {% else %}
            <div class="text-center bg-warning rounded">
                <h2>{{ trans('no-data') }}</h2>
            </div>
        {% endfor %}
    </div>
{% endmacro %}

{% macro showInstalledPlugins(fsc) %}
    <div class="m-2 mb-3">
        <input type="text" class="form-control border-dark" id="querySearchInstalledPlugins"
               placeholder="{{ trans('search') }}"/>
    </div>

    <div class="card border-success m-2 mb-3">
        <div class="card-header border-success">{{ trans('enabled-plugins') }}</div>
        {{ _self.tablePlugins(fsc.pluginList | filter(plugin => plugin.enabled)|sort((a, b) => a.order <=> b.order), fsc.url()) }}
    </div>

    <div class="card border-dark m-2">
        <div class="card-header border-dark">{{ trans('disabled-plugins') }}</div>
        {{ _self.tablePlugins(fsc.pluginList | filter(plugin => plugin.enabled == false), fsc.url()) }}
    </div>
{% endmacro %}

{% macro tablePlugins(pluginList, url) %}
    <div class="table-responsive" id="installed-plugins">
        <table class="table table-striped table-hover mb-0">
            <thead>
            <tr>
                <th>{{ trans('name') }}</th>
                <th class="text-right">{{ trans('version') }}</th>
                <th>{{ trans('description') }}</th>
                <th class="text-right pr-3">{{ trans('actions') }}</th>
            </tr>
            </thead>
            <tbody>
            {% for plugin in pluginList %}
                {% set trClass = 'table-danger' %}
                {% if plugin.enabled %}
                    {% set trClass = 'table-success' %}
                {% elseif plugin.compatible %}
                    {% set trClass = '' %}
                {% endif %}
                <tr class="{{ trClass }} item-plugin">
                    <td class="plugin-name">{{ plugin.name }}</td>
                    <td class="text-right">
                        {% if plugin.version == 0 %}
                            <span class="text-danger">v{{ plugin.version }}</span>
                        {% elseif plugin.version < 1 %}
                            <span class="text-warning">v{{ plugin.version }}</span>
                        {% else %}
                            v{{ plugin.version }}
                        {% endif %}
                    </td>
                    <td>
                        {{ plugin.description | nl2br }}
                        {% if plugin.forja('url', '') %}
                            <a href="{{ plugin.forja('url', '') }}" target="_blank" class="ml-2">
                                {{ trans('more') }} <i class="fas fa-external-link-alt"></i>
                            </a>
                        {% endif %}
                        <br/>
                        {% for requiredPluginName in plugin.require %}
                            <div class="badge badge-secondary">
                                {{ trans('plugin-needed', {'%pluginName%': requiredPluginName}) }}
                            </div>
                        {% endfor %}
                    </td>
                    <td class="text-right text-nowrap">
                        {% if plugin.hasUpdate() %}
                            <a href="Updater" class="btn btn-spin-action btn-sm btn-info mr-1"
                               title="{{ trans('updater') }}">
                                <i class="fas fa-cloud-download-alt" aria-hidden="true"></i>
                            </a>
                        {% endif %}
                        {% if plugin.enabled %}
                            <a class="btn btn-sm btn-secondary btn-spin-action" onclick="animateSpinner('add');"
                               href="{{ url }}?action=disable&amp;plugin={{ plugin.name }}&amp;multireqtoken={{ formToken(false) }}">
                                <i class="fa-solid fa-toggle-off mr-1" aria-hidden="true"></i>
                                <span class="d-none d-sm-inline-block">{{ trans('disable') }}</span>
                            </a>
                            <br/>
                            <small>{{ trans('plugin-order', {'%num%': plugin.order}) }}</small>
                        {% elseif plugin.compatible %}
                            {% if plugin.hasUpdate() %}
                                <div class="btn-group">
                                    <button type="button" class="btn btn-sm btn-warning dropdown-toggle"
                                            data-toggle="dropdown" aria-expanded="false">
                                        {{ trans('enable') }}
                                    </button>
                                    <div class="dropdown-menu">
                                        <a class="dropdown-item" href="Updater">
                                            <i class="fas fa-cloud-download-alt fa-fw mr-1" aria-hidden="true"></i>
                                            {{ trans('update') }}
                                        </a>
                                        <div class="dropdown-divider"></div>
                                        <a class="dropdown-item"
                                           href="{{ url }}?action=enable&amp;plugin={{ plugin.name }}&amp;multireqtoken={{ formToken(false) }}">
                                            <i class="fas fa-check fa-fw mr-1" aria-hidden="true"></i>
                                            {{ trans('enable') }}
                                        </a>
                                    </div>
                                </div>
                            {% else %}
                                <a class="btn btn-sm btn-success btn-spin-action" onclick="animateSpinner('add');"
                                   href="{{ url }}?action=enable&amp;plugin={{ plugin.name }}&amp;multireqtoken={{ formToken(false) }}">
                                    <i class="fa-solid fa-toggle-on mr-1" aria-hidden="true"></i>
                                    <span class="d-none d-sm-inline-block">{{ trans('enable') }}</span>
                                </a>
                            {% endif %}
                        {% else %}
                            {{ plugin.compatibilityDescription() }}
                        {% endif %}
                        {% if plugin.enabled == false and config('disable_rm_plugins', false) == false %}
                            <a class="btn btn-sm btn-danger ml-2 btn-spin-action" href="#"
                               title="{{ trans('delete') }}" onclick="deletePlugin('{{ plugin.name }}');">
                                <i class="fas fa-trash-alt" aria-hidden="true"></i>
                            </a>
                        {% endif %}
                    </td>
                </tr>
            {% else %}
                <tr class="table-warning">
                    <td colspan="4"><b>{{ trans('no-data') }}</b></td>
                </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>
{% endmacro %}