@extends('backend.layouts.app')

@section('content')
<style>
    .remove-icon{
        cursor: default !important;
    }
    .ui-autocomplete {
     z-index: 1 !important;
}
</style>
    <div class="row page-titles">
        <div class="col-md-5 align-self-center">
            <h4 class="text-themecolor"> Member</h4>
        </div>
        <div class="col-md-7 align-self-center text-right">
            <div class="d-flex justify-content-end align-items-center">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
                    <li class="breadcrumb-item active">Member</li>
                </ol>
                @can('Member-create')
                    <a href="{{ route('member.create') }}"> <button type="button"
                            class="btn btn-info d-none d-lg-block m-l-15"><i class="fa fa-plus-circle"></i> Create
                            New</button></a>
                @endcan
            </div>
        </div>
    </div>
    <div class="container-fluid">
        <div id="deleteModal" class="modal fade" role='dialog'>
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body">
                        <p>Are you sure you want to delete this?</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <span id='deleteButton'></span>
                    </div>
                </div>
            </div>
        </div>
        {{-- Status model --}}
        <div id="statusModal" class="modal fade" role='dialog'>
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body">
                        <p>Are you sure you want to change the status?</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <span id='changestatus'></span>
                    </div>
                </div>
            </div>
        </div>



        <div class="modal fade" id="permanentMessageAddModal" tabindex="-1" aria-labelledby="permanentMessageLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <form id="messageTemplateForm" action="{{route('member.permanent.message.send')}}" method="post">
                     @csrf
                     <input type="hidden" id="puids" name="puids">
                    <div class="modal-body">
                        <div class="form-group">
                            {{-- <label for="">Type your text here</label> --}}
                            <textarea name="message" id="" cols="30" rows="10" class="form-control" placeholder="Type here..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button class="btn btn-info">Send</button>
                    </div>
                    </form>
                </div>
            </div>
        </div>
</div>


        <div id="pauseModal" class="modal fade" role='dialog'>
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body">
                        <p>Select what you want to do?</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <span><button type="button" onclick="pauseUnpause('pause')" class="btn btn-info" value="pause">Pause</button></span>
                        <span><button type="button" onclick="pauseUnpause('unpause')" class="btn btn-danger" value="unpause">Unpause</button></span>
                    </div>
                </div>
            </div>
        </div>

        <div id="pauseModalAction" class="modal fade" role='dialog'>
            <form method="post" action="{{route('member.bulkPause')}}">
                @csrf
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body">
                        <p class="pause-p"></p>
                    </div>
                    <div class="modal-footer">
                        <input type="hidden" id="selectedUsersInput" name="selectedUsers">

                        <input type="hidden" id="pausestatus" name="pausestatus" value="">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <span> <button class="btn btn-primary">Submit</button></span>
                    </div>
                </div>
            </div>
        </form>
        </div>


        {{-- suspend --}}
        <div id="suspendModal" class="modal fade" role='dialog'>
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body">
                        <p>Select what you want to do?</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <span><button type="button" onclick="suspendUnsuspend('suspend')" class="btn btn-info" value="suspend">Suspend</button></span>
                        <span><button type="button" onclick="suspendUnsuspend('unsuspend')" class="btn btn-danger">Unsuspend</button></span>
                    </div>
                </div>
            </div>
        </div>

        <div id="suspendModalAction" class="modal fade" role='dialog'>
            <form method="post" action="{{route('member.bulkSuspend')}}">
                @csrf
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-body">
                            <p class="suspend-p"></p>
                        </div>
                        <div class="modal-footer">
                            <input type="hidden" id="selectedUsersIds" name="selectedUsers">
                            <input type="hidden" id="suspendstatus" name="suspendstatus" value="">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                            <span> <button class="btn btn-primary">Submit</button></span>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <div  id="emailModal"  class="modal fade"  role='dialog' >
            <div class="modal-dialog">
                <div class="modal-content">
                    <form id="EmailForm" action="{{ route('member.sendemail') }}" method="POST">
                        <input type="hidden" id="emailselectedUsersInput" name="selectedUsers">
                        @csrf
                        <div class="modal-body">
                            <div class="form-group">
                                <label>Send Email to member</label>
                                <select name="email_slug" class="form-control">
                                    <option value="">--- Select Email ---</option>
                                    @foreach($emaillist as $email)
                                        <option value="{{$email->slug}}">{{$email->name}}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                            <button class="btn btn-info">Send Email</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>


        {{-- end --}}
        <!-- Password Update Modal -->
        <div id="passwordModal" class="modal fade" role='dialog'>
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">Update Password</h4>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                        <form id="passwordForm" action="{{ route('member.update') }}" method="POST">
                            @csrf
                            <input type="hidden" name="user_id" id="user_id">

                            <div class="form-group">
                                <label for="new_password">New Password</label>
                                <div class="input-group">
                                    <input id="new_password" type="password"
                                        class="form-control @error('new_password') is-invalid @enderror"
                                        name="new_password">
                                    <span class="input-group-append">
                                        <button class="btn btn-outline-secondary cursor-pointer" type="button"
                                            id="toggleNewPassword">
                                            <i class="fa fa-eye-slash" id="eye-new-password"></i>
                                        </button>
                                    </span>
                                </div>
                                @error('new_password')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>

                            <div class="form-group">
                                <label for="new_password_confirmation">Confirm New Password</label>
                                <div class="input-group">
                                    <input id="new_password_confirmation" type="password"
                                        class="form-control @error('new_password_confirmation') is-invalid @enderror"
                                        name="new_password_confirmation">
                                    <span class="input-group-append">
                                        <button class="btn btn-outline-secondary cursor-pointer" type="button"
                                            id="toggleNewPasswordConfirm">
                                            <i class="fa fa-eye-slash" id="eye-new-password-confirm"></i>
                                        </button>
                                    </span>
                                </div>
                                @error('new_password_confirmation')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>

                            <div class="modal-footer">
                                <button type="submit" class="btn btn-primary">Update Password</button>
                                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>


        <div  id="messageModal" class="modal fade" role='dialog'>
            <div class="modal-dialog">
                <div class="modal-content">
                    <form id="messageTemplateForm" action="{{route('member.message.send')}}" method="post">
                     @csrf
                     <input type="hidden" id="smuIds" name="smuIds">
                    <div class="modal-body">
                        <div class="form-group">
                            {{-- <label for="">Type your text here</label> --}}
                            <textarea name="text" id="" cols="30" rows="10" class="form-control" placeholder="Type here..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button class="btn btn-info">Send</button>
                    </div>
                    </form>
                </div>
            </div>
        </div>

        <div  id="warningMessageModal" class="modal fade" role='dialog'>
            <div class="modal-dialog">
                <div class="modal-content">
                    <form id="messageTemplateForm" action="{{route('member.warning.message.send')}}" method="post">
                     @csrf
                     <input type="hidden" id="userids" name="userids">
                    <div class="modal-body">
                        <div class="form-group">
                            {{-- <label for="">Type your text here</label> --}}
                            <textarea name="message" id="" cols="30" rows="10" class="form-control" placeholder="Type here..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button class="btn btn-info">Send</button>
                    </div>
                    </form>
                </div>
            </div>
        </div>

        <div  id="permanentMessageModal" class="modal fade" role='dialog'>
            <div class="modal-dialog">
                <div class="modal-content">
                    
                    <form id="permanentMessageTemplateForm" action="{{route('member.permanent.message.remove')}}" method="post">
                     @csrf
                    <div class="modal-body">
                        <div class="form-group">
                            <p>Do you want to <strong>add</strong> or <strong>remove</strong> the permanent message for selected members?</p>
                            <input type="hidden" id="actionValue" name="actionValue">
                            <input type="hidden" id="suserids" name="suserids">
                        </div>
                    </div>
                    <div class="modal-footer">
                    <button type="button" class="btn btn-primary" onclick="setAction('add')">Add</button>
                    <button class="btn btn-danger ms-3" onclick="setAction('remove')">Remove</button>
                    </div>
                    </form>
                </div>
            </div>
        </div>
        

        <div id="areaSubscribeModal" class="modal fade" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <form id="areaSubscribeForm" action="{{route('member.areaSubscribe')}}" method="post">
                        @csrf
                        <div class="modal-body">
                            <input type="hidden" name="memberId" id="memberId" value="">
                            <label>Select Areas</label>
                            <div class="row">
                                @foreach ($areas as $area)
                                    <div class="col-md-4" style="margin-bottom:2rem">
                                        <input onclick="appendArea(this, '{{ $area->name }}')" type="checkbox" class="checkboxCheck" area-id="{{ $area->id }}" name="area[{{ $area->id }}]" value="{{ $area->id }}">
                                        {{ $area->name }}
                                    </div>
                                @endforeach
                            </div>
        
                            <label>Selected Areas</label>
                            <div class="row selected-areas">
                                <!-- Selected areas will be appended here -->
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                            <button class="btn btn-info">Save</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

     
        <div class="content-wrapper">
            @if (session('status'))
                <div class="alert alert-success alert-dismissible fade show" role="alert"><i
                        class="far fa-check-circle"></i>
                    {{ session('status') }}
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            @endif
            @if (session('error'))
                <div class="alert alert-danger alert-dismissible fade show" role="alert"><i
                        class="far fa-check-circle"></i>
                    {{ session('error') }}
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            @endif

            <section class="content">
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="form-inline">
                                    <form action="{{ route('member') }}" method="get" id="form">
                                        <div class="row">
                                            <!-- Search Field -->
                                            <div class="mr-3 mb-2">
                                                <input type="text" id="search_input" name="search" value="{{ $search }}" class="form-control" placeholder="Search...">
                                                {{-- <input type="text" name="search" value="{{ $search }}" class="form-control" placeholder="Search by Name, Email, or Account Number..."> --}}
                                            </div>

                                            <!-- Dropdown for Status Filter -->
                                            <div class="mr-3 mb-2">
                                                <select name="status" class="form-control">
                                                    <option value="">All Status</option>
                                                    <option value="1" {{ request('status') == '1' ? 'selected' : '' }}>Active</option>
                                                    <option value="0" {{ request('status') == '0' ? 'selected' : '' }}>Inactive</option>
                                                </select>
                                            </div>

                                            <!-- Dropdown for Reason Filter -->
                                            <div class="mr-3 mb-2">
                                                <select name="reason" class="form-control">
                                                    <option value="">All Reasons</option>
                                                    @foreach ($reasons as $reason)
                                                        <option value="{{ $reason->id }}" {{ request('reason') == $reason->id ? 'selected' : '' }}>
                                                            {{ $reason->title }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </div>

                                            <!-- Dropdown for Nature Filter -->
                                            <div class="mr-3 mb-2">
                                                <select name="nature" class="form-control">
                                                    <option value="">All Natures</option>
                                                    @foreach ($natures as $nature)
                                                        <option value="{{ $nature->id }}" {{ request('nature') == $nature->id ? 'selected' : '' }}>
                                                            {{ $nature->title }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </div>

                                            <!-- Submit Button and Reload Link -->
                                            <div class="mr-3 mb-2 d-flex">
                                                <button class="btn btn-sidebar btn btn-secondary w-100" type="submit">
                                                    <i class="fas fa-search fa-fw"></i>
                                                </button>
                                                <a onclick="clearCheckbox()" href="{{ route('member') }}" class="btn btn-secondary w-100" title="Reload">
                                                    <i class="fas fa-sync"></i>
                                                </a>
                                            </div>


                                        </div>
                                    </form>
                                </div>
                                <br>
                                <div class="action-div text-right">
                                    <div style="text-align: right">
                                        <form id="mailTemplateForm" action="{{route('member.mail.template')}}" method="post">
                                            @csrf
                                            <input type="hidden" id="selectedids" name="selectedids">
                                            <button style="float: right; margin-left: 3px;" type="button" class="btn btn-info btn-sm" onclick="customMailTemplate()" title="Send Mail">Send Mail
                                        </form>
                                        </button>

                                        <button type="button" onclick="warningMessage()" class="btn btn-success btn-sm" title="Message">Warning Message
                                        </button>
                                        <button type="button" onclick="permanentMessagePopup()" class="btn btn-success btn-sm" title="Message">Permanent Message</button>
                                        </button>
                                        <!-- permanentMessage -->
                                        
                                        <button type="button" onclick="customMessagePopup()" class="btn btn-success btn-sm" title="Message">Message
                                        {{-- </form> --}}
                                        </button>
                                        <button type="button" onclick="pauseAction()" class="btn btn-danger btn-sm" title="Pause\Unpause">Pause\Unpause
                                        </button>
                                        <button type="button" onclick="suspendAction()" class="btn btn-danger btn-sm" title="Suspend\Unsuspend">Suspend\Unsuspend
                                        </button>
                                        <button type="button" onclick="bulkemail()" class="btn btn-primary btn-sm" title="Send Email" >Send Basic Email</button>
                                    </div>

                            </div>

                            <br>

                           
                                <div class="table-responsive">
                                    <table id="user" class="table table-bordered table-hover">
                                        <thead>
                                            <th><input type="checkbox" id="selectAll">
                                            </th>

                                            <th>@sortablelink('business_area_code', 'Code')</th>
                                            <th>@sortablelink('areaCodeFull.name', 'Name')</th>
                                            <th>@sortablelink('person_significate_control', 'PSC')</th>
                                            <th>@sortablelink('account_number', 'Number')</th>
                                            <th>@sortablelink('nature.title', 'Nature')</th>
                                            <th>@sortablelink('permanent_distribution_member', 'PDF')</th>
                                            <th>@sortablelink('status', 'Status')</th>
                                            <th>@sortablelink('reason', 'Reason')</th>
                                            <th>@sortablelink('business_address', 'B Address Line 1')</th>
                                            <th>@sortablelink('business_address_line_two', 'B Address Line 2')</th>
                                            <th>@sortablelink('business_post_code', 'Postcode')</th>
                                            <th>@sortablelink('business_district_code', 'Postcode District ')</th>
                                            <th>@sortablelink('company_name', 'Company Name')</th>
                                            <th>@sortablelink('company_number', 'Company No')</th>
                                            <th>@sortablelink('company_address', 'C Address line 1')</th>
                                            <th>@sortablelink('company_address_line_two', 'C Address line 2')</th>
                                            <th>Actions</th>
                                            <th>@sortablelink('created_at', 'Created At')</th>
                                            <th>@sortablelink('updated_at', 'Updated At')</th>

                                        </thead>
                                        <tbody id="memberTable">
                                            @if (count($members) > 0)
                                                @php
                                                    $i = $members->perPage() * ($members->currentPage() - 1);
                                                @endphp
                                                @foreach ($members as $member)
                                                    <tr>
                                                        <td>
                                                            <input type="checkbox" value="{{ $member->id }}"
                                                                   class="member-checkbox"
                                                                   {{ in_array($member->id, json_decode(request()->cookie('selectedUsers') ?? '[]', true)) ? 'checked' : '' }}>
                                                        </td>

                                                    <td>{{ $member->business_area_code}}
                                                    <td>{{ $member->areaCodeFull?->name}}
                                                    <td>{{ $member->person_significate_control}}
                                                    <td>{{ $member->account_number }}</td>
                                                    <td>{{ $member->nature?->title }}</td>
                                                    <td>{{ $member->permanent_distribution_member==1? 'Yes':'No'}}</td>
                                                    <td>
                                                        @if ($member->status == 1)
                                                            <button type="button"
                                                                class="btn btn-success btn-sm remove-icon"><span>Active</span></button>
                                                        @else
                                                            <button
                                                            type="button"
                                                                class="btn btn-danger btn-sm remove-icon"><span>Inactive</span></button>
                                                        @endif
                                                    </td>
                                                    <td>{{ $member->reasonDet?->code? $member->reasonDet?->code:'' }}</td>
                                                    <td>{{ $member->business_address}}</td>
                                                    <td>{{ $member->business_address_line_two}}</td>
                                                    <td>{{ $member->business_post_code }}</td>
                                                    <td>{{ $member->business_district_code}} </td>
                                                    <td>{{ $member->company_name}} </td>
                                                    <td>{{ $member->company_number}} </td>
                                                    <td>{{ $member->company_address}} </td>
                                                    <td>{{ $member->company_address_line_two}} </td>
                                                       
                                                        {{-- <td>{{ $member->permanent_active_action==1? 'Yes':'No'  }} --}}
                                                      

                                                        <!-- <td>{{ $member->updated_at->format(config('app.time') ?? 'Y-m-d ') }}</td> -->
                                                        
                                                        <td>

                                                            @can('Member-list')
                                                                <a href="{{ route('member.view', ['id' => $member->id]) }}">
                                                                    <button class="btn btn-info btn-sm" title="view"><i
                                                                            class="fas fa-eye"></i></button>
                                                                </a>
                                                                {{-- <a href="{{ route('employer.reviews',['id' => $member->id]) }}">
                                                        <button class="btn btn-info btn-sm" title="Rating and Review"><i class="fa-solid fa-star"></i></button>
                                                    </a> --}}
                                                            @endcan
                                                            @can('Member-edit')
                                                                <a  href="{{ route('member.edit', ['id' => $member->id] + request()->query()) }}">
                                                                    <button class="btn btn-primary btn-sm" title="edit"><i
                                                                            class="fas fa-edit"></i></button>
                                                                </a>
                                                            @endcan
                                                            @can('Member-list-change-password')
                                                                <button class="btn btn-warning btn-sm" title="update password"
                                                                    onclick="showPasswordModal({{ $member->id }})"><i
                                                                        class="fas fa-key"></i></button>
                                                                {{-- <button class="btn btn-danger btn-sm" title="delete"
                                                    onclick="confirmDeleteModal(@php echo $member->id; @endphp)"><i
                                                        class="fas fa-trash"></i>
                                                    </button> --}}
                                                            @endcan
                                                            {{-- @can('Member-list-change-password') --}}
                                                            <button class="btn btn-warning btn-sm" title="update password"
                                                                onclick="areaSubscribe({{ $member }})"><i
                                                                    class="fas fa-key"></i></button>
                                                        {{-- @endcan --}}
                                                        
                                                        {{-- Send an email to member --}}
                                                            {{-- <button class="btn btn-warning btn-sm send-email-btn" data-id="{{ $member->id }}" title ="Send Welcome Email"><i class="fa fa-envelope"></i> 
                                                            </button> --}}
                                                        </td>
                                                        <td>{{ \Carbon\Carbon::parse($member->created_at)->format(config('GET.admin_date_time_format')) }}
                                                        </td>
                                                        <td>{{ \Carbon\Carbon::parse($member->updated_at)->format(config('GET.admin_date_time_format')) }}
                                                        </td>
                                                                                                       <!-- Add other columns as needed -->
                                                    </tr>
                                                    {{-- <div  id="areaSubscribeModal" class="modal fade" role='dialog'>
                                                        <div class="modal-dialog">
                                                            <div class="modal-content">
                                                                <form id="messageTemplateForm" action="{{route('member.areaSubscribe')}}" method="post">
                                                                 @csrf
                                                                <div class="modal-body">
                                                                    <input type="hidden" name="memberId" id="memberId" value="">
                                                                    <label>Select Areas</label> 
                                                                    <div class="row">
                                                                    @foreach ($areas as $code => $area)
                                                                    
                                                                    <div class="col-md-4" style="margin-bottom:2rem">
                                                                        <input onclick="appendArea(this,'{{$area->name}}')" type="checkbox" class="checkboxCheck" area-id="{{$area->id}}" name="area[{{$area->id}}]">{{$area->name}}
                                                                    </div>
                                                                    @endforeach
                                                                    </div>
                                            
                                                                    <label>Selected Areas</label> 
                                                                    <div class="row selected-areas">
                                                                    
                                                                    </div>
                                                                </div>
                                                                <div class="modal-footer">
                                                                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                                                                    <button class="btn btn-info">Save</button>
                                                                </div>
                                                                </form>
                                                            </div>
                                                        </div>
                                                    </div> --}}
                                            
                                                @endforeach
                                            @else
                                                <tr>
                                                    <td colspan="12">
                                                        <h6>
                                                            <center>No Records Found</center>
                                                        </h6>
                                                    </td>
                                                </tr>
                                            @endif
                                        </tbody>
                                    </table>
                                </div>
                                <div class="filter-count">
                                    <label for="recordsPerPage">Show:</label>
                                    <select id="recordsPerPage" class="form-control w-auto" onchange="changeRecordsPerPage()">
                                        <option value="10" {{ request()->get('recordsPerPage') == 10 ? 'selected' : '' }}>10</option>
                                        <option value="50" {{ request()->get('recordsPerPage') == 50 ? 'selected' : '' }}>50</option>
                                        <option value="100" {{ request()->get('recordsPerPage') == 100 ? 'selected' : '' }}>100</option>
                                        <option value="500" {{ request()->get('recordsPerPage') == 500 ? 'selected' : '' }}>500</option>
                                    </select>
                                </div>
                                <div class="d-flex justify-content-end mb-3 align-items-center mt-3">
                                    <label for="gotoPage" class="mr-2">Go to Page:</label>
                                    <input type="number" id="gotoPage" class="form-control w-auto" min="1" max="{{ $members->lastPage() }}" value="{{ $members->currentPage() }}">
                                    <button class="btn btn-primary ml-2" onclick="goToPage()">Go</button>
                                </div>
                                

                                @if ($members->total() > 0)
                                    <div class="d-flex justify-content-between align-items-center">
                                        <!-- Display custom number of entries -->
                                        <div class="entries-info">
                                            Showing {{ $members->firstItem() }} to {{ $members->lastItem() }} of
                                            {{ $members->total() }} entries
                                        </div>

                                        <!-- Pagination -->
                                        <div class="pagination-wrapper float-right">
                                            {{ $members->links('vendor.pagination.bootstrap-4') }}
                                        </div>
                                    </div>
                                @endif

                            </div>

                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>
@push('custom-script')
    <script>
        $(document).on("click", ".send-email-btn", function () {
            var userid = $(this).data("id");
            var button = $(this);
            button.prop('disabled', true);
            $.ajax({
                url: "{{ route('member.welcome.email.send') }}",
                type: "POST",
                data: {
                    id: userid,
                    _token: "{{ csrf_token() }}"
                },
                success: function (response) {
                    if (response.success) {
                        Swal.fire({
                            title: "Success!",
                            text: response.message,
                            icon: "success",
                            confirmButtonText: "OK"
                        });
                    } else {
                        Swal.fire({
                            title: "Error!",
                            text: "Something went wrong.",
                            icon: "error",
                            confirmButtonText: "OK"
                        });
                    }
                },
                error: function (xhr) {
                    Swal.fire({
                        title: "Error!",
                        text: xhr.responseJSON?.message || "Failed to send email.",
                        icon: "error",
                        confirmButtonText: "OK"
                    });
                },
                complete: function() {
                button.prop('disabled', false); // Re-enable button
            }
            });
        });
    </script>

    <script type="text/javascript">
        function confirmDeleteModal(id) {
            $('#deleteModal').modal();
            $('#deleteButton').html(
                '<a id="delete-button" class="btn btn-danger" style="color:white;" onclick="deleteData(' + id +
                ')">Delete</a>');
        }

        function deleteData(id) {
            $('#delete-button').addClass('disabled');
            $('#delete-button').css('pointer-events', 'none'); // Disable click events
            $('#delete-button').css('opacity', '0.6'); // Make it look disabled
            location.replace("{{ route('member.delete') }}?id=" + id);
        }

        function myFunction(id) {
            $('#statusModal').modal();
            $('#changestatus').html('<a class="btn btn-danger" style="color:white;" onclick="changedataData(' + id +
                ')">Ok</a>')
        }

        function pauseAction(id) {
            if(selectedUsers.size === 0){
                errorPopup();
                return false;
            }
            $('#pauseModal').modal();
        }

        function bulkemail() {
            if(selectedUsers.size === 0) {
                errorPopup();
                return false;
            }
            $('#emailselectedUsersInput').val(JSON.stringify([...selectedUsers]));
            $('#emailModal').modal();
        } 

        function pauseUnpause(action){
            $('#pauseModal').modal('hide');
            $('#pauseModalAction').modal();
            $('#selectedUsersInput').val(JSON.stringify([...selectedUsers]));
            $('#pausestatus').val(action);
            $('.pause-p').text(`Are you sure you want to ${action} ? `);
        }

        function suspendAction(id) {
            if( selectedUsers.size === 0 ) {
                errorPopup();
                return false;
            }
            $('#suspendModal').modal();
        }

        function suspendUnsuspend(action){
            $('#suspendModal').modal('hide');
            $('#suspendModalAction').modal();
            $('#selectedUsersIds').val(JSON.stringify([...selectedUsers]));
            $('#suspendstatus').val(action);
            $('.suspend-p').html(`Are you sure you want to ${action} ? `);
        }

        function changedataData(id) {
            $('#statusModal').modal('hide');
            location.replace("{{ route('member.changestatus') }}?id=" + id);
        }

        function showPasswordModal(id) {
            $('#user_id').val(id);
            $('#passwordModal').modal('show');
        }

        // $(document).ready(function() {
        //     $('#passwordForm').on('submit', function(e) {
        //         e.preventDefault();
        //         const form = $(this);
        //         $.ajax({
        //             url: form.attr('action'),
        //             type: 'POST',
        //             data: form.serialize(),
        //             success: function(response) {
        //                 if(response.success) {
        //                     alert('Password updated successfully');
        //                     $('#passwordModal').modal('hide');
        //                 } else {
        //                     alert('Error updating password');
        //                 }
        //             },
        //             error: function() {
        //                 alert('Error processing request');
        //             }
        //         });
        //     });
        // });
        document.addEventListener('DOMContentLoaded', function() {

            $(document).ready(function() {
                $.validator.addMethod("regex", function(value, element, regexp) {
                    var re = new RegExp(regexp);
                    return this.optional(element) || re.test(value);
                }, "Please enter a valid email address.");

                $.validator.addMethod("strongPassword", function(value, element) {
                        return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/.test(
                            value);
                    },
                    "Password must be at least 8 characters long and include one uppercase letter, one lowercase letter, one number, and one special character."
                    );

                $.validator.addMethod("noOnlySpaces", function(value, element) {
                    return $.trim(value).length !== 0;
                }, "Please enter a value other than spaces.");
                $('#passwordForm').validate({
                    rules: {
                        new_password: {
                            required: true,
                            minlength: 8,
                            noOnlySpaces: true,
                            strongPassword: true
                        },
                        new_password_confirmation: {
                            required: true,
                            equalTo: "#new_password",
                            noOnlySpaces: true
                        }
                    },
                    messages: {
                        new_password: {
                            required: "Please enter a new password",
                            minlength: "Password must be at least 6 characters long"
                        },
                        new_password_confirmation: {
                            required: "Please confirm your new password",
                            equalTo: "Passwords do not match"
                        }
                    },
                    errorPlacement: function(error, element) {
                        // Place the error message below the input-group
                        error.insertAfter(element.closest('.input-group'));
                    },
                    highlight: function(element) {
                        $(element).addClass('is-invalid').removeClass('is-valid');
                    },
                    unhighlight: function(element) {
                        $(element).removeClass('is-invalid');
                        // .addClass('is-valid');
                    },
                    submitHandler: function(form) {
                        // Disable the submit button to prevent multiple submissions
                        $(form).find('button[type="submit"]').attr("disabled", true);

                        // Submit the form
                        form.submit();
                    }
                });

                $('#messageTemplateForm').validate({
                    rules: {
                        text: {
                            required: true,
                            noOnlySpaces:true
                        },
                    },
                    messages: {
                        text: {
                            required: "Message is required",
                        }
                    },
                    submitHandler: function(form) {
                        // Disable the submit button to prevent multiple submissions
                        $(form).find('button[type="submit"]').attr("disabled", true);

                        // Submit the form
                        form.submit();
                    }
                });

                $("#EmailForm").validate({
                    rules: {
                        email_id: {
                            required: true
                        }
                    },
                    messages: {
                        email_id: {
                            required: "Please select email which you want to send."
                        }
                    },
                    submitHandler: function (form) {
                        form.submit(); // Submit form if valid
                    }
                });
                
            });
        });


        $(document).ready(function() {
            // Toggle visibility for New Password field
            $('#toggleNewPassword').click(function() {
                const newPasswordField = $('#new_password');
                const newPasswordIcon = $('#eye-new-password');
                const type = newPasswordField.attr('type') === 'password' ? 'text' : 'password';
                newPasswordField.attr('type', type);
                newPasswordIcon.toggleClass('fa-eye-slash fa-eye');
            });

            // Toggle visibility for Confirm New Password field
            $('#toggleNewPasswordConfirm').click(function() {
                const confirmPasswordField = $('#new_password_confirmation');
                const confirmPasswordIcon = $('#eye-new-password-confirm');
                const type = confirmPasswordField.attr('type') === 'password' ? 'text' : 'password';
                confirmPasswordField.attr('type', type);
                confirmPasswordIcon.toggleClass('fa-eye-slash fa-eye');
            });
        });

    var selectedUsers;
        document.addEventListener("DOMContentLoaded", function () {
    // Load selected users from localStorage
    selectedUsers = new Set(JSON.parse(localStorage.getItem("selectedUsers")) || []);

    // Function to update the state of checkboxes and the "Select All" checkbox
    function updateCheckboxState() {
        let checkboxes = document.querySelectorAll("#memberTable input[type='checkbox']");

        // Update each checkbox based on selected users
        checkboxes.forEach(checkbox => {
            checkbox.checked = selectedUsers.has(checkbox.value);
        });

        // Check "Select All" only if all checkboxes are selected (based on selectedUsers set)
        let allSelected = [...checkboxes].every(cb => selectedUsers.has(cb.value));
        document.getElementById("selectAll").checked = allSelected;
    }

    // "Select All" checkbox logic
    document.getElementById("selectAll").addEventListener("change", function () {
        let checkboxes = document.querySelectorAll("#memberTable input[type='checkbox']");

        if (this.checked) {
            // Add all users' IDs to selectedUsers
            checkboxes.forEach(cb => selectedUsers.add(cb.value));
        } else {
            // Remove all users' IDs from selectedUsers
            checkboxes.forEach(cb => selectedUsers.delete(cb.value));
        }

        // Save the updated set of selected users to localStorage
        localStorage.setItem("selectedUsers", JSON.stringify([...selectedUsers]));

        // Update checkbox states based on localStorage
        updateCheckboxState();
    });

    // Individual checkbox logic
    document.querySelectorAll("#memberTable input[type='checkbox']").forEach(checkbox => {
        checkbox.addEventListener("change", function () {
            if (this.checked) {
                selectedUsers.add(this.value);
            } else {
                selectedUsers.delete(this.value);
            }

            // Save updated set of selected users
            localStorage.setItem("selectedUsers", JSON.stringify([...selectedUsers]));

            // Update checkbox states based on localStorage
            updateCheckboxState();
        });
    });

    // Function to fetch all user IDs (this ensures the "Select All" logic works across pages)
    function fetchAllUserIds() {
        return fetch('/get-all-user-ids')
            .then(response => response.json())
            .then(data => data.userIds)
            .catch(() => []);
    }

    // Ensure checkboxes are loaded correctly from localStorage when page loads
    updateCheckboxState();
});

    function changeRecordsPerPage() {
        const recordsPerPage = document.getElementById('recordsPerPage').value;
        const currentUrl = window.location.href.split('?')[0]; // Get the base URL without query params
        const url = `${currentUrl}?recordsPerPage=${recordsPerPage}`;
        window.location.href = url; // Redirect to the same page with the new `recordsPerPage` query parameter
    }

    function customMailTemplate()
    {
        if(selectedUsers.size===0){
            errorPopup();
            return false;
        }
        document.getElementById('selectedids').value = JSON.stringify([...selectedUsers]);
        document.getElementById('mailTemplateForm').submit();
    }

    function customMessagePopup()
    {
        if(selectedUsers.size===0){
            errorPopup();
            return false;
        }
        document.getElementById('smuIds').value = JSON.stringify([...selectedUsers]);
        new bootstrap.Modal(document.getElementById('messageModal')).show();

        //  document.getElementById('mailTemplateForm').submit();
    }

     function warningMessage()
    {
        if(selectedUsers.size===0){
            errorPopup();
            return false;
        }
        document.getElementById('userids').value = JSON.stringify([...selectedUsers]);
        new bootstrap.Modal(document.getElementById('warningMessageModal')).show();

        //  document.getElementById('mailTemplateForm').submit();
    }


    function permanentMessagePopup() {
        
    // Example: Set selected IDs (Replace this with dynamic IDs from your selection)
 // This should come from your selection logic
    document.getElementById("suserids").value = JSON.stringify([...selectedUsers]);
    
    // Show the Bootstrap modal
    var myModal = new bootstrap.Modal(document.getElementById('permanentMessageModal'));
    myModal.show();
}


    // function permanentMessagePopup()
    // {
    //     if(selectedUsers.size===0){
    //         errorPopup();
    //         return false;
    //     }

    //     document.getElementById('suserids').value = JSON.stringify([...selectedUsers]);
    //     new bootstrap.Modal(document.getElementById('permanentMessageModal')).show();
    // }
    
// permanentMessage

    // function permanentMessage()
    // {
    //     if(selectedUsers.size===0){
    //         errorPopup();
    //         return false;
    //     }
    //     document.getElementById('suserids').value = JSON.stringify([...selectedUsers]);
    //     new bootstrap.Modal(document.getElementById('permanentMessageModal')).show();
    // }



    function clearCheckbox(){
        selectedUsers = [];
        localStorage.removeItem("selectedUsers");
    }


function errorPopup()
{
    Swal.fire({
            icon: "error",
            title: "Invalid Action",
            text: "Select atleast one member!",
            confirmButtonColor: "#ff5722", // Orange theme (adjust to your style)
        });
}


function areaSubscribe(member) {
    $('#areaSubscribeForm')[0].reset();
    var selectedAreas = member.areas;  // Array of area objects

    // Log selected areas to console for debugging
    console.log(selectedAreas);

    // Loop through checkboxes and check if the area ID matches
    selectedAreas.forEach(function(area) {
        console.log('area',area,'area');
    $('.checkboxCheck').each(function() {

            // Check if the checkbox's area-id matches the selected area id
                console.log('awd',$(this).attr('area-id'),area);
            if (parseInt($(this).attr('area-id')) === area.id) {
                $(this).prop('checked', true);  // Check the checkbox
                appendArea(this, area.name);  // Add the area to selected areas section
            }
        });
    });

    // Show the modal and set the member ID
    $('#areaSubscribeModal').modal('show');
    $('#memberId').val(member.id);
}

    function appendArea($this,area){
        if($($this).is(':checked')){
            $('.selected-areas').append(`<div class="col-md-4 selected-item" data-area="${area}" style="margin-bottom:2rem">${area}</div>`);
        }else{
            $('.selected-areas .selected-item').each(function() {
                if ($(this).attr('data-area') === area) {
                    $(this).remove();
                }
            });
        }

    }

$(document).ready(function() {
        $("#search_input").autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: "{{ route('member.search') }}", // API route
                    type: "GET",
                    dataType: "json",
                    data: { search: request.term },
                    success: function(data) {
                        response(data); // Pass formatted data to autocomplete
                    },
                    error: function(xhr) {
                        console.error("Error fetching autocomplete data:", xhr);
                    }
                });
            },
            minLength: 2, // Start searching after typing 2 characters
            select: function(event, ui) {
                $("#search_input").val(ui.item.value); // Set selected value
                return false;
            }
        });
    });



    function goToPage() {
        var page = parseInt(document.getElementById('gotoPage').value);
        var maxPage = {{ $members->lastPage() }}; // Get total pages

        if (page >= 1 && page <= maxPage) {
            var url = new URL(window.location.href);
            url.searchParams.set('page', page);
            window.location.href = url.toString();
        } else {
            alert("Please enter a valid page number between 1 and " + maxPage);
        }
    }


    function setAction(action) {
        if(action=="add"){
            // document.getElementById('userids').value = JSON.stringify([...selectedUsers]);
            $('#permanentMessageModal').removeClass('show').hide();

            new bootstrap.Modal(document.getElementById('permanentMessageAddModal')).show();
            $('#puids').val($('#suserids').val());
        }
        document.getElementById("actionValue").value = action;
    }
    </script>
    @endpush
@stop
