{#
/**
 * This file is part of FacturaScripts
 * Copyright (C) 2017-2025 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" %}

{% block bodyHeaderOptions %}
    <br/>
    <br/>
    <br/>
{% endblock %}

{% block body %}
    <div class="container" style="margin-top: -60px;">
        <div class="row">
            <div class="col-12">
                <form action="{{ fsc.url() }}" method="post" enctype="multipart/form-data"
                      onsubmit="animateSpinner('add')">
                    {{ formToken() }}
                    <input type="hidden" name="action" value="send"/>
                    <div class="card shadow">
                        <div class="card-body">
                            <h1 class="h3 mb-3">
                                <i class="fa-solid fa-envelope fa-fw" aria-hidden="true"></i> {{ trans('send-mail') }}
                            </h1>
                            {% for includeView in getIncludeViews('SendMail', 'beforeFrom') %}
                                {% include includeView['path'] %}
                            {% endfor %}
                            <div class="mb-3">
                                <div class="input-group">
                                    <span class="input-group-text">{{ trans('from') }}</span>
                                    <select class="form-select" name="email-from">
                                        {% for emailFrom in fsc.newMail.getAvailableMailboxes() %}
                                            <option value="{{ emailFrom }}" {{ fsc.newMail.fromEmail is same as(emailFrom) ? 'selected' : '' }}>{{ emailFrom }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>
                            {% for includeView in getIncludeViews('SendMail', 'beforeTo') %}
                                {% include includeView['path'] %}
                            {% endfor %}
                            <div class="mb-3">
                                <div class="input-group">
                                    <span class="input-group-text">{{ trans('to') }}</span>
                                    {% set emailsTo = fsc.newMail.getToAddresses() is empty ? '' : fsc.newMail.getToAddresses() | join(', ') ~ ', ' %}
                                    {% set emailsCC = fsc.newMail.getCCAddresses() is empty ? '' : fsc.newMail.getCCAddresses() | join(', ') ~ ', ' %}
                                    {% set emailsBCC = fsc.newMail.getBCCAddresses() is empty ? '' : fsc.newMail.getBCCAddresses() | join(', ') ~ ', ' %}
                                    <input type="text" id="email-to" name="email-to" value="{{ emailsTo }}" class="form-control"
                                           placeholder="{{ trans('email-to') }}" required/>
                                    <button type="button" class="btn btn-outline-secondary" style="display: {{ emailsCC is empty() ? 'block' : 'none' }};"
                                                title="{{ trans('email-cc') }}" onclick="$('#fgCC').show();
                                                $(this).hide();">{{ trans('cc') }}
                                        </button>
                                        <button type="button" class="btn btn-outline-secondary" style="display: {{ emailsBCC is empty() ? 'block' : 'none' }};"
                                                title="{{ trans('email-bcc') }}" onclick="$('#fgBCC').show();
                                                $(this).hide();">{{ trans('bcc') }}
                                        </button>
                                </div>
                            </div>
                            {% for includeView in getIncludeViews('SendMail', 'beforeCC') %}
                                {% include includeView['path'] %}
                            {% endfor %}
                            <div id="fgCC" class="mb-3" style="display: {{ emailsCC is empty() ? 'none' : 'block' }};">
                                <div class="input-group">
                                    <span class="input-group-text">{{ trans('cc') }}</span>
                                    <input type="text" id="email-cc" name="email-cc" class="form-control"
                                           placeholder="{{ trans('email-cc') }}" value="{{ emailsCC }}"/>
                                </div>
                            </div>
                            {% for includeView in getIncludeViews('SendMail', 'beforeBCC') %}
                                {% include includeView['path'] %}
                            {% endfor %}
                            <div id="fgBCC" class="mb-3" style="display: {{ emailsBCC is empty() ? 'none' : 'block' }};">
                                <div class="input-group">
                                    <span class="input-group-text">{{ trans('bcc') }}</span>
                                    <input type="text" id="email-bcc" name="email-bcc" class="form-control"
                                           placeholder="{{ trans('email-bcc') }}" value="{{ emailsBCC }}"/>
                                </div>
                            </div>
                            {% for includeView in getIncludeViews('SendMail', 'beforeSubject') %}
                                {% include includeView['path'] %}
                            {% endfor %}
                            <div class="mb-3">
                                <div class="input-group">
                                    <span class="input-group-text">{{ trans('subject') }}</span>
                                    <input type="text" name="email-subject" value="{{ fsc.newMail.title }}"
                                           class="form-control" placeholder="{{ trans('subject') }}" required/>
                                </div>
                            </div>
                            {% for includeView in getIncludeViews('SendMail', 'beforeBody') %}
                                {% include includeView['path'] %}
                            {% endfor %}
                            <div class="mb-3">
                                <textarea name="email-body" rows="5"
                                          class="form-control">{{ fsc.newMail.text | raw }}</textarea>
                            </div>
                            {% if fsc.newMail.signature %}
                                {% for includeView in getIncludeViews('SendMail', 'beforeSignature') %}
                                    {% include includeView['path'] %}
                                {% endfor %}
                                <div class="mb-3">
                                    {{ trans('email-signature') }}
                                    <textarea rows="3" class="form-control"
                                              readonly tabindex="-1">{{ fsc.newMail.signature }}</textarea>
                                </div>
                            {% endif %}
                            {% for includeView in getIncludeViews('SendMail', 'beforeAttachment') %}
                                {% include includeView['path'] %}
                            {% endfor %}
                            {% for name in fsc.newMail.getAttachmentNames() %}
                                <p>
                                    <i class="fa-solid fa-paperclip fa-fw" aria-hidden="true"></i> {{ name }}
                                </p>
                            {% endfor %}
                            <div id="email-attachments"></div>
                            {% for includeView in getIncludeViews('SendMail', 'beforeEnd') %}
                                {% include includeView['path'] %}
                            {% endfor %}
                            <div class="row align-items-end">
                                <div class="col-sm-6">
                                    {% if settings('email', 'replytouseremail', '1') in ['1', '0'] %}
                                        {% set check = settings('email', 'replytouseremail') == '1' ? 'checked' : '' %}
                                        <div class="form-check">
                                            <input type="checkbox" name="replyto" value="1" {{ check }}
                                                   class="form-check-input" id="replytoCheck"/>
                                            <label class="form-check-label" for="replytoCheck">
                                                {{ trans('email-replies-to', {'%email%': fsc.user.email}) }}
                                            </label>
                                        </div>
                                    {% endif %}
                                </div>
                                <div class="col-sm-6 text-end">
                                    <button type="submit" class="btn btn-primary btn-spin-action">
                                        <i class="fa-solid fa-envelope me-1" aria-hidden="true"></i> {{ trans('send') }}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
                {% for includeView in getIncludeViews('SendMail', 'afterEnd') %}
                    {% include includeView['path'] %}
                {% endfor %}
            </div>
        </div>
    </div>
{% endblock %}

{% block css %}
    {{ parent() }}
    <link rel="stylesheet" href="{{ asset('node_modules/jquery-ui-dist/jquery-ui.min.css') }}"/>
{% endblock %}

{% block javascripts %}
    {{ parent() }}
    <script src="{{ asset('node_modules/jquery-ui-dist/jquery-ui.min.js') }}"></script>
    <script>
        function addAnotherInputFile(input) {
            // si en el div de email-attachments el último input file está vacío, no añadimos otro
            let inputs = document.getElementById('email-attachments').getElementsByTagName('input');
            if (inputs.length > 0 && inputs[inputs.length - 1].value === '') {
                clearInputFile();
                return;
            }

            // si el archivo subido es una carpeta, no lo añadimos y limpiamos el input
            if (input && input.target.files.length > 0 && input.target.files[0].type === '') {
                input.target.value = '';
                return;
            }

            let div = document.createElement('div');
            div.className = 'mb-3';

            let file = document.createElement('input');
            file.type = 'file';
            file.name = 'uploads[]';
            file.className = 'form-control';
            file.onchange = addAnotherInputFile;
            file.multiple = true;
            div.appendChild(file);

            document.getElementById('email-attachments').appendChild(div);
            clearInputFile();
        }

        function clearInputFile() {
            // obtenemos todos los inputs file
            let inputs = document.getElementById('email-attachments').getElementsByTagName('input');

            // eliminamos los inputs que estén vacíos, excepto el último
            for (let i = 0; i < inputs.length - 1; i++) {
                if (inputs[i].value === '') {
                    inputs[i].parentNode.remove();
                }
            }
        }

        function extractLast(term) {
            return split(term).pop();
        }

        function split(val) {
            return val.split(/,\s*/);
        }

        $(document).ready(function () {
            let cacheQuery = {};
            $("#email-to,#email-cc,#email-bcc").on("keydown", function (event) {
                if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete("instance").menu.active) {
                    event.preventDefault();
                }
            }).autocomplete({
                minLength: 0,
                source: function (request, response) {
                    // Avoid re-query the same
                    let term = request.term;
                    if (term in cacheQuery) {
                        response(cacheQuery[term]);
                        return;
                    }

                    $.getJSON("SendMail", {
                        action: 'autocomplete',
                        source: 'contactos',
                        field: 'email',
                        title: 'email',
                        term: extractLast(request.term)
                    }, function (data) {
                        cacheQuery[term] = data;
                        response(data);
                    });
                },
                focus: function () {
                    // Prevent value inserted on focus
                    return false;
                },
                select: function (event, ui) {
                    let terms = split(this.value);
                    // Remove the current input
                    terms.pop();
                    // Add the selected item
                    terms.push(ui.item.value);
                    // Add placeholder to get the comma-and-space at the end
                    terms.push("");
                    this.value = terms.join(", ");
                    return false;
                }
            });

            addAnotherInputFile();
        });
    </script>
{% endblock %}