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

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

{% block meta_title %}{{ 'Invoices'|trans }}{% endblock %}

{% set active_menu = 'invoice' %}
{% set has_filter_panel = true %}
{% set filter_panel_id = 'page-search-filters' %}
{% set filter_panel_open = request_has_filters %}
{% set new_invoice_action %}
    <button class="btn btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#newInvoiceModal">
        <svg class="icon">
            <use xlink:href="#plus" />
        </svg>
        {{ 'New Invoice'|trans }}
    </button>
{% endset %}

{% block top_content %}
{% if not filter_panel_open %}
    {% set statuses = admin.invoice_get_statuses %}
    <section class="row row-cards mb-3 filter-panel-summary">
        <div class="col-sm-6 col-lg-3">
            <a class="card card-sm card-link" href="{{ 'invoice'|url(query: { 'status': 'unpaid' }) }}">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <span class="bg-danger text-white avatar">{{ statuses.unpaid }}</span>
                        </div>
                        <div class="col">
                            <div class="font-weight-medium">{{ 'Unpaid'|trans }}</div>
                        </div>
                    </div>
                </div>
            </a>
        </div>
        <div class="col-sm-6 col-lg-3">
            <a class="card card-sm card-link" href="{{ 'invoice'|url(query: { 'status': 'paid' }) }}">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <span class="bg-green text-white avatar">{{ statuses.paid }}</span>
                        </div>
                        <div class="col">
                            <div class="font-weight-medium">{{ 'Paid'|trans }}</div>
                        </div>
                    </div>
                </div>
            </a>
        </div>
        <div class="col-sm-6 col-lg-3">
            <a class="card card-sm card-link" href="{{ 'invoice'|url(query: { 'status': 'refunded' }) }}">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <span class="bg-secondary text-white avatar">{{ statuses.refunded }}</span>
                        </div>
                        <div class="col">
                            <div class="font-weight-medium">{{ 'Refunded'|trans }}</div>
                        </div>
                    </div>
                </div>
            </a>
        </div>
        <div class="col-sm-6 col-lg-3">
            <a class="card card-sm card-link" href="{{ 'invoice'|url }}">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <span class="bg-blue text-white avatar">{{ statuses.paid + statuses.unpaid + statuses.refunded }}</span>
                        </div>
                        <div class="col">
                            <div class="font-weight-medium">{{ 'Total'|trans }}</div>
                        </div>
                    </div>
                </div>
            </a>
        </div>
    </section>
    {% endif %}
{% endblock %}

{% block content %}
    <div class="card">
        <div class="card-header">
            <div>
                <h3 class="card-title">{{ 'Invoices'|trans }}</h3>
                <p class="card-subtitle">{{ 'Manage invoices, review billing records, and prepare new invoices for clients.'|trans }}</p>
            </div>
        </div>
        <div class="card-body pt-0 pb-0 px-0">
            <div class="card border-0 shadow-none rounded-0">
                {{ include('partial_search.html.twig', {
                    search_body_class: filter_panel_open ? 'pb-2 border-bottom-0' : '',
                    search_toolbar_actions: new_invoice_action
                }) }}
                <section id="{{ filter_panel_id }}" class="card-body pt-0 px-3 pb-3 border-bottom collapse{% if filter_panel_open %} show{% endif %}">
                    <form method="get" class="border border-top-0 rounded-top-0 rounded-bottom-3 bg-body-tertiary p-3">
                        {% if request.search %}
                            <input type="hidden" name="search" value="{{ request.search }}">
                        {% endif %}
                        <div class="row g-3">
                            <div class="col-md-6 col-xl-3">
                                <div>
                                    <label class="form-label text-muted small mb-1" for="filter-invoice-id">{{ 'Invoice ID'|trans }}</label>
                                    <input class="form-control" type="text" id="filter-invoice-id" name="id" value="{{ request.id }}" placeholder="{{ 'Invoice ID'|trans }}">
                                </div>
                            </div>
                            <div class="col-md-6 col-xl-3">
                                <div>
                                    <label class="form-label text-muted small mb-1" for="filter-invoice-number">{{ 'Invoice Number'|trans }}</label>
                                    <input class="form-control" type="text" id="filter-invoice-number" name="nr" value="{{ request.nr }}" placeholder="{{ 'Invoice Number'|trans }}">
                                </div>
                            </div>
                            <div class="col-md-6 col-xl-3">
                                <div>
                                    <label class="form-label text-muted small mb-1" for="client_id">{{ 'Client'|trans }}</label>
                                    <select class="form-control autocomplete-selector"
                                            placeholder="{{ 'Start Typing the Client Name or ID'|trans }}"
                                            id="client_id"
                                            name="client_id"
                                            data-resturl="/api/admin/client/get_pairs">
                                    {% if not request.client_id %}
                                    {% else %}
                                        {% set client = admin.client_get({ 'id': request.client_id }) %}
                                        <option value="{{ request.client_id }}" selected>{{ client.first_name }} {{ client.last_name }}</option>
                                    {% endif %}
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6 col-xl-3">
                                <div>
                                    <label class="form-label text-muted small mb-1" for="currency">{{ 'Currency'|trans }}</label>
                                    {{ mf.selectbox('currency', guest.currency_get_pairs, request.currency, 0, 'All Currencies'|trans) }}
                                </div>
                            </div>
                            <div class="col-md-6 col-xl-4">
                                <div>
                                    <label class="form-label text-muted small mb-1" for="issue_date">{{ 'Date Issued'|trans }}</label>
                                    <div class="input-group">
                                        <div class="input-icon w-100">
                                            <input class="form-control datepicker"
                                                   id="issue_date"
                                                   placeholder="{{ 'Select Date Range'|trans }}"
                                                   value="{% if request.date_from %}{{ request.date_from|date('Y-m-d') }}{% endif %}{% if request.date_to %} to {{ request.date_to|date('Y-m-d') }}{% endif %}"
                                                   data-name-from="date_from"
                                                   data-name-to="date_to"
                                            >
                                            <span class="input-icon-addon">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                                    <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                                                    <path d="M4 5m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z"></path>
                                                    <path d="M16 3l0 4"></path>
                                                    <path d="M8 3l0 4"></path>
                                                    <path d="M4 11l16 0"></path>
                                                    <path d="M11 15l1 0"></path>
                                                    <path d="M12 15l0 3"></path>
                                                </svg>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-xl-8">
                                <label class="form-label text-muted small mb-1">{{ 'Status'|trans }}</label>
                                <div class="d-flex flex-wrap gap-2">
                                    <input class="btn-check" id="invoiceStatusAll" type="radio" name="status" value=""{% if not request.status %} checked{% endif %}>
                                    <label class="btn btn-outline-primary" for="invoiceStatusAll">{{ 'All'|trans }}</label>

                                    <input class="btn-check" id="invoiceStatusPaid" type="radio" name="status" value="paid"{% if request.status == 'paid' %} checked{% endif %}>
                                    <label class="btn btn-outline-primary" for="invoiceStatusPaid">{{ 'Paid'|trans }}</label>

                                    <input class="btn-check" id="invoiceStatusUnpaid" type="radio" name="status" value="unpaid"{% if request.status == 'unpaid' %} checked{% endif %}>
                                    <label class="btn btn-outline-primary" for="invoiceStatusUnpaid">{{ 'Unpaid'|trans }}</label>

                                    <input class="btn-check" id="invoiceStatusRefunded" type="radio" name="status" value="refunded"{% if request.status == 'refunded' %} checked{% endif %}>
                                    <label class="btn btn-outline-primary" for="invoiceStatusRefunded">{{ 'Refunded'|trans }}</label>
                                </div>
                            </div>
                        </div>
                        <div class="d-flex justify-content-end gap-2 mt-3">
                            <a class="btn btn-outline-secondary" href="{{ request_path|url }}">{{ 'Reset'|trans }}</a>
                            <button class="btn btn-primary" type="submit">
                                <svg class="icon">
                                    <use xlink:href="#filter" />
                                </svg>
                                {{ 'Apply Filters'|trans }}
                            </button>
                        </div>
                    </form>
                </section>
              <div class="table-responsive">
                <table class="table card-table table-vcenter table-striped text-nowrap sortable">
                    <thead>
                        <tr>
                            <th class="w-1 no-sort">
                                <input type="checkbox" class="form-check-input m-0 align-middle batch-delete-master-checkbox">
                            </th>
                            <th class="w-1">#</th>
                            <th class="w-1 no-sort"></th>
                            <th>{{ 'Name'|trans }}</th>
                            <th class="text-center">{{ 'Amount'|trans }}</th>
                            <th class="text-center">{{ 'Issued at'|trans }}</th>
                            <th class="text-center">{{ 'Due Date'|trans }}</th>
                            <th class="text-center">{{ 'Paid at'|trans }}</th>
                            <th>{{ 'Status'|trans }}</th>
                            <th class="w-1 no-sort"></th>
                        </tr>
                    </thead>
                    <tbody>
                        {% set invoices = admin.invoice_get_list({ 'per_page': 25, 'page': request.page }|merge(request)) %}
                        {% for invoice in invoices.list %}
                        <tr>
                            <td>
                                <input type="checkbox" class="form-check-input m-0 align-middle batch-delete-checkbox" data-item-id="{{ invoice.id }}">
                            </td>
                            <td>
                                <a href="{{ 'invoice/manage'|url }}/{{ invoice.id }}">{{ invoice.serie_nr }}</a>
                            </td>
                            <td>
                                <a href='{{ "client/manage/#{invoice.client.id}"|url }}'>
                                    {{ avatar(invoice.buyer.email, 24, 'avatar avatar-xs') }}
                                </a>
                            </td>
                            <td>
                                <a href='{{ "client/manage/#{invoice.client.id}"|url }}'>{{ invoice.buyer.first_name }} {{ invoice.buyer.last_name }}</a>
                            </td>
                            <td class="text-center">{{ invoice.total|format_currency(invoice.currency ?? default_currency) }}</td>
                            <td class="text-center">{{ invoice.created_at|date('Y-m-d') }}</td>
                            <td class="text-center">{% if invoice.due_at %}{{ invoice.due_at|date('Y-m-d') }}{% else %}-{% endif %}</td>
                            <td class="text-center">{% if invoice.paid_at %}{{ invoice.paid_at|date('Y-m-d') }}{% else %}-{% endif %}</td>
                            <td>{{ mf.status_badge(invoice.status, 'invoice') }}</td>
                            <td>
                                <a class="btn btn-icon" href='{{ "invoice/manage/#{invoice.id}"|url }}'>
                                    <svg class="icon">
                                        <use xlink:href="#edit" />
                                    </svg>
                                </a>
                                <a class="btn btn-icon" href="{{ 'invoice/delete'|api_url(query: { 'id': invoice.id }) }}"
                                    {{ fb_api_link({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="10">{{ 'The list is empty'|trans }}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
              </div>
                <div class="card-footer d-flex align-items-center justify-content-between gap-3 flex-wrap">
                    <div>
                        {% include "partial_batch_delete.html.twig" with { 'action': 'invoice/batch_delete' } %}
                    </div>
                    <div class="d-flex align-items-center gap-2 flex-wrap">
                        {% include "partial_pagination.html.twig" with { 'list': invoices, 'url': 'invoice' } %}
                    </div>
                    <div class="d-flex align-items-center gap-2 ms-auto">
                        <a class="btn btn-secondary" href="{{ 'invoice/export_csv'|api_url(query: { CSRFToken: CSRFToken }) }}" title="{{ 'Export Invoices'|trans }}">
                            <svg class="icon">
                                <use xlink:href="#download" />
                            </svg>
                            {{ 'Export Invoices'|trans }}
                        </a>
                    </div>
                </div>

            <div class="modal modal-blur fade" id="newInvoiceModal" tabindex="-1" aria-labelledby="newInvoiceModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered modal-lg">
                    <form class="modal-content" method="post" action="{{ 'invoice/prepare'|api_url }}" {{ fb_api_form({callback: 'onAfterInvoicePrepared'}) }}>
                        <div class="modal-header">
                            <h3 class="modal-title" id="newInvoiceModalLabel">{{ 'Create New Invoice'|trans }}</h3>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{{ 'Close'|trans }}"></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-3">
                                <label class="form-label" for="client_id">{{ 'Client'|trans }}</label>
                                {% if not request.client_id %}
                                    <select class="form-control autocomplete-selector"
                                            placeholder="{{ 'Start typing the client name or ID'|trans }}"
                                            id="client_id"
                                            name="client_id"
                                            data-resturl="/api/admin/client/get_pairs">
                                    </select>
                                {% else %}
                                    {% set client = admin.client_get({ 'id': request.client_id }) %}
                                    <input type="text" id="client_id" class="form-control" disabled value="{{ client.first_name }} {{ client.last_name }}" />
                                    <input type="hidden" name="client_id" value="{{ request.client_id }}" />
                                {% endif %}
                            </div>
                            <div class="mb-0">
                                <label class="form-label" for="product_id">{{ 'Product'|trans }}</label>
                                <select class="form-control autocomplete-selector"
                                        placeholder="{{ 'Start typing to select product (optional)'|trans }}"
                                        id="product_id"
                                        name="product_id"
                                        data-resturl="/api/admin/product/get_pairs">
                                </select>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ 'Cancel'|trans }}</button>
                            <button type="submit" class="btn btn-primary">{{ 'Prepare'|trans }}</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
<script>
    function onAfterInvoicePrepared(id) {
        window.location = "{{ 'invoice/manage/'|url }}/" + id;
    }

    document.addEventListener('DOMContentLoaded', function() {
        const modalElement = document.getElementById('newInvoiceModal');
        const invoiceForm = modalElement?.querySelector('form');
        const productSelect = document.getElementById('product_id');
        let tomSelectInstance = null;
        const modal = modalElement ? bootstrap.Modal.getOrCreateInstance(modalElement) : null;

        if (window.location.hash === '#tab-new' && modal) {
            modal.show();
        }

        modalElement?.addEventListener('hidden.bs.modal', function() {
            if (window.location.hash !== '#tab-new') {
                return;
            }

            const url = new URL(window.location.href);
            url.hash = '';
            window.history.replaceState({}, '', url);
        });

        if (productSelect && productSelect.tomselect) {
            tomSelectInstance = productSelect.tomselect;
        }

        if (productSelect) {
            productSelect.addEventListener('change', function() {
                const selectedOption = this.options[this.selectedIndex];
                if (!selectedOption.value) {
                    return;
                }

                const productId = selectedOption.value;
                const productTitle = selectedOption.text;

                const productsList = document.getElementById('products-list');
                if (productsList) {
                    const existingProduct = productsList.querySelector(`[data-product-id="${productId}"]`);
                    if (existingProduct) {
                        FOSSBilling.message("{{ 'This product has already been added'|trans }}", 'warning');
                        if (tomSelectInstance) {
                            tomSelectInstance.clear();
                        }
                        return;
                    }
                }

                let itemsContainer = document.getElementById('selected-product-items');
                if (!itemsContainer) {
                    itemsContainer = document.createElement('div');
                    itemsContainer.id = 'selected-product-items';
                    itemsContainer.className = 'border-top mt-4 pt-4';
                    itemsContainer.innerHTML = '<h6 class="mb-3">{{ 'Selected products to be added as invoice items'|trans }}</h6><div id="products-list"></div>';
                    invoiceForm.querySelector('.modal-body').appendChild(itemsContainer);
                }

                const productDiv = document.createElement('div');
                productDiv.className = 'mb-3 row align-items-center';
                productDiv.dataset.productId = productId;

                const titleCol = document.createElement('div');
                titleCol.className = 'col';
                const titleInput = document.createElement('input');
                titleInput.type = 'text';
                titleInput.name = `products[${productId}][title]`;
                titleInput.value = productTitle;
                titleInput.className = 'form-control';
                titleInput.readOnly = true;
                titleCol.appendChild(titleInput);

                const qtyCol = document.createElement('div');
                qtyCol.className = 'col-3';
                const qtyInput = document.createElement('input');
                qtyInput.type = 'number';
                qtyInput.name = `products[${productId}][quantity]`;
                qtyInput.value = '1';
                qtyInput.min = '1';
                qtyInput.className = 'form-control';
                qtyInput.placeholder = "{{ 'Quantity'|trans }}";
                qtyCol.appendChild(qtyInput);

                const priceCol = document.createElement('div');
                priceCol.className = 'col-3';
                const priceInput = document.createElement('input');
                priceInput.type = 'number';
                priceInput.name = `products[${productId}][price]`;
                priceInput.step = '0.01';
                priceInput.className = 'form-control';
                priceInput.placeholder = "{{ 'Price'|trans }}";
                priceCol.appendChild(priceInput);

                const deleteCol = document.createElement('div');
                deleteCol.className = 'col-1';
                const deleteBtn = document.createElement('button');
                deleteBtn.type = 'button';
                deleteBtn.className = 'btn btn-icon btn-danger';
                deleteBtn.innerHTML = '<svg class="icon"><use xlink:href="#delete" /></svg>';
                deleteBtn.addEventListener('click', function() {
                    productDiv.remove();
                });
                deleteCol.appendChild(deleteBtn);

                productDiv.appendChild(titleCol);
                productDiv.appendChild(qtyCol);
                productDiv.appendChild(priceCol);
                productDiv.appendChild(deleteCol);

                document.getElementById('products-list').appendChild(productDiv);

                fetch(`{{ 'product/get'|api_url(query: { 'id': productId }) }}`, {
                    headers: {
                        'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]')?.content || ''
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.result && data.result.pricing) {
                        const pricing = data.result.pricing;
                        if (pricing.type === 'once' && pricing.once && pricing.once.price !== undefined) {
                            priceInput.value = pricing.once.price;
                        } else if (pricing.type === 'recurrent' && pricing.recurrent) {
                            const periods = Object.keys(pricing.recurrent);
                            if (periods.length > 0) {
                                const firstPeriod = periods[0];
                                if (pricing.recurrent[firstPeriod] && pricing.recurrent[firstPeriod].price !== undefined) {
                                    priceInput.value = pricing.recurrent[firstPeriod].price;
                                }
                            }
                        }
                    }
                })
                .catch(() => {});

                if (tomSelectInstance) {
                    tomSelectInstance.clear();
                }
            });
        }

        if (invoiceForm) {
            invoiceForm.addEventListener('submit', function() {
                const productItems = document.querySelectorAll('#selected-product-items .row[data-product-id]');
                if (productItems.length === 0) {
                    return;
                }

                const items = [];
                productItems.forEach(itemDiv => {
                    const productId = itemDiv.dataset.productId;
                    const titleInput = itemDiv.querySelector(`input[name="products[${productId}][title]"]`);
                    const quantityInput = itemDiv.querySelector(`input[name="products[${productId}][quantity]"]`);
                    const priceInput = itemDiv.querySelector(`input[name="products[${productId}][price]"]`);

                    if (titleInput && quantityInput && priceInput && quantityInput.value > 0 && priceInput.value > 0) {
                        items.push({
                            'title': titleInput.value,
                            'price': priceInput.value,
                            'quantity': parseInt(quantityInput.value),
                            'taxed': 0
                        });
                    }
                });

                invoiceForm.querySelectorAll('input[data-generated-item="true"]').forEach(input => input.remove());

                items.forEach((item, index) => {
                    Object.entries(item).forEach(([key, value]) => {
                        const itemInput = document.createElement('input');
                        itemInput.type = 'hidden';
                        itemInput.name = `items[${index}][${key}]`;
                        itemInput.value = value;
                        itemInput.dataset.generatedItem = 'true';
                        invoiceForm.appendChild(itemInput);
                    });
                });
            });
        }
    });
</script>
{% endblock %}
