@php
    $fields = [
        'stock_item' => [
            'label' => 'Stock Item',
            'type' => 'text',
            'class' => 'material-code form-control',
        ],
        'description' => [
            'label' => 'Description',
            'type' => 'textarea',
            'class' => 'description form-control',
        ],
        'quantity' => [
            'label' => 'Quantity',
            'type' => 'number',
            'class' => 'quantity form-control',
        ],
        'uom' => [
            'label' => 'UOM',
            'type' => 'text',
            'class' => 'uom form-control',
        ],
        'supply_lead_time' => [
            'label' => 'Supply Lead Time',
            'type' => 'text',
            'class' => 'Supply Lead Time form-control',
        ],
        'unit_rate' => [
            'label' => 'Unit Rate (INR)',
            'type' => 'number',
            'class' => 'rate form-control',
        ],
        'tds' => [
            'label' => 'TDS (%)',
            'type' => 'number',
            'class' => 'tds form-control',
        ],
        'discount' => [
            'label' => 'Discount (%)',
            'type' => 'number',
            'class' => 'discount form-control',
        ],
        'value' => [
            'label' => 'Value (INR)',
            'type' => 'number',
            'class' => 'value form-control',
            'readonly' => true,
        ],
        'sgst' => [
            'label' => 'SGST (%)',
            'type' => 'number',
            'class' => 'sgst form-control',
            'step' => '0.01',
        ],
        'cgst' => [
            'label' => 'CGST (%)',
            'type' => 'number',
            'class' => 'cgst form-control',
            'step' => '0.01',
        ],
        'igst' => [
            'label' => 'IGST (%)',
            'type' => 'number',
            'class' => 'igst form-control',
            'step' => '0.01',
        ],
        'amount' => [
            'label' => 'Amount (INR)',
            'type' => 'number',
            'class' => 'amount form-control',
            'readonly' => true,
        ],
    ];
@endphp
<div class="pqo-list">
    <div class="table-responsive">
        <table id="pqoItems" class="table table-bordered poq-items-table w-100">
            <thead>
                <tr>
                    <th>Sl No.</th>
                    @foreach ($fields as $key => $field)
                        <th class="th-{{ $key }}">
                            {{ $field['label'] }}
                            @if (isset($field['required']) && $field['required'])
                                <span class="required" title="required">*</span>
                            @endif
                        </th>
                    @endforeach
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <tr data-row="0" >
                    <td>1</td>
                    @foreach ($fields as $key => $field)
                        <td class="{{ $key }}">
                            @if ($field['type'] === 'textarea')
                                <textarea rows="1"></textarea>
                            @else
                                <input 
                                    type="{{ $field['type'] }}"
                                    {{ isset($field['readonly']) && $field['readonly'] ? 'readonly' : '' }}
                                    step="{{ isset($field['step']) ? $field['step'] : '' }}"
                                />
                            @endif
                        </td>
                    @endforeach
                    <td>
                        <button type="button" class="btn btn-danger" onclick="deleteRow(this)">
                            <i class="fa fa-trash"></i>
                        </button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

    <div class="row mt-3">
        <div class="col-md-2">
            <button type="button" class="btn btn-primary" id="addRowBtn">Add Row</button>
        </div>
    </div>

    <!-- Totals -->
    <div class="row total-fields">
        <div class="col-md-6">
            <label for="GT-in-letters">Indian Rupees</label>
            <input type="text" id="GT-in-letters" class="form-control" readonly>
        </div>
        <div class="col-md-6">
            <div class="totals">
                <div class="row">
                    <div class="col-md-3">
                        <label for="totalAmount">SUB TOTAL</label>
                    </div>
                    <div class="col-md-9">
                        <input type="text" name="sub_total" id="totalAmount" class="form-control" readonly>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-3">
                        <label for="qt-discount">Discount (%)</label>
                    </div>
                    <div class="col-md-9">
                        <input type="number" id="qt-discount" name="discount" class="form-control" >
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-3">
                        <label for="roundUp">RoundUp Amount</label>
                    </div>
                    <div class="col-md-9">
                        <input type="text" id="roundUp" name="round_up" class="form-control" readonly>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-3">
                        <label for="grandTotal">Grand Total</label>
                    </div>
                    <div class="col-md-9">
                        <input type="text" id="grandTotal" name="grand_total" class="form-control" readonly>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {

        const pqoItemsTableInstance = $('#pqoItems').DataTable({
            responsive: true,
            autoWidth: false,
            destroy: true,
        });

        function deleteRow(button) {
            pqoItemsTableInstance.row($(button).parents('tr')).remove().draw();
            calculateTotals(button);
        }

        calculateTotals = (item) => {
            console.log('Calculating totals...', item);
            let totalAmount = 0;
            let totalSGST = 0;
            let totalCGST = 0;
            let totalIGST = 0;

            $("#pqoItems tbody tr").each(function() {
                const quantity = parseFloat($(this).find('.quantity').find('input').val()) || 0;
                const rate = parseFloat($(this).find('.unit_rate').find('input').val()) || 0;
                const tds = parseFloat($(this).find('.tds').find('input').val()) || 0;
                const discount = parseFloat($(this).find('.discount').find('input').val()) || 0;
                const sgst = parseFloat($(this).find('.sgst').find('input').val()) || 0;
                const cgst = parseFloat($(this).find('.cgst').find('input').val()) || 0;
                const igst = parseFloat($(this).find('.igst').find('input').val()) || 0;

                const value = (quantity * rate) - ((quantity * rate) * (tds / 100)) - ((quantity * rate) * (discount / 100));
                $(this).find('.value').find('input').val(value.toFixed(2));

                const amount = value + ((value * sgst / 100) + (value * cgst / 100) + (value * igst / 100));
                $(this).find('.amount').find('input').val(amount.toFixed(2));

                totalAmount += value;
                totalSGST += (value * sgst / 100);
                totalCGST += (value * cgst / 100);
                totalIGST += (value * igst / 100);
            });

            $('#totalAmount').val(totalAmount.toFixed(2));
            $('#grandTotal').val((totalAmount + totalSGST + totalCGST + totalIGST).toFixed(2));
        };

        document.querySelector('.pqo-list #addRowBtn').addEventListener('click', function() {
            const newRow = pqoItemsTableInstance.row.add([
                pqoItemsTableInstance.rows().count() + 1, // Sl No.
                '<input type="text" class="material-code form-control">',
                '<textarea rows="1" class="description form-control"></textarea>',
                '<input type="number" class="quantity form-control">',
                '<input type="text" class="uom form-control">',
                '<input type="text" class="Supply Lead Time form-control">',
                '<input type="number" class="rate form-control">',
                '<input type="number" class="tds form-control">',
                '<input type="number" class="discount form-control">',
                '<input type="number" class="value form-control" readonly>',
                '<input type="number" class="sgst form-control">',
                '<input type="number" class="cgst form-control">',
                '<input type="number" class="igst form-control">',
                '<input type="number" class="amount form-control" readonly>',
                '<button type="button" class="btn btn-danger" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button>'
            ]).draw().node();
            console.log('New row added:', newRow);
            $(newRow).find('input, textarea').on('input', function() {
                calculateTotals(this);
            });
        });

        $('#pqoItems').find('input, textarea').on('input', function() {
            calculateTotals(this);
        });

    });
</script>
