@extends('backend.layouts.master')

@section('title')
Settings - {{ $title }}
@endsection


@section('navbar-content')
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">
                    Swing Sale </h1>
            </div><!-- /.col -->
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="{{ route('home') }}">Dashboard</a></li>
                    @if (helper::roleAccess('sale.swing.index'))
                    <li class="breadcrumb-item"><a href="{{ route('sale.swing.index') }}">Swing Sale
                            List</a></li>
                    @endif
                    <li class="breadcrumb-item active"><span>Edit Swing Sale</span></li>
                </ol>
            </div><!-- /.col -->
        </div><!-- /.row -->
    </div><!-- /.container-fluid -->
</div>
@endsection

@section('admin-content')


<div class="row">
    <div class="col-md-12">
        <div class="card card-default">
            <div class="card-header">
                <h3 class="card-title">Swing Sale Edit</h3>
                <div class="card-tools">
                    @if (helper::roleAccess('sale.swing.create'))
                    <a class="btn btn-default" href="{{ route('sale.swing.create') }}"><i
                            class="fas fa-plus"></i>
                        Add New</a>
                    @endif
                    <span id="buttons"></span>

                    <a class="btn btn-tool btn-default" data-card-widget="collapse">
                        <i class="fas fa-minus"></i>
                    </a>
                    <a class="btn btn-tool btn-default" data-card-widget="remove">
                        <i class="fas fa-times"></i>
                    </a>
                </div>
            </div>
            <!-- /.card-header -->
            <div class="card-body">
                <form class="needs-validation" method="POST" action="{{ route('sale.swing.update',$saletlist->id) }}"
                    novalidate>
                    @csrf
                    <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="{{ $saletlist->invoice_no }} " for="validationCustom01">
                            <input type="hidden" name="invoice_no" class="form-control" id=""
                                value="{{ $saletlist->invoice_no }}">
                        </div>
                        <div class="col-md-2 mb-3 d-none">
                            <label for="validationCustom01">Po Number :</label>
                            <input type="text" name="po_invoice" class="form-control" value="{{ $saletlist->po_invoice }}">
                        </div>
                        <div class="col-md-2 mb-3 d-none">
                            <label>Po Date:</label>
                            <div class="input-group date" id="reservationdate1" data-target-input="nearest">
                                <input type="text" name="po_date" data-toggle="datetimepicker"
                                    value="{{ date('YYYY-mm-dd') }}" class="form-control datetimepicker-input"
                                    data-target="#reservationdate1" />
                                <div class="input-group-append" data-target="#reservationdate1"
                                    data-toggle="datetimepicker">
                                    <div class="input-group-text"><i class="fa fa-calendar"></i></div>
                                </div>
                            </div>
                            @error('date')
                            <span class=" error text-red text-bold">{{ $message }}</span>
                            @enderror
                        </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="{{ $saletlist->date }}" class="form-control datetimepicker-input"
                                    data-target="#reservationdate" />
                                <div class="input-group-append" data-target="#reservationdate"
                                    data-toggle="datetimepicker">
                                    <div class="input-group-text"><i class="fa fa-calendar"></i></div>
                                </div>
                            </div>
                            @error('date')
                            <span class=" error text-red text-bold">{{ $message }}</span>
                            @enderror
                        </div>
                        <div class="col-md-2 mb-3">
                            <label for="validationCustom01">Branch * :</label>

                            <select class="form-control select2" id="branch_id" name="branch_id">
                               
                                @foreach ($branch as $key => $value)
                                @if($value->id ==1)
                                <option value="{{ $value->id }}" {{$saletlist->branch_id == $value->id ? "selected":"" }} >
                                    {{ $value->branchCode . ' - ' . $value->name }}
                                </option>
                                @endif
                                @endforeach
                            </select>
                            @error('branch_id')
                            <span class="error text-red text-bold">{{ $message }}</span>
                            @enderror
                        </div>

                        {{-- <div class="col-md-2 mb-3">
                            <label for="validationCustom02">Sub-Warehouse * :</label>
                            <select class="form-control select2" id="sub_warehouse_id" name="sub_warehouse_id" >
                                <option selected disabled value="">--Select Sub-Warehouse--</option>
                                @foreach ($subWarehouses as $subWarehouse)
                                    <option value="{{ $subWarehouse->id }}" {{ $subWarehouse->id == $saletlist->branch_id ? 'selected' : '' }}>
                                        {{ $subWarehouse->name }}
                                    </option>
                                @endforeach
                            </select>
                            <!-- Loading spinner -->
                            <div id="loadingSpinner" style="display:none;">
                                <img src="https://i.pinimg.com/originals/5c/87/9a/5c879ab8cba794923686df4b950f497b.gif" alt="Loading..."  width="10%"/>
                            </div>
                            @error('sub_warehouse_id')
                            <span class="error text-red text-bold">{{ $message }}</span>
                            @enderror
                        </div> --}}

                        {{-- <div class="col-md-2 mb-3">
                            <label for="validationCustom01">Customer * :</label>
                            <select class="form-control select2" name="customer_id" id="customer_id">
                                <option selected disabled value="">--Select Customer--</option>
                                @foreach ($customer as $key => $value)
                                <option {{ $saletlist->customer_id == $value->id ? 'selected' : '' }}
                                    value="{{ $value->id }}">
                                    {{ $value->customerCode . ' - ' . $value->co_name }}
                                </option>
                                @endforeach
                            </select>
                            @error('customer_id')
                            <span class=" error text-red text-bold">{{ $message }}</span>
                            @enderror
                        </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>
                                <x-account :setAccounts="$ledgers" :selectVal="$saletlist->ledger_id"/>
                            </select>
                            @error('ledger_id')
                            <span class=" error text-red text-bold">{{ $message }}</span>
                            @enderror
                        </div>
                        {{-- <div class="col-md-2 mb-3">
                            <label for="validationCustom01">Balance * :</label>
                            <input type="text" id="customer_currentBalance" class="form-control" readonly>
                        </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 active">
                                    <input type="radio" name="payment_type" value="Cash"
                                        onchange="getCustomerBalance('Cash')" id="option1" {{$saletlist->payment_type ==
                                    "Cash" ? "checked":""}}> Cash
                                </label> --}}
                                {{-- <label class="btn bg-olive">
                                    <input type="radio" name="payment_type" value="Deposit"
                                        onchange="getCustomerBalance('Deposit')" id="option2" autocomplete="off"
                                        {{$saletlist->payment_type == "Deposit" ? "checked":""}}>
                                    Deposit
                                </label> --}}
                                <label class="btn bg-olive">
                                    <input type="radio" name="payment_type" value="Due"
                                        onchange="getCustomerBalance('Due')" {{$saletlist->payment_type ==
                                    "Due" ? "checked":""}} id="option3" autocomplete="off"> Due
                                </label>
                                {{-- <label class="btn bg-olive">
                                    <input type="radio" name="payment_type" value="Credit"
                                        onchange="getCustomerBalance('Credit')" id="option3" autocomplete="off"
                                        {{$saletlist->payment_type == "Credit" ? "checked":""}}> Credit
                                </label> --}}
                            </div>
                            <input type="hidden" id="paymentType">
                            <input type="hidden" id="expireData">
                            <input type="hidden" id="paymentypeValue" value="{{$saletlist->payment_type}}">
                        </div>
                        <table class=" table-responsive table table-bordered">
                            <tr>
                                <td>
                                    <div class="col-md-9 float-left ">
                                        Sales Item
                                    </div>
                                    <div class="col-md-3 float-right">
                                        Payment Calculation
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td style="padding: 10px!important;">
                                    <div class="row">
                                        <div class="col-md-12">
                                            <div class="col-md-12 float-left">
                                                <div class="panel panel-default">
                                                    <div class="panel-body">

                                                        <table class="table table-bordered table-hover tableAddItem"
                                                            id="show_item">
                                                            <thead>
                                                                <tr>
                                                                    
                                                                    <th nowrap style="width:15%" align="center"
                                                                        id="">
                                                                        <strong>Product <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:11%" align="center">
                                                                    <strong>Vat <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>
                                                                    

                                                                    {{-- Product --}}
                                                                    <td id="product_td">
                                                                         <select class="select2 form-control proName" id="productID"
                                                                    data-placeholder="Search Product" onchange="getUnitPrice(this.value)">
                                                                    <option value="">---Select Product---</option>
                                                                    @foreach ($products as $product)
                                                                        <option value="{{ $product->id }}" proName="{{ $product->name }}">
                                                                            {{ $product->name }}
                                                                        </option>
                                                                    @endforeach
                                                                </select>
                                                                        <span class="text-success purchaseprice"></span>
                                                                    </td>
                                                                    {{-- <td>
                                                                        <input type="text" class="form-control team"
                                                                            id="team">
                                                                    </td> --}}
                                                                    {{-- Fabrics --}}
                                                                    {{-- <td>
                                                                        <select class="select2 form-control purchasetype"
                                                                            name="fabrics[]"
                                                                            onchange="getUnitPrice(this.value)">
                                                                            <option selected disabled value="">--Select Fabrics--</option>
                                                                            @foreach ($fabricType as $key => $value)
                                                                            <option value="{{ $key }}">{{ $value }}</option>
                                                                            @endforeach
                                                                        </select>


                                                                        <span
                                                                            class="text-success purchasetypeerror"></span>
                                                                    </td> --}}


                                                                    {{-- Quantity --}}
                                                                    <td>
                                                                        {{-- <input type="text" readonly
                                                                            class="form-control" style="height: 20px;"
                                                                            id="currentStock" placeholder="0"> --}}
                                                                        <input type="text" class="form-control qty"
                                                                            id="qty" onkeyup="qtyPriceCal();"
                                                                            placeholder="0">
                                                                    </td>

                                                                    {{-- <td>
                                                                        <input type="number" readonly
                                                                            class="form-control" id="gas_qty"
                                                                            min="0" value="0"
                                                                            placeholder="0">
                                                                    </td> --}}

                                                                    {{-- <td>
                                                                        <input type="text"
                                                                            class="form-control text-right vat"
                                                                            id="vat" onkeyup="qtyPriceCal();"
                                                                            placeholder="0.00">
                                                                    </td> --}}

                                                                    {{-- Unit Price --}}
                                                                    <td>
                                                                        <input type="text"
                                                                            class="form-control text-right  unitprice"
                                                                            id="unitpice" onkeyup="qtyPriceCal();"
                                                                            placeholder="0.00">
                                                                    </td>

                                                                    {{-- Total Price --}}
                                                                    <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>
                                                                @foreach ($saledetails as $key => $value)

                                                                <tr class="new_item{{ $value->product_id }}">
                                                                   
                                                                    <td align="right">
                                                                        {{ $value->product->name ?? 'N/A'}}<input
                                                                            type="hidden" class="add_quantity"
                                                                            name="proName[]"
                                                                            value="{{ $value->product_id }}">
                                                                    </td>


                                                                    <td align="right">
                                                                <input type="number" class="update-qty form-control" name="qty[]" 
                                                                    value="{{ $value->qty }}" 
                                                                    data-product-id="{{ $value->product_id }}" 
                                                                    data-unit-price="{{ $value->rate }}"
                                                                    min="1" step="1">
                                                            </td>

                                                                    <td align="right">{{ $value->rate }}<input
                                                                            type="hidden"
                                                                            class="ttlunitprice unitparice"
                                                                            name="unitprice[]"
                                                                            value="{{ $value->rate }}">
                                                                    </td>
                                                                    @php
                                                                    $totale = $value->price;
                                                                    @endphp
                                                                    <td align="right">{{ $totale }}<input type="hidden"
                                                                            class="grandtotal total" name="price[]"
                                                                            value="{{ $totale }}">
                                                                    </td>
                                                                    <td><a del_id="{{ $key + 1 }}"
                                                                            class="delete_item btn form-control btn-danger"
                                                                            href="javascript:;" title=""><i
                                                                                class="fa fa-times"></i></a>
                                                                    </td>
                                                                </tr>
                                                                @endforeach

                                                            </tbody>
                                                            <tfoot>
                                                                <tr>
                                                                    <td align="right"><strong>Sub-Total(BDT)</strong>
                                                                    </td>
                                                                   

                                                                    <td align="
                                                                    right">
                                                                    <strong
                                                                    class="ttlqty">{{$saledetails->sum('qty')}}</strong>
                                                                </td>

                                                                <td align="right"><strong
                                                                    class="ttlunitprice">{{$saledetails->sum('rate')}}</strong>
                                                                </td>
                                                                    <td align="right"><strong
                                                                            class="grandtotal">{{$saledetails->sum('price')}}</strong>
                                                                    </td>
                                                                     <td align="right"><strong class=""></strong>
                                                                    </td>
                                                                </tr>
                                                            </tfoot>
                                                        </table>
                                                    </div>
                                                </div>
                                            </div>

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

                                                        <table class="table table-bordered table-hover ">
                                                            <tbody>
                                                                <tr>
                                                                    <td nowrap align="right"><strong>Total
                                                                        </strong>
                                                                    </td>
                                                                    <td align="right"> <strong id="gtoal"
                                                                            class="grandtotal">{{$saledetails->sum('price')}}.00</strong>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td nowrap align="right">
                                                                        <strong>Previous Due </strong>
                                                                    </td>
                                                                    <td align="right"> <strong id="previous_due">{{$saletlist->previouse_due_amount}}</strong>
                                                                        <input type="hidden" id="previouse_due_amount" value="{{$saletlist->previouse_due_amount}}" name="previouse_due_amount" >
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td nowrap align="right">
                                                                        <strong>Discount ( - )
                                                                        </strong>
                                                                    </td>
                                                                    <td><input type="text" autocomplete="off"
                                                                            onkeyup="discountCalculation(this.value)"
                                                                            id="disCount" style="text-align: right"
                                                                            name="discount"
                                                                            value="{{$saletlist->discount}}"
                                                                            class="form-control" placeholder="0.00"
                                                                            oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" />
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td nowrap align="right">
                                                                        <strong>Carrying Cost ( + )
                                                                        </strong>
                                                                    </td>
                                                                    <td><input type="text"
                                                                            autocomplete="off"
                                                                            onkeyup="carrying_cost_Calculation(this.value)"
                                                                            id="carrying_cost"
                                                                            style="text-align: right"
                                                                            name="carrying_cost"
                                                                            value="{{$saletlist->carrying_cost}}"
                                                                            class="form-control"
                                                                            placeholder="0.00"
                                                                            oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" />
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td nowrap align="right">
                                                                        <strong>Labor bill ( + )
                                                                        </strong>
                                                                    </td>
                                                                    <td><input type="text"
                                                                            autocomplete="off"
                                                                            onkeyup="labor_bill_Calculation(this.value)"
                                                                            id="labor_bill"
                                                                            value="{{$saletlist->labor_bill}}"
                                                                            style="text-align: right"
                                                                            name="labor_bill"
                                                                            class="form-control"
                                                                            placeholder="0.00"
                                                                            oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" />
                                                                    </td>
                                                                </tr>
                                                                                                      <tr>
                                                                        <td nowrap align="right">
                                                                            <strong>Advance Payments
                                                                                <button type="button"
                                                                                    class="btn btn-sm btn-success ml-2"
                                                                                    id="addAdvanceBtn">
                                                                                    <i class="fa fa-plus"></i>
                                                                                </button>
                                                                            </strong>
                                                                        </td>
                                                                        <td>
                                                                            <div id="advanceContainer">
                                                                                <!-- First advance row (default) -->
                                                                                @php
                                                                                    $advances =
                                                                                        json_decode(
                                                                                            $saletlist->advance,
                                                                                            true,
                                                                                        ) ?? [];
                                                                                    $advanceLedgers =
                                                                                        json_decode(
                                                                                            $saletlist->advance_ledger_id,
                                                                                            true,
                                                                                        ) ?? [];
                                                                                @endphp

                                                                                @forelse($advances as $index => $amount)
                                                                                    <div class="advance-row mb-2"
                                                                                        data-index="{{ $index }}">
                                                                                        <div class="row">
                                                                                            <div class="col-md-5">
                                                                                                <select
                                                                                                    name="advance_ledger_id[{{ $index }}]"
                                                                                                    class="form-control select2 advance-ledger"
                                                                                                    data-index="{{ $index }}">
                                                                                                    <option value="">
                                                                                                        --Select Account--
                                                                                                    </option>

                                                                                                    <x-banck
                                                                                                        :setAccounts="$accounts"
                                                                                                        :selectVal="$advanceLedgers[
                                                                                                            $index
                                                                                                        ]" />

                                                                                                </select>
                                                                                            </div>
                                                                                            <div class="col-md-5">
                                                                                                <input type="text"
                                                                                                    class="form-control advance-amount"
                                                                                                    name="advance[{{ $index }}]"
                                                                                                    value="{{ $amount }}"
                                                                                                    data-index="{{ $index }}"
                                                                                                    style="text-align: right"
                                                                                                    placeholder="0.00"
                                                                                                    oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');"
                                                                                                    onkeyup="calculateAdvanceTotal()" />
                                                                                            </div>
                                                                                            <div class="col-md-2">
                                                                                                <button type="button"
                                                                                                    class="btn btn-sm btn-danger remove-advance"
                                                                                                    data-index="{{ $index }}"
                                                                                                    {{ $loop->first ? 'style=display:none;' : '' }}>
                                                                                                    <i
                                                                                                        class="fa fa-minus"></i>
                                                                                                </button>
                                                                                            </div>
                                                                                        </div>
                                                                                    </div>
                                                                                @empty
                                                                                    {{-- Default empty row if no advance exists --}}
                                                                                    <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>
                                                                                                    <x-banck
                                                                                                        :setAccounts="$accounts"
                                                                                                        :selectVal="$saletlist->advance_ledger_id" />
                                                                                                </select>
                                                                                            </div>
                                                                                            <div class="col-md-5">
                                                                                                <input type="text"
                                                                                                    class="form-control advance-amount"
                                                                                                    name="advance[0]"
                                                                                                    data-index="0"
                                                                                                    placeholder="0.00"
                                                                                                    oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');"
                                                                                                    onkeyup="calculateAdvanceTotal()" />
                                                                                            </div>
                                                                                            <div class="col-md-2">
                                                                                                <button type="button"
                                                                                                    class="btn btn-sm btn-danger remove-advance"
                                                                                                    data-index="0"
                                                                                                    style="display: none;">
                                                                                                    <i
                                                                                                        class="fa fa-minus"></i>
                                                                                                </button>
                                                                                            </div>
                                                                                        </div>
                                                                                    </div>
                                                                                @endforelse

                                                                            </div>
                                                                            <!-- Total advance display -->
                                                                            <div class="mt-2">
                                                                                <strong>Total
                                                                                    Advance: <span
                                                                                        id="totalAdvanceAmount">0.00</span></strong>
                                                                                <input type="hidden"
                                                                                    id="totalAdvanceHidden"
                                                                                    name="total_advance" value="0">
                                                                            </div>
                                                                        </td>
                                                                    </tr>
                                                                @php
                                                                $discount = $saledetails->sum('price') - $saletlist->discount;
                                                                @endphp
                                                                <tr id="netTotal">
                                                                    <td nowrap align="right"><strong>Net Total</strong></td>
                                                                    <td align="right"><strong id="ntotal"
                                                                            class="grandtotal">{{$discount}}.00</strong>
                                                                    </td>
                                                                </tr>
                                                                <tr id="account_id" >
                                                                    <td nowrap align="right">
                                                                        <strong>Account <span
                                                                                style="color:red;"> * </span></strong>
                                                                    </td>
                                                                    <td>
                                                                        <select name="account_id" class="form-control select2">
                                                                            <option selected value="0">Due</option>
                                                                            <x-banck :setAccounts="$accounts" />
                                                                         </select>
                                                                    </td>
                                                                </tr>
                                                                <tr class="partisals d-none">
                                                                    <td nowrap align="right"><strong>Payment
                                                                            ( -
                                                                            )<span style="color:red;"> *
                                                                            </span></strong>
                                                                    </td>
                                                                    <td><input type="text" id="payment"
                                                                            onkeyup="paymentCalculation(this.value)"
                                                                            style="text-align: right"
                                                                            name="partialPayment" readonly
                                                                            value="{{$saletlist->partialPayment}}"
                                                                            class="form-control" autocomplete="off"
                                                                            placeholder="0.00"
                                                                            oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" />
                                                                    </td>
                                                                    <!-- <input type="hidden" id="duePayment" style="text-align: right" name="duePayment" value="" readonly class="form-control" placeholder="0.00" /> -->
                                                                </tr>

                                                                <tr>
                                                                    <td nowrap align="right"><strong>Total
                                                                            Due</strong>
                                                                    </td>
                                                                    <td align="right"><strong id="totalDue"
                                                                            class="grandtotal finalDue">{{$discount
                                                                            -
                                                                            $saletlist->partialPayment}}.00</strong>
                                                                    </td>
                                                                </tr>
                                                            </tbody>
                                                        </table>

                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-6 float-right">
                                                <div class="panel">
                                                    <div class="panel-body">
                                                        <table class="table ">
                                                            <tr>
                                                                <td>
                                                                    <textarea style="
                                                                                    border:none;" cols="157"
                                                                        class="form-control" name="narration"
                                                                        placeholder="Note......" type="text"></textarea>
                                                                </td>
                                                            </tr>
                                                        </table>
                                                    </div>
                                                </div>
                                            </div>


                                        </div>
                                    </div>

                                </td>
                            </tr>
                            <tr>

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

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





                    </div>

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

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

<div class="modal fade" id="addCustomerModel" tabindex="-1" role="dialog" aria-labelledby="addCustomerModelLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addCustomerModelLabel">Add Customer</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="POST" id="addCustomerFOrm" action="{{ route('sale.sale.quiceAddCustomer') }}">
                @csrf
                <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="{{ old('co_name') }}">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="validationCustom01">Customer Group Name *:</label>
                                <select name="customergroup_id" class="form-control select2">
                                    <option value="0">Not Applicable</option>
                                    @foreach ($customerGroup as $data)
                                        <option value="{{ $data->id }}">{{ $data->name }}</option>
                                    @endforeach
                                </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="{{ old('name') }}">
                            </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">
                                 
                                    @foreach ($branch as $key => $value)
                                    @if($value->id ==1)
                                        <option value="{{ $value->id }}">
                                            {{ $value->branchCode . ' - ' . $value->name }}
                                        </option>
                                        @endif
                                    @endforeach
                                </select>
                                @error('branch_id')
                                    <span class="error text-red text-bold">{{ $message }}</span>
                                @enderror
                            </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="{{ old('email') }}" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="validationCustom01">Phone:</label>
                                <input type="text" name="phone" class="form-control" id="validationCustom01" placeholder="Phone" value="{{ 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="{{ old('address') }}" required>
                            </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="{{ 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 page
    initializePage();
    
    // Event listeners
    setupEventListeners();
    
    // Initial calculations
    recalculateAllTotals();
    calculateAdvanceTotal();
});

function initializePage() {
    // Set initial payment type
    var payTypeID = $('#paymentypeValue').val();
    if (payTypeID) {
        getCustomerBalance(payTypeID);
    }
    
    // Initialize Select2
    $('.select2').select2();
    
    // Set up datetime pickers
    $('#reservationdate, #reservationdate1').datetimepicker({
        format: 'YYYY-MM-DD',
        defaultDate: new Date()
    });
}

function setupEventListeners() {
    // Product and quantity calculations
    $('#cty_size, #qty').on('input', handleSizeQtyChange);
    $('#qty, #unitpice, #vat').on('input', qtyPriceCal);
    
    // Payment calculations
    $('#disCount').on('input', function() {
        discountCalculation(this.value);
    });
    
    $('#carrying_cost').on('input', function() {
        carrying_cost_Calculation(this.value);
    });
    
    $('#labor_bill').on('input', function() {
        labor_bill_Calculation(this.value);
    });
    
    $('#payment').on('input', function() {
        paymentCalculation(this.value);
    });
    
    // Item management
    $("#add_item").on('click', addNewItem);
    $(document).on('click', '.delete_item', deleteItem);
    $(document).on('input', '.update-qty', updateRowQuantity);
    
    // Payment type changes
    $('input[name="payment_type"]').on('change', function() {
        getCustomerBalance(this.value);
    });
    
    // Customer/Ledger changes
    $('#ledger_id').on('change', function() {
        var customerId = this.value;
        if (customerId) {
            updateCustomerBalance(customerId);
        }
    });
    
    // Product selection
    $('#productID').on('change', function() {
        if (this.value) {
            getUnitPrice(this.value);
        }
    });
    
    // Branch selection
    $('#branch_id').on('change', function() {
        var branchId = this.value;
        if (branchId) {
            getProductList(branchId);
        }
    });
    
    // Advance payment management
    $('#addAdvanceBtn').on('click', addAdvanceRow);
    $(document).on('click', '.remove-advance', removeAdvanceRow);
    $(document).on('input', '.advance-amount', calculateAdvanceTotal);
    $(document).on('change', '.advance-ledger', validateAdvanceLedger);
    
    // Customer modal
    $('#addCustomerFOrm').on('submit', handleCustomerSubmit);
}

// ===== ITEM MANAGEMENT =====
function addNewItem() {
    let productId = $('#productID option:selected').val();
    let productName = $('#productID option:selected').text();
    let qty = parseFloat($('#qty').val()) || 0;
    let unitPrice = parseFloat($('#unitpice').val()) || 0;
    let vat = parseFloat($('#vat').val()) || 0;
    let total = parseFloat($('#total').val()) || 0;

    // Validation
    if (!validateNewItem(productId, qty, unitPrice)) {
        return false;
    }

    // Check for duplicate product
    if (checkDuplicateProduct(productId)) {
        showAlert('This product already exists', 'error');
        return false;
    }

    // Add new row
    var newRow = createNewItemRow(productId, productName, qty, unitPrice, vat, total);
    $("#show_item tbody").append(newRow);

    // Clear input fields
    clearItemInputs();

    // Update all totals
    recalculateAllTotals();
    checkDepositAndCreditBalance();
}

function validateNewItem(productId, qty, unitPrice) {
    if (!productId) {
        showAlert("Please select a product", 'error');
        return false;
    }
    
    if (qty <= 0) {
        showAlert("Quantity must be greater than 0", 'error');
        return false;
    }
    
    if (unitPrice <= 0) {
        showAlert("Unit price must be greater than 0", 'error');
        return false;
    }
    
    // Check stock availability
    let currentStock = parseFloat($('#currentStock').val()) || 0;
    if (qty > currentStock) {
        showAlert('The desired product stock is not available', 'error');
        return false;
    }
    
    return true;
}

function checkDuplicateProduct(productId) {
    var exists = false;
    $('#show_item tbody tr:not(:first)').each(function() {
        var existingProId = $(this).find('input[name="proName[]"]').val();
        if (existingProId === productId) {
            exists = true;
            return false;
        }
    });
    return exists;
}

function createNewItemRow(productId, productName, qty, unitPrice, vat, total) {
    var vatAmount = (vat > 0) ? (vat / 100) * (qty * unitPrice) : 0;
    var finalTotal = (qty * unitPrice) + vatAmount;
    
    return '<tr class="new_item' + productId + '">' +
        '<td align="right">' +
            productName +
            '<input type="hidden" name="proName[]" value="' + productId + '">' +
        '</td>' +
        '<td align="right">' +
            '<input type="number" class="update-qty form-control" name="qty[]" value="' + qty + '" ' +
            'data-product-id="' + productId + '" data-unit-price="' + unitPrice + '" min="1" step="0.01">' +
        '</td>' +
        '<td align="right">' +
            unitPrice.toFixed(2) +
            '<input type="hidden" class="unitparice" name="unitprice[]" value="' + unitPrice + '">' +
        '</td>' +
        '<td align="right" class="row-total">' +
            finalTotal.toFixed(2) +
            '<input type="hidden" class="grandtotal" name="price[]" value="' + finalTotal + '">' +
        '</td>' +
        '<td>' +
            '<a del_id="' + productId + '" class="delete_item btn form-control btn-danger" href="javascript:;">' +
                '<i class="fa fa-times"></i>' +
            '</a>' +
        '</td>' +
    '</tr>';
}

function clearItemInputs() {
    $('#productID').val('').trigger('change');
    $('#qty').val('');
    $('#unitpice').val('');
    $('#vat').val('');
    $('#total').val('');
    $('#currentStock').val('');
    $('.purchaseprice').html('');
}

function updateRowQuantity() {
    var qty = parseFloat($(this).val()) || 0;
    var unitPrice = parseFloat($(this).data('unit-price')) || 0;
    var productId = $(this).data('product-id');
    var rowTotal = qty * unitPrice;
    
    // Update current row
    var row = $(this).closest('tr');
    row.find('.row-total').text(rowTotal.toFixed(2));
    row.find('input[name="price[]"]').val(rowTotal.toFixed(2));
    row.find('.grandtotal').val(rowTotal.toFixed(2));
    
    // Update all totals
    recalculateAllTotals();
}

function deleteItem() {
    var deleteAction = () => {
        var id = $(this).attr("del_id");
        $('.new_item' + id).remove();
        recalculateAllTotals();
        checkDepositAndCreditBalance();
    };
    
    if (typeof alertMessage !== 'undefined') {
        alertMessage.confirm('You want to remove this item?', deleteAction);
    } else {
        if (confirm('Are you sure you want to remove this item?')) {
            deleteAction();
        }
    }
}

// ===== CALCULATION FUNCTIONS =====
function recalculateAllTotals() {
    var totalQty = 0;
    var totalUnitPrice = 0;
    var grandTotal = 0;
    
    // Calculate from existing rows
    $('#show_item tbody tr').each(function() {
        var qtyInput = $(this).find('.update-qty, input[name="qty[]"]');
        var priceInput = $(this).find('input[name="price[]"], .grandtotal');
        
        if (qtyInput.length && priceInput.length) {
            var qty = parseFloat(qtyInput.val()) || 0;
            var price = parseFloat(priceInput.val()) || 0;
            var unitPrice = parseFloat(qtyInput.data('unit-price')) || 0;
            
            // If unit price not available from data attribute, calculate it
            if (unitPrice === 0 && qty > 0) {
                unitPrice = price / qty;
            }
            
            totalQty += qty;
            totalUnitPrice += unitPrice;
            grandTotal += price;
        }
    });
    
    // Update footer totals
    $('.ttlqty').text(totalQty.toFixed(2));
    $('.ttlunitprice').text(totalUnitPrice.toFixed(2));
    updateGrandTotal(grandTotal);
}

function updateGrandTotal(grandTotal) {
    $('.grandtotal').text(grandTotal.toFixed(2));
    $('#gtoal').text(grandTotal.toFixed(2));
    
    // Calculate net total with all adjustments
    calculateNetTotal();
}

function calculateNetTotal() {
    var grandTotal = parseFloat($('#gtoal').text()) || 0;
    var discount = parseFloat($('#disCount').val()) || 0;
    var carryingCost = parseFloat($('#carrying_cost').val()) || 0;
    var laborBill = parseFloat($('#labor_bill').val()) || 0;
    var previousDue = parseFloat($('#previouse_due_amount').val()) || 0;
    var totalAdvance = parseFloat($('#totalAdvanceHidden').val()) || 0;
    
    var netTotal = grandTotal + carryingCost + laborBill + previousDue - discount - totalAdvance;
    
    $('#ntotal').text(netTotal.toFixed(2));
    updateFinalDue(netTotal);
}

function updateFinalDue(netTotal) {
    var payment = parseFloat($('#payment').val()) || 0;
    var paymentType = $('input[name="payment_type"]:checked').val();
    
    if (paymentType === "Cash") {
        $('#payment').val(netTotal.toFixed(2));
        payment = netTotal;
    }
    
    var finalDue = netTotal - payment;
    $('#totalDue').text(finalDue.toFixed(2));
    $('.finalDue').text(finalDue.toFixed(2));
}

// ===== INDIVIDUAL CALCULATION FUNCTIONS =====
function discountCalculation(amount) {
    var grandTotal = parseFloat($('#gtoal').text()) || 0;
    
    if (parseFloat(amount) > grandTotal) {
        showAlert("Discount can't be greater than total amount", 'error');
        $('#disCount').val('0');
        calculateNetTotal();
        return;
    }
    
    calculateNetTotal();
}

function carrying_cost_Calculation(amount) {
    calculateNetTotal();
}

function labor_bill_Calculation(amount) {
    calculateNetTotal();
}

function paymentCalculation(payAmount) {
    var netTotal = parseFloat($('#ntotal').text()) || 0;
    var finalDue = netTotal - parseFloat(payAmount);
    $('.finalDue').text(finalDue.toFixed(2));
    $('#totalDue').text(finalDue.toFixed(2));
}

function qtyPriceCal() {
    var qty = parseFloat($('#qty').val()) || 0;
    var unitPrice = parseFloat($('#unitpice').val()) || 0;
    var vat = parseFloat($('#vat').val()) || 0;
    var currentStock = parseFloat($('#currentStock').val()) || 0;
    
    if (qty > currentStock) {
        showAlert('The desired product stock is not available', 'error');
        $('#qty').val('');
        $('#total').val('0.00');
        return;
    }
    
    var totalWithoutVAT = unitPrice * qty;
    var vatAmount = (vat > 0) ? (vat / 100) * totalWithoutVAT : 0;
    var totalWithVAT = totalWithoutVAT + vatAmount;
    
    $('#total').val(totalWithVAT.toFixed(2));
}

function handleSizeQtyChange() {
    let ctyval = parseFloat($('#cty_size').val()) || 0;
    let qty = parseFloat($('#qty').val()) || 0;
    let gas_qty = ctyval * qty;
    $('#gas_qty').val(gas_qty);
}

// ===== ADVANCE PAYMENT MANAGEMENT =====
let advanceIndex = 0;

function addAdvanceRow() {
    // Find the highest index
    var maxIndex = 0;
    $('.advance-row').each(function() {
        var currentIndex = parseInt($(this).data('index'));
        if (currentIndex > maxIndex) {
            maxIndex = currentIndex;
        }
    });
    
    advanceIndex = maxIndex + 1;
    
    var newRow = `
        <div class="advance-row mb-2" data-index="${advanceIndex}">
            <div class="row">
                <div class="col-md-5">
                    <select name="advance_ledger_id[${advanceIndex}]" class="form-control select2 advance-ledger" data-index="${advanceIndex}">
                        <option value="">--Select Account--</option>
                        <x-banck :setAccounts="$accounts" />
                    </select>
                </div>
                <div class="col-md-5">
                    <input type="text" class="form-control advance-amount" name="advance[${advanceIndex}]" 
                           data-index="${advanceIndex}" style="text-align: right" placeholder="0.00"
                         
                           onkeyup="calculateAdvanceTotal()" />
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-sm btn-danger remove-advance" data-index="${advanceIndex}">
                        <i class="fa fa-minus"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
    
    $('#advanceContainer').append(newRow);
    
    // Initialize select2 for new row
    $(`select[name="advance_ledger_id[${advanceIndex}]"]`).select2();
    
    // Show remove button for all rows if more than one
    if ($('.advance-row').length > 1) {
        $('.remove-advance').show();
    }
}

function removeAdvanceRow() {
    var index = $(this).data('index');
    $(`.advance-row[data-index="${index}"]`).remove();
    
    // Hide remove button if only one row remains
    if ($('.advance-row').length <= 1) {
        $('.remove-advance').hide();
    }
    
    calculateAdvanceTotal();
}

function calculateAdvanceTotal() {
    var totalAdvance = 0;
    
    $('.advance-amount').each(function() {
        var amount = parseFloat($(this).val()) || 0;
        totalAdvance += amount;
    });
    
    $('#totalAdvanceAmount').text(totalAdvance.toFixed(2));
    $('#totalAdvanceHidden').val(totalAdvance);
    
    // Recalculate net total
    calculateNetTotal();
}

function validateAdvanceLedger() {
    var selectedValue = $(this).val();
    var currentIndex = $(this).data('index');
    
    // Check for duplicate selections
    var isDuplicate = false;
    $('.advance-ledger').each(function() {
        if ($(this).data('index') !== currentIndex && $(this).val() === selectedValue && selectedValue !== '') {
            isDuplicate = true;
            return false;
        }
    });
    
    if (isDuplicate) {
        showAlert('This account is already selected in another advance payment', 'error');
        $(this).val('').trigger('change');
    }
}

// ===== PAYMENT TYPE MANAGEMENT =====
function getCustomerBalance(payment_type) {
    var ledger_id = $('#ledger_id').val();
    $("#paymentType").val(payment_type);

    // Show/hide relevant sections based on payment type
    togglePaymentSections(payment_type);

    if (!ledger_id) {
        return;
    }

    $.ajax({
        url: "{{ route('sale.sale.getCustomerBalance') }}",
        type: "GET",
        cache: false,
        dataType: "json",
        data: {
            "_token": "{{ csrf_token() }}",
            customer_id: ledger_id,
            payment_type: payment_type
        },
        success: function (data) {
            handleCustomerBalanceResponse(data, payment_type);
        },
        error: function() {
            showAlert('Error fetching customer balance', 'error');
        }
    });
}

function togglePaymentSections(payment_type) {
    if (payment_type === 'Cash') {
        $('#account_id').show();
        $('#netTotal').show();
        $('.partisals').show();
        $('#payment').prop('readonly', false);
    } else if (payment_type === 'Due') {
        $('#account_id').show();
        $('#netTotal').show();
        $('.partisals').hide();
        $('#payment').val('0').prop('readonly', true);
    } else {
        // For other payment types
        $('#account_id').show();
        $('#netTotal').show();
        $('.partisals').show();
        $('#payment').prop('readonly', false);
    }
    
    calculateNetTotal();
}

function handleCustomerBalanceResponse(data, payment_type) {
    if (payment_type === 'Cash') {
        $("#customer_currentBalance").val('');
    } else {
        $("#customer_currentBalance").val(data.finalBalance || 0);
        $("#expireData").val(data.expireData || '');
    }
    
    checkDepositAndCreditBalance();
}

function updateCustomerBalance(customerId) {
    var paymentType = $('input[name="payment_type"]:checked').val() || 'Cash';
    getCustomerBalance(paymentType);
}

// ===== PRODUCT AND STOCK MANAGEMENT =====
function getUnitPrice(productId) {
    if (!productId) return;
    
    var branch_id = $('#branch_id').val();
    
    // Get unit price
    $.ajax({
        url: "{{ route('sale.sale.saleunitPrice') }}",
        type: "GET",
        cache: false,
        data: {
            "_token": "{{ csrf_token() }}",
            'productId': productId,
        },
        success: function(data) {
            $("#unitpice").val(data.sale_price || 0);
            $(".purchaseprice").html("Last PP: " + (data.lastPurchasePrice || 'N/A'));
            qtyPriceCal();
        },
        error: function() {
            showAlert('Error fetching product price', 'error');
        }
    });

    // Get stock information
    if (branch_id) {
        $.ajax({
            url: "{{ route('sale.sale.getProductStock') }}",
            type: "GET",
            cache: false,
            data: {
                "_token": "{{ csrf_token() }}",
                productId: productId,
                branch_id: branch_id,
            },
            success: function(data) {
                $("#currentStock").val(data || 0);
            },
            error: function() {
                $("#currentStock").val(0);
            }
        });
    }
}

function getProductList(branchId) {
    if (!branchId) {
        showAlert('Branch is not selected', 'error');
        return;
    }
    
    $.ajax({
        url: "{{ route('sale.sale.getProductListForSale') }}",
        type: "GET",
        cache: false,
        data: {
            "_token": "{{ csrf_token() }}",
            branch_id: branchId
        },
        success: function (data) {
            $('#productID').html(data);
            $('#productID').trigger('change');
        },
        error: function() {
            showAlert('Error loading product list', 'error');
        }
    });
}

// ===== CUSTOMER MANAGEMENT =====
function handleCustomerSubmit(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');

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

    $.ajax({
        url: form.attr('action'),
        method: 'POST',
        data: formData,
        success: function (response) {
            if (response.success) {
                $('#addCustomerModel').modal('hide');
                
                // Add new customer to ledger dropdown
                $('select[name="ledger_id"]').append(
                    `<option value="${response.accounts.id}" selected>${response.accounts.account_name}</option>`
                );
                
                form[0].reset();
                showAlert('Customer added successfully', 'success');
            } else {
                showAlert('Unexpected error occurred.', 'error');
            }
        },
        error: function (xhr) {
            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 {
                showAlert('Something went wrong. Please try again.', 'error');
            }
        },
        complete: function() {
            // Re-enable submit button
            form.find("button[type='submit']").prop('disabled', false);
        }
    });
}

// ===== VALIDATION AND UTILITY FUNCTIONS =====
function checkDepositAndCreditBalance() {
    var paymentType = $("#paymentType").val() || 'Cash';
    var customer_currentBalance = parseFloat($("#customer_currentBalance").val()) || 0;
    var totalDue = parseFloat($("#totalDue").text()) || 0;
    var expireDatas = $("#expireData").val();
    var todaysDate = new Date().toISOString().slice(0, 10);

    if (!expireDatas) {
        expireDatas = todaysDate;
    }

    var btn = document.getElementById('subMitButton');
    
    // Enable/disable submit button based on payment type and balance
    if (paymentType === 'Cash') {
        btn.disabled = false;
    } else if (paymentType === 'Credit' && customer_currentBalance < totalDue) {
        btn.disabled = true;
        showAlert('Insufficient credit balance', 'warning');
    } else if (paymentType === 'Deposit' && customer_currentBalance < totalDue) {
        btn.disabled = true;
        showAlert('Insufficient deposit balance', 'warning');
    } else {
        btn.disabled = false;
    }
}

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

// ===== FORM VALIDATION =====
function validateForm() {
    var isValid = true;
    var errors = [];
    
    // Check if products are added
    var productCount = $('#show_item tbody tr').length - 1; // Subtract header row
    if (productCount === 0) {
        errors.push('Please add at least one product');
        isValid = false;
    }
    
    // Check payment type selection
    var paymentType = $('input[name="payment_type"]:checked').val();
    if (!paymentType) {
        errors.push('Please select a payment type');
        isValid = false;
    }
    
    // Check ledger selection
    var ledgerId = $('#ledger_id').val();
    if (!ledgerId) {
        errors.push('Please select a ledger');
        isValid = false;
    }
    
    // Check account selection for cash payments
    if (paymentType === 'Cash') {
        var accountId = $('select[name="account_id"]').val();
        if (!accountId) {
            errors.push('Please select an account for cash payment');
            isValid = false;
        }
    }
    
    // Validate advance payments
    $('.advance-row').each(function() {
        var amount = parseFloat($(this).find('.advance-amount').val()) || 0;
        var ledger = $(this).find('.advance-ledger').val();
        
        if (amount > 0 && !ledger) {
            errors.push('Please select account for advance payment');
            isValid = false;
            return false;
        }
    });
    
    if (!isValid) {
        showAlert(errors.join('\n'), 'error');
    }
    
    return isValid;
}

// Add form validation on submit
$('form').on('submit', function(e) {
    if (!validateForm()) {
        e.preventDefault();
        return false;
    }
});

// ===== KEYBOARD SHORTCUTS =====
$(document).on('keydown', function(e) {
    // Ctrl + Enter to add item
    if (e.ctrlKey && e.keyCode === 13) {
        e.preventDefault();
        $('#add_item').click();
    }
    
    // F2 to focus on product selection
    if (e.keyCode === 113) { // F2
        e.preventDefault();
        $('#productID').select2('open');
    }
    
    // F3 to focus on quantity
    if (e.keyCode === 114) { // F3
        e.preventDefault();
        $('#qty').focus();
    }
});

// ===== EXPORT FUNCTIONS FOR GLOBAL ACCESS =====
window.swingSale = {
    recalculateAllTotals: recalculateAllTotals,
    calculateAdvanceTotal: calculateAdvanceTotal,
    addNewItem: addNewItem,
    getCustomerBalance: getCustomerBalance,
    getUnitPrice: getUnitPrice,
    validateForm: validateForm
};
</script>


@endsection
