{% extends request.ajax ? 'layout_blank.html.twig' : 'layout_default.html.twig' %}

{% import 'macro_functions.html.twig' as mf %}

{% block meta_title %}{{ ticket.subject }} - {{ ticket.messages|length }} {{ 'message(s)'|trans }}{% endblock %}

{% block breadcrumbs %}
    <ul 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="{{ 'support'|url }}">{{ 'Support'|trans }}</a>
        </li>
        <li class="breadcrumb-item">
            <a href="{{ 'support'|url }}">{{ 'Tickets'|trans }}</a>
        </li>
        <li class="breadcrumb-item active" aria-current="page">#{{ ticket.id }} - {{ ticket.subject }}</li>
    </ul>
{% endblock %}

{% set active_menu = 'support' %}

{% block content %}
{% embed 'partial_admin_detail_tabs.html.twig' with {
    title: ticket.subject,
    subtitle: 'Review the ticket, manage its status, track internal notes, and inspect related client conversations.'|trans,
    outer_card_class: 'mb-3'
} %}
    {% block detail_tabs %}
                    <li class="nav-item" role="presentation">
                        <a class="nav-link active" href="#tab-index" data-bs-toggle="tab" role="tab">{{ 'Ticket'|trans }}</a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" href="#tab-manage" data-bs-toggle="tab" role="tab">{{ 'Manage'|trans }}</a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" href="#tab-notes" data-bs-toggle="tab" role="tab">{{ 'Notes'|trans }} {% if ticket.notes|length > 0 %}({{ ticket.notes|length }}){% endif %}</a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" href="#tab-support" data-bs-toggle="tab" role="tab">{{ 'Client Tickets'|trans }}</a>
                    </li>
    {% endblock %}

    {% block detail_tab_content %}
        {% import 'macro_functions.html.twig' as mf %}
        <div class="tab-pane fade show active" id="tab-index" role="tabpanel">
            <div class="p-3 d-flex flex-column gap-3">
                {% set task = ticket.rel %}
                {% embed 'partial_admin_summary_card.html.twig' with {
                    title: 'Ticket Summary'|trans,
                    subtitle: 'Review the client, helpdesk, status, and any linked task or order context for this ticket.'|trans,
                    centered_actions: true,
                    card_class: 'mb-0'
                } %}
                    {% import 'macro_functions.html.twig' as mf %}
                    {% block summary_content %}
                        <div class="table-responsive">
                            <table class="table card-table table-vcenter table-striped text-nowrap">
                                <tbody>
                                    <tr><td class="w-25">{{ 'Ticket ID'|trans }}</td><td>#{{ ticket.id }}</td></tr>
                                    <tr><td>{{ 'Client'|trans }}</td><td><a href='{{ "client/manage/#{ticket.client.id }"|url }}'>{{ ticket.client.first_name }} {{ ticket.client.last_name }}</a> (#{{ ticket.client.id }})</td></tr>
                                    <tr><td>{{ 'Helpdesk'|trans }}</td><td>{{ admin.support_helpdesk_get_pairs[ticket.support_helpdesk_id]|trans }}</td></tr>
                                    <tr><td>{{ 'Status'|trans }}</td><td>{{ mf.status_badge(ticket.status, 'ticket') }}</td></tr>
                                    <tr><td>{{ 'Time Opened'|trans }}</td><td>{{ ticket.created_at|format_date }}</td></tr>
                                    {% if task.task %}<tr><td>{{ 'Task'|trans }}</td><td>{{ mf.status_name(task.task) }}</td></tr>{% endif %}
                                    {% if task.type == 'order' %}<tr><td>{{ 'Related To'|trans }}</td><td><a href='{{ "order/manage/#{task.id}"|url }}'>Order #{{ task.id }}</a></td></tr>{% endif %}
                                    {% if task.task == 'upgrade' %}<tr><td>{{ 'Upgrade To'|trans }}</td><td><a href='{{ "product/manage/#{task.new_value}"|url }}'>{{ admin.product_get_pairs[task.new_value] }}</a></td></tr>{% endif %}
                                </tbody>
                            </table>
                        </div>
                    {% endblock %}

                    {% block summary_actions %}
                        {% if ticket.status != 'closed' %}
                        <a class="btn btn-primary" href="{{ 'support/ticket_close'|api_url(query: { 'id': ticket.id }) }}"
                            {{ fb_api_link({ message: 'Are you sure?'|trans, modal: {type: 'confirm', title: 'Are you sure?'|trans}, redirect: 'support'|url(query: { status: 'open' }) }) }}>
                            <svg class="icon"><use xlink:href="#close" /></svg>
                            {{ 'Close'|trans }}
                        </a>
                        {% endif %}
                        <a class="btn btn-danger" href="{{ 'support/ticket_delete'|api_url(query: { 'id': ticket.id }) }}"
                            {{ fb_api_link({ message: 'Are you sure?'|trans, modal: {type: 'confirm', title: 'Are you sure?'|trans}, redirect: 'support'|url }) }}>
                            <svg class="icon"><use xlink:href="#delete" /></svg>
                            {{ 'Delete'|trans }}
                        </a>
                        {% if task.status == 'pending' %}
                        <a class="btn btn-primary" href="{{ 'support/task_complete'|api_url(query: { 'id': ticket.id }) }}" {{ fb_api_link({ reload: true }) }}>
                            <svg class="icon"><use xlink:href="#check" /></svg>
                            {{ 'Set Task Complete'|trans }}
                        </a>
                        {% endif %}
                    {% endblock %}
                {% endembed %}

                <div class="card">
                    <div class="card-body pb-3">
                        <div class="d-flex flex-wrap justify-content-between align-items-start gap-3">
                            <div class="d-flex flex-column gap-1">
                                <h5 class="card-title mb-0">{{ 'Conversation'|trans }}</h5>
                                <p class="text-secondary mb-0">{{ 'Review the full message history and expand older replies when needed.'|trans }}</p>
                            </div>
                            <a href="#" class="btn btn-secondary" id="toggleMessages">
                                <svg class="icon">
                                    <use xlink:href="#eye" />
                                </svg>
                                {{ 'Show/Hide Messages'|trans }}
                            </a>
                        </div>
                    </div>
                    <div class="card-body pt-0">
                        <div class="conversation">
                            {% for i, message in ticket.messages %}
                            <div class="card {% if loop.first %}mt-2 {% endif %}mb-3 col-md-10 {% if ticket.first.author.email != message.author.email %}offset-md-2{% endif %} {{ loop.last ? 'last' : '' }}" id="{{ message.id == request_message ? 'direct-msg' : '' }}">
                                <div class="card-header" style="cursor: pointer;">
                                    {{ avatar(message.author.email, 24, 'avatar avatar-xs me-2') }}
                                    {{ message.author.name }}
                                    <a class="ms-2" href='{{ "support/ticket/#{ticket.id}/message/#{message.id}"|url }}'>
                                        <svg class="icon">
                                            <use xlink:href="#link" />
                                        </svg>
                                    </a>
                                    <span class="ms-auto text-muted">{{ message.created_at|format_datetime }}</span>
                                </div>
                                <div class="card-body" style="display:{{ loop.last or loop.index + 1 == ticket.messages|length ? 'block' : 'none' }};">
                                    {{ (message.content ?? '')|markdown_to_html }}
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                </div>

                <div class="card mb-0" id="reply-box">
                    <form method="post" action="{{ 'support/ticket_reply'|api_url }}" {{ fb_api_form({ reload: true }) }}>
                        <div class="card-body">
                            <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
                                <div class="d-flex flex-column gap-1">
                                    <h5 class="card-title mb-0">{{ 'Respond as'|trans }} {{ profile.name }}</h5>
                                    <p class="text-secondary mb-0">{{ 'Compose a reply, insert a canned response, and close the ticket when appropriate.'|trans }}</p>
                                </div>
                                <div>{{ include('mod_support_canned_selector.html.twig') }}</div>
                            </div>

                            <textarea class="editor-textarea" id="rt" name="content" rows="10" required>{{ 'Hello'|trans }} {{ ticket.client.first_name }},
{{ canned_delay_message }}

{{ profile.signature }}
{{ ticket.helpdesk.signature }}</textarea>
                        </div>
                        <div class="card-footer d-flex flex-wrap align-items-center gap-2">
                            <input type="hidden" name="id" value="{{ ticket.id }}">
                            <input type="submit" value="{{ 'Post'|trans }}" class="btn btn-primary ms-auto">

                            {% if ticket.messages|length > 2 and ticket.status != 'closed' %}
                            <a class="btn btn-warning" href="{{ 'support/ticket_close'|api_url(query: { 'id': ticket.id }) }}"
                                {{ fb_api_link({ message: 'Are you sure?'|trans, modal: {type: 'confirm', title: 'Are you sure?'|trans}, redirect: 'support'|url(query: { status: 'open' }) }) }}>
                                <svg class="icon">
                                    <use xlink:href="#check" />
                                </svg>
                                {{ 'Close Ticket'|trans }}
                            </a>
                            {% endif %}
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="tab-pane fade" id="tab-manage" role="tabpanel">
            <div class="card-body">
                <form method="post" action="{{ 'support/ticket_update'|api_url }}" {{ fb_api_form({ reload: true}) }}>
                    {% embed 'partial_admin_form_card.html.twig' with {
                        title: 'Ticket Settings'|trans,
                        subtitle: 'Update the subject, helpdesk assignment, workflow status, and priority for this ticket.'|trans
                    } %}
                        {% import 'macro_functions.html.twig' as mf %}
                        {% block form_content %}
                            <div class="row g-3">
                                <div class="col-lg-6">
                                    <label class="form-label">{{ 'Subject'|trans }}</label>
                                    <input class="form-control" type="text" name="subject" value="{{ ticket.subject }}" required>
                                </div>
                                <div class="col-lg-6">
                                    <label class="form-label">{{ 'Helpdesk'|trans }}</label>
                                    {{ mf.selectbox('support_helpdesk_id', admin.support_helpdesk_get_pairs, ticket.support_helpdesk_id, 1) }}
                                </div>
                                <div class="col-lg-6">
                                    <label class="form-label">{{ 'Status'|trans }}</label>
                                    {{ mf.selectbox('status', admin.support_ticket_get_statuses({ 'titles': true }), ticket.status, 1) }}
                                </div>
                                <div class="col-lg-6">
                                    <label class="form-label">{{ 'Priority'|trans }}</label>
                                    <input class="form-control" type="text" name="priority" value="{{ ticket.priority }}">
                                </div>
                            </div>
                            <input type="hidden" name="id" value="{{ ticket.id }}">
                        {% endblock %}

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

        <div class="tab-pane fade" id="tab-notes" role="tabpanel">
            <div class="p-3 d-flex flex-column gap-3">
                {% embed 'partial_admin_related_section.html.twig' with {
                    title: 'Internal Notes'|trans,
                    subtitle: 'Keep internal staff notes attached to this ticket and remove them when no longer needed.'|trans,
                    card_class: 'mb-0'
                } %}
                    {% block section_content %}
                        <div class="table-responsive">
                            <table class="table card-table table-vcenter table-striped text-nowrap">
                            {% for note in ticket.notes %}
                                <tr>
                                    <td class="w-1"><a href='{{ "staff/manage/#{note.admin_id}"|url }}'>{{ note.author.name }}</a></td>
                                    <td>{{ note.note }}</td>
                                    <td class="w-1">
                                        <a class="btn btn-icon" href="{{ 'support/note_delete'|api_url(query: { 'id': note.id }) }}"
                                            {{ fb_api_link({ message: 'Are you sure?'|trans, modal: {type: 'confirm', title: 'Are you sure?'|trans}, reload: true }) }}>
                                            <svg class="icon"><use xlink:href="#delete" /></svg>
                                        </a>
                                    </td>
                                </tr>
                            {% else %}
                                <tr><td class="text-muted" colspan="3">{{ 'The list is empty'|trans }}</td></tr>
                            {% endfor %}
                            </table>
                        </div>
                    {% endblock %}
                {% endembed %}

                <form method="post" action="{{ 'support/note_create'|api_url }}" {{ fb_api_form({ reload: true}) }}>
                    {% embed 'partial_admin_form_card.html.twig' with {
                        title: 'Add Internal Note'|trans,
                        subtitle: 'Record a staff-only note against this ticket.'|trans,
                        card_class: 'mb-0'
                    } %}
                        {% block form_content %}
                            <label class="form-label" for="textareaNote">{{ 'Note'|trans }}</label>
                            <textarea class="form-control" id="textareaNote" name="note" rows="3" required></textarea>
                            <input type="hidden" name="ticket_id" value="{{ ticket.id }}">
                        {% endblock %}

                        {% block form_actions %}
                            <button class="btn btn-primary" type="submit">
                                <svg class="icon">
                                    <use xlink:href="#plus" />
                                </svg>
                                {{ 'Add Note'|trans }}
                            </button>
                        {% endblock %}
                    {% endembed %}
                </form>
            </div>
        </div>

        <div class="tab-pane fade" id="tab-support" role="tabpanel">
            {% embed 'partial_admin_related_section.html.twig' with {
                title: 'Client Tickets'|trans,
                subtitle: 'Review other tickets for this client and open a new ticket without leaving the current conversation.'|trans,
                card_class: 'm-3'
            } %}
                {% block section_action %}
                    <a href="{{ 'support'|url(query: { 'client_id': ticket.client.id}) }}#tab-new" class="btn btn-primary">
                        <svg class="icon"><use xlink:href="#plus" /></svg>
                        {{ 'New Support Ticket'|trans }}
                    </a>
                {% endblock %}

                {% block section_content %}
                    {% import 'macro_functions.html.twig' as mf %}
                    <div class="table-responsive">
                        <table class="table card-table table-vcenter table-striped text-nowrap">
                            <thead>
                                <tr>
                                    <th>{{ 'ID'|trans }}</th>
                                    <th>{{ 'Helpdesk'|trans }}</th>
                                    <th>{{ 'Subject'|trans }}</th>
                                    <th>{{ 'Status'|trans }}</th>
                                    <th class="w-1"></th>
                                </tr>
                            </thead>
                            <tbody>
                                {% set tickets = admin.support_ticket_get_list({ 'per_page': 20, 'client_id': ticket.client.id, 'deep': 0, 'include_first': 0 }) %}
                                {% for related_ticket in tickets.list %}
                                <tr>
                                    <td>{{ related_ticket.id }}</td>
                                    <td>{{ related_ticket.helpdesk.name }}</td>
                                    <td><a href='{{ "support/ticket/#{related_ticket.id}"|url }}'>{{ related_ticket.subject|truncate(30) }}</a></td>
                                    <td>{{ mf.status_badge(related_ticket.status, 'ticket') }}</td>
                                    <td>
                                        <a class="btn btn-icon" href='{{ "support/ticket/#{related_ticket.id}"|url }}'>
                                            <svg class="icon"><use xlink:href="#edit" /></svg>
                                        </a>
                                    </td>
                                </tr>
                                {% else %}
                                <tr><td class="text-muted" colspan="5">{{ 'The list is empty'|trans }}</td></tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                {% endblock %}
            {% endembed %}
        </div>
    {% endblock %}
{% endembed %}
{% endblock %}

{% block js%}
<script>
    function setSelRange(inputEl, selStart, selEnd) {
        if (inputEl.setSelectionRange) {
            inputEl.focus();
            inputEl.setSelectionRange(selStart, selEnd);
        } else if (inputEl.createTextRange) {
            var range = inputEl.createTextRange();

            range.collapse(true);
            range.moveEnd('character', selEnd);
            range.moveStart('character', selStart);
            range.select();
        }
    }

    document.addEventListener("DOMContentLoaded", function() {
        document.querySelector('#reply-box textarea').focus();

        var ta = document.getElementById('rt');
        var pos = ta.innerHTML.indexOf('\n') + 2;

        setSelRange(ta, pos, pos);

        document.querySelectorAll('.shd select').forEach(function(select) {
            select.addEventListener('change', function() {
                FOSSBilling.api.admin.get('support/ticket_update', { id: {{ ticket.id }}, support_helpdesk_id: this.value });
            });
        });

        document.querySelectorAll('input.tst').forEach(function(element) {
            element.addEventListener('click', function() {
                FOSSBilling.api.admin.get('support/ticket_update', {id: {{ ticket.id }}, status: this.value });
            });
        });

        document.querySelector('.conversation').addEventListener('click', function(event) {
            const cardHeader = event.target.closest('.card-header');
            if (cardHeader) {
                const cardBody = cardHeader.nextElementSibling;
                if (cardBody && cardBody.classList.contains('card-body')) {
                    cardBody.style.display = (cardBody.style.display === 'none') ? 'block' : 'none';
                }
            }
        });

        const directMsg = document.getElementById('direct-msg');
        if (directMsg) {
            const msgBody = directMsg.querySelector('.card-body');
            if (msgBody) msgBody.style.display = 'block';

            window.scrollTo({
                top: directMsg.offsetTop - 50,
                behavior: 'smooth'
            });

            directMsg.style.backgroundColor = 'rgb(235, 235, 235)';
        }

        var showAllMessages = false;
        document.getElementById('toggleMessages').addEventListener('click', function(event) {
            event.preventDefault();

            showAllMessages = !showAllMessages;
            document.querySelectorAll('.conversation .card-body').forEach(function(element) {
                element.style.display = showAllMessages ? 'block' : 'none';
            });
        });
    });
</script>
{% endblock %}

{% block head %}{{ wysiwyg('.editor-textarea') }}{% endblock %}
