@extends('backend.layouts.app')

@section('content')
    <style>
        .selected-row {
            background-color: #dfdfdf !important;
            /* Light blue background */
        }

        .dt-buttons {
            float: right !important;
        }
    </style>
    <div class="row page-titles">
        <div class="col-md-5 align-self-center">
            <h4 class="text-themecolor"> DF Panel</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">DF Panel</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 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('area.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="selectedAreasInput" name="selectedAreas">

                            <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>


        <div id="dfDrmInputModal" class="modal fade show" role='dialog'>
            <form id="dfDrmInputForm"  method="post" action="{{ route('area.bulkDfDrmChange') }}">
                @csrf
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-body">
                            <p class="dfdrm-p"></p>
                            <input placeholder="Enter the value you want to change." type="text" class="form-control" name="value" required>
                        </div>
                        <div class="modal-footer">
                            <input type="hidden" id="dfDrmAreas" name="selectedAreas">

                            <input type="hidden" id="dfDrmStatus" name="dfDrmStatus" 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('area.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="selectedAreasIds" name="selectedAreas">
                        <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> --}}

        {{-- end --}}
        <!-- Password Update Modal -->

        <div id="messageModal" class="modal fade" role='dialog'>
            <div class="modal-dialog">
                <div class="modal-content">
                    <form id="messageTemplateForm" action="{{ route('area.message.send') }}" method="post">
                        @csrf
                        <input type="hidden" id="areaCodes" name="areaCodes">
                        <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="dfDrmModal" 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="dfDrmChange('df')" class="btn btn-info" value="pause">DF
                                Change</button></span>
                        <span><button type="button" onclick="dfDrmChange('drm')" class="btn btn-danger"
                                value="unpause">DRM Change</button></span>
                    </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">

                                <br>
                                <div class="action-div text-right">
                                    <div style="text-align: right">
                                        <form id="mailTemplateForm" action="{{ route('area.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="changeDfDrmPopup()"
                                            class="btn btn-success btn-sm" title="Message">Change DF/DRM
                                        </button>
                                        <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 class="btn btn-danger btn-sm" title="view">Terms & Conditions
                                            </button> --}}
                                    </div>
                                </div>
                                <br>
                                <div id="selected-count">Selected: 0</div>
                                <div class="table-responsive">
                                    {{ $dataTable->table(['class' => 'table table-bordered table-hover', 'style' => 'width:100%;', 'id' => 'dfpanel-table']) }}
                                </div>
                                <div style="margin-top: 10px;">
                                    <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>
            </section>
        </div>
    </div>
@endsection

@push('custom-script')
    {!! $dataTable->scripts() !!}
    <!-- Load jQuery before your custom 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('areamanager.delete') }}?id=" + id);
        }

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

        function changedataData(id) {
            $('#statusModal').modal('hide');
            location.replace("{{ route('areamanager.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();
                    }
                });


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

                        // Submit the form
                        form.submit();
                    }
                });
            });
        });
        var dfDrmModal = new bootstrap.Modal(document.getElementById('dfDrmModal'));
        // var selectedAreas = new Set(JSON.parse(localStorage.getItem("selectedAreas")) || []);
        var selectedAreas = new Set([]);


        $(document).ready(function() {
            $('#dfpanel-table tbody').attr('id', 'areaTable');

            // 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');
            });

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

                // Update each checkbox based on selected areas
                checkboxes.each(function() {
                    $(this).prop("checked", selectedAreas.has(this.value));
                });

                // Check "Select All" only if all checkboxes are selected
                let allSelected = checkboxes.length > 0 && checkboxes.toArray().every(cb => selectedAreas.has(cb
                    .value));
                $("#selectAllArea").prop("checked", allSelected);
            }

            // "Select All" checkbox logic
            $("#selectAllArea").on("change", function(e) {
                e.preventDefault();
                let checkboxes = $("#areaTable input[name='area_manager_select']");

                if (this.checked) {
                    // Add all users' IDs to selectedAreas
                    checkboxes.each(function() {
                        selectedAreas.add(this.value);
                    });
                } else {
                    // Remove all users' IDs from selectedAreas
                    checkboxes.each(function() {
                        selectedAreas.delete(this.value);
                    });
                }

                // Save updated set to localStorage
                localStorage.setItem("selectedAreas", JSON.stringify([...selectedAreas]));

                // Update checkbox states
                updateCheckboxState();
            });

            // Individual checkbox logic
            $("#areaTable").on("change", "input[name='area_manager_select']", function() {
                if (this.checked) {
                    selectedAreas.add(this.value);
                } else {
                    selectedAreas.delete(this.value);
                }

                // Save updated set to localStorage
                localStorage.setItem("selectedAreas", JSON.stringify([...selectedAreas]));
                console.log('selectedAreas', selectedAreas);
                // Update checkbox states
                updateCheckboxState();
            });

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

            $(document).on("change", ".distributionFactor", function(e) {
                e.preventDefault();
                let inputField = $(this);
                let value = inputField.val();

                // Convert to an integer and check if it's a valid positive integer
                let intValue = parseInt(value, 10);

                if (isNaN(intValue) || intValue < 0 || value.includes(".")) {
                    inputField.next('.error-tag').text('Only positive whole numbers are allowed!').css(
                        'color', 'red');
                    // Swal.fire({
                    //     icon: "error",
                    //     title: "Invalid Input",
                    //     text: "Only positive whole numbers are allowed!",
                    //     confirmButtonColor: "#ff5722", // Orange theme (adjust to your style)
                    // });
                    inputField.val(0); // Reset to 0 if invalid value is entered
                    return; // Stop execution
                } else if (intValue > 10000) {
                    inputField.next('.error-tag')
                        .text('Only positive whole numbers are allowed!')
                        .css('color', 'red'); // ✅ Correct method
                    inputField.val(0); // Reset to 0 if invalid value is entered
                    return; // Stop execution
                } else {
                    inputField.next('.error-tag').text('');
                }

                let areaCode = inputField.data("code");

                // Proceed with AJAX request only if value is valid
                $.ajax({
                    url: "{{ route('area.save.distributionFactor') }}", // Laravel route
                    type: "POST",
                    data: {
                        _token: "{{ csrf_token() }}",
                        area_code: areaCode,
                        distribution_factor: intValue
                    },
                    success: function(response) {
                        console.log("Data saved successfully");
                    },
                    error: function(xhr) {
                        console.log(xhr.responseText);
                        alert("Error saving data!");
                    }
                });
            });


            $(document).on("change", ".drm", function(e) {
                e.preventDefault();
                let inputField = $(this);
                let value = inputField.val();

                // Convert to an integer and check if it's a valid positive integer
                let intValue = parseInt(value, 10);
                if (isNaN(intValue) || intValue < 0 || value.includes(".")) {

                    inputField.next('.error-tag').text('Only positive whole numbers are allowed!').css(
                        'color', 'red');
                    // Swal.fire({
                    //     icon: "error",
                    //     title: "Invalid Input",
                    //     text: "Only positive whole numbers are allowed!",
                    //     confirmButtonColor: "#ff5722", // Orange theme (adjust to your style)
                    // });
                    inputField.val(0); // Reset to 0 if invalid value is entered
                    return; // Stop execution
                } else if (intValue > 10000) {
                    inputField.next('.error-tag').text('The maximum allowed duration is 10,000 days!').css(
                        'color', 'red');
                    inputField.val(0); // Reset to 0 if invalid value is entered
                    return; // Stop execution
                } else {
                    inputField.next('.error-tag').text('');
                }

                let areaCode = inputField.data("code");
                $.ajax({
                    url: "{{ route('area.save.drm') }}", // Laravel route
                    type: "POST",
                    data: {
                        _token: "{{ csrf_token() }}",
                        area_code: areaCode,
                        drm: intValue
                    },
                    success: function(response) {},
                    error: function(xhr) {
                        console.log(xhr.responseText);
                        alert("Error saving data!");
                    }
                });
            });

        });


        function pauseAction(id) {
            if (selectedAreas.size === 0) {
                errorPopup();
                return false;
            }

            $('#pauseModal').modal();
        }

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


        function dfDrmChange(action) {
            dfDrmModal.hide();
            $('#dfDrmInputModal').modal('show');
            console.log('awd',selectedAreas);
            alert(selectedAreas);
            $('#dfDrmAreas').val(JSON.stringify([...selectedAreas]));
            // $('.dfdrm-p').text(``);
            $('#dfDrmStatus').val(action);
        }



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

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

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

        function customMailTemplate() {
            if (selectedAreas.size === 0) {
                errorPopup();
                return false;
            }

            document.getElementById('selectedids').value = JSON.stringify([...selectedAreas]);
            document.getElementById('mailTemplateForm').submit();
        }

        function customMessagePopup() {
            if (selectedAreas.size === 0) {
                errorPopup();
                return false;
            }

            document.getElementById('areaCodes').value = JSON.stringify([...selectedAreas]);
            new bootstrap.Modal(document.getElementById('messageModal')).show();

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


        function changeDfDrmPopup() {
            if (selectedAreas.size === 0) {
                errorPopup();
                return false;
            }

            document.getElementById('areaCodes').value = JSON.stringify([...selectedAreas]);

            dfDrmModal.show();


        }


        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 errorPopup() {
            Swal.fire({
                icon: "error",
                title: "Invalid Action",
                text: "Select atleast one area!",
                confirmButtonColor: "#ff5722", // Orange theme (adjust to your style)
            });
        }




        $(document).ready(function() {
            $("#search_input").autocomplete({
                source: function(request, response) {
                    $.ajax({
                        url: "{{ route('area.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;
                }
            });
        });



        // Count selected checkboxes
        function countSelected() {

            let selectedCount = $('.member-checkbox:checked').length;
            console.log('Selected rows:', selectedCount);

            // Example: Show count somewhere
            $('#selected-count').text(`Selected: ${selectedCount}`);
        }

        // Attach count event
        $(document).on('change', '.member-checkbox, #selectAllArea', countSelected);


        $(document).on('change', '.member-checkbox', function() {
            const row = $(this).closest('tr');
            if ($(this).is(':checked')) {
                row.addClass('selected-row');
            } else {
                row.removeClass('selected-row');
            }
        });

        // Optional: Handle "Select All" checkbox behavior
        $(document).on('change', '#selectAllArea', function() {
            const isChecked = $(this).is(':checked');
            $('.member-checkbox').prop('checked', isChecked).trigger('change');
        });


        $(document).ready(function() {
            var table = $('#dfpanel-table').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>
@endpush
