{% extends "layout_default.html.twig" %}

{% block meta_title %}{{ 'Email Template'|trans }}{% endblock %}
{% set active_menu = 'system' %}
{% set can_manage_settings = has_permission('email', 'manage_settings') %}
{% set can_manage_templates = has_permission('email', 'manage_templates') %}

{% block breadcrumbs %}
    <ol class="breadcrumb">
        <li class="breadcrumb-item">
            <a href="{{ '/'|url }}">
                <svg class="icon">
                    <use xlink:href="#home" />
                </svg>
            </a>
        </li>
        <li class="breadcrumb-item">
            <a href="{{ 'system'|url }}">{{ 'Settings'|trans }}</a>
        </li>
        <li class="breadcrumb-item">
            {% if can_manage_settings %}
            <a href="{{ 'extension/settings/email'|url }}">{{ 'Email'|trans }}</a>
            {% else %}
                {{ 'Email'|trans }}
            {% endif %}
        </li>
        <li class="breadcrumb-item active" aria-current="page">{{ template.action_code }}</li>
    </ol>
{% endblock %}

{% block content %}
    {% embed 'partial_admin_detail_tabs.html.twig' with {
        title: template.action_code,
        subtitle: 'Manage the email template content, inspect available variables, and preview how the rendered message will look.'|trans
    } %}
        {% block detail_tabs %}
                        <li class="nav-item" role="presentation">
                            <a class="nav-link active" href="#tab-template" data-bs-toggle="tab" role="tab">{{ 'Template'|trans }}</a>
                        </li>
                        <li class="nav-item" role="presentation">
                            <a class="nav-link" href="#tab-vars" data-bs-toggle="tab" role="tab">{{ 'Variables'|trans }}</a>
                        </li>
                        {% if can_manage_templates %}
                            <li class="nav-item" role="presentation">
                                <a class="nav-link" href="#tab-manage" data-bs-toggle="tab" role="tab">{{ 'Template Settings'|trans }}</a>
                            </li>
                        {% endif %}
                        {% if can_manage_templates %}
                            <li class="nav-item" role="presentation">
                                <a class="nav-link" href="#tab-examples" data-bs-toggle="tab" role="tab">{{ 'Examples'|trans }}</a>
                            </li>
                        {% endif %}
        {% endblock %}

        {% block detail_tab_content %}
                <div class="tab-pane fade show active" id="tab-template" role="tabpanel">
                    <div class="p-3">
                        <form method="post" action="admin/email/template_update" {{ fb_api_form({message: 'Template Updated'|trans}) }}>
                            <input type="hidden" name="id" value="{{ template.id }}">
                            {% embed 'partial_admin_form_card.html.twig' with {
                                title: 'Manage Email Template'|trans,
                                subtitle: 'Email templates can receive variables from FOSSBilling. Available variables are listed under the Variables tab, and preview will render the current content using example values.'|trans
                            } %}
                                {% block form_content %}
                                    {% if not can_manage_templates %}
                                        <div class="alert alert-warning" role="alert">
                                            <strong class="me-1">{{ 'Warning:'|trans }}</strong>{{ 'You can view this email template, but you do not have permission to edit or preview it.'|trans }}
                                        </div>
                                    {% endif %}
                                    {% if template.is_custom %}
                                        <div class="alert alert-info" role="alert">
                                            <strong class="me-1">{{ 'Information:'|trans }}</strong>{{ 'This is a custom template stored in the database.'|trans }}
                                        </div>
                                    {% elseif not template.has_default %}
                                        <div class="alert alert-warning" role="alert">
                                            <strong class="me-1">{{ 'Warning:'|trans }}</strong>{{ 'This template no longer has a file-backed default.'|trans }}
                                        </div>
                                    {% elseif template.is_overridden %}
                                        <div class="alert alert-info" role="alert">
                                            <strong class="me-1">{{ 'Information:'|trans }}</strong>{{ 'This built-in template is customized. Reset it to use the file-backed default.'|trans }}
                                        </div>
                                    {% else %}
                                        <div class="alert alert-info" role="alert">
                                            <strong class="me-1">{{ 'Information:'|trans }}</strong>{{ 'This built-in template is using the file-backed default.'|trans }}
                                        </div>
                                    {% endif %}
                                    <div class="row g-3">
                                        <div class="col-lg-8">
                                            <label class="form-label">{{ 'Email Subject'|trans }}</label>
                                            <input class="form-control" type="text" name="subject" value="{{ template.subject }}" id="email-subject" required{% if not can_manage_templates %} readonly{% endif %}>
                                        </div>
                                        <div class="col-12">
                                            <label class="form-label">{{ 'Email Message'|trans }}</label>
                                            <textarea class="form-control" name="content" id="email-template" rows="10" required{% if not can_manage_templates %} readonly{% endif %}>{{ template.content }}</textarea>
                                        </div>
                                    </div>
                                {% endblock %}

                                {% block form_actions %}
                                    <div class="d-flex justify-content-between align-items-center w-100">
                                        <div>
                                            {% if template.has_default %}
                                                <a class="btn btn-danger"
                                                   href="{{ 'email/template_reset'|api_url(query: {'code' : template.action_code })}}"
                                                   {{ fb_api_link({modal: {type: 'danger', title: 'Are you sure?'|trans, button: 'Reset'|trans}, reload: true}) }}>
                                                    {{ 'Reset'|trans }}
                                                </a>
                                            {% elseif template.is_custom or not template.has_default %}
                                                <a class="btn btn-danger"
                                                   href="{{ 'email/template_delete'|api_url(query: {'id' : template.id })}}"
                                                   {{ fb_api_link({modal: {type: 'danger', title: 'Are you sure?'|trans, button: 'Delete'|trans}, reload: true}) }}>
                                                    {{ 'Delete'|trans }}
                                                </a>
                                            {% endif %}
                                        </div>
                                        {% if can_manage_templates %}
                                        <div class="d-flex gap-2">
                                            <button class="btn btn-secondary" id="preview-button">
                                                <svg class="icon">
                                                    <use xlink:href="#eye" />
                                                </svg>
                                                {{ 'Preview'|trans }}
                                            </button>
                                            <button class="btn btn-primary" type="submit">{{ 'Update'|trans }}</button>
                                        </div>
                                        {% endif %}
                                    </div>
                                {% endblock %}
                            {% endembed %}
                        </form>
                    </div>
                </div>

                {% if can_manage_templates %}
                <div class="tab-pane fade" id="tab-manage" role="tabpanel">
                    <div class="p-3">
                        <form method="post" action="admin/email/template_update" {{ fb_api_form({ message: 'Template Updated'|trans}) }}>
                            <input type="hidden" name="id" value="{{ template.id }}">
                            {% embed 'partial_admin_form_card.html.twig' with {
                                title: 'Template Settings'|trans,
                                subtitle: 'Enable or disable this email template and group it under a category.'|trans
                            } %}
                                {% block form_content %}
                                    <div class="row g-4">
                                        <div class="col-12">
                                            <label class="form-label">{{ 'Category'|trans }}</label>
                                            <input class="form-control" type="text" name="category" value="{{ template.category }}" required placeholder="General">
                                            <div class="form-text">{{ 'Use a clear group name to keep related templates organized in the admin list.'|trans }}</div>
                                        </div>
                                        <div class="col-12">
                                            <input type="hidden" name="enabled" value="0">
                                            <label class="form-label d-block">{{ 'Template Availability'|trans }}</label>
                                            <label class="form-check form-switch">
                                                <input class="form-check-input" id="inputTemplateEnabled" type="checkbox" name="enabled" value="1"{% if template.enabled %} checked{% endif %}>
                                                <span class="form-check-label">{{ 'Enabled'|trans }}</span>
                                            </label>
                                            <div class="form-text">{{ 'Disable this template to stop it from being used when the related email event is triggered.'|trans }}</div>
                                        </div>
                                    </div>
                                {% endblock %}

                                {% block form_actions %}
                                    <button class="btn btn-primary" type="submit">{{ 'Update'|trans }}</button>
                                {% endblock %}
                            {% endembed %}
                        </form>
                    </div>
                </div>
                {% endif %}

                <div class="tab-pane fade" id="tab-vars" role="tabpanel">
                    {% embed 'partial_admin_related_section.html.twig' with {
                        title: 'List of Variables Used in This Email'|trans,
                        subtitle: 'These values will change when real email is sent. You can pass them to admin or guest API calls to fetch additional information.'|trans,
                        card_class: 'm-3'
                    } %}
                        {% block section_content %}
                        <div class="table-responsive">
                            <table class="table card-table table-vcenter table-striped text-nowrap">
                                <thead>
                                <tr>
                                    <th>{{ 'Variable'|trans }}</th>
                                    <th>{{ 'Example Value'|trans }}</th>
                                </tr>
                                </thead>
                                <tbody>
                                {% for k,var in template.vars %}
                                    {% if var is iterable %}
                                        {% for subkey,subvalue in var %}
                                            {% if subvalue is iterable %}
                                                {% for subsubkey,subsubvalue in var %}
                                                    {% if subsubvalue is not iterable %}
                                                        <tr>
                                                            <td>{{ '{{' }} {{ k }}.{{ subkey }}.{{ subsubkey }}{{ '}}' }}</td>
                                                            <td>{{ subsubvalue }}</td>
                                                        </tr>
                                                    {% else %}
                                                        <tr>
                                                            <td>{{ '{{' }} {{ k }}.{{ subkey }}.{{ subsubkey }}{{ '}}' }}</td>
                                                            <td>Array [ ]</td>
                                                        </tr>
                                                    {% endif %}
                                                {% endfor %}
                                            {% else %}
                                                <tr>
                                                    <td>{{ '{{' }} {{ k }}.{{ subkey }} {{ '}}' }}</td>
                                                    <td>{{ subvalue }}</td>
                                                </tr>
                                            {% endif %}
                                        {% endfor %}
                                    {% else %}
                                        <tr>
                                            <td>{{ '{{' }} {{ k }} {{ '}}' }}</td>
                                            <td>{{ var }}</td>
                                        </tr>
                                    {% endif %}
                                {% else %}
                                    <tr>
                                        <td class="text-muted" colspan="2">{{ 'This template has no known parameters, you may need to take an action to trigger its sending before they become known.'|trans }}</td>
                                    </tr>
                                {% endfor %}
                                </tbody>
                            </table>
                        </div>
                        {% endblock %}
                    {% endembed %}
                </div>

                {% if can_manage_templates %}
                <div class="tab-pane fade" id="tab-examples" role="tabpanel">
                    <div class="p-3">
                        {% embed 'partial_admin_form_card.html.twig' with {
                            title: 'Email Templates Examples'|trans,
                            subtitle: 'Use this playground to try rendering example email template content.'|trans
                        } %}
                            {% block form_content %}
                                <div class="row g-3">
                                    <div class="col-12">
                                        <label class="form-label" for="email-sample-subject">{{ 'Example Subject'|trans }}</label>
                                        <input class="form-control" id="email-sample-subject" type="text" value="{{ template.subject }}">
                                    </div>
                                    <div class="col-12">
                                        <label class="form-label" for="email-sample-template">{{ 'Example Message'|trans }}</label>
                                        <textarea class="form-control" id="email-sample-template" rows="20">{% autoescape false %}{% apply markdown_to_html %}
This is an example of markdown syntax in email template

*Italic text*
**Bolded text**

Lists:

* Red
* Green
* Blue

***

Link to login form: <{{ 'login'|url(area: 'client') }}>

Company signature: {{ guest.system_company.signature }}

FOSSBilling version: {{ FOSSBillingVersion }}

Today's date: {{ now|date('Y-m-d') }}

You can event use IF statements in email templates: {% if 1 == 2 %}This will never show{% else %}Of course 1 is not equal 2{% endif %}

***

{# Comments in email templates. This text is not visible #}
{# Uncomment the line below to see what is the output #}
{% endapply %}{% endautoescape %}</textarea>
                                    </div>
                                </div>
                            {% endblock %}

                            {% block form_actions %}
                                <button class="btn btn-secondary epb" type="button">
                                    <svg class="icon">
                                        <use xlink:href="#eye" />
                                    </svg>
                                    {{ 'Preview'|trans }}
                                </button>
                            {% endblock %}
                        {% endembed %}
                    </div>
                </div>
                {% endif %}
        {% endblock %}
    {% endembed %}
{% endblock %}

{% block js %}
{% if can_manage_templates %}
{{ include('partial_email_preview.html.twig') }}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Preview button for the main email template
    const previewButton = document.getElementById('preview-button');
    previewButton.addEventListener('click', function(e) {
        e.preventDefault();

        const subjectParams = {
            _tpl: document.getElementById('email-subject').value,
            id: '{{ template.id }}',
        };

        const contentParams = {
            _tpl: document.getElementById('email-template').value,
            id: '{{ template.id }}',
        };

        let subjectResult = '';
        let contentResult = '';

        // Render subject
        FOSSBilling.api.admin.post('email/template_render', subjectParams, function(subject) {
            subjectResult = subject;

            // Render content
            FOSSBilling.api.admin.post('email/template_render', contentParams, function(content) {
                contentResult = content;
                showEmailPreview(subjectResult, contentResult);
            }, function(error) {
                FOSSBilling.message(`{{ 'Failed to render email content'|trans }}: ${error.message}`, 'error');
            });
        }, function(error) {
            FOSSBilling.message(`{{ 'Failed to render email subject'|trans }}: ${error.message}`, 'error');
        });
    });

    // Preview button for the examples tab
    const examplePreviewButton = document.querySelector('.epb');
    examplePreviewButton.addEventListener('click', function(e) {
        e.preventDefault();

        const subjectParams = {
            _tpl: document.getElementById('email-sample-subject').value,
            id: '{{ template.id }}',
        };

        const contentParams = {
            _tpl: document.getElementById('email-sample-template').value,
            id: '{{ template.id }}',
        };

        FOSSBilling.api.admin.post('email/template_render', subjectParams, function(subject) {
            FOSSBilling.api.admin.post('email/template_render', contentParams, function(content) {
                showEmailPreview(subject, content);
            }, function(error) {
                FOSSBilling.message(`{{ 'Failed to render template'|trans }}: ${error.message}`, 'error');
            });
        }, function(error) {
            FOSSBilling.message(`{{ 'Failed to render email subject'|trans }}: ${error.message}`, 'error');
        });
    });
});
</script>
{% endif %}
{% endblock %}
