{% extends 'base.html' %}

{% block title %}Create Receipt | Fox Fitt{% endblock %}

{% block content %}
<!-- === CREATE EXPENSE RECEIPT ===
     Single-page form for recording business expenses.
     - Dynamic line items (add/remove rows with JavaScript)
     - Live VAT calculation (Included / Excluded / None)
     - On submit: saves to database + emails HTML + PDF to Spark Receipt -->

<div class="container py-5">
    <div class="card border-0 shadow-sm">

        <!-- Card header -->
        <div class="card-header py-3" style="background-color: var(--primary-color);">
            <h4 class="mb-0 text-white fw-bold">
                <i class="fas fa-file-invoice-dollar me-2"></i> Create Expense Receipt
            </h4>
        </div>

        <div class="card-body p-4">
            <form method="post" id="receipt-form">
                {% csrf_token %}

                <!-- === RECEIPT HEADER FIELDS === -->
                <div class="row g-3 mb-4">
                    <div class="col-md-6">
                        <label class="form-label fw-bold text-secondary">Date</label>
                        {{ form.date }}
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold text-secondary">Vendor Name</label>
                        {{ form.vendor_name }}
                        <div class="form-text text-muted small">
                            <i class="fas fa-info-circle"></i> Will appear as the main title on the receipt.
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold text-secondary">Payment Method</label>
                        {{ form.payment_method }}
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-bold text-secondary">Description</label>
                        {{ form.description }}
                    </div>
                </div>

                <hr class="my-4">

                <!-- === LINE ITEMS SECTION ===
                     Each row is a product name + amount.
                     The "Add Line" button adds new rows via JavaScript.
                     The X button hides the row and checks a hidden DELETE checkbox. -->

                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="fw-bold text-dark m-0">Items</h5>
                    <button type="button" id="add-item" class="btn btn-sm btn-outline-secondary rounded-pill">
                        <i class="fas fa-plus me-1"></i> Add Line
                    </button>
                </div>

                <!-- Django formset management form — tracks how many item forms exist -->
                {{ items.management_form }}

                <div id="items-container">
                    {% for item_form in items %}
                    <div class="item-row row g-2 align-items-center mb-2">
                        <!-- Hidden ID field (used by Django to track existing items) -->
                        {{ item_form.id }}

                        <!-- Product name (takes most of the row) -->
                        <div class="col-12 col-md-7">
                            {{ item_form.product_name }}
                        </div>

                        <!-- Amount with "R" prefix -->
                        <div class="col-10 col-md-4">
                            <div class="input-group">
                                <span class="input-group-text bg-light border-end-0">R</span>
                                {{ item_form.amount }}
                            </div>
                        </div>

                        <!-- Delete button — hides the row and checks the DELETE checkbox -->
                        <div class="col-2 col-md-1 text-center">
                            {% if items.can_delete %}
                                <div class="form-check d-none">
                                    {{ item_form.DELETE }}
                                </div>
                                <button type="button" class="btn btn-outline-danger btn-sm delete-row rounded-circle" title="Remove">
                                    <i class="fas fa-times"></i>
                                </button>
                            {% endif %}
                        </div>
                    </div>
                    {% endfor %}
                </div>

                <hr class="my-4">

                <!-- === VAT CONFIGURATION + LIVE TOTALS === -->
                <div class="row">
                    <!-- Left: VAT type radio buttons -->
                    <div class="col-md-6 mb-3 mb-md-0">
                        <label class="form-label d-block fw-bold text-secondary mb-2">VAT Configuration (15%)</label>
                        <div class="card bg-light border-0 p-3">
                            {% for radio in form.vat_type %}
                            <div class="form-check mb-2">
                                {{ radio.tag }}
                                <label class="form-check-label" for="{{ radio.id_for_label }}">
                                    {{ radio.choice_label }}
                                </label>
                            </div>
                            {% endfor %}
                        </div>
                    </div>

                    <!-- Right: Live-updating totals panel -->
                    <div class="col-md-6">
                        <label class="form-label d-block fw-bold text-secondary mb-2">Receipt Totals</label>
                        <div class="p-3 rounded" style="background-color: #f8fafc; border: 1px solid #e2e8f0;">
                            <div class="d-flex justify-content-between mb-2">
                                <span class="text-secondary">Subtotal (Excl. VAT):</span>
                                <span class="fw-bold">R <span id="display-subtotal">0.00</span></span>
                            </div>
                            <div class="d-flex justify-content-between mb-2">
                                <span class="text-secondary">VAT (15%):</span>
                                <span class="fw-bold">R <span id="display-vat">0.00</span></span>
                            </div>
                            <div class="d-flex justify-content-between border-top pt-2 mt-2">
                                <span class="h5 mb-0 fw-bold">Total:</span>
                                <span class="h5 mb-0" style="color: var(--accent-color);">
                                    R <span id="display-total">0.00</span>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- === SUBMIT BUTTON === -->
                <div class="text-end mt-4">
                    <button type="submit" class="btn btn-accent btn-lg">
                        <i class="fas fa-paper-plane me-2"></i> Create & Send Receipt
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ==========================================================================
     JAVASCRIPT — Dynamic line items + live VAT calculation
     ========================================================================== -->
<script>
(function() {
    'use strict';

    // --- DOM REFERENCES ---
    var itemsContainer = document.getElementById('items-container');
    var addItemBtn = document.getElementById('add-item');
    var totalForms = document.querySelector('#id_line_items-TOTAL_FORMS');
    var displaySubtotal = document.getElementById('display-subtotal');
    var displayVat = document.getElementById('display-vat');
    var displayTotal = document.getElementById('display-total');

    // All VAT radio buttons — we listen for changes on these
    var vatRadios = document.querySelectorAll('input[name="vat_type"]');

    // === ADD NEW LINE ITEM ROW ===
    // When "Add Line" is clicked, build a new blank row using DOM methods.
    // We increment TOTAL_FORMS so Django knows there's an extra form.
    addItemBtn.addEventListener('click', function() {
        var formIdx = parseInt(totalForms.value);

        // Create the row container
        var row = document.createElement('div');
        row.className = 'item-row row g-2 align-items-center mb-2';

        // Hidden ID input (required by Django formset)
        var hiddenId = document.createElement('input');
        hiddenId.type = 'hidden';
        hiddenId.name = 'line_items-' + formIdx + '-id';
        hiddenId.id = 'id_line_items-' + formIdx + '-id';
        row.appendChild(hiddenId);

        // Product name column
        var prodCol = document.createElement('div');
        prodCol.className = 'col-12 col-md-7';
        var prodInput = document.createElement('input');
        prodInput.type = 'text';
        prodInput.name = 'line_items-' + formIdx + '-product_name';
        prodInput.className = 'form-control';
        prodInput.placeholder = 'Item Name';
        prodInput.id = 'id_line_items-' + formIdx + '-product_name';
        prodCol.appendChild(prodInput);
        row.appendChild(prodCol);

        // Amount column with "R" prefix
        var amtCol = document.createElement('div');
        amtCol.className = 'col-10 col-md-4';
        var inputGroup = document.createElement('div');
        inputGroup.className = 'input-group';
        var prefix = document.createElement('span');
        prefix.className = 'input-group-text bg-light border-end-0';
        prefix.textContent = 'R';
        var amtInput = document.createElement('input');
        amtInput.type = 'number';
        amtInput.name = 'line_items-' + formIdx + '-amount';
        amtInput.className = 'form-control item-amount';
        amtInput.step = '0.01';
        amtInput.placeholder = '0.00';
        amtInput.id = 'id_line_items-' + formIdx + '-amount';
        inputGroup.appendChild(prefix);
        inputGroup.appendChild(amtInput);
        amtCol.appendChild(inputGroup);
        row.appendChild(amtCol);

        // Delete button column
        var delCol = document.createElement('div');
        delCol.className = 'col-2 col-md-1 text-center';
        var delBtn = document.createElement('button');
        delBtn.type = 'button';
        delBtn.className = 'btn btn-outline-danger btn-sm delete-row rounded-circle';
        delBtn.title = 'Remove';
        var delIcon = document.createElement('i');
        delIcon.className = 'fas fa-times';
        delBtn.appendChild(delIcon);
        delCol.appendChild(delBtn);
        row.appendChild(delCol);

        // Add to DOM and update form count
        itemsContainer.appendChild(row);
        totalForms.value = formIdx + 1;

        // Recalculate totals
        updateCalculations();
    });

    // === DELETE LINE ITEM ROW ===
    // Uses event delegation — listens on the container for any delete button click.
    // If the row has a DELETE checkbox (existing saved item), checks it and hides the row.
    // If the row is brand new (no DELETE checkbox), just removes it from the DOM.
    itemsContainer.addEventListener('click', function(e) {
        var deleteBtn = e.target.closest('.delete-row');
        if (!deleteBtn) return;

        var row = deleteBtn.closest('.item-row');
        var deleteCheckbox = row.querySelector('input[name$="-DELETE"]');

        if (deleteCheckbox) {
            // Existing item — check DELETE and hide (Django will delete on save)
            deleteCheckbox.checked = true;
            row.classList.add('d-none', 'deleted');
        } else {
            // New item — just remove from DOM
            row.remove();
        }

        updateCalculations();
    });

    // === LIVE AMOUNT INPUT CHANGES ===
    // Recalculate whenever an amount field changes
    itemsContainer.addEventListener('input', function(e) {
        if (e.target.classList.contains('item-amount')) {
            updateCalculations();
        }
    });

    // === VAT TYPE RADIO CHANGES ===
    vatRadios.forEach(function(radio) {
        radio.addEventListener('change', updateCalculations);
    });

    // === VAT CALCULATION LOGIC ===
    // Mirrors the backend Python calculation exactly.
    // Three modes: Included (reverse 15%), Excluded (add 15%), None (no VAT).
    function updateCalculations() {
        // Sum all visible (non-deleted) item amounts
        var sum = 0;
        var amounts = document.querySelectorAll('.item-row:not(.deleted) .item-amount');
        amounts.forEach(function(input) {
            var val = parseFloat(input.value) || 0;
            sum += val;
        });

        // Find which VAT radio is selected
        var vatType = 'None';
        vatRadios.forEach(function(r) {
            if (r.checked) vatType = r.value;
        });

        var subtotal = 0;
        var vat = 0;
        var total = 0;

        if (vatType === 'Included') {
            // Entered amounts include VAT — reverse it out
            total = sum;
            subtotal = total / 1.15;
            vat = total - subtotal;
        } else if (vatType === 'Excluded') {
            // Entered amounts are pre-VAT — add 15% on top
            subtotal = sum;
            vat = subtotal * 0.15;
            total = subtotal + vat;
        } else {
            // No VAT
            subtotal = sum;
            vat = 0;
            total = sum;
        }

        // Update the display using textContent (safe, no HTML injection)
        displaySubtotal.textContent = subtotal.toFixed(2);
        displayVat.textContent = vat.toFixed(2);
        displayTotal.textContent = total.toFixed(2);
    }

    // Run once on page load (in case form has pre-filled values)
    updateCalculations();

})();
</script>
{% endblock %}
