<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

session_start();
require_once("../config/config.php");

// Function to get next available SKU
function getNextSKU(mysqli $conn): string {
    $sql = "SELECT sku FROM inventory_master ORDER BY id DESC LIMIT 1";
    $res = $conn->query($sql);
    $next = 1;
    if ($res && $row = $res->fetch_assoc()) {
        $lastNumber = (int) substr($row['sku'], 3);
        $next = $lastNumber + 1;
    }
    return sprintf("IN-%03d", $next);
}

$success = "";
$error = "";

// Fetch master data
$vendors = $conn->query("SELECT id, vendor_name FROM vendor_master ORDER BY vendor_name ASC")->fetch_all(MYSQLI_ASSOC);
$warehouses = $conn->query("SELECT id, warehouse_name, location FROM warehouse_master WHERE status = 'Active' ORDER BY warehouse_name ASC")->fetch_all(MYSQLI_ASSOC);
$projects = $conn->query("SELECT id, project_name FROM project_master ORDER BY project_name ASC")->fetch_all(MYSQLI_ASSOC);
$categories = $conn->query("SELECT id, category AS category_name FROM category_tbl ORDER BY category ASC")->fetch_all(MYSQLI_ASSOC);
$uoms = $conn->query("SELECT id, uom_name FROM uom_tbl ORDER BY uom_name ASC")->fetch_all(MYSQLI_ASSOC);

$nextSKU = getNextSKU($conn);

// ====================== AJAX: Add Category / UOM ======================
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    $response = ['success' => false, 'message' => ''];

    $name = trim($_POST['name'] ?? '');
    if ($name) {
        if ($_POST['action'] === 'add_category') {
            $stmt = $conn->prepare("INSERT INTO category_tbl (category) VALUES (?)");
            $stmt->bind_param("s", $name);
            if ($stmt->execute()) {
                $response = ['success' => true, 'id' => $conn->insert_id, 'name' => $name];
            }
        }
        if ($_POST['action'] === 'add_uom') {
            $stmt = $conn->prepare("INSERT INTO uom_tbl (uom_name) VALUES (?)");
            $stmt->bind_param("s", $name);
            if ($stmt->execute()) {
                $response = ['success' => true, 'id' => $conn->insert_id, 'name' => $name];
            }
        }
    }
    echo json_encode($response);
    exit;
}

// ====================== FORM SUBMISSION ======================
if ($_SERVER["REQUEST_METHOD"] === "POST" && !isset($_POST['action'])) {
    $warehouse_id = (int)($_POST['warehouse_id'] ?? 0);
    $project_id   = (int)($_POST['project_id'] ?? 0);
    $invoice_id   = trim($_POST['invoice_id'] ?? '');
    $items        = $_POST['items'] ?? [];

    if ($warehouse_id <= 0 || $project_id <= 0) {
        $error = "Please select warehouse and project.";
    } elseif (empty($items)) {
        $error = "Please add at least one material.";
    } else {
        mysqli_begin_transaction($conn);

        try {
            $stmt = $conn->prepare("INSERT INTO purchase_entries (warehouse_id, project_id, invoice_id) VALUES (?, ?, ?)");
            $stmt->bind_param("iis", $warehouse_id, $project_id, $invoice_id);
            $stmt->execute();
            $purchase_id = $conn->insert_id;

            $basic_total = 0;
            $discount_total = 0;

            $item_stmt = $conn->prepare("INSERT INTO purchase_entry_items 
                (purchase_entry_id, serial_no, sku, name, model_no, hsn_sac, category, supplier_vendor, uom, 
                 quantity, rate, amount, discount, cgst, sgst, igst, description) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

            foreach ($items as $item) {
                $serial_no     = (int)($item['serial_no'] ?? 0);
                $name          = trim($item['name'] ?? '');
                $model_no      = trim($item['model_no'] ?? '');
                $hsn_sac       = trim($item['hsn_sac'] ?? '');
                $category      = trim($item['category'] ?? '');
                $supplier_vendor = (int)($item['supplier_vendor'] ?? 0);
                $uom           = trim($item['uom'] ?? '');
                $quantity      = floatval($item['quantity'] ?? 0);
                $rate          = floatval($item['rate'] ?? 0);
                $discount      = floatval($item['discount'] ?? 0);
                $amount        = floatval($item['amount'] ?? ($quantity * $rate));
                $cgst          = floatval($item['cgst'] ?? 0);
                $sgst          = floatval($item['sgst'] ?? 0);
                $igst          = floatval($item['igst'] ?? 0);
                $description   = trim($item['description'] ?? '');

                if (empty($name) || $quantity <= 0) continue;

                $sku = trim($item['sku'] ?? '');

                // Auto create new material if not exists
                if (!empty($name)) {
                    $check = $conn->prepare("SELECT sku FROM inventory_master WHERE name = ? LIMIT 1");
                    $check->bind_param("s", $name);
                    $check->execute();
                    $result = $check->get_result();

                    if ($result->num_rows === 0) {
                        $new_sku = getNextSKU($conn);
                        $insert_inv = $conn->prepare("INSERT INTO inventory_master 
                            (sku, name, description, hsn_sac, category, warehouse_id, model_no, 
                             supplier_vendor, uom, current_stock, reorder_level) 
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)");
                        $insert_inv->bind_param("sssssissss", 
                            $new_sku, $name, $description, $hsn_sac, $category, $warehouse_id, 
                            $model_no, $supplier_vendor, $uom, $quantity
                        );
                        $insert_inv->execute();
                        $sku = $new_sku;
                    } else {
                        $existing = $result->fetch_assoc();
                        $sku = $existing['sku'];
                        $update_stock = $conn->prepare("UPDATE inventory_master SET current_stock = current_stock + ? WHERE sku = ?");
                        $update_stock->bind_param("ds", $quantity, $sku);
                        $update_stock->execute();
                    }
                }

                $item_stmt->bind_param("iisssssssdddddddd", 
                    $purchase_id, $serial_no, $sku, $name, $model_no, $hsn_sac, $category, 
                    $supplier_vendor, $uom, $quantity, $rate, $amount, $discount, 
                    $cgst, $sgst, $igst, $description
                );
                $item_stmt->execute();

                $basic_total += $amount;
                $discount_total += $discount;
            }

            $taxable_amount = $basic_total - $discount_total;
            $gst_total = $taxable_amount * 0.18;
            $grand_total = $taxable_amount + $gst_total;

            $update_header = $conn->prepare("UPDATE purchase_entries SET total_basic = ?, total_discount = ?, total_gst = ?, grand_total = ? WHERE id = ?");
            $update_header->bind_param("ddddi", $basic_total, $discount_total, $gst_total, $grand_total, $purchase_id);
            $update_header->execute();

            mysqli_commit($conn);
            $success = "Purchase saved successfully! Inventory updated.";

        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error = "Error: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Purchase Entry</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
    :root {
        --primary: #a855f7;
        --glass: rgba(255, 255, 255, 0.10);
        --glass-border: rgba(255, 255, 255, 0.20);
    }

    * { margin: 0; padding: 0; box-sizing: border-box; }

    body {
        font-family: 'Inter', system-ui, sans-serif;
        min-height: 100vh;
        background: linear-gradient(135deg, rgba(0,0,0,0.78), rgba(0,0,0,0.92)), url('../background.jpeg') center/cover no-repeat fixed;
        color: #f8fafc;
        padding: 20px;
    }

    .glass-container {
        max-width: 1350px;
        margin: 0 auto;
        background: var(--glass);
        backdrop-filter: blur(24px);
        border-radius: 32px;
        border: 1px solid var(--glass-border);
        box-shadow: 0 30px 80px rgba(0,0,0,0.7);
        overflow: hidden;
    }

    .header {
        background: linear-gradient(90deg, rgba(168,85,247,0.35), rgba(147,51,234,0.25));
        padding: 50px 40px;
        text-align: center;
    }

    .header h1 {
        font-size: clamp(32px, 5.5vw, 46px);
        font-weight: 700;
    }

    .form-area { padding: 45px 40px; }

    .section, .item-row {
        background: rgba(255,255,255,0.07);
        border: 1px solid rgba(255,255,255,0.2);
        border-radius: 20px;
        padding: 28px;
        margin-bottom: 25px;
        position: relative;
    }

    .remove-btn {
        position: absolute;
        top: 18px;
        right: 18px;
        background: rgba(239,68,68,0.5);
        color: white;
        border: none;
        width: 38px;
        height: 38px;
        border-radius: 50%;
        font-size: 24px;
        cursor: pointer;
    }

    .form-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
        gap: 18px;
    }

    label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
    }

    .required { color: #f87171; }

    input, select, textarea {
        width: 100%;
        padding: 13px 16px;
        background: rgba(255,255,255,0.09);
        border: 1px solid rgba(255,255,255,0.25);
        border-radius: 12px;
        color: white;
        font-size: 15px;
    }

    input:focus, select:focus {
        border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(168,85,247,0.25);
    }

    option{
        background: #1f2937;
        border: 1px solid #a855f7;
    }
    .add-option-btn {
        margin-top: 6px;
        font-size: 13px;
        color: #a855f7;
        cursor: pointer;
    }

    .add-row-btn, .submit-btn {
        width: 100%;
        padding: 18px;
        border-radius: 16px;
        font-weight: 700;
        font-size: 17px;
        cursor: pointer;
        margin: 25px 0;
    }

    .add-row-btn {
        background: rgba(255,255,255,0.06);
        border: 2px dashed #c084fc;
        color: white;
    }

    .submit-btn {
        background: linear-gradient(135deg, var(--primary), #c084fc);
        color: white;
        border: none;
    }

    .totals-box {
        background: linear-gradient(135deg, rgba(168,85,247,0.15), rgba(192,132,252,0.12));
        border: 1px solid #c084fc;
        border-radius: 20px;
        padding: 25px;
        margin: 30px 0;
    }

    .total-row {
        display: flex;
        justify-content: space-between;
        padding: 12px 0;
        font-size: 1.1rem;
        border-bottom: 1px solid rgba(255,255,255,0.15);
    }

    .total-row:last-child {
        border: none;
        font-size: 1.5rem;
        font-weight: 700;
        color: #ddd6fe;
    }

    .message {
        padding: 16px 24px;
        border-radius: 16px;
        margin-bottom: 25px;
        font-weight: 600;
    }

    .success { background: rgba(34,197,94,0.25); border: 1px solid #4ade80; color: #86efac; }
    .error   { background: rgba(239,68,68,0.25); border: 1px solid #f87171; color: #fca5a5; }

    .suggestions {
        position: absolute;
        z-index: 1000;
        background: #1f2937;
        border: 1px solid #a855f7;
        border-radius: 12px;
        max-height: 280px;
        overflow-y: auto;
        width: 100%;
        margin-top: 4px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.6);
    }

    .suggestion-item {
        padding: 12px 16px;
        cursor: pointer;
        border-bottom: 1px solid rgba(255,255,255,0.1);
    }

    .suggestion-item:hover {
        background: rgba(168,85,247,0.3);
    }
    </style>
</head>

<body>
    <?php include '../config/header.php'; ?>
    <div class="glass-container">
        <div class="header">
            <h1><i class="fas fa-cart-plus"></i> Add Purchase Entry</h1>
            <p>Record new purchase with live inventory sync & discount support</p>
        </div>

        <div class="form-area">
            <?php if ($success): ?><div class="message success"><?= $success ?></div><?php endif; ?>
            <?php if ($error): ?><div class="message error"><?= htmlspecialchars($error) ?></div><?php endif; ?>

            <form action="" method="POST" id="purchaseForm">
                <div class="section">
                    <div class="form-grid">
                        <div>
                            <label>Warehouse 
                                <!-- <span class="required">*</span> -->
                            </label>
                            <select name="warehouse_id">
                                <option value="">-- Select Warehouse --</option>
                                <?php foreach ($warehouses as $w): ?>
                                <option value="<?= $w['id'] ?>"><?= htmlspecialchars($w['warehouse_name']) ?> — <?= htmlspecialchars($w['location']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label>Project 
                                <!-- <span class="required">*</span> -->
                            </label>
                            <select name="project_id">
                                <option value="">-- Select Project --</option>
                                <?php foreach ($projects as $p): ?>
                                <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['project_name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label>Invoice Number</label>
                            <input type="text" name="invoice_id" placeholder="INV-XXXXXX">
                        </div>
                    </div>
                </div>

                <div class="items-container" id="itemsContainer"></div>

                <div class="add-row-btn" onclick="addNewRow()">
                    <i class="fas fa-plus-circle"></i> Add Another Material
                </div>

                <div class="totals-box" id="totalsBox">
                    <div class="total-row"><span>Basic Total:</span> <span id="basicTotal">₹ 0.00</span></div>
                    <div class="total-row"><span>Total Discount:</span> <span id="discountTotal">₹ 0.00</span></div>
                    <div class="total-row"><span>Taxable Amount:</span> <span id="taxableTotal">₹ 0.00</span></div>
                    <div class="total-row"><span>GST (18%):</span> <span id="gstTotal">₹ 0.00</span></div>
                    <div class="total-row"><span><strong>Grand Total:</strong></span> <span id="grandTotal">₹ 0.00</span></div>
                </div>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-save"></i> Save Purchase & Update Stock
                </button>
            </form>
        </div>
    </div>

    <!-- Modal -->
    <div id="addModal" class="modal" style="display:none;position:fixed;z-index:2000;left:0;top:0;width:100%;height:100%;background:rgba(0,0,0,0.8);align-items:center;justify-content:center;">
        <div style="background:#1f2937;color:white;padding:32px;border-radius:20px;width:90%;max-width:440px;">
            <div id="modalTitle" style="margin-bottom:20px;font-size:18px;font-weight:600;">Add New</div>
            <input type="text" id="modalName" placeholder="Enter Name" style="width:100%;padding:14px;border-radius:12px;background:#374151;border:none;color:white;margin-bottom:25px;">
            <div style="display:flex;gap:12px;">
                <button onclick="closeModal()" style="flex:1;padding:14px;background:#4b5563;color:white;border:none;border-radius:12px;">Cancel</button>
                <button onclick="saveModal()" style="flex:1;padding:14px;background:#a855f7;color:white;border:none;border-radius:12px;">Save</button>
            </div>
        </div>
    </div>

    <script>
    let rowCount = 0;
    let baseSKU = <?= json_encode($nextSKU) ?>;

    const vendors = <?= json_encode($vendors) ?>;
    const categories = <?= json_encode($categories) ?>;
    const uomsList = <?= json_encode($uoms) ?>;

    let currentType = '', currentRow = null;

    function generateSKU(index) {
        return "IN-" + String(parseInt(baseSKU.substring(3)) + index).padStart(3, '0');
    }

    function escapeHtml(str) {
        return str ? str.replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[m]) : '';
    }

    function searchMaterial(input) {
        const query = input.value.trim();
        const row = input.closest('.item-row');
        let dropdown = row.querySelector('.suggestions') || createDropdown(row, input);

        if (query.length < 2) {
            if (dropdown) dropdown.style.display = 'none';
            return;
        }

        fetch(`search_material.php?name=${encodeURIComponent(query)}`)
            .then(r => r.json())
            .then(data => {
                dropdown.innerHTML = '';
                if (data.length === 0) {
                    dropdown.innerHTML = `<div class="suggestion-item" style="color:#888;">No matching material. Will create new.</div>`;
                } else {
                    data.forEach(item => {
                        const div = document.createElement('div');
                        div.className = 'suggestion-item';
                        div.textContent = item.name + ' (' + (item.sku || 'New') + ')';
                        div.onclick = () => selectMaterial(row, item);
                        dropdown.appendChild(div);
                    });
                }
                dropdown.style.display = 'block';
            });
    }

    function createDropdown(row, input) {
        const div = document.createElement('div');
        div.className = 'suggestions';
        input.parentElement.style.position = 'relative';
        input.parentElement.appendChild(div);
        return div;
    }

    function selectMaterial(row, material) {
        row.querySelector('[name*="name"]').value = material.name || '';
        row.querySelector('[name*="sku"]').value = material.sku || generateSKU(rowCount - 1);
        row.querySelector('[name*="hsn_sac"]').value = material.hsn_sac || '';
        row.querySelector('[name*="category"]').value = material.category || '';
        row.querySelector('[name*="uom"]').value = material.uom || '';
        row.querySelector('[name*="model_no"]').value = material.model_no || '';
        row.querySelector('[name*="description"]').value = material.description || '';

        const dropdown = row.querySelector('.suggestions');
        if (dropdown) dropdown.style.display = 'none';

        calculateRow(row.querySelector('[name*="quantity"]'));
    }

    function addNewRow() {
        rowCount++;

        let vendorOptions = '<option value="">-- Choose Vendor --</option>';
        vendors.forEach(v => vendorOptions += `<option value="${v.id}">${escapeHtml(v.vendor_name)}</option>`);

        let catOptions = '<option value="">Select Category</option>';
        categories.forEach(c => catOptions += `<option value="${c.id}">${escapeHtml(c.category_name)}</option>`);

        let uomOptions = '<option value="">Select UOM</option>';
        uomsList.forEach(u => uomOptions += `<option value="${u.id}">${escapeHtml(u.uom_name)}</option>`);

        const html = `
            <div class="item-row" id="row-${rowCount}">
                <button type="button" class="remove-btn" onclick="removeRow(${rowCount})">×</button>
                <div class="form-grid">
                    <div><label>Sr. No</label><input type="text" name="items[${rowCount}][sr_no]" value="${rowCount}" readonly></div>
                    <div><label>Serial No</label><input type="text" name="items[${rowCount}][serial_no]"></div>
                    <div><label>Category</label><select name="items[${rowCount}][category]" class="category-select">${catOptions}</select>
                        <div class="add-option-btn" onclick="openAddModal(this, 'category')">+ Add new category</div>
                    </div>                    
                    <div style="position:relative;">
                        <label>Material Name</label>
                        <input type="text" name="items[${rowCount}][name]" required placeholder="Search or type new material..." onkeyup="searchMaterial(this)">
                    </div>

                    <div><label>SKU</label><input type="text" name="items[${rowCount}][sku]" readonly></div>
                    <div><label>Model No</label><input type="text" name="items[${rowCount}][model_no]"></div>
                    <div><label>HSN/SAC</label><input type="text" name="items[${rowCount}][hsn_sac]"></div>

                    

                    <div><label>Supplier / Vendor</label><select name="items[${rowCount}][supplier_vendor]">${vendorOptions}</select></div>

                    <div><label>UOM</label><select name="items[${rowCount}][uom]" class="uom-select">${uomOptions}</select>
                        <div class="add-option-btn" onclick="openAddModal(this, 'uom')">+ Add new UOM</div>
                    </div>

                    <div><label>Quantity</label><input type="number" step="0.001" name="items[${rowCount}][quantity]" min="0" oninput="calculateRow(this)"></div>
                    <div><label>Rate (₹)</label><input type="number" step="0.01" name="items[${rowCount}][rate]" oninput="calculateRow(this)"></div>
                    <div><label>Discount (₹)</label><input type="number" step="0.01" name="items[${rowCount}][discount]" value="0" oninput="calculateRow(this)"></div>
                    <div><label>Amount (₹)</label><input type="number" step="0.01" name="items[${rowCount}][amount]" readonly></div>

                    <div class="full-width" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:18px;">
                        <div><label>CGST (%)</label><input type="number" step="0.01" name="items[${rowCount}][cgst]" value="0" oninput="calculateTotals()"></div>
                        <div><label>SGST (%)</label><input type="number" step="0.01" name="items[${rowCount}][sgst]" value="0" oninput="calculateTotals()"></div>
                        <div><label>IGST (%)</label><input type="number" step="0.01" name="items[${rowCount}][igst]" value="0" oninput="calculateTotals()"></div>
                    </div>

                    <div class="full-width">
                        <label>Description</label>
                        <textarea name="items[${rowCount}][description]" rows="2"></textarea>
                    </div>
                </div>
            </div>
        `;

        document.getElementById('itemsContainer').insertAdjacentHTML('beforeend', html);
        calculateTotals();
    }

    function calculateRow(el) {
        const row = el.closest('.item-row');
        const qty = parseFloat(row.querySelector('[name*="quantity"]').value) || 0;
        const rate = parseFloat(row.querySelector('[name*="rate"]').value) || 0;
        const discount = parseFloat(row.querySelector('[name*="discount"]').value) || 0;

        const amount = (qty * rate) - discount;
        // const amount = (qty * rate);
        row.querySelector('[name*="amount"]').value = amount.toFixed(2);

        calculateTotals();
    }

    function calculateTotals() {

        let basic = 0;
        let discountTotal = 0;

        document.querySelectorAll('.item-row').forEach(row => {
            const qty = parseFloat(row.querySelector('[name*="quantity"]').value) || 0;
            const rate = parseFloat(row.querySelector('[name*="rate"]').value) || 0;
            basic += qty * rate;
            discountTotal += parseFloat(row.querySelector('[name*="discount"]').value) || 0;
            cgst = parseFloat(row.querySelector('[name*="cgst"]').value) || 0;
            sgst = parseFloat(row.querySelector('[name*="sgst"]').value) || 0;
            igst = parseFloat(row.querySelector('[name*="igst"]').value) || 0;
        });

        const taxable = basic - discountTotal;
        // const taxable = basic;
        const gst = basic * (cgst + sgst + igst) / 100;
        const grand = taxable + gst;

        document.getElementById('basicTotal').textContent = `₹ ${basic.toFixed(2)}`;
        document.getElementById('discountTotal').textContent = `₹ ${discountTotal.toFixed(2)}`;
        document.getElementById('taxableTotal').textContent = `₹ ${taxable.toFixed(2)}`;
        document.getElementById('gstTotal').textContent = `₹ ${gst.toFixed(2)}`;
        document.getElementById('grandTotal').textContent = `₹ ${grand.toFixed(2)}`;
    }

    function openAddModal(btn, type) {
        currentRow = btn.closest('.item-row');
        currentType = type;
        document.getElementById('modalTitle').textContent = type === 'category' ? 'Add New Category' : 'Add New UOM';
        document.getElementById('modalName').value = '';
        document.getElementById('addModal').style.display = 'flex';
    }

    function closeModal() {
        document.getElementById('addModal').style.display = 'none';
    }

    function saveModal() {
        const name = document.getElementById('modalName').value.trim();
        if (!name) return alert("Name is required!");

        const action = currentType === 'category' ? 'add_category' : 'add_uom';

        fetch('', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `action=${action}&name=${encodeURIComponent(name)}`
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                const selector = currentType === 'category' ? '.category-select' : '.uom-select';
                document.querySelectorAll(selector).forEach(sel => {
                    const opt = document.createElement('option');
                    opt.value = data.id;
                    opt.textContent = escapeHtml(data.name);
                    sel.appendChild(opt);
                });
                if (currentRow) {
                    const target = currentRow.querySelector(selector);
                    if (target) target.value = data.id;
                }
                closeModal();
            }
        });
    }

    function removeRow(id) {
        document.getElementById(`row-${id}`).remove();
        calculateTotals();
    }

    // Initialize
    window.onload = () => addNewRow();
    </script>
</body>
</html>