<div>
    @if (request()->path() == 'admin/clientSearchReport')
        <a class="noprint btn btn-primary" target="_blank" href="{{ route('clientSearchReportPrint') }}?price=yes">
            <i class="fa fa-print"></i> Print with Price
        </a>
        <a class="noprint btn btn-primary" target="_blank" href="{{ route('clientSearchReportPrint') }}?price=no">
            <i class="fa fa-print"></i> Print without Price
        </a>
        <a class="noprint btn btn-primary" href="{{ route('clientSearchReportPrint') }}?price=no&excel=yes">
            <i class="fa fa-download"></i> Download CSV
        </a>
        @can('bulk-qr-code-generate')
            <a class="noprint btn btn-primary" href="{{ route('bulkQrCodeGenerate') }}" target="_blank">
                <i class="fa fa-qrcode"></i> Bulk QR Code
            </a>
        @endcan
    @endif

    <div class="card">
        <div class="card-body">
            <div>
                <form action="" method="POST" id="fromSubmit">
                    @csrf
                    <div class="modal fade" id="multipleClientPaymentModal">
                        <div class="modal-dialog">
                            <div class="modal-content" style="padding: 5px 15px;">
                                <div class="modal-header">
                                    <h4 class="text-center">Selected customers @if (getBillingType() == 'day_to_day')
                                            package price
                                        @else
                                            due amount
                                        @endif will be paid <span id="clientName"></span></h4>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>

                                <div class="modal-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label>Collected By</label>
                                                @if (auth()->user()->hasrole('Admin'))
                                                    <select name="mulltipleCustomerPaymentCollectedBy"
                                                        class="form-control bSelect " id="mulltipleCustomerPaymentCollectedBy"
                                                        required>
                                                        <option value="">Select Employee</option>
                                                        @foreach (employees() as $employee)
                                                            @if ($employee->admin == null || $employee->admin->user_accounting_status == 'yes')
                                                                <option value="{{ $employee->id }}">
                                                                    {{ $employee->name }}</option>
                                                            @endif
                                                        @endforeach
                                                    </select>
                                                @else
                                                    @if (auth()->user()->hasPermissionTo('change-collector'))
                                                        <select name="mulltipleCustomerPaymentCollectedBy"
                                                            class="form-control"
                                                            id="mulltipleCustomerPaymentCollectedBy" required>
                                                            <option value="">Select Employee</option>
                                                            @foreach (employees() as $employee)
                                                                @if ($employee->admin == null || $employee->admin->user_accounting_status == 'yes')
                                                                    <option value="{{ $employee->id }}"
                                                                        {{ $employee->admin_user_id == auth()->user()->id ? 'selected' : '' }}>
                                                                        {{ $employee->name }}
                                                                    </option>
                                                                @endif
                                                            @endforeach
                                                        </select>
                                                    @else
                                                        <select name="mulltipleCustomerPaymentCollectedBy"
                                                            class="form-control"
                                                            id="mulltipleCustomerPaymentCollectedBy" required disabled>
                                                            <option value="">Select Employee</option>
                                                            @foreach (employees() as $employee)
                                                                <option value="{{ $employee->id }}"
                                                                    {{ $employee->admin_user_id == auth()->user()->id ? 'selected' : '' }}>
                                                                    {{ $employee->name }}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                    @endif
                                                @endif
                                            </div>


                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">

                                                <label>Payment Month </label>
                                                <select name="month" class="form-control"
                                                    id="multipleCustomerPaymentAjuxSelectMonth">
                                                    <option value="">Select Month</option>
                                                    <option value="January"
                                                        {{ today()->format('F') == 'January' ? 'selected' : '' }}>
                                                        January</option>
                                                    <option value="February"
                                                        {{ today()->format('F') == 'February' ? 'selected' : '' }}>
                                                        February</option>
                                                    <option value="March"
                                                        {{ today()->format('F') == 'March' ? 'selected' : '' }}>
                                                        March</option>
                                                    <option value="April"
                                                        {{ today()->format('F') == 'April' ? 'selected' : '' }}>
                                                        April</option>
                                                    <option value="May"
                                                        {{ today()->format('F') == 'May' ? 'selected' : '' }}>May
                                                    </option>
                                                    <option value="June"
                                                        {{ today()->format('F') == 'June' ? 'selected' : '' }}>
                                                        June</option>
                                                    <option value="July"
                                                        {{ today()->format('F') == 'July' ? 'selected' : '' }}>
                                                        July</option>
                                                    <option value="August"
                                                        {{ today()->format('F') == 'August' ? 'selected' : '' }}>
                                                        August</option>
                                                    <option value="September"
                                                        {{ today()->format('F') == 'September' ? 'selected' : '' }}>
                                                        September
                                                    </option>
                                                    <option value="October"
                                                        {{ today()->format('F') == 'October' ? 'selected' : '' }}>
                                                        October</option>
                                                    <option value="November"
                                                        {{ today()->format('F') == 'November' ? 'selected' : '' }}>
                                                        November
                                                    </option>
                                                    <option value="December"
                                                        {{ today()->format('F') == 'December' ? 'selected' : '' }}>
                                                        December
                                                    </option>
                                                </select>

                                            </div>
                                        </div>
                                        <div class="col-md-12">
                                            <div class="form-group">
                                                <label>Payment Description</label>
                                                @if (checkSettings('payment_month_show_in_remark') == 'enable')
                                                    @if (checkSettings('payment_month_short_in_remark') == 'enable')
                                                        <textarea name="multipleCustomerPaymentDescription" id="multipleCustomerPaymentDescription" class="form-control"
                                                            placeholder="Enter Description...">{{ today()->format('M') }}</textarea>
                                                    @else
                                                        <textarea name="multipleCustomerPaymentDescription" id="multipleCustomerPaymentDescription" class="form-control"
                                                            placeholder="Enter Description...">{{ today()->format('F') }}</textarea>
                                                    @endif
                                                @else
                                                    <textarea name="multipleCustomerPaymentDescription" id="multipleCustomerPaymentDescription" class="form-control"
                                                        placeholder="Enter Description...">Payment of month : {{ today()->format('F') }}. Bill Month : {{ today()->format('F') }}</textarea>
                                                @endif
                                            </div>
                                        </div>

                                        <div class="col-md-6">
                                            <div class="form-group mt-2">
                                                <label>
                                                    <input type="checkbox" class="checkbox"
                                                        name="multipleCustomerPaymentSendsms"
                                                        id="multipleCustomerPaymentSendsms"
                                                        @if (checkSettings('auto-payment-sms-send') == 'enable') checked @endif>
                                                    <b>Send SMS Notification</b>
                                                </label>
                                            </div>
                                        </div>
                                        @if (checkSettings('bank_account_deposit_from_payment') == 'enable')
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label for="multipleCustomerPaymentBankAccount">
                                                        Bank Account (Optional)
                                                    </label>
                                                    <select name="multipleCustomerPaymentBankAccount" id="multipleCustomerPaymentBankAccount" class="form-control">
                                                        <option value="">Select Bank Account</option>
                                                        @php
                                                            $bankAccounts = \App\Models\Banking::where('status', 1)->get();
                                                        @endphp
                                                        @if($bankAccounts->count() > 0)
                                                            @foreach ($bankAccounts as $bankAccount)
                                                                <option value="{{ $bankAccount->id }}">{{ $bankAccount->account_name }} -- {{ $bankAccount->bank_name }}</option>
                                                            @endforeach
                                                        @endif
                                                    </select>
                                                    <small class="text-muted">Payment will be deposited to this account.</small>
                                                </div>
                                            </div>
                                        @endif
                                    </div>
                                </div>

                                <div class="modal-footer justify-content-between">
                                    <button type="button" class="btn btn-default" data-dismiss="modal"
                                        id="multipleCustomerAjaxPaymentModalClose">Close</button>
                                    <button class="btn btn-primary buttonHide" type="submit"
                                        id="multipleCustomerAjaxPaymentProcess">Submit</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="modal fade" id="customerBulkStatusChangeModal">
                        <div class="modal-dialog">
                            <div class="modal-content" style="padding: 5px 15px;">
                                <div class="modal-header">
                                    <h4 class="text-center">Customer Status Change</h4>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>

                                <div class="modal-body">
                                    <div class="row">
                                        <div class="col-md-12">
                                            <div class="form-group">
                                                <label>Select Status</label>

                                                <select name="multipleCustomerStatus" class="form-control"
                                                    id="multipleCustomerStatus" required>
                                                    <option value="">Select one</option>
                                                    @can('id-enable')
                                                        <option value="enable">Enable</option>
                                                    @endcan
                                                    @can('id-disable')
                                                        <option value="disable">Disable</option>
                                                    @endcan
                                                    @can('customer-deactivated')
                                                        <option value="deactive">Deactive</option>
                                                    @endcan
                                                    @can('can-close')
                                                        <option value="close">Close</option>
                                                    @endcan
                                                    @can('mac-customer_destroy')
                                                        <option value="delete">Delete</option>
                                                    @endcan

                                                </select>

                                            </div>


                                        </div>

                                    </div>
                                </div>

                                <div class="modal-footer justify-content-between">
                                    <button type="button" class="btn btn-default" data-dismiss="modal"
                                        id="multipleCustomerStatusModalClose">Close</button>
                                    <button class="btn btn-primary buttonHide" type="submit"
                                        id="multipleCustomerStatusProcess">Submit</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="modal fade" id="customerBulkPopChangeModal">
                        <div class="modal-dialog">
                            <div class="modal-content" style="padding: 5px 15px;">
                                <div class="modal-header">
                                    <h4 class="text-center">Change POP for Selected Customers</h4>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>

                                <div class="modal-body">
                                    <div class="row">
                                        <div class="col-md-12">
                                            <div class="form-group">
                                                <label>Select POP</label>
                                                <select name="multipleCustomerPop" class="form-control select2" id="multipleCustomerPop" required>
                                                    <option value="">Select POP</option>
                                                    @foreach(userPops() as $pop)
                                                        <option value="{{ $pop->id }}">{{ $pop->popname }}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="modal-footer justify-content-between">
                                    <button type="button" class="btn btn-default" data-dismiss="modal"
                                        id="multipleCustomerPopModalClose">Close</button>
                                    <button class="btn btn-primary buttonHide" type="submit"
                                        id="multipleCustomerPopProcess">Submit</button>
                                </div>
                            </div>
                        </div>
                    </div>


                    @if (request()->path() == 'admin/clientSearchReport')
                        <div id="balanceHints" style="display: none">
                            <table class="table table-auto">
                                <tr id="reseller_row" style="display: none">
                                    <td>Reseller cost:</td>
                                    @if (auth()->user()->can(['dynamic-recharge']))
                                        <td><span id="selected_price" readonly></span></td>
                                        <td><span id="selected_day" readonly></span></td>
                                    @else
                                        <td><span id="selected_user_price" readonly></span></td>
                                        <td><span id="selected_user_recharge_day" readonly></span></td>
                                    @endif
                                </tr>
                                <tr style="display: none" id="sub_reseller_row">
                                    <td>
                                        @if (auth()->user()->hasRole(['Sub Reseller']))
                                            Cost:
                                        @else
                                            Sub reseller cost:
                                        @endif
                                    </td>
                                    @if (auth()->user()->can(['dynamic-recharge']))
                                        <td><span id="selected_price_sub_reseller" readonly></span></td>
                                        <td><span id="selected_day_for_sub_reseller" readonly></span></td>
                                    @else
                                        <td><span id="selected_user_price_sub_reseller" readonly></span></td>
                                        <td><span id="selected_user_recharge_day_for_sub_reseller" readonly></span>
                                        </td>
                                    @endif
                                </tr>
                            </table>
                        </div>
                    @endif

                    <input type="hidden" id="blling_day" value="{{ config('app.billing_day_count') }}">

                    @if (request()->path() == 'admin/clientSearchReport')
                        <div class="row">
                            <table class="table">
                                <tr style="background-color: rgb(241, 219, 219)">
                                    @if (checkSettings('reseller-client-dynamic-recharge') == 'enable')
                                        @can('dynamic-recharge')
                                            <td>
                                                <input type="hidden" value="yes" name="dynamic_recharge" required>
                                                <select name="recharge_day" id="recharge_day" class="form-control"
                                                    required>
                                                    <option value="">Select One</option>
                                                    @for ($i = $minimum_recharge; $i <= 30; $i++)
                                                        <option value="{{ $i }}">{{ $i }}</option>
                                                    @endfor
                                                </select>
                                            </td>
                                        @endcan
                                    @endif
                                    <td></td>
                                    <td>
                                        @if (in_array('customer-recharge', userPermissions()))
                                            <input type="hidden" name="type" id="recharge" value="Recharge">
                                            <input id="reseller_customer_sms" type="hidden"
                                                name="reseller_customer_sms" value="{{ $reseller_customer_sms }}">
                                            <button class="btn btn-primary float-right" type="submit"
                                                id="rechargeSubmit">
                                                Recharge
                                            </button>
                                        @endif
                                        @if (in_array('money-receipt-entry', userPermissions()))
                                            <button class="btn btn-warning float-right mr-2"
                                                id="multipleClientPayment" data-toggle="modal"
                                                data-target="#multipleClientPaymentModal">
                                                Payment
                                            </button>
                                        @endif

                                        <button class="btn btn-success float-right mr-2"
                                                id="multipleCustomerStatusChange" data-toggle="modal"
                                                data-target="#customerBulkStatusChangeModal">
                                                Change Status
                                        </button>
                                        @if(auth()->user()->hasRole('Admin') || auth()->user()->hasRole('Accounts Executive'))
                                            @if(globalPermission('batch_client_pop_change'))
                                                <button class="btn btn-info float-right mr-2"
                                                    id="multipleCustomerPopChange" data-toggle="modal"
                                                    data-target="#customerBulkPopChangeModal">Change POP</button>
                                            @endif
                                        @endif

                                    </td>

                                </tr>
                            </table>
                        </div>
                    @endif
                </form>

                <br>
                <div class="table-responsive">
                    <input type="hidden" id="uuid" name="uuid" value="{{ createUUID() }}">
                    @include('clients.customer_search')
                </div>
            </div>
        </div>
    </div>
</div>

@if (request()->path() == 'admin/clientSearchReport')
    <script>
        $(function() {
            var payment_month_show_in_remark = '{{ checkSettings('payment_month_show_in_remark') }}';
            var payment_month_short_in_remark = '{{ checkSettings('payment_month_short_in_remark') }}';

            $(document).on('change', '#multipleCustomerPaymentAjuxSelectMonth', function() {

                var month = $('#multipleCustomerPaymentAjuxSelectMonth').val();

                if (payment_month_show_in_remark == 'enable') {
                    if (payment_month_short_in_remark == 'enable') {
                        $('#multipleCustomerPaymentDescription').val(month.substring(0, 3));
                    } else {
                        $('#multipleCustomerPaymentDescription').val(month);
                    }
                } else {
                    $('#multipleCustomerPaymentDescription').val('Payment of month : ' + month +
                        '. Bill Month : ' + month);
                }
            });

            $('#multipleClientPayment').on('click', function(e) {
                e.preventDefault(); // Prevent the default action (form submission)
                $('.select2').val('').trigger('change');
                $('#multipleClientPaymentModal').modal('show'); // Open the modal
            });

            $('#multipleCustomerAjaxPaymentProcess').on('click', function(e) {
                e.preventDefault(); // Prevent the default action (form submission)

                let ids = [];
                $('.checkboxR').each(function() {
                    if ($(this).is(':checked')) {
                        ids.push($(this).val());
                    }
                });

                if (ids.length < 1) {
                    toastr.error('Please select a customer');
                    return;
                }

                let collectedBy = $("#mulltipleCustomerPaymentCollectedBy option:selected").val();
                if (!collectedBy) {
                    toastr.error('Please select an employee');
                    return;
                }

                let smsSend = $('#multipleCustomerPaymentSendsms').is(':checked');
                let uuid = $('#uuid').val();
                let paymentDescription = $('#multipleCustomerPaymentDescription').val();
                let bankAccountId = $('#multipleCustomerPaymentBankAccount').val();
                $('#processing').show();
                $.ajax({
                    url: "{{ route('multipleCustomerPayment') }}",
                    type: "POST",
                    data: {
                        _token: "{{ csrf_token() }}",
                        ids: ids,
                        collectedBy: collectedBy,
                        smsSend: smsSend,
                        uuid: uuid,
                        paymentDescription: paymentDescription,
                        bank_account_id: bankAccountId,
                    },
                    success: function(data) {
                        $('#processing').hide();
                        $('#multipleCustomerAjaxPaymentModalClose').trigger('click');

                        if (data.errors && data.errors.length > 0) {
                            // Loop through the errors array and display each error
                            data.errors.forEach(function(element) {
                                toastr.error("Failed for ID: " + element.id + " - " +
                                    element.message);
                            });
                        } else {
                            toastr.success(
                            "Payments processed successfully for all customers.");
                        }
                    },
                    error: function(xhr, status, error) {
                        $('#multipleCustomerAjaxPaymentModalClose').trigger('click');
                        $('#processing').hide();
                        toastr.error("An error occurred while processing the payments.");
                        console.log("Error: ", error);
                    }
                });
            });

            $('#multipleCustomerStatusChange').on('click', function(e) {
                e.preventDefault(); // Prevent the default action (form submission)
                $('#customerBulkStatusChangeModal').modal('show'); // Open the modal
            });
            $('#multipleCustomerStatusProcess').on('click', function(e) {
                e.preventDefault(); // Prevent the default action (form submission)
                let ids = [];
                $('.checkboxR').each(function() {
                    if ($(this).is(':checked')) {
                        ids.push($(this).val());
                    }
                });

                let status = $("#multipleCustomerStatus option:selected").val();
                if (!status) {
                    toastr.error('Please select a status');
                    return;
                }

                if (ids.length < 1) {
                    toastr.error('Please select a customer');
                    return;
                }
                $('#processing').show();
                $.ajax({
                    url: "{{ route('multiple-customer-status-change') }}",
                    type: "POST",
                    data: {
                        _token: "{{ csrf_token() }}",
                        ids: ids,
                        status: status
                    },
                    success: function(data) {
                        $('#processing').hide();
                        $('#customerBulkStatusChangeModal').modal('hide');
                        toastr.success(data.success);
                        // location.reload();
                        // i want to click search after status change button id is searchBtn
                        if ($('#searchBtn').length) {
                            $('#searchBtn').click();
                        } else {
                            console.error('Search button not found!');
                        }

                    },
                    error: function(xhr, status, error) {
                        $('#processing').hide();

                        toastr.error(error);

                    }
                });
            });

            $('#multipleCustomerPopChange').on('click', function(e) {
                e.preventDefault(); // Prevent the default action (form submission)
                $('.select2').val('').trigger('change');
                $('#customerBulkPopChangeModal').modal('show'); // Open the modal
            });

            $('#multipleCustomerPopProcess').on('click', function(e) {
                e.preventDefault(); // Prevent the default action (form submission)
                let ids = [];
                $('.checkboxR').each(function() {
                    if ($(this).is(':checked')) {
                        ids.push($(this).val());
                    }
                });

                if (ids.length < 1) {
                    toastr.error('Please select a customer');
                    return;
                }

                let popId = $("#multipleCustomerPop option:selected").val();
                if (!popId) {
                    toastr.error('Please select a POP');
                    return;
                }

                $('#processing').show();
                $.ajax({
                    url: "{{ route('multiple-customer-pop-change') }}",
                    type: "POST",
                    data: {
                        _token: "{{ csrf_token() }}",
                        ids: ids,
                        pop_id: popId
                    },
                    success: function(data) {
                        $('#processing').hide();
                        $('#customerBulkPopChangeModal').modal('hide');
                        if (data.success) {
                            toastr.success(data.message);
                        } else {
                            toastr.error(data.message || 'An error occurred');
                        }
                        // Refresh search results
                        if ($('#searchBtn').length) {
                            $('#searchBtn').click();
                        } else {
                            console.error('Search button not found!');
                        }
                    },
                    error: function(xhr, status, error) {
                        $('#processing').hide();
                        $('#customerBulkPopChangeModal').modal('hide');

                        let errorMessage = 'An error occurred while processing the POP change.';
                        if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorMessage = xhr.responseJSON.message;
                        } else if (xhr.responseJSON && xhr.responseJSON.error) {
                            errorMessage = xhr.responseJSON.error;
                        }

                        toastr.error(errorMessage);
                        console.log("Error: ", error);
                    }
                });
            });

            $('#rechargeSubmit').on('click', function(e) {
                e.preventDefault();

                if (!confirm('Are you sure you want to proceed with the Recharge?')) {
                    return;
                }

                let ids = [];
                $('.checkboxR').each(function() {
                    if ($(this).is(':checked')) {
                        ids.push($(this).val());
                    }
                });
                var day = $('#recharge_day').val();
                // console.log(day);
                if (day == '') {
                    toastr.error('Please Select The Day Field...');
                    return;
                }

                $(this).hide();
                $('#processing').show();

                $.ajax({
                    url: "{{ route('CustomerRecharge') }}",
                    type: "POST",
                    data: {
                        _token: "{{ csrf_token() }}",
                        ids: ids,
                        // type: $('input[name=type]:checked').val(),
                        type: $('#recharge').val(),
                        reseller_customer_sms: $('#reseller_customer_sms').val(),
                        dynamic_recharge: $('input[name=dynamic_recharge]').val(),
                        recharge_day: $('#recharge_day').val(),
                        uuid: $('#uuid').val(),
                    },
                    success: function(data) {
                        // console.log(data.status);
                        if (data.status == 'success') {
                            $('#result').html('');
                            $('#processing').hide();
                            toastr.success('Successful! ' + data.message);
                        } else {
                            $('#processing').hide();
                            $('#result').html('');
                            toastr.error('Failed.. ' + data.message);
                        }
                    }
                });



            });

            let check_sub_reseller = $('#checkSubReseller').val();
            let subreseller_role = false;
            if (check_sub_reseller) {
                subreseller_role = true;
            } else {
                subreseller_role = false;
            }
            var rsAllCost = 0;
            var rsSingleCost = 0;
            var srsAllCost = 0;
            var srsSingleCost = 0;
            total = 0;
            total_sub_reseller = 0;
            $('#allSelect').on('click', function() {

                total = 0;
                total_sub_reseller = 0;
                resellerBalance = $('#resellerBalance').text();
                if (this.checked) {


                    $('.checkboxprice').each(function() { //loop through each checkbox
                        $(this).prop('checked', true); //check
                        let price = $(this).parent('td').find('.reseller_price').val();
                        let sub_reseller_price = $(this).parent('td').find('.subreseller_price')
                            .val();
                        // console.log(sub_reseller_price);
                        //new code
                        let billing_cycle = $(this).parent('td').find('.billing_cycle').val();
                        let expire_date = $(this).parent('td').find('.ep_date').val();
                        let formated_expire_date = moment(expire_date).format('YYYY-MM-DD');
                        let current_date = moment(new Date()).format('YYYY-MM-DD');

                        //formating date for calculation
                        a = new Date(current_date),
                            b = new Date(formated_expire_date),
                            b = new Date(b.setMonth(b.getMonth() + 1));
                        difference = dateDiffInDays(a, b);

                        if (difference < 0) {
                            cost = calculationCost(formated_expire_date, billing_cycle, price);
                            total += parseInt(cost.cost);

                            subreseller_cost = calculationCost(formated_expire_date, billing_cycle,
                                sub_reseller_price);
                            total_sub_reseller += parseInt(subreseller_cost.cost);

                        } else {

                            let check_day_wise_recharge = $('#DaywiseRecharge').val();
                            let check_epire_date_is_current_date_of_hire_date = moment(
                                formated_expire_date).isSameOrAfter(current_date);
                            // console.log(check_epire_date_is_current_date_of_hire_date);

                            if (check_day_wise_recharge == "enable" && !
                                check_epire_date_is_current_date_of_hire_date) {
                                cost = calculationCost(formated_expire_date, billing_cycle, price);
                                total += parseInt(cost.cost);

                                subreseller_cost = calculationCost(formated_expire_date,
                                    billing_cycle, sub_reseller_price);
                                total_sub_reseller += parseInt(subreseller_cost.cost);
                            } else {
                                total += parseInt(price);
                                total_sub_reseller += parseInt(sub_reseller_price);
                            }

                        }



                    });
                } else {
                    $('.checkboxprice').each(function() { //loop through each checkbox
                        $(this).prop('checked', false); //uncheck
                        let price = $(this).parent('td').find('.reseller_price').val();
                        let sub_reseller_price = $(this).parent('td').find('.subreseller_price')
                            .val();
                        //new code
                        let billing_cycle = $(this).parent('td').find('.billing_cycle').val();
                        let expire_date = $(this).parent('td').find('.ep_date').val();
                        let formated_expire_date = moment(expire_date).format('YYYY-MM-DD');
                        let current_date = moment(new Date()).format('YYYY-MM-DD');

                        //formating date for calculation
                        a = new Date(current_date),
                            b = new Date(formated_expire_date),
                            b = new Date(b.setMonth(b.getMonth() + 1));
                        difference = dateDiffInDays(a, b);

                        if (difference < 0) {
                            cost = calculationCost(formated_expire_date, billing_cycle, price);
                            total -= parseInt(cost.cost);

                            subreseller_cost = calculationCost(formated_expire_date, billing_cycle,
                                sub_reseller_price);
                            total_sub_reseller -= parseInt(subreseller_cost.cost);

                        } else {
                            total -= parseInt(price);
                            total_sub_reseller -= parseInt(sub_reseller_price);


                        }

                    });
                    total = 0;
                    total_sub_reseller = 0;
                }

                if (total > 0) {
                    $('#balanceHints').show();
                } else {
                    $('#balanceHints').hide();
                }

                if (subreseller_role) {
                    $('#sub_reseller_row').show();
                } else {
                    $('#reseller_row').show();
                    $('#sub_reseller_row').show();

                }

                $('#selected_user_price').text(total);
                $('#selected_user_recharge_day').text("");

                $('#selected_user_price_sub_reseller').text(total_sub_reseller);
                $('#selected_user_recharge_day_for_sub_reseller').text("");

                rsAllCost = total;
                srsAllCost = total_sub_reseller;
            });

            function dateDiffInDays(a, b) {
                const _MS_PER_DAY = 1000 * 60 * 60 * 24;
                // Discard the time and time-zone information.
                const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
                const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
                return Math.floor((utc2 - utc1) / _MS_PER_DAY);
            }

            function getDaysInMonth(year, month) {
                return new Date(year, month, 0).getDate();
            }

            function calculationCost(formated_expire_date, billing_cycle, package_price) {
                let current_date = moment(new Date()).format('YYYY-MM-DD');

                //formating date for calculation
                a = new Date(current_date),
                    b = new Date(formated_expire_date),
                    b = new Date(b.setMonth(b.getMonth() + 1));
                difference = dateDiffInDays(a, b);

                //get how many days in this month
                let daysInMonth = getDaysInMonth(a.getFullYear(), a.getMonth() + 1);
                let billing_day = $('#blling_day').val();

                let next_expire_date = new Date(current_date);
                // set approximate expire date
                next_expire_date.setDate(billing_cycle);

                let to_day_date_time = new Date(a).getTime();
                let next_expire_date_time = new Date(next_expire_date).getTime();

                //add one month if expire date is less than today
                if (next_expire_date_time < to_day_date_time) {
                    next_expire_date = new Date(next_expire_date.setMonth(next_expire_date.getMonth() + 1));
                }

                if (billing_day == "") {
                    day = daysInMonth;
                } else {
                    day = billing_day;
                }



                let total_day_for_bill = dateDiffInDays(a, next_expire_date) + 1;
                total_cost = parseInt((package_price / daysInMonth) * total_day_for_bill);
                // console.log(daysInMonth,package_price,total_cost);

                let value = {
                    "cost": total_cost,
                    "day": total_day_for_bill,
                };

                // console.log(value);

                return value;
            }
            $('.checkboxprice').on('change', function() {


                if (this.checked) {
                    // console.log('checked');
                    //$(this).prop('checked', true);
                    let price = $(this).parent('td').find('.reseller_price').val();
                    let sub_reseller_price = $(this).parent('td').find('.subreseller_price').val();


                    //new code
                    let billing_cycle = $(this).parent('td').find('.billing_cycle').val();
                    let expire_date = $(this).parent('td').find('.ep_date').val();
                    let formated_expire_date = moment(expire_date).format('YYYY-MM-DD');
                    let current_date = moment(new Date()).format('YYYY-MM-DD');

                    //formating date for calculation
                    a = new Date(current_date),
                        b = new Date(formated_expire_date),
                        b = new Date(b.setMonth(b.getMonth() + 1));
                    difference = dateDiffInDays(a, b);


                    if (difference < 0) {


                        cost = calculationCost(formated_expire_date, billing_cycle, price);

                        total += parseInt(cost.cost);

                        subreseller_cost = calculationCost(formated_expire_date, billing_cycle,
                            sub_reseller_price);
                        total_sub_reseller += parseInt(subreseller_cost.cost);
                        if (total > 0) {
                            $('#balanceHints').show();
                        } else {
                            $('#balanceHints').hide();
                        }


                        if (subreseller_role) {
                            $('#sub_reseller_row').show();
                        } else {
                            $('#reseller_row').show();
                            $('#sub_reseller_row').show();

                        }

                        $('#selected_user_price').text(total);
                        $('#selected_user_recharge_day').text(cost.day + " day");

                        $('#selected_user_price_sub_reseller').text(total_sub_reseller);
                        $('#selected_user_recharge_day_for_sub_reseller').text(subreseller_cost.day +
                            " day");
                    } else {
                        let check_day_wise_recharge = $('#DaywiseRecharge').val();
                        let check_epire_date_is_current_date_of_hire_date = moment(formated_expire_date)
                            .isSameOrAfter(current_date);
                        // console.log(check_epire_date_is_current_date_of_hire_date);

                        if (check_day_wise_recharge == "enable" && !
                            check_epire_date_is_current_date_of_hire_date) {
                            // console.log(price);
                            cost = calculationCost(formated_expire_date, billing_cycle, price);
                            // console.log(cost);
                            total += parseInt(cost.cost);

                            subreseller_cost = calculationCost(formated_expire_date, billing_cycle,
                                sub_reseller_price);
                            total_sub_reseller += parseInt(subreseller_cost.cost);
                            if (total > 0) {
                                $('#balanceHints').show();
                            } else {
                                $('#balanceHints').hide();
                            }


                            if (subreseller_role) {
                                $('#sub_reseller_row').show();
                            } else {
                                $('#reseller_row').show();
                                $('#sub_reseller_row').show();

                            }

                            $('#selected_user_price').text(total);
                            $('#selected_user_recharge_day').text(cost.day + " day");

                            $('#selected_user_price_sub_reseller').text(total_sub_reseller);
                            $('#selected_user_recharge_day_for_sub_reseller').text(subreseller_cost.day +
                                " day");
                        } else {
                            total += parseInt(price);
                            total_sub_reseller += parseInt(sub_reseller_price);

                            if (total > 0) {
                                $('#balanceHints').show();
                            } else {
                                $('#balanceHints').hide();
                            }


                            if (subreseller_role) {
                                $('#sub_reseller_row').show();
                            } else {
                                $('#reseller_row').show();
                                $('#sub_reseller_row').show();

                            }
                            $('#selected_user_price').text(total);
                            $('#selected_user_recharge_day').text(1 + " month");

                            $('#selected_user_price_sub_reseller').text(total_sub_reseller);
                            $('#selected_user_recharge_day_for_sub_reseller').text(1 + " month");
                        }


                    }


                } else {
                    //$(this).prop('checked', false);
                    let price = $(this).parent('td').find('.reseller_price').val();
                    let sub_reseller_price = $(this).parent('td').find('.subreseller_price').val();

                    //new code
                    let billing_cycle = $(this).parent('td').find('.billing_cycle').val();
                    let expire_date = $(this).parent('td').find('.ep_date').val();
                    let formated_expire_date = moment(expire_date).format('YYYY-MM-DD');
                    let current_date = moment(new Date()).format('YYYY-MM-DD');

                    //formating date for calculation
                    a = new Date(current_date),
                        b = new Date(formated_expire_date),
                        b = new Date(b.setMonth(b.getMonth() + 1));
                    difference = dateDiffInDays(a, b);



                    if (difference < 0) {
                        cost = calculationCost(formated_expire_date, billing_cycle, price);
                        total -= parseInt(cost.cost);

                        subreseller_cost = calculationCost(formated_expire_date, billing_cycle,
                            sub_reseller_price);
                        total_sub_reseller -= parseInt(subreseller_cost.cost);
                        if (total > 0) {
                            $('#balanceHints').show();
                        } else {
                            $('#balanceHints').hide();
                        }

                        if (subreseller_role) {
                            $('#sub_reseller_row').show();
                        } else {
                            $('#reseller_row').show();
                            $('#sub_reseller_row').show();

                        }
                        $('#selected_user_price').text(total);
                        $('#selected_user_recharge_day').text("");

                        $('#selected_user_price_sub_reseller').text(total_sub_reseller);
                        $('#selected_user_recharge_day_for_sub_reseller').text("");

                    } else {

                        let check_day_wise_recharge = $('#DaywiseRecharge').val();
                        let check_epire_date_is_current_date_of_hire_date = moment(formated_expire_date)
                            .isSameOrAfter(current_date);
                        // console.log(check_epire_date_is_current_date_of_hire_date);

                        if (check_day_wise_recharge == "enable" && !
                            check_epire_date_is_current_date_of_hire_date) {
                            cost = calculationCost(formated_expire_date, billing_cycle, price);
                            total -= parseInt(cost.cost);

                            subreseller_cost = calculationCost(formated_expire_date, billing_cycle,
                                sub_reseller_price);
                            total_sub_reseller -= parseInt(subreseller_cost.cost);
                            if (total > 0) {
                                $('#balanceHints').show();
                            } else {
                                $('#balanceHints').hide();
                            }

                            if (subreseller_role) {
                                $('#sub_reseller_row').show();
                            } else {
                                $('#reseller_row').show();
                                $('#sub_reseller_row').show();

                            }
                            $('#selected_user_price').text(total);
                            $('#selected_user_recharge_day').text("");

                            $('#selected_user_price_sub_reseller').text(total_sub_reseller);
                            $('#selected_user_recharge_day_for_sub_reseller').text("");
                        } else {
                            total -= parseInt(price);
                            total_sub_reseller -= parseInt(sub_reseller_price);

                            if (total > 0) {
                                $('#balanceHints').show();
                            } else {
                                $('#balanceHints').hide();
                            }


                            if (subreseller_role) {
                                $('#sub_reseller_row').show();
                            } else {
                                $('#reseller_row').show();
                                $('#sub_reseller_row').show();

                            }
                            $('#selected_user_price').text(total);
                            $('#selected_user_recharge_day').text("");

                            $('#selected_user_price_sub_reseller').text(total_sub_reseller);
                            $('#selected_user_recharge_day_for_sub_reseller').text("");
                        }



                    }
                }

                rsSingleCost = total;
                srsSingleCost = total_sub_reseller;
            });


           $('#recharge_day').on('change', function () {
                let day = $(this).val();
                let TotalResellerCost = 0;
                let TotalSubResellerCost = 0;

                if (day === '') {
                    toastr.error('Please Select The Day Field...');
                    return;
                }

                $('.checkboxprice').each(function () {
                    // Only calculate if checked
                    if ($(this).is(':checked')) {
                        let reseller_price = parseFloat($(this).closest('td').find('.reseller_price').val()) || 0;
                        let sub_reseller_price = parseFloat($(this).closest('td').find('.subreseller_price').val()) || 0;

                        TotalResellerCost += calculateSingleUserCost(day, reseller_price);
                        TotalSubResellerCost += calculateSingleUserCost(day, sub_reseller_price);
                    }
                });

                // 🔄 Update UI after loop
                $('#selected_price').text(TotalResellerCost);
                $('#selected_day').text(day + " day");

                $('#selected_price_sub_reseller').text(TotalSubResellerCost);
                $('#selected_day_for_sub_reseller').text(day + " day");
            });



            $(document).on("click", ".package_change_action_btn", function() {

                let client_id = $(this).data('clientid');

                $.ajax({
                    type: 'get',
                    url: '{{ route('getClientDetailsForPackageChange') }}',
                    data: {
                        client_id: client_id
                    },
                    success: function(result) {

                        $('#package_change_client_name').val(result.client.clientsinfo
                            .clients_name);
                        $('#package_change_client_id').val(result.client.id);
                        $('#package_change_package').empty();
                        $('#package_change_package').append(
                            '<option value="">Select Package</option>');

                        if (result.client.pop.subreseller == 'yes') {
                            let client_packages = result.client.sub_package_id;
                            $.each(result.packages, function(key, value) {
                                if (client_packages == value.id) {
                                    $('#package_change_package').append(
                                        '<option value="' + value.id +
                                        '" selected>' + value.name + '</option>');
                                } else {

                                    $('#package_change_package').append(
                                        '<option value="' + value.id + '">' + value
                                        .name + '</option>');
                                }
                            });
                        } else {
                            let client_packages = result.client.package_id;
                            $.each(result.packages, function(key, value) {
                                if (client_packages == value.id) {
                                    $('#package_change_package').append(
                                        '<option value="' + value.id +
                                        '" selected>' + value.package_name +
                                        '</option>');
                                } else {

                                    $('#package_change_package').append(
                                        '<option value="' + value.id + '">' + value
                                        .package_name + '</option>');
                                }
                            });
                        }

                    }
                });

            });

            $(document).on('click', '.clientBillCycleChange', function() {
                var id = $(this).attr('data-id');
                var billcycle = $(this).attr('data-curdate');

                // console.log(billcycle);
                $("select#allBillCycle option").each(function() {

                    if ($(this).val() == billcycle) { // EDITED THIS LINE
                        $(this).attr("selected", "selected");
                    }
                    $('.billingCycleChange').show();
                });


                $('#bill_client_id').val(id);

            });
            $(document).on('click', '.addOtc', function() {
                // $('body').on('click', '.addOtc', function() {
                var id = $(this).attr('data-id');
                // console.log(id,'penidng');
                $('#addOtc .client_id').val(id);
            });

            $(document).on("click", ".schedule_package_change", function() {
                console.log('comes');
                let client_id = $(this).data('clientid');
                console.log(client_id);
                $.ajax({
                    type: 'get',
                    url: '{{ route('getClientDetailsForPackageChange') }}',
                    data: {
                        client_id: client_id
                    },
                    success: function(result) {

                        $('#schedule_package_change_client_name').val(result.client.clientsinfo
                            .clients_name);
                        $('#schedule_package_change_client_id').val(result.client.id);
                        $('#schedule_package_change_package').empty();
                        $('#schedule_package_change_package').append(
                            '<option value="">Select Package</option>');

                        if (result.client.pop.subreseller == 'yes') {
                            let client_packages = result.client.sub_package_id;
                            $.each(result.packages, function(key, value) {
                                if (client_packages == value.id) {
                                    $('#schedule_package_change_package').append(
                                        '<option value="' + value.id +
                                        '" selected>' + value.name + '</option>');
                                } else {

                                    $('#schedule_package_change_package').append(
                                        '<option value="' + value.id + '">' + value
                                        .name + '</option>');
                                }
                            });
                        } else {
                            let client_packages = result.client.package_id;
                            $.each(result.packages, function(key, value) {
                                if (client_packages == value.id) {
                                    $('#schedule_package_change_package').append(
                                        '<option value="' + value.id +
                                        '" selected>' + value.package_name +
                                        '</option>');
                                } else {

                                    $('#schedule_package_change_package').append(
                                        '<option value="' + value.id + '">' + value
                                        .package_name + '</option>');
                                }
                            });
                        }

                    }
                });

            });

            function calculateSingleUserCost(day, package_price) {
                let cost = (package_price / 30) * day;
                return Math.round(cost);
            }

        });

        $(document).ready(function () {
            $('#multipleClientPaymentModal').on('shown.bs.modal', function () {
                $(this).find('.select2').select2({
                    dropdownParent: $('#multipleClientPaymentModal')
                });
            });

            $('#customerBulkPopChangeModal').on('shown.bs.modal', function () {
                $(this).find('.select2').select2({
                    dropdownParent: $('#customerBulkPopChangeModal')
                });
            });
        });
    </script>
@endif
