HEX
Server: nginx/1.24.0
System: Linux localhost 5.15.0-46-generic #49-Ubuntu SMP Thu Aug 4 18:03:25 UTC 2022 x86_64
User: www (1000)
PHP: 8.3.27
Disabled: passthru,exec,system,putenv,chroot,chgrp,chown,shell_exec,popen,proc_open,pcntl_exec,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,imap_open,apache_setenv
Upload Files
File: /www/wwwroot/erp.nhatnamsst.com/storage/framework/views/b6243d5dc99193e9c3d95d0ace0448ac.php
<div class="col-12">
    <div class="row">
        
        <div class="col-md-3 col-12">
            <div class="mb-3">
                <label class="form-label"><?php echo app('translator')->get('Số hóa đơn'); ?></label>
                <input type="text" class="form-control" name="debt[invoice_number]" value="<?php echo e(old('debt.invoice_number')); ?>" placeholder="Mã tự động sinh">
            </div>
        </div>
        <div class="col-md-3 col-12">
            <div class="mb-3">
                <label class="form-label"><?php echo app('translator')->get('Sale'); ?></label>
                <?php
                    $currentAdmin = get_auth_admin();
                    $defaultSaleId = old('debt.sale_id', $defaultData['sale_id'] ?? null);
                    $isSaleOrLeaderSale = $currentAdmin ? $currentAdmin->isSaleOrLeaderSale() : false;
                    if (!$defaultSaleId && $isSaleOrLeaderSale) {
                        $defaultSaleId = $currentAdmin->id;
                    }
                    $isFromPO = isset($selectedPurchaseOrder) && $selectedPurchaseOrder;
                ?>
                <?php if (isset($component)) { $__componentOriginal5fa9746c29c1e04ec81f3e9772da4d7b = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal5fa9746c29c1e04ec81f3e9772da4d7b = $attributes; } ?>
<?php $component = Domains\Core\View\Components\Select\Select::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('core-select'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Domains\Core\View\Components\Select\Select::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['name' => 'debt[sale_id]','value' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($defaultSaleId),'disabled' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($isSaleOrLeaderSale || $isFromPO)]); ?>
                    <option value=""><?php echo app('translator')->get('--Chọn Sale--'); ?></option>
                    <?php $__currentLoopData = $saleAdmins; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $sale): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($sale->id); ?>" <?php echo e($defaultSaleId == $sale->id ? 'selected' : ''); ?>>
                            <?php echo e($sale->code ?? ''); ?> - <?php echo e($sale->fullname); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal5fa9746c29c1e04ec81f3e9772da4d7b)): ?>
<?php $attributes = $__attributesOriginal5fa9746c29c1e04ec81f3e9772da4d7b; ?>
<?php unset($__attributesOriginal5fa9746c29c1e04ec81f3e9772da4d7b); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal5fa9746c29c1e04ec81f3e9772da4d7b)): ?>
<?php $component = $__componentOriginal5fa9746c29c1e04ec81f3e9772da4d7b; ?>
<?php unset($__componentOriginal5fa9746c29c1e04ec81f3e9772da4d7b); ?>
<?php endif; ?>
                <?php if($isFromPO && $defaultSaleId): ?>
                    <input type="hidden" name="debt[sale_id]" value="<?php echo e($defaultSaleId); ?>">
                <?php endif; ?>
            </div>
        </div>
        <div class="col-md-3 col-12">
            <div class="mb-3">
                <label class="form-label"><?php echo app('translator')->get('Sale Leader'); ?></label>
                <?php
                    $defaultSaleLeaderId = old('debt.sale_leader_id', $defaultData['sale_leader_id'] ?? null);
                ?>
                <?php if (isset($component)) { $__componentOriginal5fa9746c29c1e04ec81f3e9772da4d7b = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal5fa9746c29c1e04ec81f3e9772da4d7b = $attributes; } ?>
<?php $component = Domains\Core\View\Components\Select\Select::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('core-select'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Domains\Core\View\Components\Select\Select::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['name' => 'debt[sale_leader_id]','value' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($defaultSaleLeaderId),'disabled' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($isFromPO)]); ?>
                    <option value=""><?php echo app('translator')->get('--Chọn Sale Leader--'); ?></option>
                    <?php $__currentLoopData = $saleLeaders; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $leader): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($leader->id); ?>" <?php echo e($defaultSaleLeaderId == $leader->id ? 'selected' : ''); ?>>
                            <?php echo e($leader->code ?? ''); ?> - <?php echo e($leader->fullname); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal5fa9746c29c1e04ec81f3e9772da4d7b)): ?>
<?php $attributes = $__attributesOriginal5fa9746c29c1e04ec81f3e9772da4d7b; ?>
<?php unset($__attributesOriginal5fa9746c29c1e04ec81f3e9772da4d7b); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal5fa9746c29c1e04ec81f3e9772da4d7b)): ?>
<?php $component = $__componentOriginal5fa9746c29c1e04ec81f3e9772da4d7b; ?>
<?php unset($__componentOriginal5fa9746c29c1e04ec81f3e9772da4d7b); ?>
<?php endif; ?>
                <?php if($isFromPO && $defaultSaleLeaderId): ?>
                    <input type="hidden" name="debt[sale_leader_id]" value="<?php echo e($defaultSaleLeaderId); ?>">
                <?php endif; ?>
            </div>
        </div>
        <div class="col-md-3 col-12">
            <div class="mb-3">
                <label class="form-label"><?php echo app('translator')->get('Khách hàng'); ?> <span class="text-danger">*</span></label>
                <select name="debt[customer_id]" id="customer-select" class="form-select" required <?php echo e($isFromPO ? 'disabled' : ''); ?>>
                    <option value=""><?php echo app('translator')->get('--Chọn Khách hàng--'); ?></option>
                    <?php $__currentLoopData = $customers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $customer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($customer->id); ?>" <?php echo e((old('debt.customer_id', $defaultData['customer_id'] ?? null) == $customer->id) ? 'selected' : ''); ?>>
                            <?php echo e($customer->name); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>
                <?php if($isFromPO): ?>
                    <input type="hidden" name="debt[customer_id]" value="<?php echo e($defaultData['customer_id'] ?? ''); ?>">
                <?php endif; ?>
            </div>
        </div>

        
        <div class="col-md-3 col-12">
            <div class="mb-3">
                <label class="form-label"><?php echo app('translator')->get('Ngày xuất HĐ'); ?></label>
                <input type="date" class="form-control" name="debt[invoice_date]"
                    value="<?php echo e(old('debt.invoice_date', $defaultData['invoice_date'] ?? date('Y-m-d'))); ?>">
            </div>
        </div>
        <div class="col-md-3 col-12">
            <div class="mb-3">
                <label class="form-label"><?php echo app('translator')->get('Ngày công nợ'); ?></label>
                <input type="date" class="form-control" name="debt[debt_aging_date]"
                    value="<?php echo e(old('debt.debt_aging_date', $defaultData['debt_aging_date'] ?? date('Y-m-d'))); ?>">
            </div>
        </div>
        
        <div class="col-md-3 col-12">
            <div class="mb-3">
                <label class="form-label"><?php echo app('translator')->get('Loại KH'); ?></label>
                <select name="debt[customer_type]" class="form-select" <?php echo e($isFromPO ? 'disabled' : ''); ?>>
                    <option value=""><?php echo app('translator')->get('--Chọn loại--'); ?></option>
                    <option value="1" <?php echo e((old('debt.customer_type', $defaultData['customer_type'] ?? null) == 1) ? 'selected' : ''); ?>>EU</option>
                    <option value="2" <?php echo e((old('debt.customer_type', $defaultData['customer_type'] ?? null) == 2) ? 'selected' : ''); ?>>TM</option>
                    <option value="3" <?php echo e((old('debt.customer_type', $defaultData['customer_type'] ?? null) == 3) ? 'selected' : ''); ?>>CN</option>
                </select>
                <?php if($isFromPO): ?>
                    <input type="hidden" name="debt[customer_type]" value="<?php echo e($defaultData['customer_type'] ?? ''); ?>">
                <?php endif; ?>
            </div>
        </div>

        
        <div class="col-md-3 col-12">
            <div class="mb-3">
                <label class="form-label"><?php echo app('translator')->get('Tổng giá PO'); ?></label>
                <input type="number" class="form-control" id="total_po_price" name="debt[total_po_price]" step="0.01"
                    value="<?php echo e(old('debt.total_po_price', 0)); ?>" min="0" readonly>
            </div>
        </div>
        <div class="col-md-3 col-12">
            <div class="mb-3">
                <label class="form-label"><?php echo app('translator')->get('VAT %'); ?></label>
                <div class="input-group">
                    <input type="number" class="form-control" id="vat_percent" name="debt[vat_percent]" step="0.01"
                        value="<?php echo e(old('debt.vat_percent', 10)); ?>" min="0" max="100">
                    <button type="button" class="btn btn-outline-danger small" id="btn-recalculate-vat" title="<?php echo app('translator')->get('Tính lại'); ?>">
                        <?php echo app('translator')->get('Tính lại'); ?>
                    </button>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-12">
            <div class="mb-3">
                <label class="form-label"><?php echo app('translator')->get('Tổng thanh toán'); ?></label>
                <input type="text" class="form-control" id="total_payment_amount" name="debt[total_payment_amount]"
                    value="<?php echo e(old('debt.total_payment_amount', 0)); ?>" readonly>
            </div>
        </div>
        <div class="col-md-3 col-12">
            <div class="mb-3">
                <label class="form-label"><?php echo app('translator')->get('Tiền trả trước'); ?></label>
                <input type="text" class="form-control" id="advance_payment" name="debt[advance_payment]"
                    value="<?php echo e(old('debt.advance_payment', $defaultData['advance_payment'] ?? 0)); ?>">
            </div>
        </div>

        
        <div class="col-md-4 col-12">
            <div class="mb-3">
                <label class="form-label"><?php echo app('translator')->get('Phương thức thanh toán'); ?></label>
                <input type="text" class="form-control" name="debt[payment_method]"
                    value="<?php echo e(old('debt.payment_method', $defaultData['payment_method'] ?? 'Trả sau')); ?>" placeholder="Trả sau" <?php echo e($isFromPO ? 'readonly' : ''); ?>>
            </div>
        </div>
        <div class="col-md-4 col-12">
            <div class="mb-3">
                <label class="form-label"><?php echo app('translator')->get('PO liên quan'); ?></label>
                <select id="po-select" class="form-select select2-bs5" multiple>
                    <?php $__currentLoopData = $purchaseOrders; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $po): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($po->po_number); ?>"><?php echo e($po->po_number); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>
                <input type="hidden" name="debt[related_pos]" id="related_pos_input">
            </div>
        </div>
        <div class="col-md-4 col-12">
            <div class="mb-3">
                <label class="form-label"><?php echo app('translator')->get('Ghi chú kế toán'); ?></label>
                <textarea class="form-control" name="debt[accounting_note]" rows="3"><?php echo e(old('debt.accounting_note')); ?></textarea>
            </div>
        </div>
    </div>

    <div class="mt-3">
        <span class="form-label"><?php echo app('translator')->get('Chi tiết'); ?></span>
        <div class="">
            <div class="ui-jqgrid-view table-responsive">
                <table id="details-grid"></table>
                <div id="details-pager"></div>
            </div>
        </div>
    </div>

    <div class="row mt-3">
        <div class="col-md-6 col-12">
            <label class="form-label"><?php echo app('translator')->get('File đính kèm'); ?></label>
            <div class="d-flex gap-2 align-items-center mb-3">
                <button type="button" class="btn btn-success small" id="btn-choose-attached-file">
                    <i class="ti ti-plus"></i> <?php echo app('translator')->get('Chọn file...'); ?>
                </button>
                <button type="button" class="btn btn-danger small" id="btn-delete-attached-file">
                    <i class="ti ti-trash"></i> <?php echo app('translator')->get('Xóa'); ?>
                </button>
            </div>
            <div id="attached-files-preview" class="row g-2"></div>
            <input type="file" id="attached-file-input" name="attached_file[]" multiple style="display: none;"
                accept="image/*,.pdf,.doc,.docx,.xls,.xlsx">
        </div>
    </div>
</div>

<?php $__env->startPush('libs-css'); ?>
    <link rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/themes/ui-lightness/jquery-ui.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.5/css/ui.jqgrid.min.css">
    <link href="<?php echo e(asset('/libs/select2/css/select2.min.css')); ?>" rel="stylesheet">
    <link href="<?php echo e(asset('/libs/select2/css/select2-bootstrap-5-theme.min.css')); ?>" rel="stylesheet">
<?php $__env->stopPush(); ?>

<?php $__env->startPush('libs-js'); ?>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.5/js/i18n/grid.locale-vi.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.5/jquery.jqgrid.min.js"></script>
    <script src="<?php echo e(asset('/libs/select2/js/select2.min.js')); ?>"></script>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('js'); ?>
<script>
$(document).ready(function() {
    // Format price function
    function formatPrice(value) {
        if (!value && value !== 0) return '';
        var str = String(value);
        // Bỏ tất cả dấu phẩy và khoảng trắng (giữ lại dấu chấm cho số thập phân)
        str = str.replace(/[, ]/g, '');

        // Kiểm tra xem có phải là số hợp lệ không
        if (!/^-?\d*\.?\d*$/.test(str)) return value;

        // Chuyển sang số để kiểm tra phần thập phân
        var num = parseFloat(str);
        if (isNaN(num)) return value;

        // Tách phần nguyên và phần thập phân
        var parts = str.split('.');
        var integerPart = parts[0] || '0';
        var decimalPart = parts[1];

        // Format phần nguyên với dấu phẩy ngăn cách hàng nghìn
        integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');

        // Chỉ hiển thị phần thập phân nếu có giá trị khác 0
        if (decimalPart !== undefined && decimalPart !== '') {
            // Bỏ các số 0 ở cuối phần thập phân
            decimalPart = decimalPart.replace(/0+$/, '');
            // Nếu còn phần thập phân sau khi bỏ số 0, hiển thị
            if (decimalPart !== '') {
                return integerPart + '.' + decimalPart;
            }
        }

        // Kiểm tra nếu số có phần thập phân nhưng bằng 0 (ví dụ: 1000.0)
        if (num % 1 === 0) {
            return integerPart;
        }

        return integerPart;
    }

    function unformatPrice(value) {
        if (!value && value !== 0) return '';
        var str = String(value);
        // Bỏ tất cả khoảng trắng
        str = str.replace(/ /g, '');
        str = str.replace(/,/g, '');
        var parts = str.split('.');
        if (parts.length > 1) {
            var lastPart = parts[parts.length - 1];
            // Nếu phần sau dấu chấm cuối có 3 chữ số -> đó là phân cách hàng nghìn, bỏ tất cả dấu chấm
            if (lastPart.length === 3) {
                return parts.join('');
            }
            if (lastPart.length <= 2 && parts.length === 2) {
                return parts[0] + '.' + lastPart;
            }
            // Các trường hợp khác: bỏ tất cả dấu chấm
            return parts.join('');
        }
        return str;
    }

    // Initialize select2 for PO
    $('#po-select').select2({
        theme: 'bootstrap-5',
        placeholder: 'Chọn PO liên quan',
        allowClear: true
    });

    // Format advance_payment on page load
    var advancePaymentValue = $('#advance_payment').val();
    if (advancePaymentValue) {
        $('#advance_payment').val(formatPrice(advancePaymentValue));
    }

    // Format advance_payment while typing
    $('#advance_payment').on('input', function() {
        var cursorPos = this.selectionStart;
        var oldValue = $(this).val();
        var newValue = formatPrice(oldValue);
        $(this).val(newValue);
        
        // Restore cursor position
        var diff = newValue.length - oldValue.length;
        this.setSelectionRange(cursorPos + diff, cursorPos + diff);
    });

    // Format total_payment_amount on page load
    var totalPaymentValue = $('#total_payment_amount').val();
    if (totalPaymentValue) {
        $('#total_payment_amount').val(formatPrice(totalPaymentValue));
    }

    // Unformat advance_payment and total_payment_amount before form submit
    $('form').on('submit', function() {
        var advancePayment = $('#advance_payment').val();
        if (advancePayment) {
            $('#advance_payment').val(unformatPrice(advancePayment));
        }
        var totalPaymentAmount = $('#total_payment_amount').val();
        if (totalPaymentAmount) {
            $('#total_payment_amount').val(unformatPrice(totalPaymentAmount));
        }
    });

    // Nếu có selectedPurchaseOrder từ PO, tự động chọn và load chi tiết
    <?php if(isset($selectedPurchaseOrder) && $selectedPurchaseOrder): ?>
        setTimeout(function() {
            var selectedPoNumber = '<?php echo e($selectedPurchaseOrder->po_number); ?>';
            if (selectedPoNumber) {
                $('#po-select').val([selectedPoNumber]).trigger('change');
                $('#related_pos_input').val(selectedPoNumber);
            }
        }, 100);
    <?php endif; ?>

    // Handle PO change - load details
    $('#po-select').on('change', function() {
        var poNumbers = $(this).val();
        $('#related_pos_input').val(poNumbers ? poNumbers.join(';') : '');
        if (poNumbers && poNumbers.length > 0) {
            loadPurchaseOrderDetails(poNumbers);
        } else {
            $("#details-grid").jqGrid('clearGridData');
            updateTotals();
        }
    });

    function loadPurchaseOrderDetails(poNumbers) {
        $.ajax({
            url: '<?php echo e(route('cms.debt.get-purchase-order-details')); ?>',
            method: 'GET',
            data: {
                po_ids: poNumbers
            },
            success: function(response) {
                if (response.details && response.details.length > 0) {
                    $("#details-grid").jqGrid('clearGridData');
                    
                    response.details.forEach(function(detail, index) {
                        var newRowId = 'row_' + (index + 1);
                        // Store raw unformatted values for later use
                        var rawData = {
                            po_detail_code: detail.po_detail_code || '',
                            order_date: detail.order_date || '',
                            product_description: detail.product_description || '',
                            invoice_name: detail.invoice_name || '',
                            brand_id: detail.brand_id || '',
                            quantity: parseFloat(detail.quantity) || 0,
                            unit: detail.unit || '',
                            unit_price: parseFloat(detail.unit_price) || 0,
                            total_po_price: parseFloat(detail.total_po_price) || 0,
                            vat_amount: parseFloat(detail.vat_amount) || 0,
                            total_amount: parseFloat(detail.total_amount) || 0,
                            purchase_order_detail_id: detail.purchase_order_detail_id || null
                        };
                        // Add raw data properties for easy access
                        detail._raw_quantity = rawData.quantity;
                        detail._raw_unit_price = rawData.unit_price;
                        detail._raw_total_po_price = rawData.total_po_price;
                        detail._raw_vat_amount = rawData.vat_amount;
                        detail._raw_total_amount = rawData.total_amount;
                        $("#details-grid").jqGrid('addRowData', newRowId, detail);
                    });
                    
                    // Update related_pos field
                    if (response.related_pos) {
                        $('input[name="debt[related_pos]"]').val(response.related_pos);
                    }
                    
                    updateTotals();
                } else {
                    $("#details-grid").jqGrid('clearGridData');
                    updateTotals();
                }
            },
            error: function() {
                msgError('Lỗi khi tải chi tiết PO.');
                $("#details-grid").jqGrid('clearGridData');
                updateTotals();
            }
        });
    }

    function updateTotals() {
        var allRowIds = $("#details-grid").jqGrid('getDataIDs');
        var totalPoPrice = 0;
        var totalAmount = 0;
        var gridData = $("#details-grid").jqGrid('getGridParam', 'data');
        
        allRowIds.forEach(function(rowId) {
            var rowIndex = allRowIds.indexOf(rowId);
            // Get raw data from grid's internal data array to avoid formatted values
            var rawRowData = gridData && gridData[rowIndex] ? gridData[rowIndex] : null;
            
            if (rawRowData) {
                // Use raw unformatted values
                totalPoPrice += parseFloat(rawRowData.total_po_price || 0);
                totalAmount += parseFloat(rawRowData.total_amount || 0);
            } else {
                // Fallback: get from rowData and unformat
                var rowData = $("#details-grid").jqGrid('getRowData', rowId);
                var unformattedPoPrice = unformatPrice(rowData.total_po_price || '0');
                var unformattedAmount = unformatPrice(rowData.total_amount || '0');
                totalPoPrice += parseFloat(unformattedPoPrice) || 0;
                totalAmount += parseFloat(unformattedAmount) || 0;
            }
        });
        
        $('#total_po_price').val(totalPoPrice.toFixed(2));
        $('#total_payment_amount').val(formatPrice(totalAmount));
    }

    // Function to recalculate VAT for all rows
    function recalculateVAT() {
        var vatPercent = parseFloat($('#vat_percent').val()) || 0;
        var allRowIds = $("#details-grid").jqGrid('getDataIDs');
        var gridData = $("#details-grid").jqGrid('getGridParam', 'data');
        
        if (allRowIds.length === 0) {
            msgWarning('Không có dữ liệu để tính lại.');
            return;
        }
        
        allRowIds.forEach(function(rowId) {
            var rowIndex = allRowIds.indexOf(rowId);
            var rawRowData = gridData && gridData[rowIndex] ? gridData[rowIndex] : null;
            
            var totalPoPrice = 0;
            
            if (rawRowData) {
                // Get total_po_price from raw data
                totalPoPrice = parseFloat(rawRowData.total_po_price || 0);
            } else {
                // Fallback: get from rowData
                var rowData = $("#details-grid").jqGrid('getRowData', rowId);
                totalPoPrice = parseFloat(unformatPrice(rowData.total_po_price || '0')) || 0;
            }
            
            // Calculate new VAT amount and total amount
            var vatAmount = totalPoPrice * (vatPercent / 100);
            var totalAmount = totalPoPrice + vatAmount;
            
            // Update raw data if available
            if (rawRowData) {
                rawRowData.vat_amount = vatAmount;
                rawRowData.total_amount = totalAmount;
                rawRowData._raw_vat_amount = vatAmount;
                rawRowData._raw_total_amount = totalAmount;
            }
            
            // Update grid row cells directly
            $("#details-grid").jqGrid('setCell', rowId, 'vat_amount', vatAmount);
            $("#details-grid").jqGrid('setCell', rowId, 'total_amount', totalAmount);
        });
        
        // Update totals
        updateTotals();
        
        msgSuccess('Đã tính lại VAT thành công.');
    }

    // Handle VAT % change - highlight button when value changes
    var originalVatPercent = $('#vat_percent').val();
    $('#vat_percent').on('change input', function() {
        var newVatPercent = $(this).val();
        if (newVatPercent !== originalVatPercent && newVatPercent !== '') {
            // Highlight the recalculate button to draw attention
            $('#btn-recalculate-vat').removeClass('btn-outline-danger').addClass('btn-danger');
        } else {
            $('#btn-recalculate-vat').removeClass('btn-danger').addClass('btn-outline-danger');
        }
    });
    
    // Handle recalculate button click
    $('#btn-recalculate-vat').on('click', function() {
        recalculateVAT();
        // Update original VAT percent and reset button style after recalculation
        setTimeout(function() {
            originalVatPercent = $('#vat_percent').val();
            $('#btn-recalculate-vat').removeClass('btn-danger').addClass('btn-outline-danger');
        }, 100);
    });

    // Initialize details grid
    $("#details-grid").jqGrid({
        datatype: "local",
        colNames: ['No', 'PO Chi tiết', 'Ngày đặt hàng', 'Mô tả sản phẩm', 'Tên xuất hóa đơn', 
            'Hãng', 'Số lượng', 'Đơn vị tính', 'Đơn giá', 'Tổng giá PO', 'Tiền thuế VAT', 'Tổng cộng'
        ],
        colModel: [
            {name: 'no', index: 'no', width: 60, align: 'center', formatter: function(cellvalue, options, rowObject) {
                var allRowIds = $("#details-grid").jqGrid('getDataIDs');
                var rowIndex = allRowIds.indexOf(options.rowId);
                return rowIndex >= 0 ? rowIndex + 1 : '';
            }, sortable: false},
            {name: 'po_detail_code', index: 'po_detail_code', width: 150, editable: false},
            {name: 'order_date', index: 'order_date', width: 120, editable: false, formatter: function(cellvalue, options, rowObject) {
                if (!cellvalue) return '';
                // Store original value for later use
                if (rowObject) {
                    rowObject._raw_order_date = cellvalue;
                }
                var date = new Date(cellvalue);
                return date.toLocaleDateString('vi-VN');
            }},
            {name: 'product_description', index: 'product_description', width: 300, editable: false},
            {name: 'invoice_name', index: 'invoice_name', width: 200, editable: false},
            {name: 'brand_id', index: 'brand_id', width: 150, editable: false, formatter: function(cellvalue, options, rowObject) {
                // Store original brand_id for later use
                if (rowObject) {
                    rowObject._raw_brand_id = cellvalue || rowObject.brand_id || '';
                }
                return rowObject.brand_name || cellvalue || '';
            }},
            {name: 'quantity', index: 'quantity', width: 100, editable: false, align: 'right', formatter: function(cellvalue) {
                if (cellvalue == null || cellvalue === '') return '';
                var num = parseFloat(cellvalue);
                return isNaN(num) ? cellvalue : num % 1 === 0 ? num.toString() : num.toFixed(2);
            }},
            {name: 'unit', index: 'unit', width: 100, editable: false},
            {name: 'unit_price', index: 'unit_price', width: 120, editable: false, align: 'right', formatter: function(cellvalue) {
                if (cellvalue == null || cellvalue === '') return '';
                return formatPrice(cellvalue);
            }},
            {name: 'total_po_price', index: 'total_po_price', width: 120, editable: false, align: 'right', formatter: function(cellvalue) {
                if (cellvalue == null || cellvalue === '') return '';
                return formatPrice(cellvalue);
            }},
            {name: 'vat_amount', index: 'vat_amount', width: 120, editable: false, align: 'right', formatter: function(cellvalue) {
                if (cellvalue == null || cellvalue === '') return '';
                return formatPrice(cellvalue);
            }},
            {name: 'total_amount', index: 'total_amount', width: 120, editable: false, align: 'right', formatter: function(cellvalue) {
                if (cellvalue == null || cellvalue === '') return '';
                return formatPrice(cellvalue);
            }}
        ],
        rowNum: 10,
        rowList: [10, 20, 30, 50, 100],
        pager: '#details-pager',
        sortname: 'no',
        viewrecords: true,
        sortorder: "asc",
        caption: "",
        height: 'auto',
        autowidth: true,
        shrinkToFit: true,
        editurl: 'clientArray',
        cellEdit: false
    });

    // File upload handlers
    let attachedFiles = [];
    let attachedFilesData = [];

    $('#btn-choose-attached-file').on('click', function() {
        $('#attached-file-input').click();
    });

    $('#attached-file-input').on('change', function() {
        var files = this.files;
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            attachedFiles.push(file);
            var reader = new FileReader();
            reader.onload = function(e) {
                var fileData = {
                    name: file.name,
                    size: file.size,
                    type: file.type,
                    data: e.target.result
                };
                attachedFilesData.push(fileData);
                updateFilePreview();
            };
            reader.readAsDataURL(file);
        }
    });

    $('#btn-delete-attached-file').on('click', function() {
        attachedFiles = [];
        attachedFilesData = [];
        $('#attached-file-input').val('');
        updateFilePreview();
    });

    function updateFilePreview() {
        var html = '';
        attachedFiles.forEach(function(file, index) {
            var isImage = file.type.startsWith('image/');
            html += '<div class="col-md-3">';
            if (isImage) {
                html += '<img src="' + URL.createObjectURL(file) + '" class="img-thumbnail" style="max-width: 150px;">';
            } else {
                html += '<div class="border p-2"><i class="ti ti-file"></i> ' + file.name + '</div>';
            }
            html += '</div>';
        });
        $('#attached-files-preview').html(html);
    }

    // Function to convert date from dd/mm/yyyy to Y-m-d
    function convertDateToYMD(dateStr) {
        if (!dateStr) return '';
        // Check if already in Y-m-d format
        if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
            return dateStr;
        }
        // Convert from dd/mm/yyyy to Y-m-d
        var parts = dateStr.split('/');
        if (parts.length === 3) {
            var day = parts[0].padStart(2, '0');
            var month = parts[1].padStart(2, '0');
            var year = parts[2];
            return year + '-' + month + '-' + day;
        }
        return dateStr;
    }

    // Helper function to get column index by name
    function getColumnIndex(colName) {
        var colModel = $("#details-grid").jqGrid('getGridParam', 'colModel');
        for (var i = 0; i < colModel.length; i++) {
            if (colModel[i].name === colName) {
                return i;
            }
        }
        return -1;
    }
    
    // Helper function to get raw cell value from DOM
    function getRawCellValue(rowId, colName) {
        var colIndex = getColumnIndex(colName);
        if (colIndex < 0) return null;
        
        try {
            var $row = $("#details-grid").find('tr#' + rowId);
            if ($row.length > 0) {
                var $cell = $row.find('td:eq(' + colIndex + ')');
                if ($cell.length > 0) {
                    return $cell.text().trim();
                }
            }
        } catch(e) {
            // Ignore
        }
        return null;
    }
    
    // Before form submit, collect grid data
    $('form').on('submit', function() {
        var allRowIds = $("#details-grid").jqGrid('getDataIDs');
        var details = [];
        var gridData = $("#details-grid").jqGrid('getGridParam', 'data');
        var colModel = $("#details-grid").jqGrid('getGridParam', 'colModel');
        
        allRowIds.forEach(function(rowId) {
            // Get row data (will be formatted)
            var rowData = $("#details-grid").jqGrid('getRowData', rowId);
            
            // Try to get raw order_date from cell data
            var rawOrderDate = '';
            try {
                var cellData = $("#details-grid").jqGrid('getCell', rowId, 'order_date', false, true);
                if (cellData && cellData !== rowData.order_date) {
                    rawOrderDate = cellData;
                }
            } catch(e) {
                // Fallback to grid data
                var rowIndex = allRowIds.indexOf(rowId);
                if (gridData && gridData[rowIndex] && gridData[rowIndex].order_date) {
                    rawOrderDate = gridData[rowIndex].order_date;
                }
            }
            
            if (rowData.product_description) {
                var rowIndex = allRowIds.indexOf(rowId);
                var rawRowData = gridData && gridData[rowIndex] ? gridData[rowIndex] : null;
                
                // Get brand_id from raw grid data (not formatted)
                var brandId = '';
                if (rawRowData) {
                    if (rawRowData._raw_brand_id !== undefined) {
                        brandId = rawRowData._raw_brand_id;
                    } else if (rawRowData.brand_id !== undefined) {
                        brandId = rawRowData.brand_id;
                    }
                }
                
                // If still empty, try to get from rowData (but check if it's a number)
                if (!brandId && rowData.brand_id) {
                    var testId = parseInt(rowData.brand_id);
                    if (!isNaN(testId)) {
                        brandId = testId.toString();
                    }
                }
                
                // Use raw order_date if available, otherwise convert formatted date
                var orderDate = rawOrderDate || (rawRowData ? rawRowData.order_date : rowData.order_date) || '';
                if (orderDate && !rawOrderDate && orderDate !== (rawRowData ? rawRowData.order_date : '')) {
                    orderDate = convertDateToYMD(orderDate);
                }
                
                // Convert brand_id to integer or null
                var finalBrandId = null;
                if (brandId && brandId !== '' && !isNaN(parseInt(brandId))) {
                    finalBrandId = parseInt(brandId);
                }
                
                // Convert purchase_order_detail_id to integer or null
                var purchaseOrderDetailId = null;
                var poDetailIdValue = (rawRowData && rawRowData.purchase_order_detail_id) ? rawRowData.purchase_order_detail_id : (rowData.purchase_order_detail_id || '');
                if (poDetailIdValue && poDetailIdValue !== '' && !isNaN(parseInt(poDetailIdValue))) {
                    purchaseOrderDetailId = parseInt(poDetailIdValue);
                }
                
                // Get numeric values - try multiple methods to get raw unformatted values
                var quantity = 0;
                var unitPrice = 0;
                var totalPoPrice = 0;
                var vatAmount = 0;
                var totalAmount = 0;
                
                // Method 1: Try to get from rawRowData with _raw_ prefix (stored when loading)
                if (rawRowData) {
                    if (rawRowData._raw_quantity !== undefined) quantity = parseFloat(rawRowData._raw_quantity) || 0;
                    else quantity = parseFloat(rawRowData.quantity) || 0;
                    
                    if (rawRowData._raw_unit_price !== undefined) unitPrice = parseFloat(rawRowData._raw_unit_price) || 0;
                    else unitPrice = parseFloat(rawRowData.unit_price) || 0;
                    
                    if (rawRowData._raw_total_po_price !== undefined) totalPoPrice = parseFloat(rawRowData._raw_total_po_price) || 0;
                    else totalPoPrice = parseFloat(rawRowData.total_po_price) || 0;
                    
                    if (rawRowData._raw_vat_amount !== undefined) vatAmount = parseFloat(rawRowData._raw_vat_amount) || 0;
                    else vatAmount = parseFloat(rawRowData.vat_amount) || 0;
                    
                    if (rawRowData._raw_total_amount !== undefined) totalAmount = parseFloat(rawRowData._raw_total_amount) || 0;
                    else totalAmount = parseFloat(rawRowData.total_amount) || 0;
                }
                
                // Method 2: If values are 0 or invalid, try to get from DOM cells and unformat
                if ((quantity === 0 && rowData.quantity) || (totalAmount === 0 && rowData.total_amount)) {
                    var rawQuantity = getRawCellValue(rowId, 'quantity');
                    var rawUnitPrice = getRawCellValue(rowId, 'unit_price');
                    var rawTotalPoPrice = getRawCellValue(rowId, 'total_po_price');
                    var rawVatAmount = getRawCellValue(rowId, 'vat_amount');
                    var rawTotalAmount = getRawCellValue(rowId, 'total_amount');
                    
                    if (rawQuantity !== null && quantity === 0) quantity = parseFloat(unformatPrice(rawQuantity)) || 0;
                    if (rawUnitPrice !== null && unitPrice === 0) unitPrice = parseFloat(unformatPrice(rawUnitPrice)) || 0;
                    if (rawTotalPoPrice !== null && totalPoPrice === 0) totalPoPrice = parseFloat(unformatPrice(rawTotalPoPrice)) || 0;
                    if (rawVatAmount !== null && vatAmount === 0) vatAmount = parseFloat(unformatPrice(rawVatAmount)) || 0;
                    if (rawTotalAmount !== null && totalAmount === 0) totalAmount = parseFloat(unformatPrice(rawTotalAmount)) || 0;
                }
                
                // Method 3: Final fallback - unformat from formatted rowData
                if (quantity === 0 && rowData.quantity) quantity = parseFloat(unformatPrice(rowData.quantity || '0')) || 0;
                if (unitPrice === 0 && rowData.unit_price) unitPrice = parseFloat(unformatPrice(rowData.unit_price || '0')) || 0;
                if (totalPoPrice === 0 && rowData.total_po_price) totalPoPrice = parseFloat(unformatPrice(rowData.total_po_price || '0')) || 0;
                if (vatAmount === 0 && rowData.vat_amount) vatAmount = parseFloat(unformatPrice(rowData.vat_amount || '0')) || 0;
                if (totalAmount === 0 && rowData.total_amount) totalAmount = parseFloat(unformatPrice(rowData.total_amount || '0')) || 0;
                
                details.push({
                    po_detail_code: rowData.po_detail_code || '',
                    order_date: orderDate,
                    product_description: rowData.product_description || '',
                    invoice_name: rowData.invoice_name || '',
                    brand_id: finalBrandId,
                    quantity: quantity,
                    unit: rowData.unit || '',
                    unit_price: unitPrice,
                    total_po_price: totalPoPrice,
                    vat_amount: vatAmount,
                    total_amount: totalAmount,
                    purchase_order_detail_id: purchaseOrderDetailId
                });
            }
        });
        
        // Remove existing details_json input if any
        $('input[name="details_json"]').remove();
        
        // Add hidden input with details data
        $('<input>').attr({
            type: 'hidden',
            name: 'details_json',
            value: JSON.stringify(details)
        }).appendTo(this);
        
        // Update related_pos from select2 - already handled by select2
    });
});
</script>
<?php $__env->stopPush(); ?>
<?php /**PATH /www/wwwroot/erp.nhatnamsst.com/resources/views/cms/debts/forms/create-left.blade.php ENDPATH**/ ?>