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

{% block title %}Create Journal Entry{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="card">
        <div class="card-header">
            <h2 class="mb-0">Create Journal Entry</h2>
        </div>
        <div class="card-body">
            <form method="post" id="journal-entry-form">
                {% csrf_token %}
                {{ formset.management_form }}
                <!-- Journal 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 }}
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="{{ form.project.id_for_label }}">Project (Optional)</label>
                            {{ form.project }}
                        </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-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 class="col-md-6">
                        <div class="form-group">
                            <label for="{{ form.reference.id_for_label }}">Reference</label>
                            {{ form.reference }}
                        </div>
                        
                    </div>
                </div>
                
                <div class="form-group mb-4">
                    <label for="{{ form.description.id_for_label }}">Description</label>
                    {{ form.description }}
                </div>
                
                <!-- Transactions Table -->
                <div class="table-responsive mb-4">
                    <table class="table" id="transactions-table">
                        <thead class="table-light">
                            <tr>
                                <th>Account</th>
                                <th>Debit</th>
                                <th>Credit</th>
                                <th>Description</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody id="transactions-body">
                            {% for form in formset %}
                            <tr class="transaction-row">
                                <td>{{ form.account }}</td>
                                <td>{{ form.debit |add_class:"form-control debit-input" }}</td>
                                <td>{{ form.credit |add_class:"form-control credit-input" }}</td>
                                <td>{{ form.description }}</td>
                                <td>
                                    {% if form.instance.pk %}{{ form.DELETE }}{% endif %}
                                    <button type="button" class="btn btn-sm btn-danger remove-row">
                                        ×
                                    </button>
                                </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 data-accounts='{% for account in accounts %}{{ account.id }}:{{ account.code }} - {{ account.name }}{% if not forloop.last %},{% endif %}{% endfor %}'></table>
                    </table>
                </div>
                
                <div class="d-flex justify-content-between">
                    <a href="{% url 'journal_entry_list' %}" class="btn btn-secondary">
                        <i class="bi bi-arrow-left"></i> Back to List
                    </a>
                    <button type="submit" class="btn btn-success">
                        <i class="bi bi-save"></i> Save Journal Entry
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>



<script src="{% static 'accounting/js/journal_entry_form.js' %}"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Get the total forms input
        const totalForms = document.getElementById('id_transactions-TOTAL_FORMS');
        let formCount = parseInt(totalForms.value);
        
        // Calculate totals
        function calculateTotals() {
            let totalDebit = 0;
            let totalCredit = 0;
            
            document.querySelectorAll('.debit-input').forEach(input => {
                totalDebit += parseFloat(input.value) || 0;
            });
            
            document.querySelectorAll('.credit-input').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 formCount = parseInt(totalForms.value);
            let formCount = parseInt(totalForms.value);
            const newRow = document.createElement('tr');
            newRow.className = 'transaction-row';
            newRow.innerHTML = `
                <td>
                    <select name="transactions-${formCount}-account" class="form-select account-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 debit-input" step="0.01" id="id_transactions-${formCount}-debit">
                </td>
                <td>
                    <input type="number" name="transactions-${formCount}-credit" class="form-control credit-input" step="0.01" id="id_transactions-${formCount}-credit">
                </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);
            // totalForms.value = formCount + 1;
            formCount++;
            totalForms.value = formCount;
        });
        
        // Remove row
        document.addEventListener('click', function(e) {
            if (e.target.closest('.remove-row')) {
                const row = e.target.closest('tr');
                const deleteInput = row.querySelector('input[name$="-DELETE"]');
                
                if (deleteInput) {
                    // For existing records, mark for deletion
                    deleteInput.value = 'on';
                    row.style.display = 'none';
                } else {
                    // For new rows, just remove
                    row.remove();
                }
                calculateTotals();
            }
        });
        
        // Recalculate totals when amounts change
        document.addEventListener('input', function(e) {
            if (e.target.classList.contains('debit-input') || e.target.classList.contains('credit-input')) {
                const row = e.target.closest('tr');
                if (e.target.classList.contains('debit-input') && e.target.value) {
                    row.querySelector('.credit-input').value = '';
                } else if (e.target.classList.contains('credit-input') && e.target.value) {
                    row.querySelector('.debit-input').value = '';
                }
                calculateTotals();
            }
        });
        
        // Initialize totals
        calculateTotals();
    });
    </script>
{% endblock %}