{% extends 'base.html.twig' %}
{% import "macros/widgets.html.twig" as widgets %}
{% import "macros/datatables.html.twig" as tables %}

{% set totalDuration = 0 %}
{% set totalRates = {} %}
{% set totalItems = 0 %}
{% set entries = preview is not null ? preview.exportItems : [] %}
{% set preview_items = entries|length %}

{% if preview is not null %}
    {% for row in preview.statistic %}
        {% set totalItems = totalItems + row.count %}
        {% set totalDuration = totalDuration + row.duration %}
        {% set customerCurrency = row.customer.currency %}
        {% if totalRates[customerCurrency] is not defined %}
            {% set totalRates = totalRates|merge({(customerCurrency): 0.00}) %}
        {% endif %}
        {% set totalRates = totalRates|merge({(customerCurrency): totalRates[customerCurrency] + row.rate}) %}
    {% endfor %}
{% endif %}

{% set columns = {
    'avatar': {'class': 'text-nowrap w-avatar d-none d-md-table-cell', 'title': false, 'orderBy': false},
    'date': {'class': 'alwaysVisible text-nowrap', 'orderBy': false},
    'begin': {'class': 'd-none', 'orderBy': false},
    'end': {'class': 'd-none', 'orderBy': false},
    'user': {'class': 'd-none', 'orderBy': false},
    'project': {'class': 'd-none d-sm-table-cell', 'orderBy': false},
    'activity': {'class': 'd-none', 'orderBy': false},
    'description': {'class': 'd-none d-xl-table-cell timesheet-description', 'orderBy': false},
    'tags': {'class': 'd-none d-xl-table-cell', 'orderBy': false},
    'duration': {'class': 'text-end text-nowrap', 'orderBy': false},
} %}
{% if show_rates %}
    {% set columns = columns|merge({
        'unit_price': {'class': 'd-none text-nowrap text-end', 'orderBy': false},
        'internalRate': {'class': 'text-end d-none text-nowrap', 'orderBy': false},
        'total_rate': {'class': 'text-end text-nowrap', 'orderBy': false},
    }) %}
{% endif %}
{% set columns = columns|merge({
    'actions': {'class': 'actions alwaysVisible', 'orderBy': false},
}) %}

{% set tableName = 'export' %}
{% set editExported = is_granted('edit_exported_timesheet') %}
{% set showMarkAsExportedButton = false %}
{% set showToggleButton = false %}
{% if preview is not null and form.markAsExported is defined %}
    {% set showMarkAsExportedButton = form.exported.vars.value != constant('App\\Repository\\Query\\TimesheetQuery::STATE_EXPORTED') %}
    {% set showToggleButton = form.exported.vars.value != constant('App\\Repository\\Query\\TimesheetQuery::STATE_ALL') %}
{% endif %}

{% block status %}
    {% from "macros/status.html.twig" import status_duration, status_money %}
    {% if totalDuration > 0 %}
        {{ status_duration(totalDuration|duration) }}
    {% endif %}
    {% if show_rates %}
        {% for totalCurrency, totalRate in totalRates %}
            {{ status_money(totalRate|money(totalCurrency)) }}
        {% endfor %}
    {% endif %}
{% endblock %}

{% block main_before %}
    {{ tables.data_table_column_modal(tableName, columns) }}
{% endblock %}

{% block main %}

    {% embed '@theme/embeds/card.html.twig' %}
        {% import "macros/search.html.twig" as search %}
        {% form_theme form 'form/horizontal.html.twig' %}
        {% block box_title %}{{ 'export.filter'|trans }}{% endblock %}
        {% block box_before %}{{ form_start(form) }}{% endblock %}
        {% block box_body %}
            {{ form_errors(form) }}
            {{ form_row(form.searchTerm) }}
            {{ form_row(form.daterange) }}
            {{ form_row(form.customers) }}
            {{ form_row(form.projects) }}
            {{ form_row(form.activities) }}
            {{ form_row(form.tags) }}
            {% if form.users is defined %}
                {{ form_row(form.users) }}
            {% endif %}
            {% if form.teams is defined %}
                {{ form_row(form.teams) }}
            {% endif %}
            {{ form_row(form.billable) }}
            {{ form_row(form.exported) }}
            {{ form_row(form.state) }}
            {% if form.markAsExported is defined %}
                {{ form_row(form.markAsExported) }}
            {% endif %}
        {% endblock %}
        {% block box_footer%}
            {{ search.searchButton(form) }}
        {% endblock %}
        {% block box_after %}
            {{ form_end(form) }}
            <div style="display: none" id="export-token" data-value="{{ csrf_token('export.data') }}"></div>
        {% endblock %}
    {% endembed %}

    {% if preview is not null %}
        {% if entries is empty %}
            {{ widgets.nothing_found() }}
        {% else %}
            {% embed '@theme/embeds/card.html.twig' with {fullsize: true}  %}
                {% import "macros/widgets.html.twig" as widgets %}
                {% block box_title %}
                    {{ 'preview'|trans }}
                {% endblock %}
                {% block box_attributes %}id="preview_export"{% endblock %}
                {% block box_body %}
                    <table class="table table-hover dataTable">
                        <thead>
                        <tr>
                            <th>{{ 'customer'|trans }}</th>
                            <th class="w-min text-end d-none d-sm-table-cell">{{ 'duration'|trans }}</th>
                            {% if show_rates %}
                            <th class="w-min text-end">{{ 'total_rate'|trans }}</th>
                            {% endif %}
                        </tr>
                        </thead>
                        <tbody>
                        {% for row in preview.statistic %}
                            {% set currency = row.customer.currency %}
                            <tr>
                                <td>
                                    {{ widgets.label_customer(row.customer) }}
                                </td>
                                <td class="w-min text-end d-none d-sm-table-cell">
                                    {{ row.duration|duration }}
                                </td>
                                {% if show_rates %}
                                <td class="w-min text-end">
                                    {{ row.rate|money(currency) }}
                                </td>
                                {% endif %}
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                {% endblock %}
            {% endembed %}


            {% if preview is not null %}
                {% if totalItems > max_export_items %}
                    {{ widgets.callout('danger', 'export.too_many_entries'|trans({'%limit%': max_export_items, '%count%': totalItems})) }}
                {% else %}
                    <div class="btn-list w-100 mb-3">
                        {{ tables.datatable_column_modal_link(tableName) }}
                        <div class="btn-group{% if not showMarkAsExportedButton %} me-auto{% endif %}" id="export-buttons" role="group">
                            {% set allowCreate = is_granted('create_export_template') %}
                            {% for type, group in buttons %}
                                {% if type == 'html' %}
                                    {% set type = 'print' %}
                                {% endif %}
                                {% set btnTitle = type|trans %}
                                {% if group|length == 1 %}
                                    {% for id, cfg in group %}
                                        {% set title = cfg.title %}
                                        <button type="button" id="export-{{ id }}-button" class="btn btn-primary startExportBtn" data-type="{{ id }}">
                                            {{ btnTitle }}
                                        </button>
                                    {% endfor %}
                                {% else %}
                                    <div class="btn-group">
                                        <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                            {{ btnTitle }}
                                        </button>
                                        <div class="dropdown-menu">
                                            {% for id, cfg in group %}
                                                {% set btnTitle = (cfg.title)|trans %}
                                                {% if id == type %}
                                                    {% set btnTitle = 'default'|trans %}
                                                {% endif %}
                                                <a href="#" class="dropdown-item startExportBtn" data-type="{{ id }}">
                                                    {{ btnTitle }}
                                                    {% if allowCreate and cfg.internal %}
                                                        <span class="dropdown-action modal-ajax-form open-edit ps-2 ms-auto" data-href="{{ path('export_template_edit', {exportTemplate: id}) }}">{{ icon('edit') }}</span>
                                                        <span class="dropdown-action api-link text-red dd-ts-trash text-danger ms-2" href="{{ path('delete_export_template', {id: id}) }}" data-event="kimai.exportTemplate" data-method="DELETE" data-question="confirm.delete" data-msg-error="action.delete.error">{{ icon('delete') }}</span>
                                                    {% endif %}
                                                </a>
                                            {% endfor %}
                                        </div>
                                    </div>
                                {% endif %}
                            {% endfor %}
                            {% if allowCreate %}
                                {{ widgets.action_button('create', {'url': path('export_template_create'), 'class': 'btn modal-ajax-form open-edit', 'title': 'create'|trans}) }}
                            {% endif %}
                        </div>
                        {% if showMarkAsExportedButton %}
                            <div class="form-check form-switch d-flex align-items-center mb-0 me-auto">
                                <input type="checkbox" id="markAsExportedCheck" name="markAsExportedCheck" class="form-check-input mt-0" value="1" {% if form.markAsExported.vars.value == '1' %} checked="checked"{% endif %}>
                                <label class="form-check-label ms-2" for="markAsExportedCheck">{{ 'mark_as_exported'|trans }}</label>
                            </div>
                        {% endif %}
                        {% if showToggleButton %}
                            <button id="toggle-button" class="btn ms-auto d-none d-sm-inline-flex">
                                {% if form.exported.vars.value == '5' %}
                                    {{ icon('off', true) }}
                                    {{ 'mark_as_exported'|trans }}
                                {% elseif form.exported.vars.value == '4' %}
                                    {{ icon('on', true) }}
                                    {{ 'mark_as_open'|trans }}
                                {% endif %}
                            </button>
                        {% endif %}
                    </div>
                {% endif %}
            {% endif %}

            {{ tables.datatable_header(tableName, columns, query, {columnConfig: false}) }}
            {% set edit_route = is_granted('view_other_timesheet') ? 'admin_timesheet_edit' : 'timesheet_edit' %}
            {% for entry in entries %}
                {% set currency = entry.project.customer.currency %}
                {% if entry.fixedRate is not null %}
                    {% set rate = entry.fixedRate %}
                {% else %}
                    {% set rate = entry.hourlyRate %}
                {% endif %}
                <tr{%- if entry.type == 'timesheet' and is_granted('edit', entry) %}
                    class="modal-ajax-form open-edit" data-href="{{ path(edit_route, {'id': entry.id}) }}"{% endif -%}>
                    <td class="{{ tables.data_table_column_class(tableName, columns, 'avatar') }}">
                        {{ widgets.user_avatar(entry.user) }}
                    </td>
                    <td class="{{ tables.data_table_column_class(tableName, columns, 'date') }}">
                        {{ entry.begin|date_short }}
                    </td>
                    <td class="{{ tables.data_table_column_class(tableName, columns, 'begin') }}">
                        {{ entry.begin|time }}
                    </td>
                    <td class="{{ tables.data_table_column_class(tableName, columns, 'begin') }}">
                        {% if entry.end %}
                            {{ entry.end|time }}
                        {% else %}
                            &dash;
                        {% endif %}
                    </td>
                    <td class="{{ tables.data_table_column_class(tableName, columns, 'user') }}">
                        {{ widgets.label_user(entry.user) }}
                    </td>
                    <td class="{{ tables.data_table_column_class(tableName, columns, 'project') }}">
                        {{ widgets.label_project(entry.project) }}
                        <br>
                        <small>{{ widgets.label_customer(entry.project.customer) }}</small>
                    </td>
                    <td class="{{ tables.data_table_column_class(tableName, columns, 'activity') }}">
                        {% if entry.activity is not null %}
                            {{ widgets.label_activity(entry.activity) }}
                        {% endif %}
                    </td>
                    <td class="{{ tables.data_table_column_class(tableName, columns, 'description') }}">
                        {{ entry.description|desc2html }}
                    </td>
                    <td class="{{ tables.data_table_column_class(tableName, columns, 'tags') }}">
                        {% if entry.type == 'timesheet' %}
                            {{ widgets.tag_list(entry.tags) }}
                        {% endif %}
                    </td>
                    <td class="{{ tables.data_table_column_class(tableName, columns, 'duration') }}" data-duration="{{ entry.duration }}">
                        {{ entry.duration|duration }}
                    </td>
                    {% if show_rates %}
                    <td class="{{ tables.data_table_column_class(tableName, columns, 'unit_price') }}">
                        {{ rate|money(currency) }}
                    </td>
                    <td class="{{ tables.data_table_column_class(tableName, columns, 'internalRate') }}">
                        {{ entry.internalRate|money(currency) }}
                    </td>
                    <td class="{{ tables.data_table_column_class(tableName, columns, 'total_rate') }}">
                        {{ entry.rate|money(currency) }}
                    </td>
                    {% endif %}
                    <td class="{{ tables.data_table_column_class(tableName, columns, 'actions') }}">
                    {% if is_granted('edit_export', entry) %}
                        {% if entry.exported %}
                            {% if editExported %}
                                <button type="button" class="btn btn-default exportBtn" data-toggle="button" aria-pressed="true"
                                        data-exported-text="{{ 'entryState.exported'|trans }}" data-clean-text="{{ 'entryState.not_exported'|trans }}" data-timesheet="{{ entry.id }}">
                                    {{ 'entryState.exported'|trans }}
                                </button>
                            {% else %}
                                {{ 'entryState.exported'|trans }}
                            {% endif %}
                        {% else %}
                            <button type="button" class="btn btn-default exportBtn" data-toggle="button" aria-pressed="false"
                                    data-exported-text="{{ 'entryState.exported'|trans }}" data-clean-text="{{ 'entryState.not_exported'|trans }}" data-timesheet="{{ entry.id }}">
                                {{ 'entryState.not_exported'|trans }}
                            </button>
                        {% endif %}
                    {% else %}
                        {% if entry.exported %}
                            {{ 'entryState.exported'|trans }}
                        {% else %}
                            {{ 'entryState.not_exported'|trans }}
                        {% endif %}
                    {% endif %}
                    </td>
                </tr>
            {% endfor %}
            {% if totalItems > preview_items %}
                <tr class="warning">
                    <td colspan="10">&raquo; {{ 'preview.skipped_rows'|trans({'%rows%': (totalItems - preview_items)}) }}</td>
                </tr>
            {% endif %}
            {{ tables.data_table_footer(entries) }}
        {% endif %}
    {% endif %}

{% endblock %}

{% block javascripts %}
    {{ parent() }}
    <script type="text/javascript">
        KimaiReloadPageWidget.create('kimai.exportTemplate', true);

        function updateTimesheetExportState(node, id)
        {
            /** @type {KimaiAlert} */
            const ALERT = kimai.getPlugin('alert');
            /** @type {KimaiAPI} */
            const API = kimai.getPlugin('api');

            API.patch(
                '{{ path('export_timesheet', {id: 1}) }}'.replace('1', id),
                {},
                function(data) {
                    const table = node.closest('table')
                    const row = node.closest('tr');
                    row.remove();
                    const list = table.querySelectorAll('tbody tr');
                    if (list.length === 0) {
                        document.querySelector('form#export-form button.performSearch').click();
                    }
                }
            );
        }

        document.addEventListener('kimai.initialized', function() {
            document.addEventListener('click', function (event) {
                const node = event.target;
                if (node.matches('.exportBtn')) {
                    if (node.dataset['timesheet'] !== undefined) {
                        const id = node.dataset['timesheet'];
                        updateTimesheetExportState(node, id);
                    }
                }

                {#
                    THE GROUP OF EXPORT BUTTONS FOR ALL FORMATS
                    Toggle the form, because by default it triggers the search
                #}
                if (node.matches('#export-buttons .startExportBtn')) {
                    event.preventDefault();

                    /** @type {KimaiForm} */
                    const FORM = kimai.getPlugin('form');
                    const overwrites = {
                        'renderer': node.dataset['type'],
                        '_token': document.getElementById('export-token').dataset['value'],
                    };

                    const uri = FORM.convertFormDataToQueryString(document.getElementById('export-form'), overwrites);

                    // remove the form of a previous export, it cannot be deleted right
                    // after submitting it, as that might cancel the pending request
                    const previous = document.getElementById('export-post-form');
                    if (previous !== null) {
                        previous.remove();
                    }

                    const form = document.createElement('form');
                    form.id = 'export-post-form';
                    form.method = 'POST';
                    form.action = '{{ path('export_data') }}';
                    form.target = '_blank';

                    for (const [name, value] of new URLSearchParams(uri)) {
                        const field = document.createElement('input');
                        field.type = 'hidden';
                        field.name = name;
                        field.value = value;
                        form.appendChild(field);
                    }

                    document.body.appendChild(form);
                    form.submit();
                }
            }, false);

            {% if showMarkAsExportedButton %}
            let mrkExpBtn = document.getElementById('markAsExportedCheck');
            if (mrkExpBtn !== null) {
                mrkExpBtn.addEventListener('change', function (event) {
                    document.getElementById('markAsExported').value = event.target.checked ? 1 : 0;
                });
            }
            {% endif %}
        });

        {% if showToggleButton %}
            function confirmToggleState(doExport)
            {
                let ALERT = kimai.getPlugin('alert');
                let message = '{{ 'export.clear_all'|trans }}';

                if (doExport) {
                    message = '{{ 'export.mark_all'|trans }}';
                }

                ALERT.question(message, function(value) {
                    if (!value) {
                        return;
                    }

                    [].slice.call(document.querySelectorAll('.exportBtn')).map(function (element) {
                        element.click();
                    });

                    document.getElementById('toggle-button').classList.add('d-none');
                });
            }

            let tglBtn = document.getElementById('toggle-button');

            if (tglBtn !== null) {
                tglBtn.addEventListener('click', function (event) {
                    confirmToggleState({% if form.exported.vars.value == '5' %}true{% else %}false{% endif %});
                }, false);
            }
        {% endif %}
    </script>
{% endblock %}
