{% extends "base.html" %}
{% from 'components/ui.html' import page_header %}

{% block content %}
{% set actions %}
<div class="flex flex-wrap gap-2 items-center">
<a href="{{ url_for('invoices.edit_invoice', invoice_id=invoice.id) }}" class="btn btn-primary">Edit</a>
<div class="flex flex-wrap gap-2 items-center">
    <select id="pdf-size-selector" class="bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm font-medium hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
        <option value="A4">A4</option>
        <option value="Letter">Letter</option>
        <option value="Legal">Legal</option>
        <option value="A3">A3</option>
        <option value="A5">A5</option>
        <option value="Tabloid">Tabloid</option>
    </select>
    <a id="export-pdf-link" href="{{ url_for('invoices.export_invoice_pdf', invoice_id=invoice.id) }}" class="btn bg-secondary text-white hover:bg-secondary-dark">{{ _('Export PDF') }}</a>
</div>
<button type="button" onclick="showSendEmailModal()" class="btn bg-blue-500 text-white hover:bg-blue-600">
    <i class="fas fa-envelope mr-1"></i>Send Email
</button>
{% if peppol_enabled %}
<button type="button"
        onclick="sendInvoicePeppol()"
        class="btn bg-indigo-600 text-white hover:bg-indigo-700 {% if not peppol_recipient_ready %}opacity-50 cursor-not-allowed{% endif %}"
        {% if not peppol_recipient_ready %}disabled title="Client is missing Peppol endpoint details (peppol_endpoint_id / peppol_scheme_id)"{% endif %}>
    <i class="fas fa-paper-plane mr-1"></i>Send via Peppol
</button>
{% endif %}
{% if peppol_recipient_ready and (invoices_peppol_compliant or peppol_enabled) %}
<a href="{{ url_for('invoices.export_invoice_ubl', invoice_id=invoice.id) }}" class="btn bg-slate-600 text-white hover:bg-slate-700">
    <i class="fas fa-file-code mr-1"></i>{{ _('Download UBL') }}
</a>
{% endif %}
{% if invoice.status != 'paid' and invoice.status != 'cancelled' %}
<a href="{{ url_for('payment_gateways.pay_invoice', invoice_id=invoice.id) }}" class="btn bg-blue-500 text-white hover:bg-blue-600">
    <i class="fas fa-credit-card mr-1"></i>{{ _('Pay Online') }}
</a>
{% endif %}
<a href="{{ url_for('payments.create_payment', invoice_id=invoice.id) }}" class="btn bg-green-500 text-white hover:bg-green-600">{{ _('Record Payment') }}</a>
<button type="button" onclick="showDeleteModal('{{ invoice.id }}', '{{ invoice.invoice_number }}')" class="btn btn-danger">
    <i class="fas fa-trash mr-1"></i>Delete
</button>
</div>
{% endset %}
{{ page_header('fas fa-file-invoice', 'Invoice ' ~ invoice.invoice_number, actions_html=actions, breadcrumbs=[{'text': _('Invoices'), 'url': url_for('invoices.list_invoices')}, {'text': invoice.invoice_number or _('View Invoice')}]) }}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const sizeSelector = document.getElementById('pdf-size-selector');
        const exportLink = document.getElementById('export-pdf-link');
        if (sizeSelector && exportLink) {
            const defaultSize = sizeSelector.value || 'A4';
            const baseUrl = "{{ url_for('invoices.export_invoice_pdf', invoice_id=invoice.id) }}";
            exportLink.href = baseUrl + '?size=' + defaultSize;
            sizeSelector.addEventListener('change', function() {
                const size = this.value;
                exportLink.href = baseUrl + '?size=' + size;
            });
        }
    });
</script>

<div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
            <h2 class="text-lg font-semibold">Client</h2>
            <p>{{ invoice.client_name }}</p>
            <p>{{ invoice.client_email }}</p>
            <p>{{ invoice.client_address }}</p>
        </div>
        <div>
            <h2 class="text-lg font-semibold">Details</h2>
            <p><strong>Issue Date:</strong> {{ invoice.issue_date|format_date }}</p>
            <p><strong>Due Date:</strong> {{ invoice.due_date|format_date }}</p>
            <p><strong>Status:</strong> {{ invoice.status }}</p>
            {% if invoice.payment_reference %}
            <p><strong>{{ _('Payment Reference') }}:</strong> 
                {% set link_template = link_templates_by_field.get('payment_reference') if link_templates_by_field else None %}
                {% if link_template %}
                    {% set rendered_url = link_template.render_url(invoice.payment_reference) %}
                    {% if rendered_url %}
                        <a href="{{ rendered_url }}" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline break-all">
                            {{ invoice.payment_reference }}
                            <i class="fas fa-external-link-alt ml-1 text-xs"></i>
                        </a>
                    {% else %}
                        {{ invoice.payment_reference }}
                    {% endif %}
                {% elif invoice.payment_reference is string and (invoice.payment_reference.startswith('http://') or invoice.payment_reference.startswith('https://')) %}
                    <a href="{{ invoice.payment_reference }}" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline break-all">
                        {{ invoice.payment_reference }}
                        <i class="fas fa-external-link-alt ml-1 text-xs"></i>
                    </a>
                {% elif invoice.payment_reference is string and invoice.payment_reference.startswith('www.') %}
                    <a href="https://{{ invoice.payment_reference }}" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline break-all">
                        {{ invoice.payment_reference }}
                        <i class="fas fa-external-link-alt ml-1 text-xs"></i>
                    </a>
                {% else %}
                    {{ invoice.payment_reference }}
                {% endif %}
            </p>
            {% endif %}
            {% if invoice.approvals %}
            {% set latest_approval = invoice.approvals|sort(attribute='created_at', reverse=true)|first %}
            {% if latest_approval %}
            <p><strong>{{ _('Approval Status') }}:</strong> 
                <span class="px-2 py-1 text-xs rounded
                    {% if latest_approval.status == 'approved' %}bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200
                    {% elif latest_approval.status == 'rejected' %}bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200
                    {% else %}bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200{% endif %}">
                    {{ latest_approval.status|title }}
                </span>
            </p>
            {% endif %}
            {% endif %}
        </div>
    </div>

    {% if peppol_compliance_warnings %}
    <div class="mt-4 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4">
        <h3 class="font-semibold text-amber-900 dark:text-amber-100">{{ _('PEPPOL compliance: the following are missing') }}</h3>
        <ul class="mt-2 text-sm text-amber-800 dark:text-amber-200 list-disc list-inside space-y-1">
            {% for msg in peppol_compliance_warnings %}
            <li>{{ msg }}</li>
            {% endfor %}
        </ul>
    </div>
    {% endif %}
    
    {% if invoice.status == 'draft' and (current_user.is_admin or has_permission('create_invoices')) %}
    <div class="mt-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
        <div class="flex justify-between items-center">
            <div>
                <h3 class="font-semibold text-blue-900 dark:text-blue-100">{{ _('Invoice Approval') }}</h3>
                <p class="text-sm text-blue-800 dark:text-blue-200">{{ _('Request approval before sending this invoice to the client.') }}</p>
            </div>
            {% if not invoice.approvals or (invoice.approvals|selectattr('status', 'equalto', 'pending')|list|length == 0) %}
            <a href="{{ url_for('invoice_approvals.request_approval', invoice_id=invoice.id) }}" class="btn bg-blue-600 text-white hover:bg-blue-700">
                <i class="fas fa-check-circle mr-2"></i>{{ _('Request Approval') }}
            </a>
            {% endif %}
        </div>
    </div>
    {% endif %}

    <div class="mt-6">
        <h2 class="text-lg font-semibold mb-4">Items</h2>
        <table class="w-full text-left">
            <thead>
                <tr>
                    <th class="p-2">Description</th>
                    <th class="p-2">Quantity</th>
                    <th class="p-2">Unit Price</th>
                    <th class="p-2">Total</th>
                </tr>
            </thead>
            <tbody>
                {% for item in invoice.items %}
                <tr class="border-b border-border-light dark:border-border-dark">
                    <td class="p-2">{{ item.description }}</td>
                    <td class="p-2">{{ "%.2f"|format(item.quantity) }}</td>
                    <td class="p-2">{{ "%.2f"|format(item.unit_price) }} {{ invoice.currency_code }}</td>
                    <td class="p-2">{{ "%.2f"|format(item.total_amount) }} {{ invoice.currency_code }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>

    {% if invoice.expenses.count() > 0 %}
    <div class="mt-6">
        <h2 class="text-lg font-semibold mb-4">Expenses</h2>
        <table class="w-full text-left">
            <thead>
                <tr>
                    <th class="p-2">Title</th>
                    <th class="p-2">Description</th>
                    <th class="p-2">Category</th>
                    <th class="p-2">Date</th>
                    <th class="p-2">Vendor</th>
                    <th class="p-2">Amount</th>
                </tr>
            </thead>
            <tbody>
                {% for expense in invoice.expenses %}
                <tr class="border-b border-border-light dark:border-border-dark">
                    <td class="p-2">{{ expense.title }}</td>
                    <td class="p-2">{{ expense.description or '-' }}</td>
                    <td class="p-2">{{ expense.category|capitalize }}</td>
                    <td class="p-2">{{ expense.expense_date|format_date if expense.expense_date else '-' }}</td>
                    <td class="p-2">{{ expense.vendor or '-' }}</td>
                    <td class="p-2">{{ "%.2f"|format(expense.total_amount) }} {{ expense.currency_code }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
    {% endif %}

    {% if invoice.extra_goods.count() > 0 %}
    <div class="mt-6">
        <h2 class="text-lg font-semibold mb-4">{{ _('Extra Goods') }}</h2>
        <table class="w-full text-left">
            <thead>
                <tr>
                    <th class="p-2">Name</th>
                    <th class="p-2">Description</th>
                    <th class="p-2">Category</th>
                    <th class="p-2">Quantity</th>
                    <th class="p-2">Unit Price</th>
                    <th class="p-2">Total</th>
                </tr>
            </thead>
            <tbody>
                {% for good in invoice.extra_goods %}
                <tr class="border-b border-border-light dark:border-border-dark">
                    <td class="p-2">{{ good.name }}</td>
                    <td class="p-2">{{ good.description or '-' }}</td>
                    <td class="p-2">{{ good.category|capitalize }}</td>
                    <td class="p-2">{{ "%.2f"|format(good.quantity) }}</td>
                    <td class="p-2">{{ "%.2f"|format(good.unit_price) }} {{ invoice.currency_code }}</td>
                    <td class="p-2">{{ "%.2f"|format(good.total_amount) }} {{ invoice.currency_code }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
    {% endif %}

    <div class="mt-6 flex justify-end">
        <div class="w-full md:w-1/3">
            <div class="flex justify-between">
                <span>Subtotal</span>
                <span>{{ "%.2f"|format(invoice.subtotal) }} {{ invoice.currency_code }}</span>
            </div>
            <div class="flex justify-between">
                <span>Tax ({{ "%.2f"|format(invoice.tax_rate) }}%)</span>
                <span>{{ "%.2f"|format(invoice.tax_amount) }} {{ invoice.currency_code }}</span>
            </div>
            <div class="flex justify-between font-bold text-lg border-t border-gray-300 dark:border-gray-600 pt-2">
                <span>Total</span>
                <span>{{ "%.2f"|format(invoice.total_amount) }} {{ invoice.currency_code }}</span>
            </div>
            <div class="flex justify-between text-green-600 dark:text-green-400 mt-2">
                <span>Amount Paid</span>
                <span>{{ "%.2f"|format(invoice.amount_paid or 0) }} {{ invoice.currency_code }}</span>
            </div>
            <div class="flex justify-between font-semibold text-red-600 dark:text-red-400 border-t border-gray-300 dark:border-gray-600 pt-2 mt-2">
                <span>Outstanding</span>
                <span>{{ "%.2f"|format(invoice.outstanding_amount) }} {{ invoice.currency_code }}</span>
            </div>
        </div>
    </div>

    <!-- Payment History -->
    {% if invoice.payments.count() > 0 %}
    <div class="mt-8 border-t border-gray-300 dark:border-gray-600 pt-6">
        <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold">{{ _('Payment History') }}</h2>
            <a href="{{ url_for('payments.create_payment', invoice_id=invoice.id) }}" class="btn bg-green-500 text-white hover:bg-green-600">
                <i class="fas fa-plus mr-2"></i>Add Payment
            </a>
        </div>
        <table class="w-full text-left">
            <thead>
                <tr class="border-b border-gray-300 dark:border-gray-600">
                    <th class="p-2">Date</th>
                    <th class="p-2">Amount</th>
                    <th class="p-2">Method</th>
                    <th class="p-2">Reference</th>
                    <th class="p-2">Status</th>
                    <th class="p-2">Actions</th>
                </tr>
            </thead>
            <tbody>
                {% for payment in invoice.sorted_payments %}
                <tr class="border-b border-border-light dark:border-border-dark hover:bg-gray-50 dark:hover:bg-gray-700">
                    <td class="p-2">{{ payment.payment_date|format_date if payment.payment_date else 'N/A' }}</td>
                    <td class="p-2 font-semibold text-green-600 dark:text-green-400">
                        {{ "%.2f"|format(payment.amount) }} {{ payment.currency or invoice.currency_code }}
                        {% if payment.gateway_fee %}
                        <span class="text-xs text-gray-500 dark:text-gray-400">(Fee: {{ "%.2f"|format(payment.gateway_fee) }})</span>
                        {% endif %}
                    </td>
                    <td class="p-2">{{ payment.method or 'N/A' }}</td>
                    <td class="p-2 text-sm">
                        {% if payment.reference %}
                            {% set link_template = link_templates_by_field.get('payment_reference') if link_templates_by_field else None %}
                            {% if link_template %}
                                {% set rendered_url = link_template.render_url(payment.reference) %}
                                {% if rendered_url %}
                                    <a href="{{ rendered_url }}" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline break-all">
                                        {{ payment.reference }}
                                        <i class="fas fa-external-link-alt ml-1 text-xs"></i>
                                    </a>
                                {% else %}
                                    {{ payment.reference }}
                                {% endif %}
                            {% elif payment.reference is string and (payment.reference.startswith('http://') or payment.reference.startswith('https://')) %}
                                <a href="{{ payment.reference }}" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline break-all">
                                    {{ payment.reference }}
                                    <i class="fas fa-external-link-alt ml-1 text-xs"></i>
                                </a>
                            {% elif payment.reference is string and payment.reference.startswith('www.') %}
                                <a href="https://{{ payment.reference }}" target="_blank" rel="noopener noreferrer" class="text-primary hover:underline break-all">
                                    {{ payment.reference }}
                                    <i class="fas fa-external-link-alt ml-1 text-xs"></i>
                                </a>
                            {% else %}
                                {{ payment.reference }}
                            {% endif %}
                        {% else %}
                            —
                        {% endif %}
                    </td>
                    <td class="p-2">
                        {% if payment.status == 'completed' %}
                        <span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-100">
                            Completed
                        </span>
                        {% elif payment.status == 'pending' %}
                        <span class="px-2 py-1 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800 dark:bg-yellow-800 dark:text-yellow-100">
                            Pending
                        </span>
                        {% elif payment.status == 'failed' %}
                        <span class="px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800 dark:bg-red-800 dark:text-red-100">
                            Failed
                        </span>
                        {% elif payment.status == 'refunded' %}
                        <span class="px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800 dark:bg-gray-600 dark:text-gray-100">
                            Refunded
                        </span>
                        {% endif %}
                    </td>
                    <td class="p-2">
                        <a href="{{ url_for('payments.view_payment', payment_id=payment.id) }}" class="text-primary hover:text-primary-dark text-sm">
                            View
                        </a>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
    {% else %}
    <div class="mt-8 border-t border-gray-300 dark:border-gray-600 pt-6">
        <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold">{{ _('Payment History') }}</h2>
            <a href="{{ url_for('payments.create_payment', invoice_id=invoice.id) }}" class="btn bg-green-500 text-white hover:bg-green-600">
                <i class="fas fa-plus mr-2"></i>Record First Payment
            </a>
        </div>
        <p class="text-gray-500 dark:text-gray-400 text-center py-4">No payments recorded yet.</p>
    </div>
    {% endif %}
</div>

<!-- Delete Invoice Modal -->
<div id="deleteInvoiceModal" class="hidden fixed inset-0 z-50" role="dialog" aria-modal="true" aria-labelledby="deleteModalTitle">
  <div class="absolute inset-0 bg-black/50" onclick="hideDeleteModal()"></div>
  <div class="relative max-w-lg mx-auto mt-24 bg-card-light dark:bg-card-dark text-text-light dark:text-text-dark rounded-xl shadow-xl border border-border-light dark:border-border-dark">
    <div class="p-4 border-b border-border-light dark:border-border-dark flex items-center justify-between">
      <h5 id="deleteModalTitle" class="text-lg font-semibold flex items-center gap-2">
        <i class="fas fa-trash text-red-500"></i> {{ _('Delete Invoice') }}
      </h5>
      <button type="button" class="px-2 py-1 hover:bg-background-light dark:hover:bg-background-dark rounded text-2xl leading-none" aria-label="{{ _('Close') }}" onclick="hideDeleteModal()">&times;</button>
    </div>
    <div class="p-4">
      <div class="bg-yellow-50 dark:bg-yellow-900/30 text-yellow-900 dark:text-yellow-100 rounded-lg p-3 ring-1 ring-yellow-200/60 dark:ring-yellow-700/50 flex items-start gap-2">
        <i class="fas fa-exclamation-triangle mt-1"></i>
        <div>
          <strong>{{ _('Warning:') }}</strong> {{ _('This action cannot be undone.') }}
        </div>
      </div>
      <p class="mt-4">{{ _('Are you sure you want to delete invoice') }} <strong id="deleteInvoiceNumber"></strong>?</p>
      <p class="text-text-muted-light dark:text-text-muted-dark mt-2">
        <small>{{ _('All invoice items, extra goods, and payment records associated with this invoice will be permanently deleted.') }}</small>
      </p>
    </div>
    <div class="p-4 border-t border-border-light dark:border-border-dark flex items-center justify-between">
      <button type="button" class="btn btn-secondary" onclick="hideDeleteModal()">
        <i class="fas fa-times"></i> {{ _('Cancel') }}
      </button>
      <form method="POST" id="deleteInvoiceForm" class="inline">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <button type="submit" class="btn btn-danger">
          <i class="fas fa-trash"></i> {{ _('Delete Invoice') }}
        </button>
      </form>
    </div>
  </div>
</div>

<!-- Email History Section -->
{% if email_history|length > 0 %}
<div class="mt-6 bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
    <h2 class="text-lg font-semibold mb-4 flex items-center">
        <i class="fas fa-envelope mr-2"></i>Email History
    </h2>
    <div class="overflow-x-auto">
        <table class="w-full text-left">
            <thead>
                <tr class="border-b border-border-light dark:border-border-dark">
                    <th class="p-2 text-sm font-medium">Sent At</th>
                    <th class="p-2 text-sm font-medium">Recipient</th>
                    <th class="p-2 text-sm font-medium">Status</th>
                    <th class="p-2 text-sm font-medium">Subject</th>
                    <th class="p-2 text-sm font-medium">Actions</th>
                </tr>
            </thead>
            <tbody>
                {% for email in email_history %}
                <tr class="border-b border-border-light dark:border-border-dark">
                    <td class="p-2 text-sm">
                        {{ email.sent_at|user_datetime if email.sent_at else 'N/A' }}
                    </td>
                    <td class="p-2 text-sm">{{ email.recipient_email }}</td>
                    <td class="p-2 text-sm">
                        <span class="px-2 py-1 rounded text-xs font-medium
                            {% if email.status == 'sent' %}bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200
                            {% elif email.status == 'opened' %}bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200
                            {% elif email.status == 'paid' %}bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200
                            {% elif email.status == 'failed' %}bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200
                            {% elif email.status == 'bounced' %}bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200
                            {% else %}bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200
                            {% endif %}">
                            {{ email.status|title }}
                        </span>
                    </td>
                    <td class="p-2 text-sm">{{ email.subject }}</td>
                    <td class="p-2 text-sm">
                        <button onclick="resendInvoiceEmail({{ invoice.id }}, {{ email.id }}, '{{ email.recipient_email }}')" 
                                class="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 text-sm font-medium">
                            <i class="fas fa-redo mr-1"></i>Resend
                        </button>
                    </td>
                </tr>
                {% if email.error_message %}
                <tr class="bg-red-50 dark:bg-red-900/20">
                    <td colspan="5" class="p-2 text-sm text-red-600 dark:text-red-400">
                        <i class="fas fa-exclamation-circle mr-1"></i>Error: {{ email.error_message }}
                    </td>
                </tr>
                {% endif %}
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>
{% endif %}

<!-- Peppol History Section -->
{% if peppol_history is defined and peppol_history|length > 0 %}
<div class="mt-6 bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
    <h2 class="text-lg font-semibold mb-4 flex items-center">
        <i class="fas fa-paper-plane mr-2"></i>Peppol History
    </h2>
    <div class="overflow-x-auto">
        <table class="w-full text-left">
            <thead>
                <tr class="border-b border-border-light dark:border-border-dark">
                    <th class="p-2 text-sm font-medium">Created</th>
                    <th class="p-2 text-sm font-medium">Status</th>
                    <th class="p-2 text-sm font-medium">Recipient</th>
                    <th class="p-2 text-sm font-medium">Message ID</th>
                    <th class="p-2 text-sm font-medium">Error</th>
                </tr>
            </thead>
            <tbody>
                {% for tx in peppol_history %}
                <tr class="border-b border-border-light dark:border-border-dark">
                    <td class="p-2 text-sm">{{ tx.created_at|user_datetime if tx.created_at else 'N/A' }}</td>
                    <td class="p-2 text-sm">
                        <span class="px-2 py-1 rounded text-xs font-medium
                            {% if tx.status == 'sent' %}bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200
                            {% elif tx.status == 'failed' %}bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200
                            {% else %}bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200{% endif %}">
                            {{ tx.status|title }}
                        </span>
                    </td>
                    <td class="p-2 text-sm">{{ (tx.recipient_scheme_id or '') ~ ':' ~ (tx.recipient_endpoint_id or '') }}</td>
                    <td class="p-2 text-sm">{{ tx.message_id or '—' }}</td>
                    <td class="p-2 text-sm text-red-600 dark:text-red-400">{{ tx.error_message or '—' }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>
{% endif %}

<!-- Send Email Modal -->
<div id="sendEmailModal" class="hidden fixed inset-0 bg-black/50 overflow-y-auto h-full w-full z-50">
  <div class="relative top-20 mx-auto p-5 max-w-sm w-full sm:w-96 bg-card-light dark:bg-card-dark rounded-xl shadow-xl border border-border-light dark:border-border-dark mx-4 sm:mx-auto">
    <div class="mt-3">
      <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-4">{{ _('Send Invoice via Email') }}</h3>
      <form id="sendEmailForm" onsubmit="sendInvoiceEmail(event)">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <div class="mb-4">
          <label for="recipient_email" class="form-label">Recipient Email *</label>
          <input type="email" id="recipient_email" name="recipient_email" value="{{ invoice.client_email }}" required class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100">
        </div>
        <div class="mb-4">
          <label for="email_template_id" class="form-label">Email Template (Optional)</label>
          <select id="email_template_id" name="email_template_id" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100">
            <option value="">Default Template</option>
            {% for template in email_templates %}
            <option value="{{ template.id }}">{{ template.name }}</option>
            {% endfor %}
          </select>
        </div>
        <div class="mb-4">
          <label for="custom_message" class="form-label">{{ _('Custom Message') }} ({{ _('Optional') }})</label>
          <textarea id="custom_message" name="custom_message" rows="4" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"></textarea>
        </div>
        <div class="flex flex-wrap justify-end gap-3">
          <button type="button" onclick="hideSendEmailModal()" class="btn btn-secondary">Cancel</button>
          <button type="submit" class="btn bg-blue-500 text-white hover:bg-blue-600">{{ _('Send Email') }}</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function showSendEmailModal() {
  const modal = document.getElementById('sendEmailModal');
  if (modal) modal.classList.remove('hidden');
}

function hideSendEmailModal() {
  const modal = document.getElementById('sendEmailModal');
  if (modal) modal.classList.add('hidden');
}

function sendInvoiceEmail(event) {
  event.preventDefault();
  const form = event.target;
  const formData = new FormData(form);
  
  // Show loading state
  const submitBtn = form.querySelector('button[type="submit"]');
  const originalText = submitBtn.textContent;
  submitBtn.disabled = true;
  submitBtn.textContent = 'Sending...';
  
  fetch("{{ url_for('invoices.send_invoice_email_route', invoice_id=invoice.id) }}", {
    method: 'POST',
    body: formData
  })
  .then(async response => {
    // Check content type to determine how to parse
    const contentType = response.headers.get('content-type') || '';
    const isJson = contentType.includes('application/json');
    
    // Always try JSON first if content-type suggests it, otherwise read as text
    if (isJson) {
      const data = await response.json();
      // Handle both success and error responses
      if (!response.ok) {
        return { success: false, error: data.error || data.message || `HTTP ${response.status}: ${response.statusText}` };
      }
      return data;
    } else {
      // Not JSON, read as text (only once)
      const text = await response.text();
      if (!response.ok) {
        throw new Error(text || `HTTP ${response.status}: ${response.statusText}`);
      }
      // If successful but not JSON, return error format
      return { success: false, error: text || 'Unexpected response format' };
    }
  })
  .then(data => {
    if (data.success) {
      if (window.toastManager) {
        window.toastManager.success('Invoice email sent successfully!');
      } else {
        alert('Invoice email sent successfully!');
      }
      hideSendEmailModal();
      // Optionally reload the page to show updated status
      setTimeout(() => window.location.reload(), 1000);
    } else {
      const errorMsg = data.error || 'Failed to send email';
      console.error('Email send error:', errorMsg);
      if (window.toastManager) {
        window.toastManager.error('Error: ' + errorMsg);
      } else {
        alert('Error: ' + errorMsg);
      }
      submitBtn.disabled = false;
      submitBtn.textContent = originalText;
    }
  })
  .catch(error => {
    console.error('Email send error:', error);
    const errorMsg = error.message || 'Failed to send email. Please check server logs for details.';
    if (window.toastManager) {
      window.toastManager.error(errorMsg);
    } else {
      alert(errorMsg);
    }
    submitBtn.disabled = false;
    submitBtn.textContent = originalText;
  });
}

function showDeleteModal(invoiceId, invoiceNumber) {
  const numberEl = document.getElementById('deleteInvoiceNumber');
  const formEl = document.getElementById('deleteInvoiceForm');
  if (numberEl) numberEl.textContent = invoiceNumber || '';
  if (formEl) formEl.action = "{{ url_for('invoices.delete_invoice', invoice_id=0) }}".replace('0', invoiceId);
  const modal = document.getElementById('deleteInvoiceModal');
  if (modal) modal.classList.remove('hidden');
}

function hideDeleteModal() {
  const modal = document.getElementById('deleteInvoiceModal');
  if (modal) modal.classList.add('hidden');
}

function resendInvoiceEmail(invoiceId, emailId, recipientEmail) {
  if (!confirm(`Resend invoice email to ${recipientEmail}?`)) {
    return;
  }
  
  // Show the send email modal with pre-filled recipient
  const modal = document.getElementById('sendEmailModal');
  const recipientInput = document.getElementById('recipient_email');
  if (modal && recipientInput) {
    recipientInput.value = recipientEmail;
    modal.classList.remove('hidden');
    
    // Override form submission to use resend endpoint
    const form = document.getElementById('sendEmailForm');
    if (form) {
      const originalOnSubmit = form.onsubmit;
      form.onsubmit = function(event) {
        event.preventDefault();
        const formData = new FormData(form);
        
        // Show loading state
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.textContent;
        submitBtn.disabled = true;
        submitBtn.textContent = 'Resending...';
        
        fetch(`/invoices/${invoiceId}/resend-email/${emailId}`, {
          method: 'POST',
          body: formData
        })
        .then(async response => {
          const contentType = response.headers.get('content-type') || '';
          const isJson = contentType.includes('application/json');
          
          if (isJson) {
            const data = await response.json();
            if (!response.ok) {
              return { success: false, error: data.error || data.message || `HTTP ${response.status}: ${response.statusText}` };
            }
            return data;
          } else {
            const text = await response.text();
            if (!response.ok) {
              throw new Error(text || `HTTP ${response.status}: ${response.statusText}`);
            }
            return { success: false, error: text || 'Unexpected response format' };
          }
        })
        .then(data => {
          if (data.success) {
            if (window.toastManager) {
              window.toastManager.success('Invoice email resent successfully!');
            } else {
              alert('Invoice email resent successfully!');
            }
            hideSendEmailModal();
            setTimeout(() => window.location.reload(), 1000);
          } else {
            const errorMsg = data.error || 'Failed to resend email';
            console.error('Email resend error:', errorMsg);
            if (window.toastManager) {
              window.toastManager.error('Error: ' + errorMsg);
            } else {
              alert('Error: ' + errorMsg);
            }
            submitBtn.disabled = false;
            submitBtn.textContent = originalText;
          }
        })
        .catch(error => {
          console.error('Email resend error:', error);
          const errorMsg = error.message || 'Failed to resend email';
          if (window.toastManager) {
            window.toastManager.error('Error: ' + errorMsg);
          } else {
            alert('Error: ' + errorMsg);
          }
          submitBtn.disabled = false;
          submitBtn.textContent = originalText;
        });
        
        // Restore original handler after use
        setTimeout(() => {
          form.onsubmit = originalOnSubmit;
        }, 100);
      };
    }
  }
}

function sendInvoicePeppol() {
  // Hard guard if button is disabled by template state
  {% if not peppol_recipient_ready %}
  return;
  {% endif %}

  if (!confirm('Send this invoice via Peppol?')) {
    return;
  }

  const body = new FormData();
  body.append('csrf_token', "{{ csrf_token() }}");

  fetch("{{ url_for('invoices.send_invoice_peppol_route', invoice_id=invoice.id) }}", {
    method: 'POST',
    body
  })
  .then(async response => {
    const contentType = response.headers.get('content-type') || '';
    const isJson = contentType.includes('application/json');
    const data = isJson ? await response.json() : { error: await response.text() };
    if (!response.ok) {
      throw new Error(data.error || data.message || `HTTP ${response.status}: ${response.statusText}`);
    }
    return data;
  })
  .then(data => {
    if (data.success) {
      if (window.toastManager) {
        window.toastManager.success(data.message || 'Sent via Peppol');
      } else {
        alert(data.message || 'Sent via Peppol');
      }
      setTimeout(() => window.location.reload(), 800);
    } else {
      const errorMsg = data.error || 'Failed to send via Peppol';
      if (window.toastManager) {
        window.toastManager.error(errorMsg);
      } else {
        alert('Error: ' + errorMsg);
      }
    }
  })
  .catch(err => {
    const msg = err && err.message ? err.message : 'Failed to send via Peppol';
    if (window.toastManager) {
      window.toastManager.error(msg);
    } else {
      alert('Error: ' + msg);
    }
  });
}
</script>
{% endblock %}
