<form
    action="@if (!empty($packages)) {{ route('batchUserPackageChange') }} @else {{ route('batchUserBillingCycleChange') }} @endif"
    method="POST" class="flex flex-wrap" id="batchUserPackageChange">
    @csrf

    <!-- Changed from client_ids[] to client_ids (single input) -->
    <input type="hidden" name="client_ids" id="client_ids">
    <input type="hidden" id="uuid" name="uuid" value="{{createUUID()}}">

    <div class="table-responsive">
        <table class="table table-bordered">
            <thead style="background: #78716C;color:white;">
                <tr>
                    <th class="text-center">
                        <input type="checkbox" id="allSelect">
                    </th>
                    <th scope="col" class="">
                        ID
                    </th>

                    <th scope="col" class="">
                        User name
                    </th>

                    <th scope="col" class="">
                        Expire Date
                    </th>

                    <th scope="col" class="">
                        Bill Cycle
                    </th>

                    @unlessrole('Sub Reseller')
                        <th scope="col" class="">
                            Package
                        </th>
                    @endunlessrole
                    <th scope="col" class="">
                        Sub Package
                    </th>

                    <th scope="col" class="">
                        Contact No
                    </th>
                </tr>
            </thead>
            <tbody class="">
                @forelse ($r as $row)
                    <tr>
                        <td class="text-center">
                            <!-- Removed name attribute - will be handled by JavaScript -->
                            <input type="checkbox" class="checkbox new_class_for_client_id_of_pending"
                                data-id="{{ $row->id }}" value="{{ $row->id }}">
                        </td>
                        <td>
                            {{ $row->id }}
                        </td>
                        <td>
                            {{ $row->userid }}
                        </td>

                        <td class="whitespace-nowrap">
                            {{ date('d-M-Y', strtotime($row->expire_date)) }}
                        </td>

                        <td>
                            {{ $row->billing_cycle }}
                        </td>

                        @unlessrole('Sub Reseller')
                            <td>
                                {{ $row->packages->package_name }}
                            </td>
                        @endunlessrole

                        <td>
                            @if ($row->subpack)
                                {{ $row->subpack->name }}
                            @endif
                        </td>

                        <td>
                            {{ $row->clientsinfo->contact_no ?? '' }}
                        </td>
                    </tr>

                @empty
                    <tr>
                        <td colspan="8" class="text-center">No records found</td>
                    </tr>
                @endforelse

                @if (!empty($packages))
                    <tr>
                        <td colspan="8">
                            <div class="row">
                                @can('batch-package-change-without-cost')
                                    <div class="col-sm-2">
                                        <label class="flex-1 block text-gray-700 text-sm font-bold mb-2"
                                            for="change_pack_without_cost">
                                            Change Package Without Cost
                                        </label>
                                    </div>
                                    <div class="col-sm-2">
                                        <select name="change_pack_without_cost" id="change_pack_without_cost"
                                            class="form-control">
                                            <option value="no">No</option>
                                            <option value="yes">Yes</option>
                                        </select>
                                    </div>
                                @endcan
                                <div class="col-sm-4"></div>
                                <div class="col-sm-2">

                                    @if ($row->pop->subreseller == 'yes')

                                        <select name="package_id" class="form-control" required>
                                            <option value="">Select</option>
                                            @foreach ($packages as $p)
                                                <option value="{{ $p->id }}">
                                                    ({{ $p->id }})
                                                    - {{ $p->name }} @if (globalPermission('package-change-price-show'))
                                                        ({{ $p->rate }} TK) (s)
                                                    @endif
                                                </option>
                                            @endforeach

                                        </select>
                                    @else
                                        <select name="package_id" class="form-control" required>
                                            <option value="">Select</option>
                                            @foreach ($packages as $p)
                                                <option value="{{ $p->id }}">
                                                    ({{ $p->id }})
                                                    - {{ $p->package_name }}
                                                    @if (globalPermission('package-change-price-show'))
                                                        ({{ $p->package_rate }} TK)
                                                    @endif
                                                </option>
                                            @endforeach

                                        </select>

                                    @endif

                                </div>

                                <div class="col-sm-2">
                                    <button type="button" class="btn btn-primary" id="changePack">Change Package</button>
                                </div>
                            </div>
                        </td>
                    </tr>
                @else
                    <tr>
                        <td colspan="8">

                            <div class="container-fluid " style="background: #d8b4fe;">
                                <div class="row border  p-2">
                                    @can('change-billing-cycle-without-cost')
                                        <div class="col-sm-2">
                                            <label class="flex-1 block text-gray-700 text-sm font-bold mb-2"
                                                for="change_without_cost">
                                                Change Without Cost
                                            </label>
                                        </div>
                                        <div class="col-sm-2">
                                            <select name="change_without_cost" id="change_without_cost"
                                                class="form-control">
                                                <option value="no">No</option>
                                                <option value="yes">Yes</option>
                                            </select>
                                        </div>
                                    @endcan
                                    <div class="col-sm-4"></div>
                                    <div class="col-sm-2 border " id="billCycle">
                                        <select name="billCycle" class="form-control">
                                            <option value="">Select Cycle</option>
                                            @foreach (explode(',', $confday) as $item)
                                                <option value="{{ $item }}">
                                                    {{ $item }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-sm-2" id="expireDate" style="display: none">
                                        <input type="date" class="form-control" name="expire_date">
                                    </div>

                                    <div class="col-sm-2">
                                        <button type="button" class="btn btn-primary" id="changePack">Billing Cycle Change</button>
                                    </div>
                                </div>
                            </div>

                        </td>
                    </tr>

                @endif
            </tbody>
        </table>
    </div>

    <!-- Selected Count Display -->
    <div class="mt-3">
        <span id="selectedCount" class="badge badge-info">Selected: 0</span>
    </div>
</form>

<script>
    $(function() {
        // Update selected count
        function updateSelectedCount() {
            var count = $('.new_class_for_client_id_of_pending:checked').length;
            $('#selectedCount').text('Selected: ' + count);
        }

        // Select/Deselect All
        $('#allSelect').on('click', function() {
            var isChecked = this.checked;
            $('.new_class_for_client_id_of_pending').prop('checked', isChecked);
            updateSelectedCount();
        });

        // Update count when individual checkbox is clicked
        $('.new_class_for_client_id_of_pending').on('change', function() {
            updateSelectedCount();

            // Update "select all" checkbox state
            var totalCheckboxes = $('.new_class_for_client_id_of_pending').length;
            var checkedCheckboxes = $('.new_class_for_client_id_of_pending:checked').length;
            $('#allSelect').prop('checked', totalCheckboxes === checkedCheckboxes);
        });

        // Handle form submission
        $('#changePack').on('click', function(e) {
            e.preventDefault();

            // Collect all checked IDs
            var ids = [];
            $('.new_class_for_client_id_of_pending:checked').each(function() {
                ids.push($(this).val());
            });

            // Validate that at least one checkbox is selected
            if (ids.length === 0) {
                alert('Please select at least one user to proceed.');
                return false;
            }

            // Additional validation for package/billing cycle
            @if (!empty($packages))
                var packageId = $('select[name="package_id"]').val();
                if (!packageId) {
                    alert('Please select a package.');
                    return false;
                }
            @else
                // Check if expire date field is visible
                if ($('#expireDate').is(':visible')) {
                    var expireDate = $('#expireDate input[name="expire_date"]').val();
                    console.log('Expire Date Value:', expireDate); // Debug
                    if (!expireDate || expireDate.trim() === '') {
                        alert('Please select an expire date.');
                        return false;
                    }
                } else {
                    // Otherwise validate billing cycle
                    var billCycle = $('#billCycle select[name="billCycle"]').val();
                    console.log('Bill Cycle Value:', billCycle); // Debug
                    if (!billCycle || billCycle === '') {
                        alert('Please select a billing cycle.');
                        return false;
                    }
                }
            @endif

            // Confirm action
            var confirmMessage = 'Are you sure you want to change ' + ids.length + ' user(s)?';
            if (!confirm(confirmMessage)) {
                return false;
            }

            // Disable button to prevent double submission
            $('#changePack').prop('disabled', true).text('Processing...');

            // Store IDs as comma-separated string in hidden input
            $('#client_ids').val(ids.join(','));

            // Submit the form
            $('#batchUserPackageChange').submit();
        });

        // Toggle between billing cycle dropdown and date picker
        $('#change_without_cost').on('change', function() {
            let type_val = $(this).val();

            if (type_val == 'yes') {
                $('#billCycle').hide();
                $('#billCycle select').prop('required', false);
                $('#expireDate').show();
                $('#expireDate input').prop('required', true);
            } else {
                $('#billCycle').show();
                $('#billCycle select').prop('required', true);
                $('#expireDate').hide();
                $('#expireDate input').prop('required', false);
            }
        });

        // Initialize selected count on page load
        updateSelectedCount();
    });
</script>
