{% extends request.ajax ? "layout_blank.html.twig" : "layout_default.html.twig" %}
{% set active_menu = 'emails' %}

{% block meta_title %}{{ 'Emails'|trans }}{% endblock %}
{% block breadcrumb %}
    <li class="active breadcrumb-item" aria-current="page">{{ 'Emails'|trans }}</li>{% endblock %}

{% set emails = client.email_get_list({"per_page":10, "page":request.page}) %}

{% block body_class %}email-index{% endblock %}
{% block content %}
    <div class="row">
        <div class="col-md-12">
            <div class="card mb-4">
                <div class="card-header py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h1 class="mb-1">{{ 'Emails'|trans }}</h1>
                            <span class="small text-muted">{{ "Here you can find all the emails we've sent you."|trans }}</span>
                        </div>
                    </div>
                </div>
                <div class="card-body p-0">
                    {% if emails.list is empty %}
                    <div class="m-2 alert alert-info"
                         id="information-block">{{ 'There are no emails to display'|trans }}</div>
                    {% else %}
                    <div class="d-flex">
                        <div class="nav nav-tabs flex-column col-md-4 border-0">
                            <div class="list-group email-list" id="list-tab" role="tablist">
                                {% for i, email in emails.list %}
                                    <a class="list-group-item list-group-item-action mt-0{% if loop.first %} active{% endif %}"
                                       href="#mail-{{ loop.index }}" data-bs-toggle="list" role="tab">
                                        <div class="flex-column py-1">
                                            <p class="m-0" style="font-size: 80%;">{{ email.subject|truncate }}</p>
                                            <span class="text-muted small" style="font-size: 80%;">{{ email.created_at|format_datetime }}</span>
                                        </div>
                                    </a>
                                {% endfor %}
                            </div>
                        </div>

                        <div class="col-md-8 tab-content m-0 border-start">
                            {% for i, email in emails.list %}
                                <div class="tab-pane fade{% if loop.first %} show active{% endif %}"
                                     id="mail-{{ loop.index }}" role="tabpanel">
                                    <div class="card-body">
                                        <h6 class="mb-0">{{ email.subject }}</h6>
                                        <div class="card-header px-0">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <div class="d-flex flex-column gap-1">
                                                    <span class="d-block"><span class="text-muted me-2">{{ 'From'|trans }}</span>{{ email.sender }}</span>
                                                    <span class="d-block"><span class="text-muted me-2">{{ 'To'|trans }}</span>{{ email.recipients }}</span>
                                                </div>
                                                <div class="d-flex flex-column gap-2">
                                                    <div class="btn-group d-flex" role="group" aria-label="{{ 'Mail Action'|trans }}">
                                                        <a class="btn btn-sm btn-outline-secondary border-end-0" href='{{ "email/#{email.id}"|url }}' data-bs-toggle="tooltip" data-bs-title="{{ 'View'|trans }}">
                                                            <svg class="svg-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12,9A3,3 0 0,1 15,12A3,3 0 0,1 12,15A3,3 0 0,1 9,12A3,3 0 0,1 12,9M12,4.5C17,4.5 21.27,7.61 23,12C21.27,16.39 17,19.5 12,19.5C7,19.5 2.73,16.39 1,12C2.73,7.61 7,4.5 12,4.5M3.18,12C4.83,15.36 8.24,17.5 12,17.5C15.76,17.5 19.17,15.36 20.82,12C19.17,8.64 15.76,6.5 12,6.5C8.24,6.5 4.83,8.64 3.18,12Z" /></svg>
                                                        </a>
                                                        <a class="btn btn-sm btn-outline-secondary email-resend" href="#" data-id="{{ email.id }}" data-bs-toggle="tooltip" data-bs-title="{{ 'Resend'|trans }}">
                                                            <svg class="svg-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M6,5.75L10.25,10H7V16H13.5L15.5,18H7A2,2 0 0,1 5,16V10H1.75L6,5.75M18,18.25L13.75,14H17V8H10.5L8.5,6H17A2,2 0 0,1 19,8V14H22.25L18,18.25Z" /></svg>
                                                        </a>
                                                        <a class="btn btn-sm btn-outline-danger border-start-0 email-delete" href="#" data-id="{{ email.id }}" data-bs-toggle="tooltip" data-bs-title="{{ 'Delete'|trans }}">
                                                            <svg class="svg-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19M8,9H16V19H8V9M15.5,4L14.5,3H9.5L8.5,4H5V6H19V4H15.5Z" /></svg>
                                                        </a>
                                                    </div>
                                                    <small class="text-muted">{{ email.created_at|format_date }}</small>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="card-body">
                                            {# Workaround: email styling can effect the style of this page, so instead we use JS to insert the email contents into an iframe. A default height is set in case of errors #}
                                            <iframe class="ratio ratio-1x1 email" id="email-content-{{ i }}" src="about:blank" sandbox="allow-same-origin allow-popups" style="height: 30em"></iframe>
                                            <script>
                                                (function () {
                                                    const frame = document.getElementById("email-content-{{ i }}");
                                                    frame.srcdoc = '{{ email.content_html|e('js') }}';
                                                })();
                                            </script>
                                        </div>
                                    </div>
                                </div>
                            {% endfor %}
                        </div>
                    </div>
                </div>
                    {% if emails.pages >= 2 %}
                        <div class="card-footer">
                            {{ include('partial_pagination.html.twig', { 'list': emails }) }}
                        </div>
                    {% endif %}
                {% endif %}
            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
    {% autoescape "js" %}
        <script>
            document.addEventListener("DOMContentLoaded", () => {
                const resendEmailBtn = document.querySelectorAll('.email-resend');
                const deleteEmailBtn = document.querySelectorAll('.email-delete');

                resendEmailBtn.forEach((resendBtn) => {
                    resendBtn.addEventListener('click', (e) => {
                        e.preventDefault();
                        toggleLoader();
                        FOSSBilling.api.client.post('email/resend', { id: resendBtn.dataset.id },
                            () => {
                                flashMessage({
                                    message: 'Email resent',
                                    reload: '{{ 'email'|url }}'
                                });
                            },
                            (res) => {
                                FOSSBilling.message(`${res.message} (${res.code})`, 'error');
                                toggleLoader();
                            }
                        )
                    });
                });

                deleteEmailBtn.forEach((deleteBtn) => {
                    deleteBtn.addEventListener('click', (e) => {
                        e.preventDefault();
                        if (confirm('Are you sure?')) {
                            toggleLoader();
                            FOSSBilling.api.client.post('email/delete', { id: deleteBtn.dataset.id },
                                () => {
                                    flashMessage({
                                        message: 'Email #'+ deleteBtn.dataset.id +' deleted',
                                        reload: '{{ 'email'|url }}'
                                    });
                                },
                                (res) => {
                                    FOSSBilling.message(`${res.message} (${res.code})`, 'error');
                                    toggleLoader();
                                }
                            )
                        }
                    });
                });

                const toggleLoader = () => {
                    let loader = document.querySelector('.wait');
                    if (loader.style.display === 'none') {
                        loader.style.display = 'block';
                    } else {
                        loader.style.display = 'none';
                    }
                }

                {# Resizing the email iframes proved to be temperamental. The below code does it automatically using events. We can't do it all at once as the hidden tabs end up with a height of 0 #}
                function setEmailHeights(){
                    const emails = document.querySelectorAll('.email');
                    emails.forEach(email => {
                        var body = email.contentDocument.body;
                        var html = email.contentDocument.documentElement;
                        if(body){
                            var height = Math.max(body.scrollHeight, body.offsetHeight);
                        } else if (html) {
                            var height = Math.max(html.clientHeight, html.scrollHeight, html.offsetHeight);
                        } else {
                            return;
                        }
                        email.height = height;
                    });
                };

                window.addEventListener("DOMContentLoaded", setEmailHeights());

                var tabElms = document.querySelectorAll('a[data-bs-toggle="list"]');

                tabElms.forEach(element => {
                    element.addEventListener('shown.bs.tab', function() {
                        setEmailHeights()
                    });
                });
            });
        </script>
    {% endautoescape %}
{% endblock %}
