<?php $__env->startSection('content'); ?>
    <style>
        body {
            background-color: #f7f6f6;
        }

        .card {
            border: none;
            box-shadow: 5px 6px 6px 2px #e9ecef;
            border-radius: 4px;
        }

        .user-img {
            margin-top: 4px;
        }

        .icons i {
            margin-left: 8px;
        }

        .reply small {
            color: #b7b4b4;
        }

        .reply small:hover {
            color: green;
            cursor: pointer;
        }
    </style>

    <div id="main-wrapper">
        <div class="page-wrapper customWrap">
            <div class="container-fluid">
                <div class="row pt-25">
                    <div class="col-md-12 col-lg-12 col-xlg-12 ftneshed">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <span><?php echo e($categories->categories); ?></span>
                            <span>
                <a href="#" data-toggle="modal" data-target="#createPostModal" id="createPostBtn">+ Create Post</a>
            </span>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-lg-8 col-xlg-9">
                        <?php if(count($posts) != 0): ?>

                            <?php $__currentLoopData = $posts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $post): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>

                                <div class="card postCard" id="post-<?php echo e($post->id); ?>">
                                    <div class="row post-box">
                                        <div class="col-sm-12">
                                            <a class="profileVisit">
                                                <img
                                                    src="<?php echo e($post->user ? asset('profile_image/'.$post->user->profile_image) : asset('profile_image/user.png')); ?>"
                                                    style="width: 50px">
                                                <div class="uInfo">
                                                    <h4 class="userName"><?php echo e($post->user->name ?? ''); ?></h4>
                                                    <h5 class="postTiming"><?php echo e($post->created_at->diffForHumans()); ?></h5>
                                                </div>
                                            </a>
                                            <div class="postContent">
                                                <p><?php echo e($post->post_content ?? ''); ?></p>
                                                <?php
                                                    $jsonDecodeTags = json_decode($post->post_tags);
                                                ?>

                                                <?php if($jsonDecodeTags !== null && is_array($jsonDecodeTags)): ?>
                                                    <?php $__currentLoopData = $jsonDecodeTags; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $tag): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                        <a href="#"><?php echo e($tag); ?></a>
                                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                <?php endif; ?>

                                                <?php if($post->post_video): ?>
                                                    <div class="postImg">
                                                        <div class="row">
                                                            <div class="col-md-6">
                                                                <video ref="Sorry! SomeThing went Wrong" playsInline
                                                                       autoPlay loop controls>
                                                                    <source
                                                                        src=<?php echo e(asset('post/'.$post->post_video)); ?> type="video/mp4"/>
                                                                </video>
                                                            </div>
                                                        </div>
                                                    </div>
                                                <?php endif; ?>

                                                <?php if($post->post_image): ?>
                                                    <div class="postImg">
                                                        <div class="row">
                                                            <div class="col-md-6"><img
                                                                    src="<?php echo e(asset('post/'.$post->post_image)); ?>"></div>
                                                        </div>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>

                                        <button class="btnMore absBtn" onclick="openPostDetail(<?php echo e($post->id); ?>)">
                                            <img src="<?php echo e(asset('images/icon/more-btn.png')); ?>">
                                        </button>
                                        <div id="postDropdown<?php echo e($post->id); ?>" class="dropdown-content">
                                            <?php if($post->user_id == $user->id): ?>
                                                <ul>
                                                    <li class="text-center" onclick="deletePost(<?php echo e($post->id); ?>)">Delete
                                                        Post
                                                    </li>
                                                </ul>
                                            <?php else: ?>
                                                <ul>
                                                    <li class="text-center" onclick="hidePost(<?php echo e($post->id); ?>)">Hide
                                                        Post
                                                    </li>
                                                </ul>
                                            <?php endif; ?>
                                        </div>

                                    </div>
                                    <div class="row">
                                        <div class="col-sm-12">
                                            <div class="functionBtns">
                                                <div class="row">
                                                    <div class="col-sm-6 d-flex">
                                                        <?php if(isset($post->like)): ?>
                                                            <?php if($post->like->user_id != $user->id): ?>

                                                                <div class="likeBtn shareBox"
                                                                     id="likeBtn-<?php echo e($post->id); ?>">
                                                                    <input type="hidden" name="like"
                                                                           value="<?php echo e($post->likes); ?>">
                                                                    <button
                                                                        class="like-btn"
                                                                        onclick="likePost(<?php echo e($post); ?>)">
                                                                        <i
                                                                            style="cursor: pointer""
                                                                        id="thumbsUpIcon_<?php echo e($post->id); ?>"
                                                                        class="fas fa-thumbs-up"></i> <span
                                                                            id="likesCount_<?php echo e($post->id); ?>"><?php echo e($post->likes); ?></span>
                                                                    </button>
                                                                </div>

                                                            <?php else: ?>
                                                                

                                                                <div class="likeBtn shareBox"
                                                                     id="undoLikeBtn-<?php echo e($post->id); ?>">
                                                                    <input type="hidden" name="like"
                                                                           value="<?php echo e($post->likes); ?>">
                                                                    <button
                                                                        class="like-btn"
                                                                        onclick="undoLikePost(<?php echo e($post); ?>)">
                                                                        <i
                                                                            id="thumbsUpIcon_<?php echo e($post->id); ?>"
                                                                            class="fas fa-thumbs-up"
                                                                            style="color: #0A66C2;cursor: pointer"></i><span
                                                                            id="likesCount_<?php echo e($post->id); ?>"><?php echo e($post->likes); ?></span>
                                                                    </button>
                                                                </div>

                                                            <?php endif; ?>
                                                        <?php else: ?>

                                                            <div class="likeBtn shareBox" id="likeBtn-<?php echo e($post->id); ?>">
                                                                <input type="hidden" name="like"
                                                                       value="<?php echo e($post->likes); ?>">
                                                                <button
                                                                    class="like-btn"
                                                                    onclick="likePost(<?php echo e($post); ?>)">
                                                                    <i
                                                                        style="cursor: pointer""
                                                                    id="thumbsUpIcon_<?php echo e($post->id); ?>"
                                                                    class="fas fa-thumbs-up"></i> <span
                                                                        id="likesCount_<?php echo e($post->id); ?>"><?php echo e($post->likes); ?></span>
                                                                </button>
                                                            </div>
                                                        <?php endif; ?>
                                                        <div class="comBtn shareBox">
                                                            <a><i class="fal fa-comment-dots"
                                                                  style="cursor: pointer"></i>
                                                                <span><?php echo e($post->comment_count); ?></span>
                                                            </a>

                                                        </div>
                                                    </div>

                                                    <div class="col-sm-6 d-flex flex-row-reverse">
                                                        <div class="shareBtn shareBox">
                                                            
                                                            
                                                            <input name="post_id" value="<?php echo e($post->id); ?>"
                                                                   type="hidden">
                                                            <button style="cursor: pointer"
                                                                    class="like-btn" type="submit"
                                                                    onclick="postShare(<?php echo e($post->id); ?>)"><i
                                                                    class="fal fa-share-alt"></i> <span
                                                                    id="sharesCount_<?php echo e($post->id); ?>"><?php echo e($post->shares_count ?? ''); ?>

                                                                        </span>Share
                                                            </button>
                                                            
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="comments-list-<?php echo e($post->id); ?>">
                                        <?php $__currentLoopData = $post->latest_comments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $comment): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <div class="container mt-12 comment-item">
                                                <div class="row d-flex justify-content-center">
                                                    <div class="col-md-12">
                                                        <div class="card p-3">
                                                            <div
                                                                class="d-flex justify-content-between align-items-center">
                                                                <div class="user d-flex flex-row align-items-center">
                                                                    <img
                                                                        src="<?php echo e(isset($comment->user->profile_image) ? asset('profile_image/'.$comment->user->profile_image) : asset('profile_image/user.png')); ?>"
                                                                        width="30" class="user-img rounded-circle mr-2">
                                                                    <span>
                                <small class="font-weight-bold text-primary"><?php echo e($comment->user->name ?? ''); ?></small>
                                <small class="font-weight-bold"><?php echo e($comment->comment ?? ''); ?></small>
                            </span>
                                                                </div>
                                                                <small><?php echo e($comment->created_at->diffForHumans()); ?></small>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </div>

                                    <!-- Load More button -->
                                    <?php if($post->comment->count() >= 3): ?>
                                        <button onclick="openLoadComments(<?php echo e($post->id); ?>)"
                                                id="load-more-btn-<?php echo e($post->id); ?>" data-post-id="<?php echo e($post->id); ?>">Load
                                            More
                                        </button>
                                    <?php endif; ?>
                                    <div class="row">
                                        <div class="col-sm-12">
                                            <div class="commentBox">
                                                
                                                
                                                <input type="hidden" name="postId" value="<?php echo e($post->id); ?>">
                                                <div class="input-group">
                                                    <div class="input-group-prepend">
                                                <span class="input-group-text" id="basic-addon1"><img
                                                        src="<?php echo e(isset($user->profile_image) ? asset('profile_image/'.$user->profile_image) : asset('profile_image/user.png')); ?>"
                                                        width="40"></span>
                                                    </div>
                                                    <input type="text" name="comment" class="form-control"
                                                           id="comment-box-<?php echo e($post->id); ?>"
                                                           placeholder="Write a Comment..."
                                                           aria-label="Username" aria-describedby="basic-addon1"
                                                           required
                                                           onkeyup="checkEnterOnComment(event , <?php echo e($post->id); ?>)">
                                                    <div class="input-group-prepend">
                                                        <button class="btn-success" type="submit"
                                                                onclick="sendComment(<?php echo e($post->id); ?>)"><i
                                                                class="fas fa-paper-plane"></i></button>
                                                    </div>
                                                </div>
                                                
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- End : Card With Image -->
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

                        <?php else: ?>
                            <h2>Sorry No Posts In This Category!!!</h2>
                    <?php endif; ?>
                    <!-- Begin : Card Post -->

                    </div>
                    <!-- Column -->

                    <!-- Column -->
                </div>
                <!-- Row -->
            </div>
        </div>
    </div>
    <!-- Bootstrap Modal -->
    <div class="modal fade" id="createPostModal" tabindex="-1" role="dialog" aria-labelledby="createPostModalLabel"
         aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="createPostModalLabel">Create Post</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form action="<?php echo e(route('dashboard.post')); ?>" method="post" enctype="multipart/form-data">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" value="<?php echo e($categories->id); ?>" name="categoryId">
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="postContent">Post Content</label>
                            <textarea class="form-control" id="postContent" name="postContent" required></textarea>
                        </div>
                        <div class="form-group">
                            <input class="form-control" name="tags" type="text" id="tagsInput"
                                   placeholder="Enter tags separated by space"/>
                            <div id="tagsContainer"></div>
                            <input type="hidden" name="tagsArray" value="">
                        </div>
                        <div class="form-group">
                            <label for="postImage">Post Image</label>
                            <input type="file" class="form-control-file" id="postImage" name="postImage"
                                   onchange="previewImage(event)">
                        </div>
                        <div id="imagePreview"></div>

                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Create</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <!-- JavaScript -->

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


    <script>
        document.getElementById('createPostBtn').addEventListener('click', function () {
            $('#createPostModal').modal('show');
        });

        function previewImage(event) {
            var input = event.target;
            var imagePreview = document.getElementById('imagePreview');

            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    var imgElement = document.createElement('img');
                    imgElement.setAttribute('src', e.target.result);
                    imgElement.setAttribute('class', 'img-fluid');
                    imgElement.style.width = '30%'; // Set the width to 80%
                    imagePreview.innerHTML = '';
                    imagePreview.appendChild(imgElement);
                };

                reader.readAsDataURL(input.files[0]);
            } else {
                imagePreview.innerHTML = '';
            }
        }

        const tagsInput = document.getElementById('tagsInput');
        const tagsContainer = document.getElementById('tagsContainer');
        const tagsArray = [];

        tagsInput.addEventListener('keydown', function (event) {
            if (event.key === ' ' || event.key === 'Enter') {
                event.preventDefault();
                let tag = tagsInput.value.trim();

                // Add "#" sign if not already present
                if (!tag.startsWith('#')) {
                    tag = '#' + tag;
                }

                if (tag !== '') {
                    const tagElement = document.createElement('span');
                    tagElement.textContent = tag + ' ';
                    tagsContainer.appendChild(tagElement);
                    tagsInput.value = '';

                    // Save the tag to the array
                    tagsArray.push(tag);

                    // Update the value of the hidden input field
                    document.querySelector('input[name="tagsArray"]').value = JSON.stringify(tagsArray);
                }
            }
        });

        let currentPage = 1;

        // document.querySelector('.load-more-btn').addEventListener('click', function () {
        //     var postId = this.dataset.postId;
        //     console.log("postId", postId);
        //     loadMoreComments(postId);
        // });

        let currentPostId = 0

        function openLoadComments(postId) {
            console.log("postId", postId);
            if (currentPostId == postId) {
                currentPage++
            } else {
                currentPostId = postId;
                currentPage = 1
            }
            loadMoreComments(postId);
        }

        function loadMoreComments(postId) {

            console.log("currentPage", currentPage);
            var loadMoreBtn = document.getElementById(`load-more-btn-${postId}`);

            loadMoreBtn.disabled = true; // Disable the button temporarily during the fetch request

            console.log("loadMoreComments postId", postId)
            fetch(`<?php echo e(url('/')); ?>/posts/${postId}/comments?page=${currentPage + 1}`)
                .then(response => response.json())
                .then(data => {
                    var commentsList = document.querySelector(`.comments-list-${postId}`);
                    console.log("load comment data", data);

                    data.data.forEach(comment => {
                        if (comment.user) {
                            var div = document.createElement('div');
                            div.classList.add('container', 'mt-12', 'comment-item');
                            div.innerHTML = `
                        <div class="row d-flex justify-content-center">
                            <div class="col-md-12">
                                <div class="card p-3">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div class="user d-flex flex-row align-items-center">
                                            <img src="${comment.user.profile_image_url}" width="30" class="user-img rounded-circle mr-2">
                                            <span>
                                                <small class="font-weight-bold text-primary">${comment.user.name ?? ''}</small>
                                                <small class="font-weight-bold">${comment.comment ?? ''}</small>
                                            </span>
                                        </div>
                                         <small>${comment.formatted_created_at}</small>
                                    </div>
                                </div>
                            </div>
                        </div>`;
                            commentsList.appendChild(div);
                        }
                    });

                    // Update the current page
                    // currentPage++;

                    // Enable the button if there are more pages
                    if (currentPage < data.last_page) {
                        loadMoreBtn.disabled = false;
                    } else {
                        loadMoreBtn.parentNode.removeChild(loadMoreBtn);
                    }
                })
                .catch(error => {
                    console.error(error);
                })
                .finally(() => {
                    loadMoreBtn.disabled = false; // Re-enable the button after the fetch request completes
                });
        }

        <!-- Include the necessary JavaScript code -->

        function checkEnterOnComment(event, postId) {
            if (event.key === "Enter") {
                // Call your function here
                sendComment(postId);
            }
        }

        function sendComment(postId) {

            var comment = $('#comment-box-' + postId).val();

            console.log("comment", comment);

            if (comment.trim() === '') {
                toastr.error("You cant submit empty comment")
                return
            }

            $.ajax({
                type: 'POST',
                url: '<?php echo e(route('post.comment')); ?>', // Use the named route from your web.php
                data: {
                    postId: postId, // Add the roomUser to the data object
                    comment: comment,
                    _token: '<?php echo e(csrf_token()); ?>',
                },
                success: function (res) {
                    console.log("res", res);
                    if (res.status == 200) {
                        var commentsList = document.querySelector(`.comments-list-${postId}`);

                        if (res.data.user) {
                            var div = document.createElement('div');
                            div.classList.add('container', 'mt-12', 'comment-item');

                            div.innerHTML = `<div class="row d-flex justify-content-center">
                                                    <div class="col-md-12">
                                                        <div class="card p-3">
                                                            <div
                                                                class="d-flex justify-content-between align-items-center">
                                                                <div class="user d-flex flex-row align-items-center">
                                                                    <img
                                                                        src="${res.data.user.profile_image_url}"
                                                                        width="30" class="user-img rounded-circle mr-2">
                                                                    <span>
                                <small class="font-weight-bold text-primary">${res.data.user.name ?? ''}</small>
                                <small class="font-weight-bold">${res.data.comment ?? ''}</small>
                            </span>
                                                                </div>
                                                                <small>${res.data.formatted_created_at}</small>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>`;


                            commentsList.appendChild(div);
                        }
                        $('#comment-box-' + postId).val('');

                        toastr.success(res.message);

                    }
                },
                error: function (xhr, status, error) {
                    // Handle any errors that occur during the AJAX request
                },
            });
        }

        function undoLikePost(post) {
            console.log("undo post", post);

            var likesCountSpan = $('#likesCount_' + post.id);
            var currentLikes = parseInt(likesCountSpan.text());

            $.ajax({
                type: 'POST',
                url: '<?php echo e(route('check.post.like')); ?>', // Use the named route from your web.php
                data: {
                    postId: post.id, // Add the roomUser to the data object
                    _token: '<?php echo e(csrf_token()); ?>',
                },
                success: function (res) {
                    console.log("res", res);
                    if (res.data == null) {
                        likePost(post)
                    } else {
                        $.ajax({
                            type: 'POST',
                            url: '<?php echo e(route('undo.post.like')); ?>', // Use the named route from your web.php
                            data: {
                                postId: post.id, // Add the roomUser to the data object
                                likes: currentLikes,
                                _token: '<?php echo e(csrf_token()); ?>',
                            },
                            success: function (res) {
                                console.log("res", res);
                                if (res.status == 200) {
                                    $('#thumbsUpIcon_' + post.id).css('color', 'grey');


                                    likesCountSpan.text(currentLikes - 1);

                                    toastr.success(res.message);

                                }
                            },
                            error: function (xhr, status, error) {
                                // Handle any errors that occur during the AJAX request
                            },
                        });
                    }
                },
                error: function (xhr, status, error) {
                    // Handle any errors that occur during the AJAX request
                },
            });


        }

        function likePost(post) {
            console.log("post", post)

            $.ajax({
                type: 'POST',
                url: '<?php echo e(route('check.post.like')); ?>', // Use the named route from your web.php
                data: {
                    postId: post.id, // Add the roomUser to the data object
                    _token: '<?php echo e(csrf_token()); ?>',
                },
                success: function (res) {
                    console.log("res", res);

                    var likesCountSpan = $('#likesCount_' + post.id);
                    var currentLikes = parseInt(likesCountSpan.text());

                    if (res.data != null) {
                        undoLikePost(post)
                    } else {
                        $.ajax({
                            type: 'POST',
                            url: '<?php echo e(route('post.like')); ?>', // Use the named route from your web.php
                            data: {
                                postId: post.id, // Add the roomUser to the data object
                                likes: currentLikes,
                                _token: '<?php echo e(csrf_token()); ?>',
                            },
                            success: function (res) {
                                console.log("res", res);
                                if (res.status == 200) {
                                    $('#thumbsUpIcon_' + post.id).css('color', '#0A66C2');


                                    likesCountSpan.text(currentLikes + 1);

                                    toastr.success(res.message);

                                }
                            },
                            error: function (xhr, status, error) {
                                // Handle any errors that occur during the AJAX request
                            },
                        });
                    }
                },
                error: function (xhr, status, error) {
                    // Handle any errors that occur during the AJAX request
                },
            });


        }

        function deletePost(postId) {
            $.ajax({
                type: 'POST',
                url: '<?php echo e(route('delete.post')); ?>', // Use the named route from your web.php
                data: {
                    postId: postId, // Add the roomUser to the data object
                    _token: '<?php echo e(csrf_token()); ?>',
                },
                success: function (res) {
                    console.log("res", res);
                    $(`#post-${postId}`).remove();
                    toastr.success(res.message);
                },
                error: function (xhr, status, error) {
                    // Handle any errors that occur during the AJAX request
                },
            });
        }

        function hidePost(postId) {
            $.ajax({
                type: 'POST',
                url: '<?php echo e(route('hide.post')); ?>', // Use the named route from your web.php
                data: {
                    postId: postId, // Add the roomUser to the data object
                    _token: '<?php echo e(csrf_token()); ?>',
                },
                success: function (res) {
                    console.log("res", res);
                    $(`#post-${postId}`).remove();
                    toastr.success(res.message);
                },
                error: function (xhr, status, error) {
                    // Handle any errors that occur during the AJAX request
                },
            });
        }

        function postShare(postId) {

            var shareCountSpan = $('#sharesCount_' + postId);
            var currentShares = parseInt(shareCountSpan.text());

            $.ajax({
                type: 'POST',
                url: '<?php echo e(route('post.share')); ?>', // Use the named route from your web.php
                data: {
                    postId: postId, // Add the roomUser to the data object
                    _token: '<?php echo e(csrf_token()); ?>',
                },
                success: function (res) {
                    console.log("res", res);

                    shareCountSpan.text(currentShares + 1);


                    toastr.success(res.message);
                },
                error: function (xhr, status, error) {
                    // Handle any errors that occur during the AJAX request
                },
            });
        }

    </script>

    <!-- Include jQuery library (if not already included) -->

    <script>
        function openPostDetail(postId) {
            // Get the specific dropdown content by post ID
            var dropdown = $("#postDropdown" + postId);

            // Check if the dropdown is currently visible
            var isVisible = dropdown.is(":visible");

            // Hide all other open dropdowns (if any)
            $(".dropdown-content").hide();

            // Toggle the dropdown visibility
            if (!isVisible) {
                dropdown.show();
            }
        }

        // Close dropdown when clicking outside
        $(document).on("click", function (event) {
            if (!$(event.target).closest(".absBtn").length) {
                $(".dropdown-content").hide();
            }
        });
    </script>

<?php $__env->stopSection(); ?>

<?php echo $__env->make('layout.dashboard-app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/servicedemoweb/public_html/global-man-cave/resources/views/dashboard/category.blade.php ENDPATH**/ ?>