<?php $__env->startSection('title'); ?>
    Settings - <?php echo e($title); ?>

    <style>
        .table-container {
            margin: 20px 0;
        }
        .form-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .calculation-panel {
            background: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
        }
        .readonly-input {
            background-color: #f8f9fa;
        }
        .text-right {
            text-align: right;
        }
        
        /* Image preview styles */
        .image-preview-container {
            position: relative;
            display: inline-block;
            margin: 10px 0;
        }
        .image-preview {
            max-width: 200px;
            max-height: 200px;
            border: 2px dashed #ddd;
            border-radius: 8px;
            padding: 10px;
            display: none;
        }
        .image-preview img {
            max-width: 100%;
            max-height: 100%;
            border-radius: 4px;
        }
        .image-remove-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 50%;
            width: 25px;
            height: 25px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
        }
        .image-remove-btn:hover {
            background: #c82333;
        }
        .file-input-wrapper {
            position: relative;
            overflow: hidden;
            display: inline-block;
            width: 100%;
        }
        .file-input-wrapper input[type=file] {
            position: absolute;
            left: -9999px;
        }
        .file-input-label {
            display: block;
            padding: 10px 15px;
            cursor: pointer;
            background: #f8f9fa;
            border: 2px dashed #ddd;
            border-radius: 8px;
            text-align: center;
            transition: all 0.3s ease;
        }
        .file-input-label:hover {
            background: #e9ecef;
            border-color: #007bff;
        }
        .file-input-label i {
            font-size: 24px;
            color: #6c757d;
            margin-bottom: 5px;
        }
        .file-name {
            margin-top: 5px;
            font-size: 12px;
            color: #6c757d;
        }
</style>
<?php $__env->stopSection(); ?>


<?php $__env->startSection('navbar-content'); ?>
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">
                        Inventory </h1>
                </div><!-- /.col -->
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="<?php echo e(route('home')); ?>">Dashboard</a></li>
                        <?php if(helper::roleAccess('sale.sale.index')): ?>
                            <li class="breadcrumb-item"><a href="<?php echo e(route('sale.sale.index')); ?>">Sale
                                    List</a></li>
                        <?php endif; ?>
                        <li class="breadcrumb-item active"><span>Edit Sale</span></li>
                    </ol>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div><!-- /.container-fluid -->
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('admin-content'); ?>
    <div class="row">
        <div class="col-md-12">
            <div class="card card-default">
                <div class="card-header">
                    <h3 class="card-title">Sale Edit</h3>
                    <div class="card-tools">
                        <?php if(helper::roleAccess('sale.sale.create')): ?>
                            <a class="btn btn-default" href="<?php echo e(route('sale.sale.create')); ?>"><i class="fas fa-plus"></i>
                                Add New</a>
                        <?php endif; ?>
                        <span id="buttons"></span>

                        <a class="btn btn-tool btn-default" data-card-widget="collapse">
                            <i class="fas fa-minus"></i>
                        </a>
                        <a class="btn btn-tool btn-default" data-card-widget="remove">
                            <i class="fas fa-times"></i>
                        </a>
                    </div>
                </div>
                <!-- /.card-header -->
                <div class="card-body">
                    <form class="needs-validation" method="POST" action="<?php echo e(route('sale.sale.update', $saletlist->id)); ?>"
                        novalidate>
                        <?php echo csrf_field(); ?>
                        <div class="form-row">
                            <div class="col-md-2 mb-3">
                                <label for="validationCustom01">Invoice Number :</label>
                                <input class="bg-green form-control" readonly=""
                                    style="padding: 5px; font-weight : bold; width: 100%"
                                    value="<?php echo e($saletlist->invoice_no); ?> " for="validationCustom01">
                                <input type="hidden" name="invoice_no" class="form-control" id=""
                                    value="<?php echo e($saletlist->invoice_no); ?>">
                            </div>
                            <div class="col-md-2 mb-3 d-none">
                                <label for="validationCustom01">Po Number :</label>
                                <input type="text" name="po_invoice" class="form-control"
                                    value="<?php echo e($saletlist->po_invoice); ?>">
                            </div>
                            <div class="col-md-2 mb-3 d-none">
                                <label>Po Date:</label>
                                <div class="input-group date" id="reservationdate1" data-target-input="nearest">
                                    <input type="text" name="po_date" data-toggle="datetimepicker"
                                        value="<?php echo e(date('YYYY-mm-dd')); ?>" class="form-control datetimepicker-input"
                                        data-target="#reservationdate1" />
                                    <div class="input-group-append" data-target="#reservationdate1"
                                        data-toggle="datetimepicker">
                                        <div class="input-group-text"><i class="fa fa-calendar"></i></div>
                                    </div>
                                </div>
                                <?php $__errorArgs = ['date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <span class=" error text-red text-bold"><?php echo e($message); ?></span>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>
                            <div class="col-md-2 mb-3">
                                <label>Date:</label>
                                <div class="input-group date" id="reservationdate" data-target-input="nearest">
                                    <input type="text" name="date" data-toggle="datetimepicker"
                                        value="<?php echo e($saletlist->date); ?>" class="form-control datetimepicker-input"
                                        data-target="#reservationdate" />
                                    <div class="input-group-append" data-target="#reservationdate"
                                        data-toggle="datetimepicker">
                                        <div class="input-group-text"><i class="fa fa-calendar"></i></div>
                                    </div>
                                </div>
                                <?php $__errorArgs = ['date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <span class=" error text-red text-bold"><?php echo e($message); ?></span>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>
                            <div class="col-md-2 mb-3">
                                <label for="validationCustom01">Branch * :</label>

                                <select class="form-control select2" id="branch_id" name="branch_id">

                                    <?php $__currentLoopData = $branch; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <?php if($value->id == 2): ?>
                                            <option value="<?php echo e($value->id); ?>"
                                                <?php echo e($saletlist->branch_id == $value->id ? 'selected' : ''); ?>>
                                                <?php echo e($value->branchCode . ' - ' . $value->name); ?>

                                            </option>
                                        <?php endif; ?>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                                <?php $__errorArgs = ['branch_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <span class="error text-red text-bold"><?php echo e($message); ?></span>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>


                            <div class="col-md-2 mb-3">
                                <label for="ledger_id">Ledger * :

                                    <button type="button" class="btn btn-sm btn-primary ml-2" data-toggle="modal"
                                        data-target="#addCustomerModel">
                                        +
                                    </button>
                                </label>
                                <select class="form-control select2" name="ledger_id" id="ledger_id">
                                    <option selected disabled value="">--Select Ledger--</option>
                                    <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.account','data' => ['setAccounts' => $ledgers,'selectVal' => $saletlist->ledger_id]]); ?>
<?php $component->withName('account'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes(['setAccounts' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($ledgers),'selectVal' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($saletlist->ledger_id)]); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4)): ?>
<?php $component = $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4; ?>
<?php unset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4); ?>
<?php endif; ?>
                                </select>
                                <?php $__errorArgs = ['ledger_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <span class=" error text-red text-bold"><?php echo e($message); ?></span>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>

                            <div class="col-md-2 mb-3">
                                <label for="validationCustom01">Payment Type * :</label>
                                <br>
                                <div class="btn-group btn-group-toggle" data-toggle="buttons">

                                    <label class="btn bg-olive">
                                        <input type="radio" name="payment_type" value="Due"
                                            onchange="getCustomerBalance('Due')"
                                            <?php echo e($saletlist->payment_type == 'Due' ? 'checked' : ''); ?> id="option3"
                                            autocomplete="off"> Due
                                    </label>

                                </div>
                                <input type="hidden" id="paymentType">
                                <input type="hidden" id="expireData">
                                <input type="hidden" id="paymentypeValue" value="<?php echo e($saletlist->payment_type); ?>">
                            </div>
                            <table class=" table-responsive table table-bordered">
                                <tr>
                                    <td>
                                        <div class="col-md-9 float-left ">
                                            Sales Item
                                        </div>
                                        <div class="col-md-3 float-right">
                                            Payment Calculation
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="padding: 10px!important;">
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="col-md-12 float-left">
                                                    <div class="panel panel-default">
                                                        <div class="panel-body">

                                                            <table class="table table-bordered table-hover tableAddItem"
                                                                id="show_item">
                                                                <thead>
                                                                    <tr>
                                                                        <th nowrap style="width:15%" align="center"
                                                                            id="">
                                                                            <strong>Product Category <span
                                                                                    style="color:red;">
                                                                                    *</span></strong>
                                                                        </th>
                                                                        <th nowrap style="width:15%" align="center">
                                                                            <strong>Product <span
                                                                                    style="color:red;">*</span></strong>
                                                                        </th>
                                                                        <th nowrap style="width:11%" align="center">
                                                                            <strong>Team <span
                                                                                    style="color:red;">*</span></strong>
                                                                        </th>
                                                                        <th nowrap style="width:11%" align="center">
                                                                            <strong>Fabrics <span
                                                                                    style="color:red;">*</span></strong>
                                                                        </th>
                                                                        <th nowrap style="width:11%" align="center">
                                                                            <strong>Quantity <span
                                                                                    style="color:red;">*</span></strong>
                                                                        </th>
                                                                        <th nowrap style="width:12%" align="center">
                                                                            <strong>Unit Price(BDT) <span
                                                                                    style="color:red;">*</span></strong>
                                                                        </th>
                                                                        <th nowrap style="width:13%" align="center">
                                                                            <strong>Total Price(BDT) <span
                                                                                    style="color:red;">*</span></strong>
                                                                        </th>
                                                                        <th align="center" style="width:5%">
                                                                            <strong>Action</strong>
                                                                        </th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody>
                                                                    <!-- Input row -->
                                                                    <tr>

                                                                        <td id="product_td">
                                                                            <select onchange="getProductList(this.value)"
                                                                                class="select2 form-control catName"
                                                                                id="form-field-select-3"
                                                                                data-placeholder="Search Category">
                                                                                <option disabled selected>--- Select
                                                                                    Category
                                                                                    ---</option>
                                                                                <?php foreach ($category_info as $eachInfo) : ?>
                                                                                <option catName="<?php echo e($eachInfo->name); ?>"
                                                                                    value="<?php echo e($eachInfo->id); ?>">
                                                                                    <?php echo e($eachInfo->name); ?></option>
                                                                                <?php endforeach; ?>
                                                                            </select>
                                                                        </td>
                                                                        <td id="product_td">
                                                                            <select class="select2 form-control proName"
                                                                                id="productID"
                                                                                data-placeholder="Search Product"
                                                                                onchange="getUnitPrice(this.value)">
                                                                                <option disabled selected>---Select
                                                                                    Product---
                                                                                </option>
                                                                            </select>
                                                                            <span
                                                                                class="text-success purchaseprice"></span>
                                                                        </td>
                                                                        <td>
                                                                            <input type="text"
                                                                                class="form-control team" id="team">
                                                                        </td>
                                                                        <td>
                                                                            <select
                                                                                class="select2 form-control purchasetype"
                                                                                name="fabrics[]"
                                                                                onchange="getUnitPrice(this.value)">
                                                                                <option selected disabled value="">
                                                                                    --Select Fabrics--</option>
                                                                                <?php $__currentLoopData = $fabricType; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                                    <option value="<?php echo e($key); ?>">
                                                                                        <?php echo e($value); ?></option>
                                                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                                            </select>
                                                                            <span
                                                                                class="text-success purchasetypeerror"></span>
                                                                        </td>
                                                                        <td>
                                                                            <input type="text" class="form-control qty"
                                                                                id="qty" onkeyup="qtyPriceCal();"
                                                                                placeholder="0">
                                                                        </td>
                                                                        <td>
                                                                            <input type="text"
                                                                                class="form-control text-right unitprice"
                                                                                id="unitpice" onkeyup="qtyPriceCal();"
                                                                                placeholder="0.00">
                                                                        </td>
                                                                        <td>
                                                                            <input type="text"
                                                                                class="form-control text-right ttlamount total"
                                                                                id="total" placeholder="0.00"
                                                                                readonly="readonly">
                                                                        </td>
                                                                        <td>
                                                                            <a id="add_item"
                                                                                class="btn btn-info form-control"
                                                                                href="javascript:;" title="Add Item">
                                                                                <i class="fa fa-plus"></i>
                                                                            </a>
                                                                        </td>
                                                                    </tr>

                                                                    <!-- Existing items with UPDATED structure -->
                                                                    <?php $__currentLoopData = $saledetails; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                        <tr class="new_item<?php echo e($value->category_id); ?>">
                                                                            <td align="right">
                                                                                <?php echo e($value->category->name ?? 'N/A'); ?>

                                                                                <input type="hidden" class="add_quantity"
                                                                                    name="catName[]"
                                                                                    value="<?php echo e($value->category_id); ?>">
                                                                            </td>
                                                                            <td align="right">
                                                                                <?php echo e($value->product->name ?? 'N/A'); ?>

                                                                                <input type="hidden" class="add_quantity"
                                                                                    name="proName[]"
                                                                                    value="<?php echo e($value->product_id); ?>">
                                                                            </td>
                                                                            <td align="right">
                                                                                <?php echo e($value->team); ?>

                                                                                <input type="hidden" name="team[]"
                                                                                    value="<?php echo e($value->team); ?>">
                                                                            </td>
                                                                            <td align="right">
                                                                                <?php echo e($value->fabricDetails->name ?? ''); ?>

                                                                                <input type="hidden"
                                                                                    name="purchasetype[]"
                                                                                    value="<?php echo e($value->fabrics); ?>">
                                                                            </td>
                                                                            <td align="right">
                                                                                <input type="number"
                                                                                    class="update-qty form-control"
                                                                                    name="qty[]"
                                                                                    value="<?php echo e($value->qty); ?>"
                                                                                    data-product-id="<?php echo e($value->product_id); ?>"
                                                                                    data-unit-price="<?php echo e($value->rate); ?>"
                                                                                    min="1" step="1">
                                                                            </td>
                                                                            <td align="right">
                                                                                
                                                                                <input type="number"
                                                                                    class="form-control ttlunitprice unitparice"
                                                                                    name="unitprice[]"
                                                                                    value="<?php echo e($value->rate); ?>"
                                                                                    step="0.01">
                                                                            </td>
                                                                            <td align="right">
                                                                                <span
                                                                                    class="total-price-display"><?php echo e($value->price); ?></span>
                                                                                <input type="hidden" class="grandtotal"
                                                                                    name="price[]"
                                                                                    value="<?php echo e($value->price); ?>">
                                                                            </td>
                                                                            <td>
                                                                                <a del_id="<?php echo e($value->product_id); ?>"
                                                                                    class="delete_item btn form-control btn-danger"
                                                                                    href="javascript:;" title="">
                                                                                    <i class="fa fa-times"></i>
                                                                                </a>
                                                                            </td>
                                                                        </tr>
                                                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                                </tbody>
                                                                <tfoot>
                                                                    <tr>
                                                                        <td align="right"><strong>Sub-Total(BDT)</strong>
                                                                        </td>
                                                                        <td align="right"><strong
                                                                                class=""></strong></td>
                                                                        <td align="right"><strong
                                                                                class=""></strong></td>
                                                                        <td align="right"><strong
                                                                                class=""></strong></td>
                                                                        <td align="right">
                                                                            <strong
                                                                                class="ttlqty"><?php echo e($saledetails->sum('qty')); ?></strong>
                                                                        </td>
                                                                        <td align="right">
                                                                            <strong
                                                                                class="ttlunitprice"><?php echo e($saledetails->sum('rate')); ?></strong>
                                                                        </td>
                                                                        <td align="right">
                                                                            <strong
                                                                                class="grandtotal"><?php echo e($saledetails->sum('price')); ?></strong>
                                                                        </td>
                                                                        <td align="right"><strong
                                                                                class=""></strong></td>
                                                                    </tr>
                                                                </tfoot>
                                                            </table>
                                                        </div>
                                                    </div>
                                                </div>

                                                <div class="col-md-8 float-right">
                                                    <div class="panel  panel-default">
                                                        <div class="panel-body">

                                                            <table class="table table-bordered table-hover ">
                                                                <tbody>
                                                                    <tr>
                                                                        <td nowrap align="right"><strong>Total
                                                                            </strong>
                                                                        </td>
                                                                        <td align="right"> <strong id="gtoal"
                                                                                class="grandtotal"><?php echo e($saledetails->sum('price')); ?>.00</strong>
                                                                        </td>
                                                                    </tr>
                                                                    <tr>
                                                                        <td nowrap align="right">
                                                                            <strong>Previous Due </strong>
                                                                        </td>
                                                                        <td align="right"> <strong
                                                                                id="previous_due"><?php echo e($saletlist->previouse_due_amount); ?></strong>
                                                                            <input type="hidden"
                                                                                id="previouse_due_amount"
                                                                                value="<?php echo e($saletlist->previouse_due_amount); ?>"
                                                                                name="previouse_due_amount">
                                                                        </td>
                                                                    </tr>
                                                                    <tr>
                                                                        <td nowrap align="right">
                                                                            <strong>Discount ( - )
                                                                            </strong>
                                                                        </td>
                                                                        <td><input type="text" autocomplete="off"
                                                                                onkeyup="discountCalculation(this.value)"
                                                                                id="disCount" style="text-align: right"
                                                                                name="discount"
                                                                                value="<?php echo e($saletlist->discount); ?>"
                                                                                class="form-control" placeholder="0.00"
                                                                                oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" />
                                                                        </td>
                                                                    </tr>
                                                                    <tr>
                                                                        <td nowrap align="right">
                                                                            <strong>Carrying Cost ( + )
                                                                            </strong>
                                                                        </td>
                                                                        <td><input type="text" autocomplete="off"
                                                                                onkeyup="carrying_cost_Calculation(this.value)"
                                                                                id="carrying_cost"
                                                                                style="text-align: right"
                                                                                name="carrying_cost"
                                                                                value="<?php echo e($saletlist->carrying_cost); ?>"
                                                                                class="form-control" placeholder="0.00"
                                                                                oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" />
                                                                        </td>
                                                                    </tr>
                                                                    <tr>
                                                                        <td nowrap align="right">
                                                                            <strong>Labor bill ( + )
                                                                            </strong>
                                                                        </td>
                                                                        <td><input type="text" autocomplete="off"
                                                                                onkeyup="labor_bill_Calculation(this.value)"
                                                                                id="labor_bill"
                                                                                value="<?php echo e($saletlist->labor_bill); ?>"
                                                                                style="text-align: right"
                                                                                name="labor_bill" class="form-control"
                                                                                placeholder="0.00"
                                                                                oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" />
                                                                        </td>
                                                                    </tr>

                                                                    <tr>
                                                                        <td nowrap align="right">
                                                                            <strong>Advance Payments
                                                                                <button type="button"
                                                                                    class="btn btn-sm btn-success ml-2"
                                                                                    id="addAdvanceBtn">
                                                                                    <i class="fa fa-plus"></i>
                                                                                </button>
                                                                            </strong>
                                                                        </td>
                                                                        <td>
                                                                            <div id="advanceContainer">
                                                                                <!-- First advance row (default) -->
                                                                                <?php
                                                                                    $advances =
                                                                                        json_decode(
                                                                                            $saletlist->advance,
                                                                                            true,
                                                                                        ) ?? [];
                                                                                    $advanceLedgers =
                                                                                        json_decode(
                                                                                            $saletlist->advance_ledger_id,
                                                                                            true,
                                                                                        ) ?? [];
                                                                                ?>

                                                                                <?php $__empty_1 = true; $__currentLoopData = $advances; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $amount): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                                                                    <div class="advance-row mb-2"
                                                                                        data-index="<?php echo e($index); ?>">
                                                                                        <div class="row">
                                                                                            <div class="col-md-5">
                                                                                                <select
                                                                                                    name="advance_ledger_id[<?php echo e($index); ?>]"
                                                                                                    class="form-control select2 advance-ledger"
                                                                                                    data-index="<?php echo e($index); ?>">
                                                                                                    <option value="">
                                                                                                        --Select Account--
                                                                                                    </option>

                                                                                                    <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.account','data' => ['setAccounts' => $accounts,'selectVal' => $advanceLedgers[
                                                                                                            $index
                                                                                                        ]]]); ?>
<?php $component->withName('account'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes(['setAccounts' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($accounts),'selectVal' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($advanceLedgers[
                                                                                                            $index
                                                                                                        ])]); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4)): ?>
<?php $component = $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4; ?>
<?php unset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4); ?>
<?php endif; ?>

                                                                                                </select>
                                                                                            </div>
                                                                                            <div class="col-md-5">
                                                                                                <input type="text"
                                                                                                    class="form-control advance-amount"
                                                                                                    name="advance[<?php echo e($index); ?>]"
                                                                                                    value="<?php echo e($amount); ?>"
                                                                                                    data-index="<?php echo e($index); ?>"
                                                                                                    style="text-align: right"
                                                                                                    placeholder="0.00"
                                                                                                    oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');"
                                                                                                    onkeyup="calculateAdvanceTotal()" />
                                                                                            </div>
                                                                                            <div class="col-md-2">
                                                                                                <button type="button"
                                                                                                    class="btn btn-sm btn-danger remove-advance"
                                                                                                    data-index="<?php echo e($index); ?>"
                                                                                                    <?php echo e($loop->first ? 'style=display:none;' : ''); ?>>
                                                                                                    <i
                                                                                                        class="fa fa-minus"></i>
                                                                                                </button>
                                                                                            </div>
                                                                                        </div>
                                                                                    </div>
                                                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                                                                    
                                                                                    <div class="advance-row mb-2"
                                                                                        data-index="0">
                                                                                        <div class="row">
                                                                                            <div class="col-md-5">
                                                                                                <select
                                                                                                    name="advance_ledger_id[0]"
                                                                                                    class="form-control select2 advance-ledger"
                                                                                                    data-index="0">
                                                                                                    <option value="">
                                                                                                        --Select Account--
                                                                                                    </option>
                                                                                                    <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.account','data' => ['setAccounts' => $accounts,'selectVal' => $saletlist->advance_ledger_id]]); ?>
<?php $component->withName('account'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes(['setAccounts' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($accounts),'selectVal' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($saletlist->advance_ledger_id)]); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4)): ?>
<?php $component = $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4; ?>
<?php unset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4); ?>
<?php endif; ?>
                                                                                                </select>
                                                                                            </div>
                                                                                            <div class="col-md-5">
                                                                                                <input type="text"
                                                                                                    class="form-control advance-amount"
                                                                                                    name="advance[0]"
                                                                                                    data-index="0"
                                                                                                    placeholder="0.00"
                                                                                                    oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');"
                                                                                                    onkeyup="calculateAdvanceTotal()" />
                                                                                            </div>
                                                                                            <div class="col-md-2">
                                                                                                <button type="button"
                                                                                                    class="btn btn-sm btn-danger remove-advance"
                                                                                                    data-index="0"
                                                                                                    style="display: none;">
                                                                                                    <i
                                                                                                        class="fa fa-minus"></i>
                                                                                                </button>
                                                                                            </div>
                                                                                        </div>
                                                                                    </div>
                                                                                <?php endif; ?>

                                                                            </div>
                                                                            <!-- Total advance display -->
                                                                            <div class="mt-2">
                                                                                <strong>Total
                                                                                    Advance: <span
                                                                                        id="totalAdvanceAmount">0.00</span></strong>
                                                                                <input type="hidden"
                                                                                    id="totalAdvanceHidden"
                                                                                    name="total_advance" value="0">
                                                                            </div>
                                                                        </td>
                                                                    </tr>

                                                                    <?php
                                                                        $discount =
                                                                            $saledetails->sum('price') -
                                                                            $saletlist->discount;
                                                                    ?>
                                                                    <tr id="netTotal">
                                                                        <td nowrap align="right"><strong>Net
                                                                                Total</strong></td>
                                                                        <td align="right"><strong id="ntotal"
                                                                                class="grandtotal"><?php echo e($discount); ?>.00</strong>
                                                                        </td>
                                                                    </tr>
                                                                    <tr id="account_id">
                                                                        <td nowrap align="right">
                                                                            <strong>Account <span style="color:red;"> *
                                                                                </span></strong>
                                                                        </td>
                                                                        <td>
                                                                            <select name="account_id"
                                                                                class="form-control select2">
                                                                                <option selected value="0">Due
                                                                                </option>
                                                                                <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.account','data' => ['setAccounts' => $accounts,'selectVal' => $saletlist->account_id]]); ?>
<?php $component->withName('account'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes(['setAccounts' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($accounts),'selectVal' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($saletlist->account_id)]); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4)): ?>
<?php $component = $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4; ?>
<?php unset($__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4); ?>
<?php endif; ?>
                                                                            </select>
                                                                        </td>
                                                                    </tr>
                                                                    <tr class="partisals d-none">
                                                                        <td nowrap align="right"><strong>Payment
                                                                                ( -
                                                                                )<span style="color:red;"> *
                                                                                </span></strong>
                                                                        </td>
                                                                        <td><input type="text" id="payment"
                                                                                onkeyup="paymentCalculation(this.value)"
                                                                                style="text-align: right"
                                                                                name="partialPayment" readonly
                                                                                value="<?php echo e($saletlist->partialPayment); ?>"
                                                                                class="form-control" autocomplete="off"
                                                                                placeholder="0.00"
                                                                                oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" />
                                                                        </td>
                                                                        <!-- <input type="hidden" id="duePayment" style="text-align: right" name="duePayment" value="" readonly class="form-control" placeholder="0.00" /> -->
                                                                    </tr>

                                                                    <tr>
                                                                        <td nowrap align="right"><strong>Total
                                                                                Due</strong>
                                                                        </td>
                                                                        <td align="right"><strong id="totalDue"
                                                                                class="grandtotal finalDue"><?php echo e($discount - $saletlist->partialPayment); ?>.00</strong>
                                                                        </td>
                                                                    </tr>
                                                                </tbody>
                                                            </table>

                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-md-4 float-right">
                                                    <div class="panel">
                                                        <div class="panel-body">
                                                            <table class="table ">
                                                                <tr>
                                                                    <td>
                                                                        <textarea style="
                                                                                    border:none;"
                                                                            cols="50" class="form-control" name="narration" placeholder="Note......" type="text"><?php echo e($saletlist->narration); ?></textarea>
                                                                    </td>
                                                                </tr>
                                                            </table>
                                                        </div>
                                                    </div>
                                                </div>


                                            </div>
                                        </div>

                                    </td>
                                </tr>
                                <tr>

                                </tr>
                                <tr>
                                    <td>
                                        <div class="clearfix"></div>
                                        <div class="clearfix form-actions float-right">
                                            <div class="col-md-offset-1 col-md-10">
                                                <button class="btn btn-info" id="subMitButton" type="submit">
                                                    Save
                                                </button>
                                                &nbsp; &nbsp; &nbsp;

                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            </table>





                        </div>

                    </form>
                </div>
                <!-- /.card-body -->
                <div class="card-footer">

                </div>
            </div>
        </div>
        <!-- /.col-->
    </div>

    <div class="modal fade" id="addCustomerModel" tabindex="-1" role="dialog" aria-labelledby="addCustomerModelLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addCustomerModelLabel">Add Customer</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="POST" id="addCustomerFOrm" action="<?php echo e(route('sale.sale.quiceAddCustomer')); ?>">
                    <?php echo csrf_field(); ?>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="validationCustom01">Company Name *:</label>
                                    <input type="text" name="co_name" class="form-control" id="validationCustom01"
                                        placeholder="Company Name" value="<?php echo e(old('co_name')); ?>">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="validationCustom01">Customer Group Name *:</label>
                                    <select name="customergroup_id" class="form-control select2">
                                        <option value="0">Not Applicable</option>
                                        <?php $__currentLoopData = $customerGroup; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $data): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($data->id); ?>"><?php echo e($data->name); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="validationCustom01">Contact Person:</label>
                                    <input type="text" name="name" class="form-control" id="validationCustom01"
                                        placeholder="Contact Person" value="<?php echo e(old('name')); ?>">
                                </div>
                            </div>
                            <div class="col-md-2 mb-3">
                                <label for="validationCustom01">Branch * :</label>

                                <select class="form-control select2" id="branch_id" name="branch_id">

                                    <?php $__currentLoopData = $branch; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $value): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <?php if($value->id == 2): ?>
                                            <option value="<?php echo e($value->id); ?>"
                                                <?php echo e($saletlist->branch_id == $value->id ? 'selected' : ''); ?>>
                                                <?php echo e($value->branchCode . ' - ' . $value->name); ?>

                                            </option>
                                        <?php endif; ?>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                                <?php $__errorArgs = ['branch_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <span class="error text-red text-bold"><?php echo e($message); ?></span>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="validationCustom02">E-mail:</label>
                                    <input type="text" name="email" class="form-control" id="validationCustom02"
                                        placeholder="E-mail" value="<?php echo e(old('email')); ?>" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="validationCustom01">Phone:</label>
                                    <input type="text" name="phone" class="form-control" id="validationCustom01"
                                        placeholder="Phone" value="<?php echo e(old('phone')); ?>" required>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="validationCustom02">Address:</label>
                                    <input name="address" class="form-control" id="validationCustom02"
                                        placeholder="Address" value="<?php echo e(old('address')); ?>" required>
                                </div>
                            </div>
                             <div class="col-md-6 mb-3">

                            <div class="form-group">
                                <label>Image</label>
                                <div class="file-input-wrapper">
                                    <input type="file" 
                                           id="voucher-input" 
                                           name="image" 
                                           accept="image/*,.pdf,.doc,.docx"
                                           class="<?php $__errorArgs = ['image'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>">
                                    <label for="voucher-input" class="file-input-label">
                                        <i class="fa fa-cloud-upload"></i>
                                        <div>Click to select file</div>
                                        <small>Images, PDF, DOC files supported</small>
                                    </label>
                                    <div class="file-name" id="file-name"></div>
                                </div>
                                <?php $__errorArgs = ['image'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <div class="invalid-feedback"><?php echo e($message); ?></div>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                
                                <!-- Image Preview Container -->
                                <div class="image-preview-container">
                                    <div class="image-preview" id="image-preview">
                                        <img id="preview-img" src="" alt="Preview">
                                        <button type="button" class="image-remove-btn" id="remove-image">
                                            <i class="fa fa-times"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="validationCustom07">Bin:</label>
                                    <input name="bin" class="form-control" id="validationCustom07" placeholder="Bin"
                                        value="<?php echo e(old('bin')); ?>">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">Save Customer</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script type="text/javascript">
      $(document).ready(function() {
    
    // File upload functionality
    $('#voucher-input').on('change', function(e) {
        const file = e.target.files[0];
        const fileName = $('#file-name');
        const imagePreview = $('#image-preview');
        const previewImg = $('#preview-img');
        
        if (file) {
            // Show file name
            fileName.text(file.name);
            
            // Check if file is an image
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImg.attr('src', e.target.result);
                    imagePreview.show();
                }
                reader.readAsDataURL(file);
            } else {
                // For non-image files, show file info
                imagePreview.hide();
                fileName.html(`<i class="fa fa-file"></i> ${file.name} (${(file.size / 1024).toFixed(2)} KB)`);
            }
            
            // Update label text
            $('.file-input-label').html(`
                <i class="fa fa-check-circle" style="color: #28a745;"></i>
                <div>File selected successfully</div>
                <small>Click to change file</small>
            `);
        }
    });

    // Remove image functionality
    $('#remove-image').on('click', function() {
        $('#voucher-input').val('');
        $('#image-preview').hide();
        $('#file-name').text('');
        $('.file-input-label').html(`
            <i class="fa fa-cloud-upload"></i>
            <div>Click to select file</div>
            <small>Images, PDF, DOC files supported</small>
        `);
    });

    // Drag and drop functionality
    $('.file-input-label').on('dragover', function(e) {
        e.preventDefault();
        $(this).addClass('drag-over');
    });

    $('.file-input-label').on('dragleave', function(e) {
        e.preventDefault();
        $(this).removeClass('drag-over');
    });

    $('.file-input-label').on('drop', function(e) {
        e.preventDefault();
        $(this).removeClass('drag-over');
        
        const files = e.originalEvent.dataTransfer.files;
        if (files.length > 0) {
            $('#voucher-input')[0].files = files;
            $('#voucher-input').trigger('change');
        }
    });

    // Global variables
    let advanceRowIndex = 0;
    let isProcessingAdvanceOperation = false;
    let deletionInProgress = false;
    
    let alertMessage = {
        error: function(msg) {
            alert('Error: ' + msg);
            console.error(msg);
        },
        confirm: function(msg, onConfirm, onCancel = null) {
            if (confirm(msg)) {
                if (typeof onConfirm === 'function') {
                    onConfirm();
                }
            } else {
                if (typeof onCancel === 'function') {
                    onCancel();
                }
            }
        },
        success: function(msg) {
            alert('Success: ' + msg);
            console.log(msg);
        }
    };

    // Initialize Select2 dropdowns
    $('.select2').select2({
        placeholder: function() {
            return $(this).data('placeholder') || 'Select an option';
        },
        allowClear: true
    });

    // Product list functionality
    window.getProductList = function(cat_id) {
        var branch_id = $('#branch_id').val();

        if (branch_id == null) {
            alertMessage.error('Branch is not selected');
            return;
        }

        $.ajax({
            "url": "/admin/getProductListForSale",
            "type": "GET",
            cache: false,
            data: {
                "_token": $('meta[name="csrf-token"]').attr('content'),
                cat_id: cat_id,
                branch_id: branch_id
            },
            beforeSend: function() {
                $('#productID').prop('disabled', true);
                $('#productID').html('<option>Loading...</option>');
            },
            success: function(data) {
                $('#productID').prop('disabled', false);
                $('#productID').select2();
                $('#productID option').remove();
                $('#productID').append(
                    '<option disabled selected>---Select Product---</option>');
                $('#productID').append($(data));
                $("#productID").trigger("select2:updated");
            },
            error: function(xhr, status, error) {
                $('#productID').prop('disabled', false);
                alertMessage.error('Failed to load products: ' + error);
            }
        });
    };

    // Get unit price and stock information
    window.getUnitPrice = function(productId) {
        let branch_id = $('#branch_id option:selected').val();
        let purchasetype = $('.purchasetype option:selected').val();

        if (!productId) {
            return;
        }

        // Get unit price
        $.ajax({
            "url": "<?php echo e(route('sale.sale.saleunitPrice')); ?>",
            "type": "GET",
            cache: false,
            data: {
                "_token": $('meta[name="csrf-token"]').attr('content'),
                'productId': productId,
            },
            success: function(data) {
                $("#unitpice").val(data.sale_price || '');
                $(".purchaseprice").html("Last PP: " + (data.lastPurchasePrice || 'N/A'));
            },
            error: function(xhr, status, error) {
                alertMessage.error('Failed to get unit price: ' + error);
            }
        });

        // Get product stock
        if (purchasetype && branch_id) {
            $.ajax({
                "url": "/sale/sale/getProductStock",
                "type": "GET",
                cache: false,
                data: {
                    "_token": $('meta[name="csrf-token"]').attr('content'),
                    productId: productId,
                    type: purchasetype,
                    branch_id: branch_id,
                },
                success: function(data) {
                    $("#currentStock").val(data || 0);
                },
                error: function(xhr, status, error) {
                    console.warn('Failed to get stock: ' + error);
                }
            });
        }
    };

    // Calculate quantity and price
    window.qtyPriceCal = function() {
        var qty = parseFloat($('#qty').val()) || 0;
        var unitprice = parseFloat($('#unitpice').val()) || 0;
        var currentStock = parseFloat($('#currentStock').val()) || 0;

        // Validate stock
        if (qty > currentStock && currentStock > 0) {
            alertMessage.error(`Insufficient stock! Available: ${currentStock}`);
            $('#qty').val(currentStock);
            qty = currentStock;
        }

        var total = unitprice * qty;
        document.getElementById('total').value = total.toFixed(2);
    };

    // Add item functionality
    $("#add_item").click(function() {
        // Get all input values
        var catId = $('.catName').val();
        var catName = $(".catName").find('option:selected').attr('catName');
        var team = $('.team').val();
        var proId = $('.proName').val();
        var proName = $(".proName").find('option:selected').attr('proName');
        var purchasetypeval = $('.purchasetype').find('option:selected').val();
        var purchasetypetext = $('.purchasetype').find('option:selected').text();
        var qty = parseFloat($('.qty').val()) || 0;
        var unitprice = parseFloat($('.unitprice').val()) || 0;
        var total = parseFloat($('.total').val()) || 0;
        var patmentType = $('input[name="payment_type"]:checked').val();
        var customer_id = $('#ledger_id').val();
        var currentStock = parseFloat($('#currentStock').val()) || 0;

        // Validation
        if (!catId) {
            alertMessage.error("Category can't be empty.");
            return false;
        }
        if (!proId) {
            alertMessage.error("Product can't be empty.");
            return false;
        }
        if (!team) {
            alertMessage.error("Team can't be empty.");
            return false;
        }
        if (!purchasetypeval) {
            alertMessage.error("Please Select Fabrics Type.");
            return false;
        }
        if (unitprice <= 0) {
            alertMessage.error("Unit price can't be empty or zero.");
            $('.unitprice').focus();
            return false;
        }
        if (qty <= 0) {
            alertMessage.error("Quantity can't be empty or zero.");
            $('#qty').focus();
            return false;
        }
        if (qty > currentStock && currentStock > 0) {
            alertMessage.error(`Insufficient stock! Available: ${currentStock}`);
            $('#qty').focus();
            return false;
        }
        if (!customer_id) {
            alertMessage.error("Please select a Customer.");
            $('#ledger_id').focus();
            return false;
        }
        if (!patmentType) {
            alertMessage.error("Please select Payment Type.");
            return false;
        }

        if (total === 0) {
            total = qty * unitprice;
        }

        // Generate unique identifier for the row
        var uniqueId = 'item_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);

        // Add new row to table with unique class
        var newRow = `
            <tr class="dynamic-item" data-item-id="${uniqueId}">
                <td align="right">
                    ${catName}
                    <input type="hidden" name="catName[]" value="${catId}">
                </td>
                <td align="right">
                    ${proName}
                    <input type="hidden" class="add_quantity" name="proName[]" value="${proId}">
                </td>
                <td align="right">
                    ${team}
                    <input type="hidden" name="team[]" value="${team}">
                </td>
                <td align="right">
                    ${purchasetypetext}
                    <input type="hidden" name="purchasetype[]" value="${purchasetypeval}">
                </td>
                <td align="right">
                    <input type="number" class="update-qty form-control" name="qty[]" value="${qty}" 
                           data-product-id="${proId}" data-unit-price="${unitprice}" data-max-stock="${currentStock}"
                           min="1" step="1" style="text-align: right;">
                </td>
                <td align="right" style="position: relative;">
                    <input type="number" step="0.01" class="ttlunitprice unitparice form-control" name="unitprice[]" value="${unitprice}">
                </td>
                <td align="right">
                    <span class="total-price-display">${total.toFixed(2)}</span>
                    <input type="hidden" class="grandtotal" name="price[]" value="${total}">
                </td>
                <td>
                    <a del_id="${uniqueId}" class="delete_item btn form-control btn-danger" href="javascript:;" title="Remove Item">
                        <i class="fa fa-times"></i>
                    </a>
                </td>
            </tr>
        `;

        $("#show_item tbody").append(newRow);

        // Clear input fields
        clearProductInputs();

        // Recalculate totals
        recalculateAllTotals();
        checkDepositAndCreditBalance();
    });

    // Delete item from the list
    $(document).on('click', '.delete_item', function() {
        const $deleteBtn = $(this);

        alertMessage.confirm('Are you sure you want to remove this item?', function() {
            var deleteId = $deleteBtn.attr("del_id");
            var $rowToDelete = $deleteBtn.closest('tr');

            // Remove the row
            $rowToDelete.remove();

            // Recalculate totals after deletion
            recalculateAllTotals();
            checkDepositAndCreditBalance();
        });
    });

    // Unit price editing functionality
    $(document).on('dblclick', '.unit-price-display', function() {
        const $span = $(this);
        const $row = $span.closest('tr');
        const currentPrice = parseFloat($span.text()) || 0;

        // Prevent multiple edit inputs
        if ($row.find('.edit-unit-price').length > 0) {
            return;
        }

        // Create input field
        const $input = $(
            '<input type="number" class="form-control edit-unit-price" step="0.01" min="0" style="width: 100%; display: inline-block;">'
        );
        $input.val(currentPrice.toFixed(2));

        // Hide span and show input
        $span.hide();
        $span.after($input);
        $input.focus().select();

        // Handle save on blur, enter, or escape
        $input.on('blur keydown', function(e) {
            // Save on blur or Enter key
            if (e.type === 'blur' || e.which === 13) {
                saveUnitPrice($input, $span, $row);
            }
            // Cancel on Escape key
            else if (e.which === 27) {
                cancelUnitPriceEdit($input, $span);
            }
        });
    });

    $(document).on('click', '.unit-price-edit-btn', function() {
        const $btn = $(this);
        const $row = $btn.closest('tr');
        const $span = $row.find('.unit-price-display');
        const currentPrice = parseFloat($span.text()) || 0;

        // Prevent multiple edit inputs
        if ($row.find('.edit-unit-price').length > 0) {
            return;
        }

        // Create input field
        const $input = $(
            '<input type="number" class="form-control edit-unit-price" step="0.01" min="0" style="width: 80%; display: inline-block;">'
        );
        $input.val(currentPrice.toFixed(2));

        // Create save and cancel buttons
        const $saveBtn = $(
            '<button type="button" class="btn btn-sm btn-success ml-1 save-price-btn"><i class="fa fa-check"></i></button>'
        );
        const $cancelBtn = $(
            '<button type="button" class="btn btn-sm btn-secondary ml-1 cancel-price-btn"><i class="fa fa-times"></i></button>'
        );

        // Hide span and show input with buttons
        $span.hide();
        $span.after($input).after($saveBtn).after($cancelBtn);
        $btn.hide();
        $input.focus().select();

        // Save button click
        $saveBtn.on('click', function() {
            saveUnitPrice($input, $span, $row, $btn, $saveBtn, $cancelBtn);
        });

        // Cancel button click
        $cancelBtn.on('click', function() {
            cancelUnitPriceEdit($input, $span, $btn, $saveBtn, $cancelBtn);
        });

        // Handle Enter and Escape keys
        $input.on('keydown', function(e) {
            if (e.which === 13) { // Enter
                saveUnitPrice($input, $span, $row, $btn, $saveBtn, $cancelBtn);
            } else if (e.which === 27) { // Escape
                cancelUnitPriceEdit($input, $span, $btn, $saveBtn, $cancelBtn);
            }
        });
    });

    // Save unit price function
    function saveUnitPrice($input, $span, $row, $btn = null, $saveBtn = null, $cancelBtn = null) {
        const newPrice = parseFloat($input.val()) || 0;
        const qty = parseFloat($row.find('.update-qty').val()) || parseFloat($row.find(
            'input[name="qty[]"]').val()) || 0;

        // Validate price
        if (newPrice < 0) {
            alertMessage.error('Unit price cannot be negative');
            $input.focus();
            return;
        }

        // Update displays and hidden inputs
        $span.text(newPrice.toFixed(2)).show();
        $row.find('input[name="unitprice[]"]').val(newPrice.toFixed(2));

        // Update quantity input data attribute if exists
        const $qtyInput = $row.find('.update-qty');
        if ($qtyInput.length) {
            $qtyInput.data('unit-price', newPrice);
        }

        // Calculate and update total for this row
        updateRowTotal($row, qty, newPrice);

        // Clean up edit elements
        $input.remove();
        if ($saveBtn) $saveBtn.remove();
        if ($cancelBtn) $cancelBtn.remove();
        if ($btn) $btn.show();

        // Show success message
        alertMessage.success('Unit price updated successfully');
    }

    // Cancel unit price edit function
    function cancelUnitPriceEdit($input, $span, $btn = null, $saveBtn = null, $cancelBtn = null) {
        // Clean up edit elements
        $input.remove();
        if ($saveBtn) $saveBtn.remove();
        if ($cancelBtn) $cancelBtn.remove();
        if ($btn) $btn.show();

        // Show original span
        $span.show();
    }

    // Handle quantity changes
    $(document).on('input change', '.update-qty', function() {
        const $row = $(this).closest('tr');
        const newQty = parseFloat($(this).val()) || 0;
        const unitPrice = parseFloat($row.find('input[name="unitprice[]"]').val()) || 0;
        const maxStock = parseFloat($(this).data('max-stock')) || 0;

        // Validate quantity
        if (newQty < 0) {
            $(this).val(1);
            alertMessage.error('Quantity cannot be negative');
            return;
        }

        // Check stock if available
        if (maxStock > 0 && newQty > maxStock) {
            alertMessage.error(`Quantity cannot exceed available stock (${maxStock})`);
            $(this).val(maxStock);
            updateRowTotal($row, maxStock, unitPrice);
            return;
        }

        updateRowTotal($row, newQty, unitPrice);
    });

    // Handle unit price input changes
    $(document).on('input change', 'input[name="unitprice[]"]', function() {
        const $row = $(this).closest('tr');
        const newUnitPrice = parseFloat($(this).val()) || 0;
        const qty = parseFloat($row.find('.update-qty').val()) || parseFloat($row.find(
            'input[name="qty[]"]').val()) || 0;

        // Update display
        $row.find('.unit-price-display').text(newUnitPrice.toFixed(2));

        updateRowTotal($row, qty, newUnitPrice);
    });

    // Update row total function
    function updateRowTotal($row, qty, unitPrice) {
        const newTotal = qty * unitPrice;

        // Update total display and hidden input
        $row.find('.total-price-display').text(newTotal.toFixed(2));
        $row.find('input[name="price[]"]').val(newTotal.toFixed(2));

        // Recalculate all totals
        recalculateAllTotals();
    }

    // Recalculate all totals
    function recalculateAllTotals() {
        var grandTotal = 0;
        var totalQty = 0;
        var totalUnitPrice = 0;

        // Sum all quantities, unit prices, and totals from existing items
        $('#show_item tbody tr:not(:first)').each(function() {
            var $row = $(this);

            // Get quantity
            var qty = parseFloat($row.find('.update-qty').val()) ||
                parseFloat($row.find('input[name="qty[]"]').val()) || 0;
            totalQty += qty;

            // Get unit price
            var unitPrice = parseFloat($row.find('input[name="unitprice[]"]').val()) || 0;
            totalUnitPrice += unitPrice;

            // Get total price
            var total = parseFloat($row.find('input[name="price[]"]').val()) || 0;
            grandTotal += total;
        });

        // Update footer totals
        $('.ttlqty').text(totalQty.toFixed(0));
        $('.ttlunitprice').text(totalUnitPrice.toFixed(2));
        $('.grandtotal').not('input').text(grandTotal.toFixed(2));
        $('#gtoal').text(grandTotal.toFixed(2));

        // Calculate net total with adjustments
        calculateNetTotal(grandTotal);
    }

    // Calculate net total with all adjustments
    function calculateNetTotal(grandTotal = null) {
        if (grandTotal === null) {
            grandTotal = parseFloat($('#gtoal').text()) || 0;
        }

        var discount = parseFloat($('#disCount').val()) || 0;
        var carrying_cost = parseFloat($('#carrying_cost').val()) || 0;
        var labor_bill = parseFloat($('#labor_bill').val()) || 0;
        var totalAdvance = calculateAdvanceTotal();
        var previous_due = parseFloat($('#previouse_due_amount').val()) || 0;

        var netTotal = grandTotal - discount + carrying_cost + labor_bill + previous_due - totalAdvance;
        $('#ntotal').text(netTotal.toFixed(2));
        $('#totalDue').text(netTotal.toFixed(2));

        // Update payment if cash
        var paymentType = $('input[name="payment_type"]:checked').val();
        if (paymentType == "Cash") {
            $('#payment').val(netTotal.toFixed(2));
            if (typeof paymentCalculation === 'function') {
                paymentCalculation(netTotal);
            }
        }
    }

    // Discount calculation
    window.discountCalculation = function(amount) {
        var gtoal = parseFloat(document.getElementById("gtoal").innerText) || 0;

        if (gtoal < parseFloat(amount)) {
            alertMessage.error("Discount can't be greater than total amount");
            $('#disCount').val('');
            calculateNetTotal();
            return;
        }

        calculateNetTotal();
    };

    // Carrying cost calculation
    window.carrying_cost_Calculation = function(amount) {
        calculateNetTotal();
    };

    // Labor bill calculation
    window.labor_bill_Calculation = function(amount) {
        calculateNetTotal();
    };

    // Payment calculation
    window.paymentCalculation = function(payamount) {
        var ntotal = parseFloat(document.getElementById("ntotal").innerText) || 0;
        var totalDue = ntotal - payamount;
        $('.finalDue').text(totalDue.toFixed(2));
    };

    // ===========================================
    // FIXED ADVANCE PAYMENT FUNCTIONALITY
    // ===========================================

    // Add new advance payment row with improved event handling
    $('#addAdvanceBtn').off('click').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        if (isProcessingAdvanceOperation) {
            return false;
        }
        
        isProcessingAdvanceOperation = true;
        addAdvanceRow();
        
        setTimeout(() => {
            isProcessingAdvanceOperation = false;
        }, 100);
    });

    // Remove advance payment row with fixed event handling
    $(document).off('click', '.remove-advance').on('click', '.remove-advance', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        const $btn = $(this);
        
        // Prevent multiple rapid clicks
        if (deletionInProgress || $btn.hasClass('processing')) {
            return false;
        }
        
        deletionInProgress = true;
        $btn.addClass('processing');
        
        const index = $btn.data('index');
        
        // Check if this is the last row
        const totalRows = $('.advance-row').length;
        if (totalRows <= 1) {
            alertMessage.error('At least one advance payment row must remain');
            deletionInProgress = false;
            $btn.removeClass('processing');
            return false;
        }
        
        alertMessage.confirm('Are you sure you want to remove this advance payment?', 
            function() {
                // Confirmed - proceed with deletion
                removeAdvanceRowSafe(index);
            },
            function() {
                // Cancelled - reset flags
                deletionInProgress = false;
                $btn.removeClass('processing');
            }
        );
    });

    // Calculate advance total on input change
    $(document).on('input keyup', '.advance-amount', function() {
        calculateAdvanceTotal();
        calculateNetTotal();
    });

    // Validate advance ledger selection
    $(document).on('change', '.advance-ledger', function() {
        validateAdvanceRows();
    });

    // Add new advance payment row with unique indexing
    function addAdvanceRow() {
        // Use timestamp + random to ensure uniqueness
        const uniqueIndex = Date.now() + Math.floor(Math.random() * 1000);
        advanceRowIndex = uniqueIndex;

        const newRow = `
            <div class="advance-row mb-2" data-index="${uniqueIndex}">
                <div class="row">
                    <div class="col-md-5">
                        <select name="advance_ledger_id[${uniqueIndex}]" 
                                class="form-control select2 advance-ledger" 
                                data-index="${uniqueIndex}">
                            <option value="">--Select Account--</option>
                            ${getAccountOptions()}
                        </select>
                    </div>
                    <div class="col-md-5">
                        <input type="text" 
                               autocomplete="off"
                               class="form-control advance-amount"
                               name="advance[${uniqueIndex}]"
                               data-index="${uniqueIndex}"
                               style="text-align: right"
                               placeholder="0.00"
                              
                               onkeyup="calculateAdvanceTotal()" />
                    </div>
                    <div class="col-md-2">
                        <button type="button" 
                                class="btn btn-sm btn-danger remove-advance" 
                                data-index="${uniqueIndex}">
                            <i class="fa fa-minus"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;

        $('#advanceContainer').append(newRow);

        // Initialize Select2 for the new row
        $(`[data-index="${uniqueIndex}"] .select2`).select2({
            placeholder: "--Select Account--",
            allowClear: true
        });

        // Show remove buttons for all rows if more than one exists
        updateRemoveButtonsVisibility();
    }

    // Safe remove advance payment row
    function removeAdvanceRowSafe(index) {
        const $rowToDelete = $(`.advance-row[data-index="${index}"]`);
        
        if ($rowToDelete.length === 0) {
            deletionInProgress = false;
            return;
        }
        
        const totalRows = $('.advance-row').length;
        if (totalRows <= 1) {
            alertMessage.error('Cannot delete the last remaining advance payment row');
            deletionInProgress = false;
            return;
        }
        
        $rowToDelete.fadeOut(300, function() {
            $(this).remove();
            
            // Recalculate totals
            calculateAdvanceTotal();
            calculateNetTotal();
            
            // Update remove buttons visibility
            updateRemoveButtonsVisibility();
            
            // Reset deletion flag
            deletionInProgress = false;
        });
    }

    // Calculate total advance amount
    function calculateAdvanceTotal() {
        let totalAdvance = 0;

        $('.advance-amount').each(function() {
            const amount = parseFloat($(this).val()) || 0;
            totalAdvance += amount;
        });

        // Update display and hidden input
        $('#totalAdvanceAmount').text(totalAdvance.toFixed(2));
        $('#totalAdvanceHidden').val(totalAdvance.toFixed(2));

        return totalAdvance;
    }

    // Get account options HTML
    function getAccountOptions() {
        let options = '';

        $('.advance-ledger').first().find('option').each(function() {
            if ($(this).val() !== '') {
                options += `<option value="${$(this).val()}">${$(this).text()}</option>`;
            }
        });

        return options;
    }

    // Update remove buttons visibility
    function updateRemoveButtonsVisibility() {
        const totalRows = $('.advance-row').length;

        if (totalRows > 1) {
            $('.remove-advance').show().removeClass('d-none');
        } else {
            $('.remove-advance').hide().addClass('d-none');
        }
    }

    // Validate advance rows
    function validateAdvanceRows() {
        let isValid = true;
        let selectedLedgers = [];

        $('.advance-row').each(function() {
            const $row = $(this);
            const ledgerId = $row.find('.advance-ledger').val();
            const amount = parseFloat($row.find('.advance-amount').val()) || 0;

            if (ledgerId) {
                selectedLedgers.push(ledgerId);
            }
        });

        return isValid;
    }

    // ===========================================
    // CUSTOMER MANAGEMENT
    // ===========================================

    // Get customer balance based on payment type
    window.getCustomerBalance = function(paymentType) {
        var customer_id = $('#ledger_id').val();

        if (!customer_id) {
            return;
        }

        $.ajax({
            url: '/sale/sale/getCustomerBalance',
            type: 'GET',
            data: {
                '_token': $('meta[name="csrf-token"]').attr('content'),
                'customer_id': customer_id,
                'payment_type': paymentType
            },
            success: function(data) {
                $('#customer_currentBalance').val(data.balance || 0);
                $('#previous_due').text(data.previous_due || '0.00');
                $('#previouse_due_amount').val(data.previous_due || 0);
                calculateNetTotal();
                checkDepositAndCreditBalance();
            },
            error: function(xhr, status, error) {
                console.warn('Failed to get customer balance: ' + error);
            }
        });
    };

    // Quick add customer form submission
    $('#addCustomerFOrm').on('submit', function(e) {
        e.preventDefault();

        var formData = $(this).serialize();

        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: formData,
            beforeSend: function() {
                $('button[type="submit"]').prop('disabled', true);
            },
            success: function(response) {
                if (response.success) {
                    // Add new customer to ledger dropdown
                    $('#ledger_id').append(new Option(response.customer.name, response
                        .customer.id, true, true));

                    // Close modal and reset form
                    $('#addCustomerModel').modal('hide');
                    $('#addCustomerFOrm')[0].reset();

                    alertMessage.success('Customer added successfully');
                } else {
                    alertMessage.error(response.message || 'Failed to add customer');
                }
            },
            error: function(xhr, status, error) {
                var errorMessage = 'Failed to add customer';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMessage = xhr.responseJSON.message;
                }
                alertMessage.error(errorMessage);
            },
            complete: function() {
                $('button[type="submit"]').prop('disabled', false);
            }
        });
    });

    // ===========================================
    // UTILITY FUNCTIONS
    // ===========================================

    // Clear product input fields
    function clearProductInputs() {
        $(".catName").val(null).trigger("change");
        $(".proName").val(null).trigger("change");
        $(".purchasetype").val(null).trigger("change");
        $(".team").val("");
        $("#currentStock").val("");
        $("#qty").val("");
        $("#cty_size").val("");
        $("#gas_qty").val("");
        $(".unitprice").val("");
        $(".ttlamount").val("");
        $("#total").val("");
        $(".purchaseprice").html("");
    }

    // Check deposit and credit balance
    function checkDepositAndCreditBalance() {
        var paymentType = $("#paymentType").val() || 'Cash';
        var customer_currentBalance = parseFloat($("#customer_currentBalance").val()) || 0;
        var totalDue = parseFloat($("#totalDue").text()) || 0;
        var btn = document.getElementById('subMitButton');

        if ((paymentType == 'Deposit') && (customer_currentBalance < totalDue)) {
            btn.disabled = true;
            alertMessage.error('Insufficient deposit balance');
        } else {
            btn.disabled = false;
        }
    }

    // Format number to 2 decimal places
    function formatNumber(num) {
        return parseFloat(num || 0).toFixed(2);
    }

    // Validate numeric input
    function validateNumericInput(input) {
        var value = parseFloat(input) || 0;
        return value >= 0 ? value : 0;
    }

    // ===========================================
    // EVENT HANDLERS
    // ===========================================

    // Handle payment type change
    $('input[name="payment_type"]').on('change', function() {
        var paymentType = $(this).val();
        $('#paymentType').val(paymentType);

        if (paymentType === 'Cash') {
            $('.partisals').removeClass('d-none');
            $('#account_id').show();
        } else if (paymentType === 'Due') {
            $('.partisals').addClass('d-none');
            $('#account_id').show();
        } else {
            $('.partisals').addClass('d-none');
            $('#account_id').hide();
        }

        getCustomerBalance(paymentType);
        calculateNetTotal();
    });

    // Handle ledger change
    $('#ledger_id').on('change', function() {
        var paymentType = $('input[name="payment_type"]:checked').val();
        if (paymentType) {
            getCustomerBalance(paymentType);
        }
    });

    // Handle fabric type change
    $('.purchasetype').on('change', function() {
        var productId = $('#productID').val();
        if (productId) {
            getUnitPrice(productId);
        }
    });

    // Handle numeric input validation
    $(document).on('input', 'input[type="number"], .numeric-input', function() {
        var value = $(this).val();
        if (value < 0) {
            $(this).val(0);
        }
    });

    // Handle decimal input validation
    $(document).on('input', '.decimal-input', function() {
        this.value = this.value.replace(/[^0-9.]/g, '');
        this.value = this.value.replace(/(\..*)\./g, '$1');
    });

    // ===========================================
    // FORM VALIDATION AND SUBMISSION
    // ===========================================

    // Validate form before submission
    function validateForm() {
        var isValid = true;
        var errors = [];

        // Check if customer is selected
        if (!$('#ledger_id').val()) {
            errors.push('Please select a customer');
            isValid = false;
        }

        // Check if payment type is selected
        if (!$('input[name="payment_type"]:checked').val()) {
            errors.push('Please select payment type');
            isValid = false;
        }

        // Check if at least one item is added
        var itemCount = $('#show_item tbody tr:not(:first)').length;
        if (itemCount === 0) {
            errors.push('Please add at least one item');
            isValid = false;
        }

        // Validate advance payments
        if (!validateAdvanceRows()) {
            isValid = false;
        }

        // Display errors
        if (errors.length > 0) {
            alertMessage.error(errors.join('\n'));
        }

        return isValid;
    }

    // Get advance payment data in required format
    function getAdvancePaymentData() {
        const ledgerData = {};
        const amountData = {};

        $('.advance-row').each(function(index) {
            const $row = $(this);
            const ledgerId = $row.find('.advance-ledger').val();
            const amount = parseFloat($row.find('.advance-amount').val()) || 0;

            if (ledgerId && amount > 0) {
                ledgerData[index] = ledgerId;
                amountData[index] = amount.toString();
            }
        });

        return {
            ledgers: JSON.stringify(ledgerData),
            amounts: JSON.stringify(amountData)
        };
    }

    // Form submission handler
    $('form.needs-validation').on('submit', function(e) {
        // Validate form
        if (!validateForm()) {
            e.preventDefault();
            return false;
        }

        // Add hidden inputs with advance data in required format
        const advanceData = getAdvancePaymentData();

        // Remove existing hidden inputs if any
        $('input[name="advance_ledgers_json"]').remove();
        $('input[name="advance_amounts_json"]').remove();

        // Add new hidden inputs
        $(this).append(
            `<input type="hidden" name="advance_ledgers_json" value='${advanceData.ledgers}'>`);
        $(this).append(
            `<input type="hidden" name="advance_amounts_json" value='${advanceData.amounts}'>`);

        // Show loading state
        $('#subMitButton').prop('disabled', true).html(
            '<i class="fa fa-spinner fa-spin"></i> Saving...');

        return true;
    });

    // ===========================================
    // KEYBOARD SHORTCUTS
    // ===========================================

    // Handle keyboard shortcuts
    $(document).on('keydown', function(e) {
        // Alt + A to add item
        if (e.altKey && e.which === 65) {
            e.preventDefault();
            $('#add_item').click();
        }

        // Alt + S to save form
        if (e.altKey && e.which === 83) {
            e.preventDefault();
            $('form.needs-validation').submit();
        }

        // Alt + C to add customer
        if (e.altKey && e.which === 67) {
            e.preventDefault();
            $('#addCustomerModel').modal('show');
        }

        // Escape to clear form
        if (e.which === 27) {
            if (!$('.modal').hasClass('show')) {
                clearProductInputs();
            }
        }
    });

    // ===========================================
    // PRINT AND EXPORT FUNCTIONS
    // ===========================================

    // Print invoice
    window.printInvoice = function() {
        var printContent = $('.card-body').html();
        var printWindow = window.open('', '_blank');

        printWindow.document.write(`
            <html>
                <head>
                    <title>Invoice Print</title>
                    <style>
                        body { font-family: Arial, sans-serif; }
                        table { width: 100%; border-collapse: collapse; }
                        th, td { border: 1px solid #000; padding: 8px; text-align: left; }
                        .no-print { display: none; }
                        @media  print {
                            .no-print { display: none !important; }
                        }
                    </style>
                </head>
                <body>
                    ${printContent}
                </body>
            </html>
        `);

        printWindow.document.close();
        printWindow.focus();
        printWindow.print();
        printWindow.close();
    };

    // Export to Excel (requires XLSX library)
    window.exportToExcel = function() {
        if (typeof XLSX !== 'undefined') {
            var table = $('#show_item');
            var wb = XLSX.utils.table_to_book(table[0], {
                sheet: "Sale Details"
            });
            XLSX.writeFile(wb, "sale_invoice.xlsx");
        } else {
            alertMessage.error('XLSX library not loaded. Cannot export to Excel.');
        }
    };

    // ===========================================
    // SEARCH AND FILTER FUNCTIONS
    // ===========================================

    // Search products
    $('#productSearch').on('input', function() {
        var searchTerm = $(this).val().toLowerCase();

        $('#productID option').each(function() {
            var optionText = $(this).text().toLowerCase();
            if (optionText.includes(searchTerm) || searchTerm === '') {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });

    // Filter products by category
    $('#categoryFilter').on('change', function() {
        var categoryId = $(this).val();
        if (categoryId) {
            getProductList(categoryId);
        }
    });

    // ===========================================
    // BULK OPERATIONS
    // ===========================================

    // Select all items
    $('#selectAllItems').on('change', function() {
        var isChecked = $(this).is(':checked');
        $('.item-checkbox').prop('checked', isChecked);
    });

    // Delete selected items
    $('#deleteSelectedItems').on('click', function() {
        var selectedItems = $('.item-checkbox:checked');

        if (selectedItems.length === 0) {
            alertMessage.error('Please select items to delete');
            return;
        }

        alertMessage.confirm(
            `Are you sure you want to delete ${selectedItems.length} selected items?`,
            function() {
                selectedItems.each(function() {
                    $(this).closest('tr').find('.delete_item').click();
                });
            });
    });

    // Apply discount to selected items
    $('#applyBulkDiscount').on('click', function() {
        var selectedItems = $('.item-checkbox:checked');
        var discountPercent = parseFloat($('#bulkDiscountPercent').val()) || 0;

        if (selectedItems.length === 0) {
            alertMessage.error('Please select items to apply discount');
            return;
        }

        if (discountPercent <= 0 || discountPercent > 100) {
            alertMessage.error('Please enter valid discount percentage (1-100)');
            return;
        }

        selectedItems.each(function() {
            var $row = $(this).closest('tr');
            var currentPrice = parseFloat($row.find('input[name="unitprice[]"]').val()) || 0;
            var discountAmount = (currentPrice * discountPercent) / 100;
            var newPrice = currentPrice - discountAmount;

            $row.find('input[name="unitprice[]"]').val(newPrice.toFixed(2));
            $row.find('.unit-price-display').text(newPrice.toFixed(2));

            var qty = parseFloat($row.find('.update-qty').val()) || 0;
            updateRowTotal($row, qty, newPrice);
        });

        alertMessage.success(`Discount applied to ${selectedItems.length} items`);
    });

    // ===========================================
    // AUTO-SAVE FUNCTIONALITY
    // ===========================================

    let autoSaveTimer;

    // Auto-save draft
    function autoSaveDraft() {
        var formData = $('form.needs-validation').serialize();

        $.ajax({
            url: '/sale/sale/autosave',
            type: 'POST',
            data: formData + '&is_draft=1',
            success: function(response) {
                if (response.success) {
                    $('#autoSaveStatus').text('Draft saved at ' + new Date()
                    .toLocaleTimeString());
                }
            },
            error: function() {
                $('#autoSaveStatus').text('Auto-save failed');
            }
        });
    }

    // Start auto-save timer
    function startAutoSave() {
        autoSaveTimer = setInterval(autoSaveDraft, 30000); // Save every 30 seconds
    }

    // Stop auto-save timer
    function stopAutoSave() {
        if (autoSaveTimer) {
            clearInterval(autoSaveTimer);
        }
    }

    // ===========================================
    // INITIALIZATION
    // ===========================================

    // Initialize all components
    function initializeComponents() {
        // Initialize Select2
        $('.select2').select2({
            placeholder: function() {
                return $(this).data('placeholder') || 'Select an option';
            },
            allowClear: true
        });

        // Initialize date pickers if library is available
        if (typeof $.fn.datetimepicker !== 'undefined') {
            $('.datetimepicker-input').datetimepicker({
                format: 'YYYY-MM-DD',
                defaultDate: new Date()
            });
        }

        // Initialize tooltips
        if (typeof $.fn.tooltip !== 'undefined') {
            $('[data-toggle="tooltip"]').tooltip();
        }

        // Set up advance payments
        updateRemoveButtonsVisibility();
        calculateAdvanceTotal();

        // Calculate initial totals
        recalculateAllTotals();

        // Start auto-save if enabled
        if ($('#enableAutoSave').is(':checked')) {
            startAutoSave();
        }

        // Load existing data if in edit mode
        if ($('#editMode').val() === '1') {
            // Load existing advance data if available
            var existingAdvanceData = $('#existingAdvanceData').val();
            if (existingAdvanceData) {
                try {
                    var advanceData = JSON.parse(existingAdvanceData);
                    loadExistingAdvanceData(advanceData.ledgers, advanceData.amounts);
                } catch (e) {
                    console.warn('Failed to load existing advance data:', e);
                }
            }
        }
    }

    // Load existing advance data (for edit mode)
    function loadExistingAdvanceData(ledgerData, amountData) {
        try {
            const ledgers = typeof ledgerData === 'string' ? JSON.parse(ledgerData) : ledgerData;
            const amounts = typeof amountData === 'string' ? JSON.parse(amountData) : amountData;

            // Clear existing rows except the first one
            $('.advance-row:not(:first)').remove();

            let isFirstRow = true;
            for (const [index, ledgerId] of Object.entries(ledgers)) {
                const amount = amounts[index] || '0';

                if (isFirstRow) {
                    // Update first row
                    $(`.advance-row[data-index="0"] .advance-ledger`).val(ledgerId).trigger('change');
                    $(`.advance-row[data-index="0"] .advance-amount`).val(amount);
                    isFirstRow = false;
                } else {
                    // Add new row
                    addAdvanceRow();
                    $(`.advance-row[data-index="${advanceRowIndex}"] .advance-ledger`).val(ledgerId)
                        .trigger('change');
                    $(`.advance-row[data-index="${advanceRowIndex}"] .advance-amount`).val(amount);
                }
            }

            // Calculate total
            calculateAdvanceTotal();
            calculateNetTotal();

        } catch (error) {
            console.error('Error loading advance data:', error);
            alertMessage.error('Error loading existing advance payment data');
        }
    }

    // ===========================================
    // GLOBAL FUNCTION ASSIGNMENTS
    // ===========================================

    // Make functions available globally
    window.calculateAdvanceTotal = calculateAdvanceTotal;
    window.loadExistingAdvanceData = loadExistingAdvanceData;
    window.getAdvancePaymentData = getAdvancePaymentData;
    window.validateAdvancePayments = validateAdvanceRows;
    window.calculateNetTotal = calculateNetTotal;
    window.recalculateAllTotals = recalculateAllTotals;
    window.clearProductInputs = clearProductInputs;
    window.updateRowTotal = updateRowTotal;

    // ===========================================
    // RESPONSIVE AND UI ENHANCEMENTS
    // ===========================================

    // Handle window resize
    $(window).on('resize', function() {
        // Adjust table responsiveness
        if ($(window).width() < 768) {
            $('.table-responsive').addClass('table-sm');
        } else {
            $('.table-responsive').removeClass('table-sm');
        }
    });

    // Add loading states
    function showLoading($element) {
        $element.addClass('loading').prop('disabled', true);
        $element.find('i').removeClass().addClass('fa fa-spinner fa-spin');
    }

    function hideLoading($element, originalIcon = 'fa-plus') {
        $element.removeClass('loading').prop('disabled', false);
        $element.find('i').removeClass().addClass(`fa ${originalIcon}`);
    }

    // Enhanced error highlighting
    function highlightError($element) {
        $element.addClass('error-highlight');
        setTimeout(() => {
            $element.removeClass('error-highlight');
        }, 3000);
    }

    function highlightSuccess($element) {
        $element.addClass('success-highlight');
        setTimeout(() => {
            $element.removeClass('success-highlight');
        }, 2000);
    }

    // ===========================================
    // CUSTOM STYLING
    // ===========================================

    // Add custom CSS for better UI
    $('<style>')
        .prop('type', 'text/css')
        .html(`
            .advance-row {
                border-left: 3px solid #28a745;
                padding-left: 10px;
                margin-bottom: 10px;
                transition: all 0.3s ease;
            }
            .advance-row:hover {
                background-color: #f8f9fa;
                border-radius: 5px;
            }
            #totalAdvanceAmount {
                color: #28a745;
                font-weight: bold;
                font-size: 1.1em;
            }
            .remove-advance {
                transition: all 0.3s ease;
            }
            .remove-advance:hover {
                background-color: #dc3545 !important;
                border-color: #dc3545 !important;
                transform: scale(1.1);
            }
            .remove-advance.processing {
                opacity: 0.6;
                pointer-events: none;
            }
            #addAdvanceBtn:hover {
                background-color: #218838 !important;
                border-color: #1e7e34 !important;
                transform: scale(1.05);
            }
            .unit-price-display {
                cursor: pointer;
                position: relative;
            }
            .unit-price-display:hover {
                background-color: #e9ecef;
                border-radius: 3px;
                padding: 2px 4px;
            }
            .edit-unit-price {
                border: 2px solid #007bff !important;
                box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
            }
            .dynamic-item {
                animation: slideIn 0.3s ease-in-out;
            }
            @keyframes  slideIn {
                from {
                    opacity: 0;
                    transform: translateY(-10px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }
            .loading {
                opacity: 0.6;
                pointer-events: none;
            }
            .error-highlight {
                border: 2px solid #dc3545 !important;
                box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
                animation: shake 0.82s cubic-bezier(.36,.07,.19,.97) both;
            }
            .success-highlight {
                border: 2px solid #28a745 !important;
                box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
            }
            @keyframes  shake {
                10%, 90% { transform: translate3d(-1px, 0, 0); }
                20%, 80% { transform: translate3d(2px, 0, 0); }
                30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
                40%, 60% { transform: translate3d(4px, 0, 0); }
            }
            #autoSaveStatus {
                position: fixed;
                top: 10px;
                right: 10px;
                padding: 5px 10px;
                background: #28a745;
                color: white;
                border-radius: 3px;
                font-size: 12px;
                z-index: 9999;
                display: none;
            }
            .table-responsive {
                box-shadow: 0 0 20px rgba(0,0,0,0.1);
                border-radius: 8px;
            }
            @media (max-width: 768px) {
                .advance-row .col-md-5,
                .advance-row .col-md-2 {
                    margin-bottom: 10px;
                }
            }
        `)
        .appendTo('head');

    // Initialize everything when document is ready
    initializeComponents();

    // Handle page unload
    $(window).on('beforeunload', function() {
        stopAutoSave();
    });

    // Add console log for debugging
    console.log('Product Management System initialized successfully');
    console.log('Advance payment functionality enabled with deletion protection');
});
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('backend.layouts.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH E:\jubayer\resources\views/backend/pages/sale/edit.blade.php ENDPATH**/ ?>