@extends('backend.layouts.app')

@section('content')
<style>
    .dt-buttons{
        float: right !important;
    }
</style>
  <div class="row page-titles">
        <div class="col-md-5 align-self-center">
            <h4 class="text-themecolor">Lead Report</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">Lead Report</li>
                </ol>
            </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 id="pauseModal" class="modal fade" role='dialog'>
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body">
                        <p>Select option?</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <span>Pause</span>
                        <span>Unpause</span>
                    </div>
                </div>
            </div>
        </div>
        <div id="pauseModalAction" class="modal fade" role='dialog'>
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body">
                        <p>Are you sure you want to pause?</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <span id='changePauseStatus'></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 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 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="col-md-12">
                                    <form action="{{ route('leadDistributionList') }}" method="get"
                                        id="custom-filter-form">
                                        <div class="row">
                                            <!-- Dropdown for Status Filter -->
                                    

                                    <div class="col-md-3 mr-3 mb-2">
                                    <select name="area[]" id="area_id" multiple class="form-control">
                                        @foreach ($areas as $key => $item)
                                            <option value="{{ $item->name }}" {{ in_array($item->id, request()->input('area', [])) ? 'selected' : '' }}>
                                                {{ $item->code.'-'.$item->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>

                                {{-- Filter by Member Area --}}
                                <div class="col-md-3 mr-3 mb-2">
                                    <select name="member_area[]" id="member_area_id" multiple class="form-control">
                                        @foreach ($areas as $key => $item)
                                            <option value="{{ $item->code }}" {{ in_array($item->id, request()->input('member_area', [])) ? 'selected' : '' }}>
                                                {{ $item->code.'-'.$item->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>

                                {{-- Filter by Member --}}
                                <div class="mr-3 mb-2">
                                    <select name="member_id[]" id="member_id" multiple class="form-control">
                                        @foreach ($allMembers as $memberId => $memberDetail)
                                            <option value='{{ $memberDetail->id }}' {{ collect(request()->member_id)->contains($memberDetail->id) ? 'selected' : '' }}>
                                                {{ $memberDetail->business_name . ' - ' . $memberDetail->account_number }}
                                            </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 href="{{ route('leadDistributionList') }}"
                                                    class="btn btn-secondary w-100" title="Reload">
                                                    <i class="fas fa-sync"></i>
                                                </a>
                                            </div>


                                        </div>
                                    </form>
                                </div>
                                <br>
                                <div class="table-responsive">
                                    {{ $dataTable->table(['class' => 'table-auto w-full border-collapse border border-gray-300 table table-bordered table-hover', 'style' => 'width:100%;', 'id' => 'report-dataTable']) }}
                                <div>
                                    <label for="goToPageInput">Go to Page:</label>
                                    <input type="number" id="goToPageInput" min="1" style="width: 60px;">
                                    <button id="goToPageBtn" class="btn btn-sm btn-primary">Go</button>
                                </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>
@endsection

@push('custom-script')
    {!! $dataTable->scripts() !!}
    <!-- Load jQuery before your custom script -->
    <script type="text/javascript">
        $(document).ready(function() {
            var DataaTable = $('#report-dataTable').DataTable();

            $(document).on('submit', '#custom-filter-form', function(e) {
                e.preventDefault();
                var areas = $('#area_id').val() || '';
                var member_areas = $('#member_area_id').val() || '';
                var memberIds = $('#member_id').val() || '';
                var params = {
                    area: areas,
                    member_area: member_areas,
                    member_id:memberIds 
                };
                DataaTable.ajax.url("{{ route('leadDistributionList') }}?" + $.param(params)).load();
            });
        });

        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) {
            $('#pauseModal').modal();
            $('#changePauseStatus').html(
                '<a href="{{ route('member.bulkPause') }}" class="btn btn-danger" style="color:white;">Ok</a>')
        }


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


        $(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');
            });
        });
        $(document).ready(function() {
            $('#area_id').select2({
                placeholder: "Subscribed Areas",
                allowClear: true
            });
            $('#member_area_id').select2({
                placeholder: "Members Areas",
                allowClear: true
            });

            $('#member_id').select2({
                placeholder: "Members",
                allowClear: true
            });

            
        });


        $(document).ready(function() {
            var table = $('#report-dataTable').DataTable();
            $('#goToPageBtn').on('click', function() {
                var pageNumber = parseInt($('#goToPageInput').val(), 10);

                if (!isNaN(pageNumber) && pageNumber > 0 && pageNumber <= table.page.info().pages) {
                    table.page(pageNumber - 1).draw('page');
                } else {
                    alert('Invalid page number');
                }
            });
        });
    </script>
    {{-- <script>
    console.log(window.Echo);
 document.addEventListener('DOMContentLoaded', function () {
    window.Echo.private('leads')
        .listen('.lead.created', (e) => {
            console.log("🔄 New Lead Received:", e);
            window.Livewire.dispatch('lead.created');
        });
});

</script> --}}
@endpush
