<div class="d-flex justify-content-between border-bottom py-3 px-4">
    <div class="d-flex gap-3 align-items-center">
        <div>
            @if ($seller?->image)
                <img src="{{ custom_asset($seller?->image) }}" class="rounded-circle person-image" alt="" />
            @else
                <img src="{{ custom_asset($general_setting->default_avatar) }}" class="rounded-circle person-image"
                    alt="" />
            @endif
        </div>
        <div>
            <h4 class="text-dark-300 fw-bold text-18">
                {{ html_decode($seller?->name) }}
            </h4>
            @if ($last_message)
                <p class="text-dark-200 fs-6">{{ $last_message->created_at->diffForHumans() }}</p>
            @endif
        </div>
    </div>
    <div class="d-md-block d-none">
        <div class="btn-group" role="group">
            <button id="btnGroupDrop1" type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown"
                aria-expanded="false">
                <i class="fa-solid fa-ellipsis-vertical"></i>
            </button>
            <ul class="dropdown-menu" aria-labelledby="btnGroupDrop1">
                @php
                    $block_user = App\Models\BlockUser::where('blocked_user_id', $seller->id)->first();
                @endphp
                <li>
                    <button class="dropdown-item" type="button" data-bs-toggle="modal"
                        data-bs-target="#staticBackdrop">
                        {{ $block_user != null ? 'Ublock' : 'Block' }}
                    </button>
                </li>
                <li><a class="dropdown-item" href="{{ route('freelancer', $seller->username) }}"
                        target="_blank">{{ __('translate.View Profile') }}</a></li>
            </ul>
        </div>
    </div>



    <!-- Modal -->
    <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1"
        aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <form action="{{ route('user.block') }}" method="POST">
                    @csrf
                    <input type="hidden" name="user_id" value="{{ $seller->id }}">

                    <div class="modal-header">
                        <h5 class="modal-title" id="staticBackdropLabel">{{ __('Block User') }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>

                    <div class="modal-body">
                        <p><strong>{{ html_decode($seller->name) }}</strong> </p>
                        <p class="text-danger fw-bold">{{ __('Are you sure you want to block this user') }}?</p>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary"
                            data-bs-dismiss="modal">{{ __('Cancel') }}</button>
                        <button type="submit" class="btn btn-danger">{{ __('Block User') }}</button>
                    </div>
                </form>
            </div>
        </div>
    </div>


</div>

<div class="py-3 px-4 overflow-y-auto body-h-535 scrolling-body">


    <ul class="conversation-text pt-5 message-list">

        @foreach ($messages as $message)
            @if ($message->send_by == 'buyer')
                <li class="d-flex flex-column align-items-end gap-1">
                    @if ($message->message !== null)
                        <p class="bg-blue-300 text-white p-2 rounded-3 text-p-message">
                            {{ html_decode($message->message) }}
                        </p>
                    @endif
                    <span class="text-dark-200 text-14">{{ $message->created_at->diffForHumans() }}</span>

                    @if ($message->documents)
                        <div class="fr-support__items">
                            @foreach (json_decode($message->documents) as $document)
                                <a href="{{ route('message-download-file', $document->id) }}" target="_blank"
                                    class="upload_photo">
                                    <i class="fas fa-link"></i> {{ __('click to download') }}
                                </a>
                            @endforeach
                        </div>
                    @endif
                </li>
            @else
                <li class="d-flex flex-column  gap-1 left-side">
                    @if ($message->message !== null)
                        <p class="bg-blue-300 align-items-start  p-2 rounded-3 text-p-message">
                            {{ html_decode($message->message) }}
                        </p>
                    @endif
                    <span class="text-dark-200 text-14">{{ $message->created_at->diffForHumans() }}</span>

                    @if ($message->documents)
                        <div class="fr-support__items">
                            @foreach (json_decode($message->documents) as $document)
                                <a href="{{ route('message-download-file', $document->id) }}" target="_blank"
                                    class="upload_photo">
                                    <i class="fas fa-link"></i> {{ __('click to download') }}
                                </a>
                            @endforeach
                        </div>
                    @endif
                </li>
            @endif
        @endforeach

    </ul>
</div>

<div class="position-relative overflow-x-hidden">
    <form class="px-4 py-2 msg-write-input d-flex flex-column flex-md-row align-items-center gap-3"
        id="sendMessageForm">
        @csrf
        <input type="hidden" name="seller_id" value="{{ $seller->id }}" id="seller_id">

        @php
            $authId = auth()->id();
            $sellerId = $seller->id;
            $iBlocked = App\Models\BlockUser::where('user_id', $authId)->where('blocked_user_id', $sellerId)->exists();
            $heBlocked = App\Models\BlockUser::where('user_id', $sellerId)->where('blocked_user_id', $authId)->exists();
        @endphp

        @if ($iBlocked)
            <p>You have blocked this user.</p>
        @endif

        @if ($heBlocked)
            <p class="text-red">This user has blocked you. You cannot message them.</p>
        @endif

        @if (!$iBlocked && !$heBlocked)
            <div class="position-relative flex-grow-1">
                <input type="text" class="form-control rounded-5 bg-offWhite shadow-none"
                    placeholder="{{ __('translate.Type your message') }}" autocomplete="off" name="message"
                    id="message" />


                <div class="fr-chatbox-attach">
                    <button type="button" id="uploadImageButton">
                        <span>
                            <svg width="21" height="20" viewBox="0 0 21 20" fill="none"
                                xmlns="http://www.w3.org/2000/svg">
                                <path
                                    d="M19.0337 1.97517C16.4164 -0.658391 12.1576 -0.658391 9.53985 1.97517L1.40201 10.1633C-0.46744 12.0445 -0.467317 15.1054 1.40226 16.9865C2.33713 17.9272 3.56473 18.3975 4.79282 18.3974C6.02058 18.3973 7.24884 17.9271 8.18354 16.9865L15.643 9.48076C16.1864 8.93402 16.4858 8.20706 16.4859 7.43384C16.4859 6.66057 16.1866 5.93365 15.6431 5.38675C14.5212 4.25807 12.6959 4.25812 11.5743 5.38696L6.69607 10.2952C6.32156 10.672 6.32156 11.283 6.69599 11.6599C7.07046 12.0368 7.6777 12.0367 8.05225 11.6599L12.9305 6.75157C13.3044 6.37532 13.9128 6.37524 14.2868 6.75149C14.4679 6.93373 14.5677 7.17607 14.5677 7.4338C14.5677 7.69152 14.4679 7.93377 14.2868 8.1161L6.82728 15.6219C5.70546 16.7505 3.88026 16.7507 2.75852 15.6219C1.63679 14.4932 1.6367 12.6566 2.75832 11.5278L10.8961 3.33983C12.7659 1.45861 15.8079 1.45861 17.6774 3.33983C18.5832 4.25106 19.082 5.46269 19.082 6.75141C19.082 8.04013 18.5831 9.25175 17.6774 10.1631L9.53973 18.3513C9.16525 18.7282 9.16525 19.3391 9.53981 19.716C9.72709 19.9045 9.97253 19.9986 10.2179 19.9986C10.4634 19.9986 10.7088 19.9043 10.8961 19.716L19.0336 11.5278C20.3017 10.252 21 8.55575 21 6.75145C21 4.94719 20.3017 3.25094 19.0337 1.97517Z"
                                    fill="#CACACA" />
                            </svg>
                        </span>
                    </button>
                    <input type="file" name="documents[]" id="uploadImageInput" multiple style="display:none">
                    <div id="fileNameDisplay"></div>
                </div>
            </div>
            <button type="submit" class="msg-send-btn" id="sendMessageBtn">{{ __('Send') }}</button>
        @endif








        <script>
            // Trigger file input when the upload button is clicked
            document.getElementById('uploadImageButton').addEventListener('click', function() {
                document.getElementById('uploadImageInput').click();
                // Optional: if file_type is an element, make sure it exists
                const fileTypeInput = document.getElementById('file_type');
                if (fileTypeInput) {
                    fileTypeInput.value = 'document';
                }
            });

            // Handle file selection and display file count
            document.getElementById('uploadImageInput').addEventListener('change', function(event) {
                const files = event.target.files;
                const fileNameDisplay = document.getElementById('fileNameDisplay');
                fileNameDisplay.innerHTML = ''; // Clear previous file names

                if (files.length > 0) {
                    // Display the count of selected files
                    const fileElement = document.createElement('p');
                    fileElement.textContent = files.length + " File(s) selected";
                    fileNameDisplay.appendChild(fileElement);
                } else {
                    fileNameDisplay.textContent = "";
                }
            });

            // Clear fileNameDisplay content on form submission
            document.getElementById('sendMessageForm').addEventListener('submit', function(event) {
                const fileNameDisplay = document.getElementById('fileNameDisplay');
                fileNameDisplay.innerHTML = ''; // Clear content
            });
        </script>
    </form>
</div>

<script>
    (function($) {
        "use strict";
        $(document).ready(function() {
            $("#sendMessageForm").on("submit", function(e) {
                e.preventDefault();

                let formData = new FormData(this);
                let message = $("#message").val();

                // Fix: check correct file input and allow file-only submission
                if (!message && !$("#uploadImageInput")[0].files.length) return;

                var isDemo = "{{ env('APP_MODE') }}";
                if (isDemo == "DEMO") {
                    toastr.error("This Is Demo Version. You Can Not Change Anything");
                    return;
                }

                $.ajax({
                    type: "post",
                    url: "{{ url('/buyer/store-message/') }}",
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        $(".message-list").html(response);
                        $("#message").val("");
                        $("#uploadImageInput").val(""); // Clear file input
                        scrollToBottomFunc();
                    },
                    error: function(err) {
                        $("#message").val("");
                        $("#uploadImageInput").val("");
                    },
                });
            });
        });
    })(jQuery);

    function loadedLatestMessage() {
        setInterval(() => {
            let seller_id = $("#seller_id").val()
            $.ajax({
                type: "get",
                url: "{{ url('/buyer/get-message-list/') }}" + "/" + seller_id,
                success: function(response) {
                    $(".message-list").html(response);
                    scrollToBottomFunc();
                },
                error: function(err) {}
            })
        }, 5000);
    }

    loadedLatestMessage()
</script>

{{-- <script>
    (function($) {
        "use strict";
        $(document).ready(function() {
            $("#sendMessageForm").on("submit", function(e) {
                e.preventDefault();

                let formData = new FormData(this);
                let message = $("#message").val();

                if (!message && !$("#file")[0].files.length) return;

                var isDemo = "{{ env('APP_MODE') }}";
                if (isDemo == "DEMO") {
                    toastr.error("This Is Demo Version. You Can Not Change Anything");
                    return;
                }

                $.ajax({
                    type: "post",
                    url: "{{ url('/buyer/store-message/') }}",
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        $(".message-list").html(response);
                        $("#message").val("");
                        $("#file").val(""); // Clear file input
                        scrollToBottomFunc();
                    },
                    error: function(err) {
                        $("#message").val("");
                        $("#file").val("");
                    },
                });
            });
        });
    })(jQuery);


    function loadedLatestMessage() {
        setInterval(() => {

            let seller_id = $("#seller_id").val()

            $.ajax({
                type: "get",
                url: "{{ url('/buyer/get-message-list/') }}" + "/" + seller_id,
                success: function(response) {
                    $(".message-list").html(response);
                    scrollToBottomFunc();
                },
                error: function(err) {}
            })

        }, 5000);
    }

    loadedLatestMessage()
</script> --}}
