<div class="row mb-3">
    <div class="col-sm-11">
        <div class="page-title-box">
            <h2 class="page-title">Update Purchase Order</h2>
        </div>
    </div>
    <div class="col-sm-1 text-right">
        <a href="po_list" class="btn btn-danger">Back</a>
    </div>
</div>
<?= $this->Form->create('User', ['type' => 'file']); ?>
                
<div class="row mb-3">
    <div class="col-sm-12">
        <div class="card">
            <div class="card-body">
                <div class="form-row">
                    <div class="form-group col-md-3">
                        <?= $this->Form->input('po_ids', [
                            'label' => 'PO Id',
                            'class' => 'form-control',
                            'readonly' => true,
                            'value' => $purchase_orders[0]['inventory_purchase_order']['p_o_id']
                        ]); ?>
                    </div>
                    <div class="form-group col-md-3">
                        <?= $this->Form->input('Indent Id', [
                            'class' => 'form-control',
                            'readonly' => true,
                            'value' => $purchase_orders[0]['inventory_purchase_order']['internal_indent_id']
                        ]); ?>
                    </div>
                    <div class="form-group col-md-3">
                        <?= $this->Form->input('Location Name', [
                            'class' => 'form-control',
                            'readonly' => true,
                            'value' => $purchase_orders[0]['inventory_purchase_order']['location_name']
                        ]); ?>
                    </div>
                    <div class="form-group col-md-3">
                        <?= $this->Form->input('Vendor Name', [
                            'class' => 'form-control',
                            'readonly' => true,
                            'value' => $purchase_orders[0]['inventory_purchase_order']['vendor_name']
                        ]); ?>
                    </div>
                    <div class="form-group col-md-3">
                        <?= $this->Form->input('charge', [
                                'div' => ['class' => 'form-group'],
                                'id' => 'charge',
                                'label' => 'Charges',
                                'class' => 'form-control',
                                'required' => true,
                                'type' => 'number',
                                'value' => $purchase_orders[0]['inventory_purchase_order']['charge'],
                                'step' => 'any',
                                'min' => '0'
                            ]); ?>
                    </div>
                    <div class="form-group col-md-3">
                        <label>PO Date</label>
                        <input type="date" id="po_date" name="po_date" class="form-control" value="<?= h($purchase_orders[0]['inventory_purchase_order']['po_date']) ?>"  required>
                    </div>
                        
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-sm-12">
        <div class="card">
            <div class="card-body">
                <?= $this->Form->hidden('indent', ['value' => $vendor_items[0]['i']['indent_id'] ?? '']); ?>
                <?= $this->Form->hidden('p_o_id', ['value' => $purchase_orders[0]['inventory_purchase_order']['p_o_id']]); ?>

                <h5>Items Served by Vendor</h5>
                <div class="table-responsive">
                    <table id="example" class="display table table-hover table-condensed" cellspacing="0" width="100%">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Name</th>
                                <th>Brand</th>
                                <th>Unit</th>
                                <th>Price</th>
                                <th>Tax Percentage</th>
                                <th>Tax Value</th>
                                <th>Quantity</th>
                                <th>Discount Type</th>
                                <th>Discount</th>
                                <th>Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $x = 1; foreach ($vendor_items as $vendor_item):
                                $sku_price = $vendor_item['p']['psku_price'] ?? $vendor_item['p']['vprice'];
                                $sku_quantity = $vendor_item['p']['psku_quantity'] ?? 0;
                                $max_qty = $vendor_item['i']['sku_quantity']-$vendor_item['i']['completed_quantity']+$vendor_item['p']['psku_quantity'];
                                $sku_id = $vendor_item['i']['sku_id'];
                                $disabled = ($vendor_item['i']['is_completed'] == 1) ? 'disabled' : '';
                                
                            ?>
                            
                                <?php
                                
                                    $discount = $vendor_item['p']['psku_discount'] ?? 0;
                                    $discountType = $vendor_item['p']['psku_discount_type'] ?? 'flat';
                                    
                                    $base = $sku_price * $sku_quantity;
                                    
                                    if ($discountType == 'percentage') {
                                        $validDiscount = ($base * $discount) / 100;
                                    } else {
                                        $validDiscount = min($discount, $base);
                                    }
                                    
                                    $afterDiscount = $base - $validDiscount;
                                    
                                    $tax = ($afterDiscount * ($vendor_item['tax']['ssku_tax'] ?? 0)) / 100;
                                    
                                    $total = $afterDiscount + $tax;
                                ?>
                            <tr>
                                <td><?= $x++; ?></td>
                                <td><?= h($vendor_item['i']['sku_name']); ?></td>
                                <td><?= h($vendor_item['i']['sku_brand']); ?></td>
                                <td><?= h($vendor_item['i']['sku_unit_name']); ?></td>
                                <td>
                                    <input type="number"
                                           name="prices[<?= $sku_id ?>]"
                                           value="<?= $sku_price ?>"
                                           class="form-control"
                                           step="any" />
                                </td>
                                
                                <td><?= h($vendor_item['tax']['ssku_tax'] ?? 0); ?> % </td>
                                <td><?= h($vendor_item['p']['psku_total_tax_value'] ?? $vendor_item['i']['sku_total_tax_value']); ?>  </td>
                                <td>
                                    <input type="number"
                                           name="quantity[<?= $sku_id ?>]"
                                           value="<?= $sku_quantity ?>"
                                           class="form-control vendor-quantity"
                                           step="any">
                                </td>
                                <td>
                                    <select name="discount_type[<?= $sku_id ?>]" class="form-control discount-type">
                                        <option value="flat" <?= $discountType=='flat'?'selected':'' ?>>Flat</option>
                                        <option value="percentage" <?= $discountType=='percentage'?'selected':'' ?>>Percentage</option>
                                    </select>
                                </td>
                                
                                <td>
                                    <input type="number"
                                       name="discount[<?= $sku_id ?>]"
                                       value="<?= $discount ?>"
                                       class="form-control vendor-discount"
                                       step="any"
                                       min="0">
                                </td>
                                <td><?php
                                    if($vendor_item['p']['psku_total_tax_value']){
                                        $tax_value=$vendor_item['p']['psku_total_tax_value'];
                                    }else{
                                        $tax_value=$vendor_item['i']['sku_total_tax_value'];
                                    }
                                ?>
                                
                                <?= number_format($total,2); ?>
                                </td>
                                
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <div class="text-right mt-3">
                    <a href="po_list" class="btn btn-danger ml-2">Cancel</a>
                    <?= $this->Form->button('Save', [
                        'class' => 'btn btn-success',
                        'id' => 'saveBtn'
                    ]); ?>

                </div>

                <?= $this->Form->end(); ?>
            </div>
        </div>
    </div>
</div>

<script>

function showUpdatePOConfirmation(po_date, charge, onConfirm) {

    let html = `
        <table class="table table-bordered table-sm text-start">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Brand</th>
                    <th>Unit</th>
                    <th>Price</th>
                    <th>Qty</th>
                    <th>Base</th>
                    <th>Discount</th>
                    <th>Tax %</th>
                    <th>Tax</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
    `;
    let subtotalwithoutdis = 0;
    let subtotal = 0;
    let totalTax = 0;
    let totalDiscount = 0;   // ADD THIS
    
    const table = $('#example').DataTable();

    table.rows().every(function () {
    
        const $row = $(this.node());
    
        const qty = parseFloat($row.find("input[name^='quantity']").val()) || 0;
        if (qty <= 0) return;
    
        const name  = $row.find('td').eq(1).text().trim();
        const brand = $row.find('td').eq(2).text().trim();
        const unit  = $row.find('td').eq(3).text().trim();
    
        const price  = parseFloat($row.find("input[name^='prices']").val()) || 0;
        const taxPct = parseFloat($row.find('td').eq(5).text()) || 0;
    
        const discountInput = parseFloat($row.find("input[name^='discount']").val()) || 0;
        const discountType = $row.find("select[name^='discount_type']").val();
        
        const base = price * qty;
        
        let validDiscount = 0;
        
        if (discountType === 'percentage') {
        
            validDiscount = (base * discountInput) / 100;
        
        } else {
        
            validDiscount = Math.min(discountInput, base);
        
        }
        
        const afterDiscount = base - validDiscount;
        
        const tax = (afterDiscount * taxPct) / 100;
        const total = afterDiscount + tax;

        subtotalwithoutdis += base;
        subtotal += afterDiscount;
        totalTax += tax;
        totalDiscount += validDiscount;   // ADD

        html += `
            <tr>
                <td>${name}</td>
                <td>${brand}</td>
                <td>${unit}</td>
                <td>₹${price.toFixed(2)}</td>
                <td>${qty}</td>
                <td>₹${base.toFixed(2)}</td>
                <td>₹${validDiscount.toFixed(2)}</td>
                <td>${taxPct}%</td>
                <td>₹${tax.toFixed(2)}</td>
                <td><b>₹${total.toFixed(2)}</b></td>
            </tr>
        `;
    });


    const chargeVal  = parseFloat(charge) || 0;
    const grandTotal = subtotal + totalTax + chargeVal;

    html += `
        </tbody>
        </table>

        <div class="text-end mt-3">
            <h6>PO Date : ${po_date}</h6>
            <h6>Subtotal : ₹${subtotalwithoutdis.toFixed(2)}</h6>
            <h6>Total Discount : ₹${totalDiscount.toFixed(2)}</h6>
            <h6>Total Tax : ₹${totalTax.toFixed(2)}</h6>
            <h6>Charges : ₹${chargeVal.toFixed(2)}</h6>
            <h5 class="mt-2"><b>Grand Total : ₹${grandTotal.toFixed(2)}</b></h5>
        </div>
    `;

    Swal.fire({
        title: 'Confirm Update Purchase Order',
        html: html,
        icon: 'warning',
        width: '1100px',
        showCancelButton: true,
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        reverseButtons: true
    }).then((result) => {
        if (result.isConfirmed) {
            onConfirm();
        }
    });
}


$(document).ready(function () {
    
    $(document).on('input', "input[name^='quantity']", function () {

        const row = $(this).closest('tr');
    
        const price = parseFloat(row.find("input[name^='prices']").val()) || 0;
        const qty = parseFloat($(this).val());
    
        if (isNaN(qty)) return;
    
        const base = price * qty;
    
        const discountInput = row.find('.vendor-discount');
        let discount = parseFloat(discountInput.val());
    
        if (isNaN(discount)) discount = 0;
    
        const discountType = row.find('.discount-type').val();
    
        if (discountType === 'flat' && discount > base) {
            discountInput.val(base.toFixed(2));
        }
    
        if (discountType === 'percentage' && discount > 100) {
            discountInput.val(100);
        }
    });
    
    $(document).on('input', '.vendor-discount', function () {

        const row = $(this).closest('tr');
    
        const price = parseFloat(row.find("input[name^='prices']").val()) || 0;
        const qty   = parseFloat(row.find("input[name^='quantity']").val()) || 0;
    
        const baseAmount = price * qty;
        let discount = parseFloat($(this).val()) || 0;
        const discountType = row.find('.discount-type').val();
        
        if (discountType === 'flat' && discount > baseAmount) {
    
            Swal.fire({
                toast: true,
                icon: 'warning',
                title: 'Discount cannot exceed item amount ₹' + baseAmount.toFixed(2),
                timer: 2000,
                showConfirmButton: false
            });
    
            $(this).val(baseAmount.toFixed(2));
        }
        
        if (discountType === 'percentage' && discount > 100) {
        
            Swal.fire({
                toast: true,
                icon: 'warning',
                title: 'Percentage discount cannot exceed 100%',
                timer: 2000,
                showConfirmButton: false
            });
        
            $(this).val(100);
        }
        if (discount < 0) {
            $(this).val(0);
        }
        
        if (qty < 0) {
            $(this).val(0);
        }
    });

    const table = $('#example').DataTable();

    /* ===============================
       HELPER: CHECK ANY QTY > 0
    =============================== */
    function hasAnySelectedQuantity() {
        
        let hasQty = false;
        
        table.rows().every(function () {
            const qty = parseFloat($(this.node()).find("input[name^='quantity']").val()) || 0;
        
            if (qty > 0) {
                hasQty = true;
                return false;
            }
        });
        
        return hasQty;
    }


    /* ===============================
       INITIAL STATE
    =============================== */
    $('#saveBtn').prop('disabled', !hasAnySelectedQuantity());

    /* ===============================
       LIVE QTY CHANGE
    =============================== */
    $(document).on('input', "input[name^='quantity']", function () {
        $('#saveBtn').prop('disabled', !hasAnySelectedQuantity());
    });

    /* ===============================
       FINAL SUBMIT VALIDATION
    =============================== */
    $('form').on('submit', function (e) {
        e.preventDefault(); // â›” stop immediate submit
    
        // ðŸ”´ No vendor items
        if (table.rows().count() === 0){
            Swal.fire({
                icon: 'error',
                title: 'No item found for this vendor'
            });
            return;
        }
    
        // ðŸ”´ All quantities zero
        if (!hasAnySelectedQuantity()) {
            Swal.fire({
                icon: 'error',
                title: 'No item selected',
                text: 'Please enter quantity for at least one item'
            });
            return;
        }
    
        const form = this;
        const charge = $('#charge').val();
        const po_date = $('#po_date').val();
    
        // ðŸ”¥ CONFIRMATION POPUP
        showUpdatePOConfirmation(po_date, charge, function () {
    
            // ðŸ§¹ Remove old hidden inputs
            $(form)
                .find('input[type=hidden][name^="prices["], input[type=hidden][name^="quantity["], input[type=hidden][name^="discount["]')
                .remove();
    
            // ðŸ“¦ Submit ALL DataTable rows
            table.rows().every(function () {
    
                const $row = $(this.node());
                const priceInput = $row.find('input[name^="prices["]');
                const qtyInput   = $row.find('input[name^="quantity["]');
                const discountInput = $row.find('input[name^="discount["]');
                const discountTypeInput = $row.find('select[name^="discount_type["]');
                
                if (!priceInput.length || !qtyInput.length) return;
    
                const skuId = priceInput.attr('name').match(/\[(.*?)\]/)[1];
    
                $('<input>', {
                    type: 'hidden',
                    name: `prices[${skuId}]`,
                    value: priceInput.val()
                }).appendTo(form);
    
                $('<input>', {
                    type: 'hidden',
                    name: `quantity[${skuId}]`,
                    value: qtyInput.val()
                }).appendTo(form);
                
                $('<input>', {
                    type: 'hidden',
                    name: `discount[${skuId}]`,
                    value: discountInput.val()
                }).appendTo(form);
                
                $('<input>', {
                    type: 'hidden',
                    name: `discount_type[${skuId}]`,
                    value: discountTypeInput.val()
                }).appendTo(form);
            });
    
            // âœ… FINAL SUBMIT
            form.submit();
        });
    });


});
</script>

