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

<?php $__env->stopSection(); ?>

<?php $__env->startSection('styles'); ?>
    <style>
        .bootstrap-switch-large {
            width: 200px;
        }
    </style>
    <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</a></li>
                        <?php endif; ?>
                        <li class="breadcrumb-item active"><span>Sale List</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 Invoice</h3>
                </div>
                <div class="card-body">
                    <form class="needs-validation" method="POST" id="salveForm" action="<?php echo e(route('sale.sale.store')); ?>"
                        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($invoice_no); ?> "
                                    for="validationCustom01">
                                <input type="hidden" name="invoice_no" class="form-control" id=""
                                    value="<?php echo e($invoice_no); ?>">
                            </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(date('YYYY-mm-dd')); ?>" 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 selected value="<?php echo e($value->id); ?>">
                                                <?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]]); ?>
<?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)]); ?>
<?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')" checked id="option3" autocomplete="off">
                                        Due
                                    </label>
                                    
                                    

                                </div>
                                <input type="hidden" id="paymentType">
                                <input type="hidden" id="expireData">
                            </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">
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="padding: 10px!important;">
                                        <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"
                                                                        id="">
                                                                        <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>
                                                                <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"
                                                                            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>
                                                            </tbody>
                                                            <tfoot>
                                                                <tr>
                                                                    <td align="right"><strong class=""></strong>
                                                                    </td>
                                                                    <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="ttlqty"></strong>
                                                                    </td>
                                                                    <td align="right"><strong
                                                                            class="ttlunitprice"></strong>
                                                                    </td>
                                                                    <td align="right"><strong
                                                                            class="grandtotal"></strong>
                                                                    </td>
                                                                    <td align="right"><strong class=""></strong>
                                                                    </td>
                                                                </tr>
                                                            </tfoot>


                                                            <div class="col-md-12">
                                                                <table class="">
                                                                    <tr>
                                                                        <td>
                                                                            <textarea cols="50" class="form-control" name="narration" placeholder="Note......" type="text">
                                                                                    </textarea>
                                                                            <div id="customeNote">

                                                                            </div>

                                                                        </td>

                                                                        <td>
                                                                            <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"></strong>
                                                                                                </td>
                                                                                            </tr>
                                                                                            <tr>
                                                                                                <td nowrap align="right">
                                                                                                    <strong>Previous Due
                                                                                                    </strong>
                                                                                                </td>
                                                                                                <td align="right"> <strong
                                                                                                        id="previous_due">0</strong>
                                                                                                    <input type="hidden"
                                                                                                        id="previouse_due_amount"
                                                                                                        name="previouse_due_amount">
                                                                                                </td>
                                                                                            </tr>
                                                                                            <tr>
                                                                                                <td nowrap align="right">
                                                                                                    <strong>Discount ( -
                                                                                                        )</strong>
                                                                                                </td>
                                                                                                <td>
                                                                                                    <div
                                                                                                        class="input-group">
                                                                                                        <input
                                                                                                            type="text"
                                                                                                            autocomplete="off"
                                                                                                            onkeyup="discountCalculation(this.value)"
                                                                                                            id="disCount"
                                                                                                            style="text-align: right"
                                                                                                            name="discount"
                                                                                                            value=""
                                                                                                            class="form-control"
                                                                                                            placeholder="0.00"
                                                                                                            oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" />
                                                                                                        <select
                                                                                                            id="discountType"
                                                                                                            class="form-control"
                                                                                                            onchange="discountCalculation(document.getElementById('disCount').value)">
                                                                                                            <option
                                                                                                                value="flat">
                                                                                                                Flat
                                                                                                            </option>
                                                                                                            <option
                                                                                                                value="percentage">
                                                                                                                Percentage
                                                                                                            </option>
                                                                                                        </select>
                                                                                                    </div>
                                                                                                </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"
                                                                                                        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"
                                                                                                        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 id="netTotal">
                                                                                                <td nowrap align="right">
                                                                                                    <strong>Net
                                                                                                        Total</strong>
                                                                                                </td>
                                                                                                <td align="right"><strong
                                                                                                        id="ntotal"
                                                                                                        class="grandtotal"></strong>
                                                                                                </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) -->
                                                                                                        <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.banck','data' => ['setAccounts' => $accounts]]); ?>
<?php $component->withName('banck'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes(['setAccounts' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($accounts)]); ?>
<?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"
                                                                                                                        autocomplete="off"
                                                                                                                        onkeyup="calculateAdvanceTotal()"
                                                                                                                        class="form-control advance-amount"
                                                                                                                        name="advance[0]"
                                                                                                                        data-index="0"
                                                                                                                        style="text-align: right"
                                                                                                                        placeholder="0.00"
                                                                                                                        oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" />
                                                                                                                </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>
                                                                                                    </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>

                                                                                            <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.banck','data' => ['setAccounts' => $accounts]]); ?>
<?php $component->withName('banck'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes(['setAccounts' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($accounts)]); ?>
<?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"
                                                                                                        value=""
                                                                                                        readonly
                                                                                                        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"></strong>
                                                                                                </td>
                                                                                            </tr>
                                                                                        </tbody>
                                                                                    </table>

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

                                                    </div>
                                    <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 float-right" id="subMitButton"
                                                    type="submit">
                                                    Save
                                                </button>
                                                &nbsp; &nbsp; &nbsp;

                                            </div>
                                        </div>
                                    </td>
                        </div>
                </div>

            </div>

            </td>
            </tr>

            </table>



        </div>

        </form>
    </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 d-none">
                                <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')); ?>" required>
                                </div>
                            </div>
                            <div class="col-md-6 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($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')); ?>">
                                </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')); ?>">
                                </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() {
            // Initialize variables
            let advanceRowIndex = 0;


            $('#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');
                }
            });

            // Ledger change handler for previous due amount
            $('#ledger_id').on('change', function() {
                var ledgerId = $(this).val();

                if (ledgerId) {
                    $.ajax({
                        url: '<?php echo e(route('sale.sale.olddueamount')); ?>',
                        type: 'GET',
                        data: {
                            account_id: ledgerId
                        },
                        success: function(response) {
                            $("#previous_due").text(response.due);
                            $("#previouse_due_amount").val(response.due);
                            $("#customeNote").html(
                                `<textarea cols="50" class="form-control"  placeholder="Note......" type="text">${response.customer ?? ''}</textarea>`
                            );
                            updateTotals(); // Recalculate totals when previous due changes
                        },
                        error: function(xhr) {
                            console.error('Error:', xhr.responseText);
                        }
                    });
                }
            });

            // Form submission handler
            $('#salveForm').on('submit', function(e) {
                e.preventDefault();

                var ledgerId = $('#ledger_id').val();
                var branchId = $('#branch_id').val();

                if (!ledgerId) {
                    alertMessage.error("Please Select Customer");
                    $("#subMitButton").prop("disabled", false);
                    return;
                }
                if (!branchId) {
                    alertMessage.error("Please Select Branch");
                    $("#subMitButton").prop("disabled", false);
                    return;
                }

                // Validate advance payments
                if (!validateAdvancePayments()) {
                    $("#subMitButton").prop("disabled", false);
                    return;
                }

                $(this).off('submit').submit();
            });

            // Customer form submission handler
            $('#addCustomerFOrm').on('submit', function(e) {
                e.preventDefault();

                const form = $(this);
                const formData = form.serialize();

                // Clear previous errors
                form.find('.text-danger').remove();
                form.find('.is-invalid').removeClass('is-invalid');

                $.ajax({
                    url: form.attr('action'),
                    method: 'POST',
                    data: formData,
                    success: function(response) {
                        if (response.success) {
                            $('#addCustomerModel').modal('hide');
                            $('select[name="ledger_id"]').append(
                                `<option value="${response.accounts.id}" selected>${response.accounts.account_name} (${response.customer.phone})</option>`
                            );
                            form[0].reset();
                        } else {
                            alert('Unexpected error occurred.');
                        }
                    },
                    error: function(xhr) {
                        form.find("button[type='submit']").prop('disabled', false);

                        if (xhr.status === 422) {
                            const errors = xhr.responseJSON.errors;
                            for (const field in errors) {
                                const input = form.find(`[name="${field}"]`);
                                input.addClass('is-invalid');
                                input.after(
                                    `<span class="text-danger">${errors[field][0]}</span>`);
                            }
                        } else {
                            alert('Something went wrong. Please try again.');
                        }
                    }
                });

                form.find("button[type='submit']").prop('disabled', true);
            });

            // Quantity calculation for main form
            $('#cty_size, #qty').on('input', function() {
                let ctyval = $('#cty_size').val();
                let qty = $('#qty').val();
                let gas_qty = ctyval * qty;
                $('#gas_qty').val(gas_qty);
            });

            // Branch change handler
            $('#branch_id').on('change', function() {
                $(".proName").val(null).trigger("change");
            });

            // Add item functionality
            $("#add_item").click(function() {
                let seaschproduct = $('#productID option:selected')[0].getAttribute("value");
                let tbody = $('tbody').find(".new_item" + seaschproduct).length;

                var purchasetypeval = $('.purchasetype').find('option:selected').val();
                var purchasetypetext = $('.purchasetype').find('option:selected').text();
                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 qty = $('.qty').val();
                var vat = parseFloat($('#vat').val()) || 0;
                var patmentType = $('input[name="payment_type"]:checked').val();
                var customer_id = $('#ledger_id').val();
                var unitprice = $('.unitprice').val();
                var total = $('.total').val();

                // Validation checks
                if (catId == '' || catId == null) {
                    alertMessage.error("Category can't be empty.");
                    return false;
                }
                if (proId == '' || proId == null) {
                    alertMessage.error("Product can't be empty.");
                    return false;
                }
                if (team == '' || team == null) {
                    alertMessage.error("Team can't be empty.");
                    return false;
                }
                if (purchasetypeval == '' || purchasetypeval == null) {
                    alertMessage.error("Please Select Type.");
                    return false;
                }
                if (unitprice == '' || unitprice == null || parseFloat(unitprice) <= 0) {
                    alertMessage.error("Unit price can't be empty or zero.");
                    return false;
                }
                if (qty == '' || qty == null || qty == 0) {
                    alertMessage.error("Quantity can't be empty or zero.");
                    return false;
                }
                if (customer_id === null) {
                    alertMessage.error("Please select a Customer.");
                    return false;
                }
                if (patmentType === undefined) {
                    alertMessage.error("Please select Payment Type.");
                    return false;
                }

                // Add new row with editable quantity and unit price
                $("#show_item tbody").append(
                    '<tr class="new_item' + proId + '">' +
                    '<td style="padding-left:15px;">' +
                    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" class="" name="team[]" value="' + team + '">' +
                    '</td>' +
                    '<td align="right">' +
                    purchasetypetext +
                    '<input type="hidden" class="add_quantity" name="purchasetype[]" value="' +
                    purchasetypeval + '">' +
                    '</td>' +
                    '<td align="right">' +
                    '<input type="number" class="ttlqty form-control" min="1" step="1" name="qty[]" value="' +
                    qty + '" style="text-align:right;">' +
                    '</td>' +
                    '<td align="right">' +
                    '<input type="number" class="ttlunitprice form-control unitparice" min="0" step="0.01" name="unitprice[]" value="' +
                    unitprice + '" style="text-align:right;">' +
                    '</td>' +
                    '<td align="right">' +
                    total +
                    '<input type="hidden" class="grandtotal" name="total[]" value="' + total + '">' +
                    '</td>' +
                    '<td>' +
                    '<a del_id="' + proId +
                    '" class="delete_item btn form-control btn-danger" href="javascript:;" title="Remove Item">' +
                    '<i class="fa fa-times"></i>' +
                    '</a>' +
                    '</td>' +
                    '</tr>'
                );

                // Clear form fields
                $(".proName").val(null).trigger("change");
                $("#currentStock").val("");
                $("#qty").val("");
                $("#cty_size").val("");
                $("#gas_qty").val("");
                $(".unitprice").val("");
                $(".ttlamount").val("");

                findqtyamount();
                findunitamount();
                findgrandtottal();
                checkDepositAndCreditBalance();
                updateTotals();
            });

            // Delete item handler
            $(document).on('click', '.delete_item', function() {
                let deleteitem = () => {
                    var id = $(this).attr("del_id");
                    $('.new_item' + id).remove();
                    findqtyamount();
                    findunitamount();
                    findgrandtottal();
                    checkDepositAndCreditBalance();
                    updateTotals();
                }

                alertMessage.confirm('You want to remove this item?', deleteitem);
            });

            // Event handler for quantity change in added rows
            $(document).on('input change', '.ttlqty', function() {
                var currentRow = $(this).closest('tr');
                var qty = parseFloat($(this).val()) || 0;

                if (qty <= 0) {
                    alertMessage.error("Quantity must be greater than 0");
                    $(this).val(1);
                    qty = 1;
                }

                calculateRowTotal(currentRow);
            });

            // Event handler for unit price change in added rows
            $(document).on('input change', '.unitparice', function() {
                var currentRow = $(this).closest('tr');
                var unitPrice = parseFloat($(this).val()) || 0;

                if (unitPrice <= 0) {
                    alertMessage.error("Unit price must be greater than 0");
                    $(this).val(0);
                    return;
                }

                calculateRowTotal(currentRow);
            });

            // Discount calculation event handlers
            $('#disCount').on('input', function() {
                var discountValue = $(this).val();
                discountCalculation(discountValue);
            });

            $('#discountType').on('change', function() {
                var discountValue = $('#disCount').val();
                discountCalculation(discountValue);
            });

            // Other calculation event handlers
            $('#carrying_cost').on('input', function() {
                var carryingCost = $(this).val();
                carrying_cost_Calculation(carryingCost);
            });

            $('#labor_bill').on('input', function() {
                var laborBill = $(this).val();
                labor_bill_Calculation(laborBill);
            });

            // MULTIPLE ADVANCE PAYMENT FUNCTIONALITY

            // Add new advance row
            $('#addAdvanceBtn').on('click', function() {
                advanceRowIndex++;

                const newRow = `
            <div class="advance-row mb-2" data-index="${advanceRowIndex}">
                <div class="row">
                    <div class="col-md-5">
                        <select name="advance_ledger_id[${advanceRowIndex}]" class="form-control select2 advance-ledger" data-index="${advanceRowIndex}">
                            <option value="">--Select Account--</option>
                              <?php if (isset($component)) { $__componentOriginalc254754b9d5db91d5165876f9d051922ca0066f4 = $component; } ?>
<?php $component = $__env->getContainer()->make(Illuminate\View\AnonymousComponent::class, ['view' => 'components.banck','data' => ['setAccounts' => $accounts]]); ?>
<?php $component->withName('banck'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes(['setAccounts' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($accounts)]); ?>
<?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"
                            autocomplete="off"
                            class="form-control advance-amount"
                            name="advance[${advanceRowIndex}]"
                            data-index="${advanceRowIndex}"
                            style="text-align: right"
                            placeholder="0.00"
                             />
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-sm btn-danger remove-advance" data-index="${advanceRowIndex}">
                            <i class="fa fa-minus"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;

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

                // Initialize select2 for the new select element
                $(`.advance-ledger[data-index="${advanceRowIndex}"]`).select2();

                // Show remove button for all rows if more than one exists
                updateRemoveButtons();
            });

            // Remove advance row
            $(document).on('click', '.remove-advance', function() {
                const index = $(this).data('index');
                $(`.advance-row[data-index="${index}"]`).remove();
                calculateAdvanceTotal();
                updateRemoveButtons();
            });

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

            // Payment type change handler
            $('input[name="payment_type"]').on('change', function() {
                var paymentType = $(this).val();
                getCustomerBalance(paymentType);
            });

            // Payment calculation handler
            $('#payment').on('input', function() {
                var paymentAmount = $(this).val();
                paymentCalculation(paymentAmount);
            });
        });

   
        var findqtyamount = function() {
            var ttlqty = 0;
            $('.ttlqty').each(function() {
                var qty = parseFloat($(this).val()) || 0;
                ttlqty += qty;
            });
            $('.ttlqty').text(parseFloat(ttlqty).toFixed(2));
        };

        // Calculate total unit price
        var findunitamount = function() {
            var ttlunitprice = 0;
            $('.ttlunitprice').each(function() {
                var unitprice = parseFloat($(this).val()) || 0;
                ttlunitprice += unitprice;
            });
            $('.ttlunitprice').text(parseFloat(ttlunitprice).toFixed(2));
        };

        // Calculate grand total
        var findgrandtottal = function() {
            var grandtotal = 0;
            $('.grandtotal').each(function() {
                var total = parseFloat($(this).val()) || 0;
                grandtotal += total;
            });

            $('.grandtotal').text(parseFloat(grandtotal).toFixed(2));

            var paymentType = $('input[name="payment_type"]:checked').val();
            if (paymentType == "Cash") {
                $('#payment').val(parseFloat(grandtotal).toFixed(2));
                paymentCalculation(parseFloat(grandtotal));
            }
        };

        // Function to calculate row total based on qty and unit price
        function calculateRowTotal(row) {
            var qty = parseFloat(row.find('.ttlqty').val()) || 0;
            var unitPrice = parseFloat(row.find('.unitparice').val()) || 0;
            var total = qty * unitPrice;

            // Update the hidden total input and display
            row.find('.grandtotal').val(total.toFixed(2));
            row.find('td:nth-child(7)').html(
                total.toFixed(2) +
                '<input type="hidden" class="grandtotal" name="total[]" value="' + total.toFixed(2) + '">'
            );

            // Recalculate all totals
            findqtyamount();
            findunitamount();
            findgrandtottal();
            checkDepositAndCreditBalance();
            updateTotals();
        }

        // Updated gamount function to handle multiple advances
        function gamount() {
            var gtoal = parseFloat(document.getElementById("gtoal").innerText) || 0;
            var carrying_cost = parseFloat($("#carrying_cost").val()) || 0;
            var discount = parseFloat($("#disCount").val()) || 0;
            var labor_bill = parseFloat($("#labor_bill").val()) || 0;
            var totalAdvance = parseFloat($("#totalAdvanceHidden").val()) || 0;
            var previouse_due_amount = parseFloat($("#previouse_due_amount").val()) || 0;

            // Handle discount type
            var discountType = document.getElementById("discountType") ? document.getElementById("discountType").value :
                'flat';
            if (discountType === "percentage") {
                discount = (gtoal * discount) / 100;
            }

            return ((gtoal + carrying_cost + previouse_due_amount + labor_bill) - discount - totalAdvance);
        }

        // Discount calculation
        function discountCalculation(amount) {
            var gtoal = parseFloat(document.getElementById("gtoal").innerText) || 0;
            var discountType = document.getElementById("discountType") ? document.getElementById("discountType").value :
                'flat';
            var discount = parseFloat(amount) || 0;

            if (discountType === "percentage") {
                if (discount > 100) {
                    alertMessage.error("Percentage discount cannot exceed 100%");
                    $('#disCount').val('');
                    updateTotals();
                    return;
                }
                var calculatedDiscount = (gtoal * discount) / 100;
                if (calculatedDiscount > gtoal) {
                    alertMessage.error("Discount amount cannot be greater than the total amount");
                    $('#disCount').val('');
                    updateTotals();
                    return;
                }
            } else {
                if (discount > gtoal) {
                    alertMessage.error("Discount cannot be greater than the total amount");
                    $('#disCount').val('');
                    updateTotals();
                    return;
                }
            }

            updateTotals();
        }

        // Carrying cost calculation
        function carrying_cost_Calculation(amount) {
            updateTotals();
        }

        // Labor bill calculation
        function labor_bill_Calculation(amount) {
            updateTotals();
        }

        // New unified function to update all totals
        function updateTotals() {
            var finalAmount = gamount();
            $('#ntotal').text(parseFloat(finalAmount).toFixed(2));
            $('#totalDue').text(parseFloat(finalAmount).toFixed(2));

            var paymentType = $('input[name="payment_type"]:checked').val();
            if (paymentType === "Cash") {
                $('#payment').val(finalAmount.toFixed(2));
                paymentCalculation(finalAmount);
            }
        }

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

        // Quantity and price calculation for main form
        function qtyPriceCal() {
            var qty = parseFloat($('#qty').val()) || 0;
            var unitpice = parseFloat($('#unitpice').val()) || 0;
            var vat = parseFloat($('#vat').val()) || 0;

            var totalWithoutVAT = unitpice * qty;
            var vatAmount = (vat > 0) ? (vat / 100) * totalWithoutVAT : 0;
            var totalWithVAT = totalWithoutVAT + vatAmount;
            document.getElementById('total').value = totalWithVAT.toFixed(2);
        }

        // MULTIPLE ADVANCE PAYMENT FUNCTIONS

        // Function to show/hide remove buttons
        function updateRemoveButtons() {
            const totalRows = $('.advance-row').length;
            if (totalRows > 1) {
                $('.remove-advance').show();
            } else {
                $('.remove-advance').hide();
            }
        }

        // Function to calculate total advance amount
        function calculateAdvanceTotal() {
            let total = 0;
            $('.advance-amount').each(function() {
                const value = parseFloat($(this).val()) || 0;
                total += value;
            });

            $('#totalAdvanceAmount').text(total.toFixed(2));
            $('#totalAdvanceHidden').val(total.toFixed(2));

            // Update the main calculation
            updateTotals();
        }

        // Validation function to check if advance payments are properly filled
        function validateAdvancePayments() {
            let isValid = true;
            let errorMessage = '';

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

                if ((ledger && !amount) || (!ledger && amount)) {
                    isValid = false;
                    errorMessage = 'Please select both account and amount for all advance payments.';
                    return false;
                }

                if (amount && parseFloat(amount) <= 0) {
                    isValid = false;
                    errorMessage = 'Advance amount must be greater than 0.';
                    return false;
                }
            });

            if (!isValid && errorMessage) {
                alertMessage.error(errorMessage);
            }

            return isValid;
        }

        // AJAX FUNCTIONS

        // Get product list based on category
        function getProductList(cat_id) {
            var branch_id = $('#branch_id').val();

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

            $.ajax({
                "url": "<?php echo e(route('sale.sale.getProductListForSale')); ?>",
                "type": "GET",
                cache: false,
                data: {
                    "_token": "<?php echo e(csrf_token()); ?>",
                    cat_id: cat_id,
                    branch_id: branch_id
                },
                success: function(data) {
                    $('#productID').select2();
                    $('#productID option').remove();
                    $('#productID').append($(data));
                    $("#productID").trigger("select2:updated");
                }
            });
        }

        // Get customer balance
        function getCustomerBalance(payment_type) {
            var customer_id = $('#ledger_id').val();
            if (!customer_id) {
                alertMessage.error('Please Select Customer');
                return;
            }
            $("#paymentType").val(payment_type);

            if (payment_type == 'Cash') {
                $('#account_id').show();
                $('#netTotal').show();
                $('.partisals').show();
                calculatetotal();
            } else {
                calculatetotal();
                $('.partisals').css('display', 'none');
                $('#account_id').css('display', 'none');
                $('#netTotal').css('display', 'none');
            }

            $.ajax({
                "url": "<?php echo e(route('sale.sale.getCustomerBalance')); ?>",
                "type": "GET",
                cache: false,
                dataType: "json",
                data: {
                    "_token": "<?php echo e(csrf_token()); ?>",
                    customer_id: customer_id,
                    payment_type: payment_type
                },
                success: function(data) {
                    if (payment_type == 'Cash') {
                        $("#customer_currentBalance").val('');
                    } else {
                        $("#customer_currentBalance").val(data.finalBalance);
                        $("#expireData").val(data.expireData);
                    }
                }
            });
        }

        // Get unit price for product
        function getUnitPrice(v) {
            let branch_id = $('#branch_id option:selected').val();
            let purchasetype = $('.purchasetype option:selected').val();
            let productId = $('#productID option:selected').val();

            $.ajax({
                "url": "<?php echo e(route('sale.sale.saleunitPrice')); ?>",
                "type": "GET",
                cache: false,
                data: {
                    "_token": "<?php echo e(csrf_token()); ?>",
                    'productId': productId,
                },
                success: function(data) {
                    $("#unitpice").val(data.sale_price);
                    $(".purchaseprice").html("Last PP :" + data.lastPurchasePrice);
                }
            });

            $.ajax({
                "url": "<?php echo e(route('sale.sale.getProductStock')); ?>",
                "type": "GET",
                cache: false,
                data: {
                    "_token": "<?php echo e(csrf_token()); ?>",
                    productId: productId,
                    type: purchasetype,
                    branch_id: branch_id,
                },
                success: function(data) {
                    $("#currentStock").val(data);
                }
            });
        }

        // ADDITIONAL HELPER FUNCTIONS

        // Check deposit and credit balance
        function checkDepositAndCreditBalance() {
            var paymentType = $("#paymentType").val();
            if (paymentType == '') {
                paymentType = 'Cash';
            }

            var customer_currentBalance = $("#customer_currentBalance").val();
            var totalDue = $("#totalDue").text();
            var expireDatas = $("#expireData").val();
            var todaysDate = new Date().toISOString().slice(0, 10);

            if (expireDatas == '') {
                expireDatas = todaysDate;
            }

            var btn = document.getElementById('subMitButton');
            if ((paymentType == 'Deposit') && (parseFloat(customer_currentBalance) < parseFloat(totalDue))) {
                btn.disabled = true;
            } else if (paymentType == 'Cash') {
                btn.disabled = false;
            } else {
                btn.disabled = false;
            }
        }

        // Calculate total function for compatibility
        var calculatetotal = function() {
            var grandtotal = 0;
            $('.grandtotal').each(function() {
                var total = parseFloat($(this).val()) || 0;
                grandtotal += total;
            });

            if (parseFloat(grandtotal) > 0) {
                $('.grandtotal').text(parseFloat(grandtotal).toFixed(2));
                var paymentType = $('input[name="payment_type"]:checked').val();
                if (paymentType == "Cash") {
                    $('#payment').val(parseFloat(grandtotal).toFixed(2));
                    paymentCalculation(parseFloat(grandtotal));
                }
            }
        };

        // Function to load existing advance payments when editing
        function loadAdvancePayments(saleId) {
            $.ajax({
                url: '/sale/advance-payments/' + saleId,
                type: 'GET',
                success: function(response) {
                    if (response.success && response.data.length > 0) {
                        // Clear existing rows except the first one
                        $('.advance-row:not(:first)').remove();

                        // Populate the data
                        response.data.forEach(function(advance, index) {
                            if (index === 0) {
                                // Update first row
                                $(`select[name="advance_ledger_id[0]"]`).val(advance.account_id)
                                    .trigger('change');
                                $(`input[name="advance[0]"]`).val(advance.amount);
                            } else {
                                // Add new rows
                                $('#addAdvanceBtn').click();
                                $(`select[name="advance_ledger_id[${index}]"]`).val(advance.account_id)
                                    .trigger('change');
                                $(`input[name="advance[${index}]"]`).val(advance.amount);
                            }
                        });

                        // Recalculate totals
                        calculateAdvanceTotal();
                    }
                },
                error: function(xhr) {
                    console.error('Error loading advance payments:', xhr.responseText);
                }
            });
        }

        // Function to get advance payments summary
        function getAdvancePaymentsSummary(saleId) {
            $.ajax({
                url: '/sale/advance-payments/' + saleId + '/summary',
                type: 'GET',
                success: function(response) {
                    if (response.success) {
                        $('#totalAdvanceAmount').text(response.total.toFixed(2));
                        $('#totalAdvanceHidden').val(response.total);
                        updateTotals();
                    }
                }
            });
        }

        // Show alert function
        function showAlert(message, type = 'info') {
            if (typeof alertMessage !== 'undefined') {
                alertMessage[type](message);
            } else {
                alert(message);
            }
        }

        // Check stock availability function
        function checkStockAvailability(productId, purchaseType, branchId, requestedQty, row) {
            $.ajax({
                url: "<?php echo e(route('sale.sale.getProductStock')); ?>",
                type: "GET",
                cache: false,
                data: {
                    "_token": "<?php echo e(csrf_token()); ?>",
                    productId: productId,
                    type: purchaseType,
                    branch_id: branchId,
                },
                success: function(availableStock) {
                    if (parseFloat(requestedQty) > parseFloat(availableStock)) {
                        alertMessage.warning('Requested quantity (' + requestedQty +
                            ') exceeds available stock (' + availableStock + ')');
                    }
                },
                error: function() {
                    console.log('Could not check stock availability');
                }
            });
        }
    </script>
<?php $__env->stopSection(); ?>

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