{% extends "base.html" %}
{% load static %}

{% block title %}Edit Journal Entry {{ entry.entry_number }}{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h2 class="mb-0">Edit Journal Entry: {{ entry.entry_number }}</h2>
            <div>
                <a href="{% url 'journal_entry_list' %}" class="btn btn-sm btn-outline-secondary me-2">
                    <i class="bi bi-x"></i> Cancel
                </a>
            </div>
        </div>
        
        <div class="card-body">
            <form method="post" id="journal-entry-form">
                {% csrf_token %}
                
                {% if form.non_field_errors or formset.non_form_errors %}
                <div class="alert alert-danger">
                    {{ form.non_field_errors }}
                    {{ formset.non_form_errors }}
                </div>
                {% endif %}
                
                <!-- Entry Header -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="{{ form.date.id_for_label }}">Date*</label>
                            {{ form.date }}
                            {% if form.date.errors %}
                            <div class="invalid-feedback d-block">
                                {{ form.date.errors }}
                            </div>
                            {% endif %}
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="{{ form.status.id_for_label }}">Status*</label>
                            {{ form.status }}
                            {% if form.status.errors %}
                            <div class="invalid-feedback d-block">
                                {{ form.status.errors }}
                            </div>
                            {% endif %}
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="{{ form.reference.id_for_label }}">Reference</label>
                            {{ form.reference }}
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="{{ form.job.id_for_label }}">Job</label>
                            {{ form.job }}
                        </div>
                    </div>
                </div>
                <div class="row mb-4">  
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="{{ form.supplier.id_for_label }}">Supplier (Optional)</label>
                            {{ form.supplier }}
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="{{ form.customer.id_for_label }}">Customer (Optional)</label>
                            {{ form.customer }}
                        </div>
                    </div>
                </div>
                <div class="form-group mb-4">
                    <label for="{{ form.description.id_for_label }}">Description*</label>
                    {{ form.description }}
                    {% if form.description.errors %}
                    <div class="invalid-feedback d-block">
                        {{ form.description.errors }}
                    </div>
                    {% endif %}
                </div>
                
                <!-- Transactions Table -->
                <div class="table-responsive mb-4">
                    {{ formset.management_form }}
                    <table class="table" id="transactions-table">
                        <thead class="table-light">
                            <tr>
                                <th>Account</th>
                                <th class="text-end">Debit</th>
                                <th class="text-end">Credit</th>
                                <th>Description</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody id="transactions-body">
                            {% for form in formset %}
                            <tr class="transaction-row {% if form.DELETE %}d-none{% endif %}">
                                <td>
                                    {{ form.id }}
                                    {{ form.account }}
                                    {% if form.account.errors %}
                                    <div class="invalid-feedback d-block">
                                        {{ form.account.errors }}
                                    </div>
                                    {% endif %}
                                </td>
                                <td>
                                    {{ form.debit }}
                                    {% if form.debit.errors %}
                                    <div class="invalid-feedback d-block">
                                        {{ form.debit.errors }}
                                    </div>
                                    {% endif %}
                                </td>
                                <td>
                                    {{ form.credit }}
                                    {% if form.credit.errors %}
                                    <div class="invalid-feedback d-block">
                                        {{ form.credit.errors }}
                                    </div>
                                    {% endif %}
                                </td>
                                <td>
                                    {{ form.description }}
                                </td>
                                <td class="align-middle">
                                    {% if form.instance.pk %}
                                    {{ form.DELETE }}
                                    <label for="{{ form.DELETE.id_for_label }}" class="btn btn-sm btn-danger mb-0">
                                        <i class="bi bi-trash"></i>
                                    </label>
                                    {% else %}
                                    <button type="button" class="btn btn-sm btn-danger remove-row">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                    {% endif %}
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="5">
                                    <button type="button" id="add-row" class="btn btn-sm btn-primary">
                                        <i class="bi bi-plus"></i> Add Row
                                    </button>
                                </td>
                            </tr>
                            <tr class="table-active">
                                <td><strong>Total</strong></td>
                                <td class="text-end" id="total-debit">0.00</td>
                                <td class="text-end" id="total-credit">0.00</td>
                                <td colspan="2"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
                
                <div class="d-flex justify-content-between">
                    {% if entry.status != 'posted' %}
                    <button type="submit" name="action" value="save" class="btn btn-success">
                        <i class="bi bi-save"></i> Save Changes
                    </button>
                    {% else %}
                    <p class="text-muted">This entry is completed and cannot be edited.</p>
                    {% endif %}
                    <!-- {% if entry.status == 'draft' %}
                    <button type="submit" name="action" value="post" class="btn btn-primary">
                        <i class="bi bi-check-circle"></i> Save and Post
                    </button>
                    {% endif %} -->
                </div>
            </form>
        </div>
    </div>
</div>


<script src="{% static 'accounting/js/journal_entry_form.js' %}"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize with existing rows
    const totalForms = document.getElementById('id_transactions-TOTAL_FORMS');
    let formCount = parseInt(totalForms.value);
    
    // Calculate initial totals
    function calculateTotals() {
        let totalDebit = 0;
        let totalCredit = 0;
        
        document.querySelectorAll('[id$="-debit"]').forEach(input => {
            totalDebit += parseFloat(input.value) || 0;
        });
        
        document.querySelectorAll('[id$="-credit"]').forEach(input => {
            totalCredit += parseFloat(input.value) || 0;
        });
        
        document.getElementById('total-debit').textContent = totalDebit.toFixed(2);
        document.getElementById('total-credit').textContent = totalCredit.toFixed(2);
    }
    
    // Add new row
    document.getElementById('add-row').addEventListener('click', function() {
        const newRow = document.createElement('tr');
        newRow.className = 'transaction-row';
        newRow.innerHTML = `
            <td>
                <select name="transactions-${formCount}-account" class="form-select" id="id_transactions-${formCount}-account">
                    {% for account in accounts %}
                    <option value="{{ account.id }}">{{ account.code }} - {{ account.name }}</option>
                    {% endfor %}
                </select>
            </td>
            <td>
                <input type="number" name="transactions-${formCount}-debit" class="form-control" step="0.01" id="id_transactions-${formCount}-debit" value="0.00">
            </td>
            <td>
                <input type="number" name="transactions-${formCount}-credit" class="form-control" step="0.01" id="id_transactions-${formCount}-credit" value="0.00">
            </td>
            <td>
                <input type="text" name="transactions-${formCount}-description" class="form-control" id="id_transactions-${formCount}-description">
            </td>
            <td>
                <button type="button" class="btn btn-sm btn-danger remove-row">
                    <i class="bi bi-trash"></i>
                </button>
            </td>
        `;
        
        document.getElementById('transactions-body').appendChild(newRow);
        formCount++;
        totalForms.value = formCount;
    });
    
    // Remove row
    document.getElementById('transactions-body').addEventListener('click', function(e) {
        if (e.target.closest('.remove-row')) {
            const row = e.target.closest('tr');
            row.remove();
            calculateTotals();
        }
    });
    
    // Recalculate totals when amounts change
    document.getElementById('transactions-body').addEventListener('input', function(e) {
        if (e.target.matches('[id$="-debit"], [id$="-credit"]')) {
            const row = e.target.closest('tr');
            if (e.target.id.includes('-debit') && e.target.value !== '0.00') {
                row.querySelector('[id$="-credit"]').value = '0.00';
            } else if (e.target.id.includes('-credit') && e.target.value !== '0.00') {
                row.querySelector('[id$="-debit"]').value = '0.00';
            }
            calculateTotals();
        }
    });
    
    // Initial calculation
    calculateTotals();
});
</script>
{% endblock %}

