@extends('Admin.layouts.master')

@section('content')
    @php
        $currentPage = 'manage-contact-us';
    @endphp
    <style>
        .action-buttons {
            display: flex;
            gap: 10px;
            /* Adjust the gap between buttons as needed */
            margin: 10px 0;
            /* Add margin if needed to separate from other elements */
        }

        .action-btn {
            display: flex;
            align-items: center;
            text-decoration: none;
            color: inherit;
            background-color: #f1f1f1;
            /* Adjust background color as needed */
            padding: 10px 15px;
            /* Adjust padding as needed */
            border-radius: 5px;
            /* Adjust border radius as needed */
            transition: background 0.3s;
            border: 1px solid #ccc;
            /* Add border for better visibility */
        }

        .action-btn img {
            margin-right: 5px;
            /* Adjust spacing between icon and text as needed */
            width: 16px;
            /* Set a fixed width for the icon */
            height: 16px;
            /* Set a fixed height for the icon */
        }

        .action-btn:hover {
            background-color: #e0e0e0;
            /* Adjust hover background color as needed */
        }

        .action-btn span {
            font-size: 14px;
            /* Adjust font size as needed */
            line-height: 1.5;
            /* Adjust line height as needed */
        }
    </style>

    <div class="layout-px-spacing">
        <div class="middle-content container-xxl p-0">
            <div class="row layout-top-spacing ">
                <div class="top-tabel">
                    <div class="row">
                        <div class="col-md-4">
                            <h6 class="card-title">Manage Contact Us</h6>
                        </div>
                        <div class="col-md-8">
                            <div class="btns-datatabel">
                                <div class="row">
                                    <div class="col-md-7"></div>


                                </div>
                            </div>
                        </div>
                    </div>


                </div>
                <div class="col-xl-12 col-lg-12 col-sm-12  layout-spacing">
                    <div class="widget-content widget-content-area br-8 position-btn">
                        <table id="zero-config" class="table dt-table-hover" style="width:100%">
                            <thead class="text-center">
                                <tr>
                                    <th class="text-start">Sr No.</th>
                                    <th class="text-start">First Name</th>
                                    <th class="text-start">Last Name</th>
                                    <th class="text-start">Email address</th>
                                    <th class="text-start">Date</th>
                                    <th class="text-start">Message</th>
                                    <th class="text-start">Status</th>
                                    <th class="no-content">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="text-center">
                                @foreach ($queries as $querie)
                                    <tr>
                                        <td class="text-start">{{ $loop->iteration }}</td>
                                        <td class="text-start">{{ $querie->customer?->first_name ?? 'N/A' }}</td>
                                        <td class="text-start">{{ $querie->customer?->last_name ?? 'N/A' }}</td>
                                        <td class="text-start">{{ $querie['email'] }}</td>
                                        <td class="text-start">{{ $querie['created_at']->format('d-m-y') }}</td>
                                        <td>
                                            <a class="view-btn m-0" href="#" data-toggle="modal"
                                                data-target="#view-message-modal" data-ids="{{ $querie['id'] }}"
                                                data-message="{{ $querie['message'] }}">View</a>
                                        </td>
                                        <td class="text-center">
                                            <form>
                                                <div class="switch-btn" id="status-change">
                                                    <input type="checkbox" id="switch{{ $querie['id'] }}" switch="bool"
                                                        data-id="{{ $querie['id'] }}" name="status" value="1"
                                                        {{ $querie['is_reply'] ? 'checked' : '' }} />
                                                    <label for="switch{{ $querie['id'] }}" data-on-label="Resolved"
                                                        data-off-label="Pending"></label>
                                                </div>
                                            </form>
                                        </td>
                                        <td>
                                            <!-- <div class="dropout">
                                                                                                                                                <button class="more">
                                                                                                                                                    <span></span>
                                                                                                                                                    <span></span>
                                                                                                                                                    <span></span>
                                                                                                                                                </button>
                                                                                                                                                <ul>
                                                                                                                                                    <li>
                                                                                                                                                        <a href="" data-toggle="modal" data-target="#reply-modal">
                                                                                                                                                            <img src="../src/assets/img/restore.svg" />
                                                                                                                                                            <span>Reply</span>
                                                                                                                                                        </a>
                                                                                                                                                    </li>
                                                                                                                                                    <li>
                                                                                                                                                        <a href="" data-toggle="modal" data-target="#delete-modal">
                                                                                                                                                            <img src="../src/assets/img/delete-recycle.svg" />
                                                                                                                                                            <span>Delete</span>
                                                                                                                                                        </a>
                                                                                                                                                    </li>
                                                                                                                                                </ul>

                                                                                                                                            </div> -->
                                            @if (!$querie['is_reply'])
                                                <div class="action-buttons">
                                                    <a href="#" class="action-btn reply-button" data-toggle="modal"
                                                        data-target="#reply-modal" data-query-id="{{ $querie['id'] }}"
                                                        data-query-name="{{ $querie['name'] }}">
                                                        <img src="{{ asset('public/assets/img/restore.svg') }}" />
                                                        <span>Reply</span>
                                                    </a>
                                            @endif

                                            @if ($querie['is_reply'])
                                                <div class="action-buttons">

                                                    <a href="#" class="action-btn replymessage-button"
                                                        data-toggle="modal" data-query-id="{{ $querie['id'] }}"
                                                        data-query-name="{{ $querie['name'] }}"
                                                        data-reply-message="{{ $querie['reply_message'] }}"
                                                        data-target="#replymessage-modal">
                                                        <span>View reply</span>
                                                    </a>
                                            @endif

                                            <a class="action-btn delete_user" data-id="{{ $querie['id'] }}"
                                                data-toggle="modal" data-target="#delete-modal">


                                                <img src="{{ asset('public/assets/img/delete-recycle.svg') }}" />
                                                <span>Delete</span>
                                            </a>
                    </div>

                    </td>
                    <div class="modal fade" id="view-message-modal" tabindex="-1" role="dialog"
                        aria-labelledby="viewMessageModalLabel" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered" role="document">
                            <div class="modal-content">
                                <div class="modal-body">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="viewMessageModalLabel">Message</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <p id="message-content"></p>
                                </div>
                            </div>
                        </div>
                    </div>
                    </tr>


                    </tbody>

                    <form action="{{ route('send.reply', ['id' => $querie['id']]) }}" method="post" id="replyForm">
                        @csrf
                        <div class="modal fade" id="reply-modal" tabindex="-1" role="dialog"
                            aria-labelledby="exampleModalLabel" aria-hidden="true">
                            <div class="modal-dialog modal-dialog-centered" role="document">
                                <div class="modal-content">
                                    <div class="modal-body">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="exampleModalLabel">Reply to
                                                <span id="query-name"></span>
                                            </h5>
                                            <button type="button" class="close" data-dismiss="modal"
                                                aria-label="Close">
                                                <span aria-hidden="true">&times;</span>
                                            </button>
                                        </div>
                                        <div class="col-xxl-12">
                                            <textarea name="reply_message" class="form-control" id="post-meta-description" cols="10" rows="5"
                                                required></textarea>
                                            <button type="submit" class="download-btn reply_user_button">Reply</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                    <div class="modal fade" id="replymessage-modal" tabindex="-1" role="dialog"
                        aria-labelledby="exampleModalLabel" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered" role="document">
                            <div class="modal-content">
                                <div class="modal-body">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="exampleModalLabel">Reply Message:
                                            <span id="query-name"></span>
                                        </h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="col-xxl-12">
                                        <p><span id="reply-message"></span></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    @endforeach
                    </table>
                </div>
            </div>
        </div>
    </div>
    </div>

    <div class="modal fade" id="delete-modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close">
                        x
                    </button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="delete_user_id" name="user_id">
                    <p class="modal-text">Are you sure you want to<br>Delete </p>
                    <div class="modal-btn d-flex ">
                        <a type="button" href="route{{ 'manage.contact' }}" class="extra-btn"
                            data-dismiss="modal">No</a>
                        <a type="button" class="download-btn-custom delete_user_button" data-dismiss="modal">Yes</a>
                    </div>

                </div>
            </div>
        </div>
    </div>
@endsection


@section('section_script')
    <script src="../src/plugins/src/table/datatable/datatables.js"></script>
    <script>
        $('#zero-config').DataTable({
            "dom": "<'dt--top-section'<'row'<'col-12 col-sm-6 d-flex justify-content-sm-start justify-content-center'l><'col-12 col-sm-6 d-flex justify-content-sm-end justify-content-center mt-sm-0 mt-3'f>>>" +
                "<'table-responsive'tr>" +
                "<'dt--bottom-section d-sm-flex justify-content-sm-between text-center'<'dt--pages-count  mb-sm-0 mb-3'i><'dt--pagination'p>>",
            "oLanguage": {
                "oPaginate": {
                    "sPrevious": '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>',
                    "sNext": '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>'
                },
                "sInfo": "Showing page _PAGE_ of _PAGES_",
                "sSearch": '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-search"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>',
                "sSearchPlaceholder": "Search...",
                "sLengthMenu": "Results :  _MENU_",
            },
            "stripeClasses": [],
            "lengthMenu": [7, 10, 20, 50],
            "pageLength": 10
        });
    </script>
    <script>
        $(document).ready(function() {
            $('<button><ul class="navbar-item flex-row ms-lg-auto ms-0"><li class="nav-item dropdown action-dropdown  order-lg-0 order-1"><a href="javascript:void(0);"class="nav-link dropdown-toggle user extra-btn" id="actionDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><div class="avatar-container"><div class="avatar avatar-sm avatar-indicators avatar-online"><h3>Filter</h3></div></div></a><div class="dropdown-menu position-absolute" aria-labelledby="actionDropdown"><div class="dropdown-item"><a href="{{ route('manage.contact') }}" id="allFilter" class="default-filter"><span>All</span></a></div><div class="dropdown-item"><a href="{{ route('manage.contact', ['is_reply' => true]) }}" id="activeFilter"><span>Resolved</span></a></div><div class="dropdown-item"><a href="{{ route('manage.contact', ['is_reply' => false]) }}" id="expiredFilter"> <span>Pending</span></a></div></div></li></ul></button>')
                .insertBefore("#zero-config_filter label");

            // Retrieve the selected filter from local storage
            var selectedFilter = localStorage.getItem('selectedFilter');

            // If a selected filter exists, set its color
            if (selectedFilter) {
                handleChange(selectedFilter);
            } else {
                // If no selected filter is found, simulate a click event on the default filter button
                $('#allFilter').trigger('click');
            }

            // Add event listeners to filter links
            $('#activeFilter').on('click', function() {
                // Prevent the default anchor behavior
                handleChange('active');
                // Store selected filter in local storage
                localStorage.setItem('selectedFilter', 'active');
            });

            $('#expiredFilter').on('click', function() {
                // Prevent the default anchor behavior
                handleChange('expired');
                // Store selected filter in local storage
                localStorage.setItem('selectedFilter', 'expired');
            });

            $('#allFilter').on('click', function() {
                // Prevent the default anchor behavior
                handleChange('all');
                // Store selected filter in local storage
                localStorage.setItem('selectedFilter', 'all');
            });
        });
    </script>
    <script>
        $(document).on("click", ".delete_user", function() {
            var delete_id = $(this).data('id');
            $('#delete_user_id').val(delete_id); // Fix the selector here
        });

        $(document).on("click", ".delete_user_button", function(e) {
            e.preventDefault();
            let base_url = url_path;
            var delete_id = $('#delete_user_id').val();
            $.ajaxSetup({
                headers: {
                    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                },
            });
            $.ajax({
                type: "POST", // Change the type to POST since you're using Route::post in Laravel
                url: base_url + "/delete_user/" + delete_id,
                data: {
                    _method: 'post', // Laravel requires a hidden _method field for DELETE requests
                },
                success: function(response) {
                    console.log(response);
                    toastr.info("Contact Deleted Successfully");
                    window.location.reload();
                }
            });
        });
    </script>
    <script>
        $(document).ready(function() {
            $('.view-btn').click(function() {
                var message = $(this).data('message');
                var id = $(this).data('ids');

                $('#view-message-modal #message-content').text(message);

                $('#view-message-modal').modal('show');
            });
        });
    </script>
    <script>
        $(document).on("click", ".reply-button", function() {
            var queryId = $(this).data('query-id');
            var queryName = $(this).data('query-name');

            $('#query-name').text(queryName);

            $('#reply-modal').data('query-id', queryId);

            $('#reply-modal').modal('show');
        });

        $(document).on("click", "#reply-button", function(e) {
            e.preventDefault();

            var queryId = $('#reply-modal').data('query-id');

            $('#reply-modal').modal('hide');
        });
    </script>
    <script>
        $(document).on("click", ".replymessage-button", function() {
            var queryId = $(this).data('query-id');
            var queryName = $(this).data('query-name');
            var replyMessage = $(this).data('reply-message');

            // Set the query name and reply message in the modal
            $('#query-name').text(queryName);
            $('#reply-message').text(replyMessage);

            // Set the query ID as a data attribute for future use
            $('#replymessage-modal').data('query-id', queryId);

            // Show the modal
            $('#replymessage-modal').modal('show');
        });

        $(document).on("click", "#replymessage-button", function(e) {
            e.preventDefault();

            // Get the query ID from the modal data attribute
            var queryId = $('#replymessage-modal').data('query-id');

            // Your other AJAX code for handling the reply
            // ...

            // Hide the modal after handling the reply
            $('#replymessage-modal').modal('hide');
        });
    </script>


    <script>
        $(document).ready(function() {
            $('.reply_user_button').on('click', function(event) {
                event.preventDefault();

                var replyMessage = $('#post-meta-description').val().trim();
                if (replyMessage === "") {
                    toastr.error("Please enter a reply message.");
                    return;
                }

                var csrfToken = $('meta[name="csrf-token"]').attr('content');
                var queryId = $('#reply-modal').data('query-id');

                $.ajax({
                    url: "{{ route('send.reply') }}",
                    type: 'POST',
                    data: {
                        reply_message: replyMessage,
                        user_id: queryId,
                        _token: csrfToken
                    },
                    dataType: 'json',
                    success: function(response) {
                        console.log(response);
                        toastr.success('Reply sent successfully');
                        window.location.reload();
                        $('#reply-modal').modal('hide');
                    },
                    error: function(error) {
                        console.error(error);
                        toastr.error("An error occurred. Please try again.");
                    }
                });
            });
        });
    </script>

    <script>
        $(document).ready(function() {
            // Handle click event on the "View" button
            $('.view-btn').click(function() {
                // Get the message and id from the data attributes
                var message = $(this).data('message');
                var id = $(this).data('ids');

                // Set the message in the modal
                $('#message-modal-' + id + ' .modal-body').html('<p id="modal-message-' + id + '">' +
                    message + '</p>');
            });
        });
    </script>
@endsection
