<?php

/** @var yii\web\View $this */
/** @var common\forms\InvoiceForm $form */
/** @var common\models\Customer[] $customers */

use yii\bootstrap5\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;

$this->title = 'New Invoice';
?>

<form id="invoice-form" method="POST" action="<?= Url::to(['/invoice/create']) ?>">
    <?= Html::hiddenInput(Yii::$app->request->csrfParam, Yii::$app->request->csrfToken) ?>

    <div class="row g-3">
        <!-- Left -->
        <div class="col-lg-4">
            <div class="card">
                <div class="card-header bg-white fw-semibold">Invoice Details</div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Customer <span class="text-danger">*</span></label>
                        <select name="InvoiceForm[customer_id]" class="form-select" required>
                            <option value="">— Select Customer —</option>
                            <?php foreach ($customers as $c): ?>
                                <option value="<?= $c->id ?>"><?= Html::encode($c->name) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Invoice Date</label>
                        <input type="date" name="InvoiceForm[invoice_date]" class="form-control"
                               value="<?= date('Y-m-d') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Due Date</label>
                        <input type="date" name="InvoiceForm[due_date]" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">GST Rate (%)</label>
                        <input type="number" name="InvoiceForm[gst_rate]" class="form-control"
                               value="18" min="0" max="100" step="0.1" oninput="recalcTotal()">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Discount (₹)</label>
                        <input type="number" name="InvoiceForm[discount_amount]" class="form-control"
                               value="0" min="0" oninput="recalcTotal()">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Notes</label>
                        <textarea name="InvoiceForm[notes]" class="form-control" rows="2"></textarea>
                    </div>
                </div>
            </div>
        </div>

        <!-- Right: Line Items -->
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <span class="fw-semibold">Line Items</span>
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="addItem()">
                        <i class="bi bi-plus-lg"></i> Add Item
                    </button>
                </div>
                <div class="card-body">
                    <table class="table table-sm" id="items-table">
                        <thead>
                            <tr>
                                <th>Description</th>
                                <th style="width:90px">Qty</th>
                                <th style="width:120px">Unit Price (₹)</th>
                                <th style="width:120px" class="text-end">Total</th>
                                <th style="width:40px"></th>
                            </tr>
                        </thead>
                        <tbody id="items-body"></tbody>
                    </table>
                </div>
                <div class="card-footer bg-white">
                    <div class="row justify-content-end">
                        <div class="col-md-5">
                            <table class="table table-sm small mb-0">
                                <tr><td class="text-muted">Subtotal</td><td class="text-end" id="s-subtotal">₹0.00</td></tr>
                                <tr><td class="text-muted">GST</td><td class="text-end" id="s-gst">₹0.00</td></tr>
                                <tr><td class="text-muted">Discount</td><td class="text-end text-danger" id="s-discount">−₹0.00</td></tr>
                                <tr class="fw-bold border-top"><td>Total</td><td class="text-end fs-5" id="s-total">₹0.00</td></tr>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="d-flex gap-2 mt-3">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-check-lg"></i> Create Invoice
                </button>
                <a href="<?= Url::to(['/invoice/index']) ?>" class="btn btn-outline-secondary">Cancel</a>
            </div>
        </div>
    </div>
</form>

<script>
let itemIdx = 0;

function addItem(desc = '', qty = 1, price = 0) {
    const idx = itemIdx++;
    const tbody = document.getElementById('items-body');
    const tr = document.createElement('tr');
    tr.id = `item-row-${idx}`;
    tr.innerHTML = `
        <td><input type="text" name="items[${idx}][description]" class="form-control form-control-sm"
             value="${desc}" placeholder="Service/Plan description" required></td>
        <td><input type="number" name="items[${idx}][quantity]" id="qty-${idx}" class="form-control form-control-sm"
             value="${qty}" min="0.01" step="0.01" oninput="updateRow(${idx})"></td>
        <td><input type="number" name="items[${idx}][unit_price]" id="price-${idx}" class="form-control form-control-sm"
             value="${price}" min="0" step="0.01" oninput="updateRow(${idx})"></td>
        <td class="text-end" id="row-total-${idx}">₹0.00</td>
        <td><button type="button" class="btn btn-sm btn-outline-danger" onclick="removeItem(${idx})">
            <i class="bi bi-trash"></i></button></td>
    `;
    tbody.appendChild(tr);
    updateRow(idx);
}

function updateRow(idx) {
    const qty   = parseFloat(document.getElementById(`qty-${idx}`)?.value || 0);
    const price = parseFloat(document.getElementById(`price-${idx}`)?.value || 0);
    const total = qty * price;
    const el = document.getElementById(`row-total-${idx}`);
    if (el) el.textContent = '₹' + total.toFixed(2);
    recalcTotal();
}

function removeItem(idx) {
    document.getElementById(`item-row-${idx}`)?.remove();
    recalcTotal();
}

function recalcTotal() {
    let subtotal = 0;
    document.querySelectorAll('[id^="row-total-"]').forEach(el => {
        subtotal += parseFloat(el.textContent.replace('₹','')) || 0;
    });
    const gstRate = parseFloat(document.querySelector('[name="InvoiceForm[gst_rate]"]')?.value || 0);
    const discount= parseFloat(document.querySelector('[name="InvoiceForm[discount_amount]"]')?.value || 0);
    const gst     = subtotal * gstRate / 100;
    const total   = subtotal + gst - discount;

    document.getElementById('s-subtotal').textContent = '₹' + subtotal.toFixed(2);
    document.getElementById('s-gst').textContent      = '₹' + gst.toFixed(2);
    document.getElementById('s-discount').textContent = '−₹' + discount.toFixed(2);
    document.getElementById('s-total').textContent    = '₹' + total.toFixed(2);
}

// Add default row on load
addItem('Nutrition Plan / Consultation', 1, 0);
</script>
