Snippets Collections
$("[data-lenis-start]").on("click", function () {
  lenis.start();
});
$("[data-lenis-stop]").on("click", function () {
  lenis.stop();
});
$("[data-lenis-toggle]").on("click", function () {
  $(this).toggleClass("stop-scroll");
  if ($(this).hasClass("stop-scroll")) {
    lenis.stop();
  } else {
    lenis.start();
  }
});
<script src="https://cdn.jsdelivr.net/gh/studio-freight/lenis@1.0.23/bundled/lenis.min.js"></script> 
<script>
// LENIS SMOOTH SCROLL
let lenis;
if (Webflow.env("editor") === undefined) {
  lenis = new Lenis({
    lerp: 0.1,
    wheelMultiplier: 0.7,
    gestureOrientation: "vertical",
    normalizeWheel: false,
    smoothTouch: false
  });
  function raf(time) {
    lenis.raf(time);
    requestAnimationFrame(raf);
  }
  requestAnimationFrame(raf);
}
</script>
<script src="https://cdn.jsdelivr.net/gh/studio-freight/lenis@1.0.23/bundled/lenis.min.js"></script> 
<script>
// LENIS SMOOTH SCROLL
let lenis;
if (Webflow.env("editor") === undefined) {
  lenis = new Lenis({
    lerp: 0.1,
    wheelMultiplier: 0.7,
    gestureOrientation: "vertical",
    normalizeWheel: false,
    smoothTouch: false
  });
  function raf(time) {
    lenis.raf(time);
    requestAnimationFrame(raf);
  }
  requestAnimationFrame(raf);
}
</script>
<style>
html.lenis {
  height: auto;
}
.lenis.lenis-smooth {
  scroll-behavior: auto;
}
.lenis.lenis-smooth [data-lenis-prevent] {
  overscroll-behavior: contain;
}
.lenis.lenis-stopped {
  overflow: hidden;
}
</style>
@extends('new_layouts.app')
@section('styles')
    <style>
        .modal-icon {
            font-size: 3rem;
            color: #dc3545;
        }

        .modal-body {
            padding: 2rem;
        }

        .modal-title {
            font-size: 1.25rem;
            margin-top: 1rem;
        }

        .modal-body p {
            font-size: 1rem;
            margin-top: 0.5rem;
        }

        .custom-table {
            border-collapse: collapse;
            border-radius: 1rem;
            border-style: hidden;
            box-shadow: 0 0 0 1px #e6ebef;
            overflow: hidden;
            text-align: left;
            width: 100%;
        }

        .badge-file-extension {
            background-color: #f25961;
            color: white;
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            border-radius: 0.375rem;
            margin-left: 0.5rem;
        }

        .bookmark-active svg {
            fill: #FF9800;
        }

        .description-text {
            font-size: 1.1rem;
            color: #555;
            margin-top: 0.5rem;
        }

        .comment {
            margin-top: 1rem;
            margin-bottom: 1rem;
        }

        .comment-section {
            border: 1px solid #e9ebee;
            border-radius: 1rem;
            padding: 1.5rem;
            background-color: #ffffff;
            /* box-shadow: 0 0 1rem rgba(0, 0, 0, 0.1); */
        }

        .comment-header {
            border-bottom: 1px solid #e9ebee;
            padding-bottom: 0.75rem;
            margin-bottom: 1rem;
        }

        .comment-avatar {
            height: 48px;
            width: 48px;
            border-radius: 50%;
            margin-right: 1rem;
        }

        .comment-author {
            font-size: 1rem;
            font-weight: 600;
        }

        .comment-time {
            font-size: 0.875rem;
            color: #90949c;
        }

        .comment-body {
            margin: 0.75rem 0;
            font-size: 1rem;
        }

        .comment-actions a {
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-right: 1rem;
        }

        .comment-actions i {
            margin-right: 0.5rem;
        }

        .reply-list {
            margin-top: 1rem;
            padding-left: 2rem;
        }

        .reply-list .comment {
            border-left: 1px dotted #d3d6db;
            padding-left: 1rem;
            margin-top: 1rem;
        }

        .reply-toggle {
            cursor: pointer;
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-top: 1rem;
            display: block;
        }

        .reply-form {
            display: none;
            position: relative;
            z-index: 10;
        }

        .comment-input {
            border-radius: 0.5rem;
        }

        .like-button.active i {
            color: #4caf50;
        }

        .dislike-button.active i {
            color: #dc3545;
        }


        /* Dropdown Styles */
        .dropdown-toggle::after {
            display: none;
            /* Remove the default arrow */
        }

        .dropdown-menu {
            right: 0;
            left: auto;
        }
    </style>
@endsection
@section('content')
    <div class="container">

        <div>
            <div class="d-flex flex-column">
                <h1>Title: {{ $material->title }}</h1>
                @if ($material->description)
                    <p class="description-text"><strong>Description:</strong> {{ $material->description }}</p>
                @endif
            </div>

            <div class="d-flex justify-content-end mb-4">
                <a class="btn rounded-3" style="background-color: #4CAF50; color: white"
                    href="{{ route('materials.downloadAll', $material) }}">
                    <i class="fas fa-download me-1"></i> Download All
                </a>
            </div>

            <div class="table-responsive">
                <table class="table table-striped custom-table">
                    <thead>
                        <tr>
                            <th scope="col">Bookmarks</th>
                            <th scope="col">Document</th>
                            <th scope="col">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($files as $file)
                            <tr>
                                <td>
                                    @php
                                        $isBookmarked = $file->bookmarks()->where('user_id', Auth::id())->exists();
                                    @endphp
                                    <button type="button"
                                        class="btn btn-outline-dark bookmark-toggle {{ $isBookmarked ? 'bookmark-active' : '' }}"
                                        data-file-id="{{ $file->id }}">
                                        @if ($isBookmarked)
                                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"
                                                fill="currentColor" class="bi bi-bookmarks-fill" viewBox="0 0 16 16">
                                                <path
                                                    d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5z" />
                                                <path
                                                    d="M4.268 1A2 2 0 0 1 6 0h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L13 13.768V2a1 1 0 0 0-1-1z" />
                                            </svg>
                                        @else
                                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"
                                                fill="currentColor" class="bi bi-bookmarks" viewBox="0 0 16 16">
                                                <path
                                                    d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5zm2-1a1 1 0 0 0-1 1v10.566l3.723-2.482a.5.5 0 0 1 .554 0L11 14.566V4a1 1 0 0 0-1-1z" />
                                                <path
                                                    d="M4.268 1H12a1 1 0 0 1 1 1v11.768l.223.148A.5.5 0 0 0 14 13.5V2a2 2 0 0 0-2-2H6a2 2 0 0 0-1.732 1" />
                                            </svg>
                                        @endif
                                        <span class="visually-hidden">Button</span>
                                    </button>
                                </td>
                                <td>
                                    <div>
                                        @php
                                            $extension = pathinfo($file->name, PATHINFO_EXTENSION);
                                        @endphp
                                        <i class="fa-solid fa-file-lines" style="color: #0068b8; margin-right: 5px;"></i>
                                        <a href="{{ Storage::url($file->path) }}" target="_blank">
                                            {{ pathinfo($file->name, PATHINFO_FILENAME) }}
                                        </a>
                                        <span>
                                            <span class="badge badge-file-extension">
                                                {{ strtoupper($extension) }} File
                                            </span>
                                        </span>
                                    </div>
                                </td>
                                <td>
                                    <a class="btn btn-primary rounded-pill" href="{{ Storage::url($file->path) }}" download>
                                        <i class="fas fa-download me-1"></i> Download
                                    </a>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>


        <div class="mt-4 comment-section">
            <h3>Comments ( {{ $comments->count() }} )</h3>
            <div class="comment-header d-flex justify-content-between align-items-center">
            </div>
            <div class="comment-body">
                <div class="d-flex mb-3">
                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                        class="comment-avatar">
                    <div class="w-100">
                        <form id="comment-form" action="{{ route('comments.store', $material) }}" method="POST">
                            @csrf
                            <div class="d-flex flex-column">
                                <textarea name="content" class="form-control comment-input" placeholder="Write a comment..." rows="3"></textarea>
                                <div class="d-flex justify-content-between mt-2">
                                    <div id="comment-form-error" class="text-danger"></div>
                                    <button type="submit" class="btn btn-primary">Post Comment</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div id="comment-list" class="comment-list">
                    @foreach ($comments as $comment)
                        <div class="comment" data-comment-id="{{ $comment->id }}">
                            <div class="d-flex">
                                <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                                    class="comment-avatar">
                                <div class="w-100">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <div class="comment-author">{{ $comment->user->name }}</div>
                                            <div class="comment-time">{{ $comment->created_at->diffForHumans() }}</div>
                                        </div>
                                        @if ($comment->user_id === auth()->id())
                                            <div class="dropdown">
                                                <button class="btn btn-link dropdown-toggle" type="button"
                                                    id="dropdownMenuButton{{ $comment->id }}" data-bs-toggle="dropdown"
                                                    aria-expanded="false">
                                                    <i class="fa-solid fa-ellipsis-vertical"></i>
                                                </button>
                                                <ul class="dropdown-menu"
                                                    aria-labelledby="dropdownMenuButton{{ $comment->id }}">
                                                    <li><a class="dropdown-item" href="#" data-action="edit"
                                                            data-comment-id="{{ $comment->id }}">Edit</a></li>
                                                    <li><a class="dropdown-item text-danger" href="#"
                                                            data-action="delete"
                                                            data-comment-id="{{ $comment->id }}">Delete</a></li>
                                                </ul>
                                            </div>
                                        @endif
                                    </div>
                                    <div class="comment-body">{{ $comment->content }}</div>
                                    <div class="comment-actions">
                                        <a href="#"
                                            class="like-button {{ $comment->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="like" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-up"></i>
                                            <span class="like-dislike-count">{{ $comment->likes }}</span>
                                        </a>
                                        <a href="#"
                                            class="dislike-button {{ $comment->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="dislike" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-down"></i>
                                            <span class="like-dislike-count">{{ $comment->dislikes }}</span>
                                        </a>
                                        <a href="#" class="reply-link" data-comment-id="{{ $comment->id }}"
                                            data-author="{{ $comment->user->name }}">
                                            <i class="fa-solid fa-reply"></i> Reply
                                        </a>
                                    </div>
                                    <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>

                                    <form class="reply-form" action="{{ route('replies.store', $comment) }}"
                                        method="POST">
                                        @csrf
                                        <div class="d-flex flex-column">
                                            <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                            <div class="d-flex justify-content-between mt-2">
                                                <div id="reply-form-error" class="text-danger"></div>
                                                <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                            </div>
                                        </div>

                                    </form>
                                    <div class="reply-list" style="display: none;">
                                        @foreach ($comment->replies as $reply)
                                            <div class="comment reply" data-comment-id="{{ $reply->id }}">
                                                <div class="d-flex">
                                                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg"
                                                        alt="avatar" class="comment-avatar">
                                                    <div class="w-100">
                                                        <div class="d-flex justify-content-between align-items-start">
                                                            <div>
                                                                <div class="comment-author">{{ $reply->user->name }}</div>
                                                                <div class="comment-time">
                                                                    {{ $reply->created_at->diffForHumans() }}</div>
                                                            </div>
                                                            @if ($reply->user_id === auth()->id())
                                                                <div class="dropdown">
                                                                    <button class="btn btn-link dropdown-toggle"
                                                                        type="button"
                                                                        id="dropdownMenuButton{{ $reply->id }}"
                                                                        data-bs-toggle="dropdown" aria-expanded="false">
                                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                                    </button>
                                                                    <ul class="dropdown-menu"
                                                                        aria-labelledby="dropdownMenuButton{{ $reply->id }}">
                                                                        <li><a class="dropdown-item" href="#"
                                                                                data-action="edit"
                                                                                data-comment-id="{{ $reply->id }}">Edit</a>
                                                                        </li>
                                                                        <li><a class="dropdown-item text-danger"
                                                                                href="#" data-action="delete"
                                                                                data-comment-id="{{ $reply->id }}">Delete</a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            @endif
                                                        </div>
                                                        <div class="comment-body">
                                                            @if ($reply->parent)
                                                                <a href="#"
                                                                    class="reply-mention">{{ '@' . $reply->parent->user->name }}</a>
                                                            @endif
                                                            <span class="reply-content">{{ $reply->content }}</span>
                                                        </div>
                                                        <div class="comment-actions">
                                                            <a href="#"
                                                                class="like-button {{ $reply->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="like" data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-up"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->likes }}</span>
                                                            </a>
                                                            <a href="#"
                                                                class="dislike-button {{ $reply->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="dislike"
                                                                data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-down"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->dislikes }}</span>
                                                            </a>
                                                            <a href="#" class="reply-link"
                                                                data-comment-id="{{ $reply->id }}"
                                                                data-author="{{ $reply->user->name }}">
                                                                <i class="fa-solid fa-reply"></i> Reply
                                                            </a>
                                                        </div>
                                                        <form class="reply-form"
                                                            action="{{ route('replies.store', $reply) }}" method="POST">
                                                            @csrf
                                                            <div class="d-flex flex-column">
                                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                                <div class="d-flex justify-content-between mt-2">
                                                                    <div id="reply-form-error" class="text-danger"></div>
                                                                    <button type="submit"
                                                                        class="btn btn-primary ms-auto">Post Reply</button>
                                                                </div>
                                                            </div>

                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                            @include('materials.comment', ['replies' => $reply->replies])
                                        @endforeach
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>
    <!-- delete model -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-body text-center">
                    <div class="mb-3">
                        <i class="fa-solid fa-triangle-exclamation modal-icon"></i>
                    </div>
                    <h5 class="modal-title" id="deleteModalLabel">Delete Comment</h5>
                    <p>Are you sure you want to delete this comment?</p>
                </div>
                <div class="modal-footer d-flex justify-content-center">
                    <button type="button" class="btn btn-danger ms-2" id="confirmDelete">Delete</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>
@endsection


@section('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const commentForm = document.getElementById('comment-form');
            const replyForms = document.querySelectorAll('.reply-form');

            commentForm.addEventListener('submit', function(e) {
                const content = this.querySelector('textarea[name="content"]').value.trim();
                if (content === '') {
                    e.preventDefault();
                    document.getElementById('comment-form-error').innerText =
                        'Error: Comment cannot be empty';
                }
            });

            replyForms.forEach(function(replyForm) {
                replyForm.addEventListener('submit', function(e) {
                    const content = this.querySelector('textarea[name="content"]').value.trim();
                    if (content === '') {
                        e.preventDefault();
                        this.querySelector('#reply-form-error').innerText =
                            'Error: Reply cannot be empty';
                    }
                });
            });

            const commentList = document.getElementById('comment-list');

            // Handle edit button click
            commentList.addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="edit"]');
                if (button) {
                    event.preventDefault();
                    const commentId = button.getAttribute('data-comment-id');
                    const commentElement = document.querySelector(
                        `.comment[data-comment-id="${commentId}"]`);
                    const commentBodyElement = commentElement.querySelector('.comment-body');

                    // Extract mention and content
                    const mentionElement = commentBodyElement.querySelector('.reply-mention');
                    const mention = mentionElement ? mentionElement.innerText.trim() : '';
                    const contentElement = mentionElement ? mentionElement.nextElementSibling :
                        commentBodyElement;
                    const content = contentElement.innerText.trim();

                    // Store original content for cancel action
                    commentBodyElement.dataset.originalContent = commentBodyElement.innerHTML;

                    const editForm = `
                        <form class="edit-comment-form" data-comment-id="${commentId}">
                            ${mention ? `<span class="reply-mention">${mention}</span>` : ''}
                            <textarea class="form-control">${content}</textarea>
                            <div class="d-flex justify-content-between mt-2">
                                <div id="edit-comment-form-error" class="text-danger"></div>
                                <div>
                                    <button type="submit" class="btn btn-primary">Save</button>
                                    <button type="button" class="btn btn-secondary cancel-edit">Cancel</button>
                                </div>
                            </div>
                        </form>
                    `;

                    commentBodyElement.innerHTML = editForm;
                    attachEditFormListeners(commentId);
                }
            });

            function attachEditFormListeners(commentId) {
                const editForm = document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"]`);

                editForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    const textarea = this.querySelector('textarea');
                    const content = textarea.value.trim();
                    const mention = this.querySelector('.reply-mention') ? this.querySelector(
                        '.reply-mention').innerText.trim() : '';

                    if (content === '') {
                        this.querySelector('#edit-comment-form-error').innerText =
                            'Error: Comment cannot be empty';
                        return;
                    }

                    fetch(`/comments/${commentId}`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content')
                            },
                            body: JSON.stringify({
                                content
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const commentBodyElement = document.querySelector(
                                    `.comment[data-comment-id="${commentId}"] .comment-body`);
                                const mentionElement = mention ?
                                    `<a href="#" class="reply-mention">${mention}</a>` : '';
                                commentBodyElement.innerHTML =
                                    `${mentionElement} <span class="reply-content">${data.content}</span>`;
                            } else {
                                alert('Error updating comment.');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                        });
                });

                editForm.querySelector('.cancel-edit').addEventListener('click', function() {
                    const originalContent = document.querySelector(
                            `.comment[data-comment-id="${commentId}"] .comment-body`).dataset
                        .originalContent;
                    document.querySelector(`.comment[data-comment-id="${commentId}"] .comment-body`)
                        .innerHTML = originalContent;
                });
            }
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {

            // for delete 
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="delete"]');
                if (button) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');
                    const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));

                    document.getElementById('confirmDelete').onclick = function() {
                        fetch(`/comments/${commentId}`, {
                                method: 'DELETE',
                                headers: {
                                    'X-Requested-With': 'XMLHttpRequest',
                                    'X-CSRF-TOKEN': document.querySelector(
                                        'meta[name="csrf-token"]').getAttribute('content'),
                                    'Content-Type': 'application/json',
                                }
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    const commentElement = document.querySelector(
                                        `.comment[data-comment-id="${commentId}"]`);
                                    if (commentElement) {
                                        commentElement.remove();
                                    }
                                    deleteModal.hide();
                                } else {
                                    alert(data.message || 'Error deleting comment');
                                }
                            })
                            .catch(error => {
                                console.error('Error:', error);
                                alert('Something went wrong');
                            });
                    };

                    deleteModal.show();
                }
            });


            // for like and dislike
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a');
                if (button && (button.classList.contains('like-button') || button.classList.contains(
                        'dislike-button'))) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');
                    const action = button.getAttribute('data-action');

                    fetch(`/comments/${commentId}/${action}`, {
                            method: 'POST',
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content'),
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                _method: 'POST'
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const commentElement = document.querySelector(
                                    `.comment[data-comment-id="${commentId}"]`);
                                const likeCount = commentElement.querySelector(
                                    '.like-button .like-dislike-count');
                                const dislikeCount = commentElement.querySelector(
                                    '.dislike-button .like-dislike-count');

                                likeCount.textContent = data.comment.likes;
                                dislikeCount.textContent = data.comment.dislikes;

                                if (action === 'like') {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.dislike-button').classList.remove(
                                        'active');
                                } else {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.like-button').classList.remove(
                                        'active');
                                }
                            } else {
                                alert(data.message || 'Error updating like/dislike');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('Something went wrong');
                        });
                }
            });

            // For submission of the main comment form
            document.getElementById('comment-form')?.addEventListener('submit', function(event) {
                event.preventDefault();
                const formData = new FormData(this);
                const errorDiv = document.getElementById('comment-form-error');
                errorDiv.textContent = ''; // Clear previous errors

                fetch(this.action, {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                .getAttribute('content')
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const commentList = document.getElementById('comment-list');
                            if (commentList) {
                                const newCommentHtml = `
                            <div class="comment" data-comment-id="${data.comment.id}">
                                <div class="d-flex">
                                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                    <div class="w-100">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <div class="comment-author">${data.comment.user_name}</div>
                                                <div class="comment-time">${data.comment.created_at}</div>
                                            </div>
                                            <div class="dropdown">
                                                <button class="btn btn-link dropdown-toggle" type="button"
                                                    id="dropdownMenuButton${data.comment.id}" data-bs-toggle="dropdown"
                                                    aria-expanded="false">
                                                    <i class="fa-solid fa-ellipsis-vertical"></i>
                                                </button>
                                                <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.comment.id}">
                                                    <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.comment.id}">Edit</a></li>
                                                    <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.comment.id}">Delete</a></li>
                                                </ul>
                                            </div>
                                        </div>
                                        <div class="comment-body">${data.comment.content}</div>
                                        <div class="comment-actions">
                                            <a href="#" class="like-button" data-action="like" data-comment-id="${data.comment.id}">
                                                <i class="fa-solid fa-thumbs-up"></i>
                                                <span class="like-dislike-count">0</span>
                                            </a>
                                            <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.comment.id}">
                                                <i class="fa-solid fa-thumbs-down"></i>
                                                <span class="like-dislike-count">0</span>
                                            </a>
                                            <a href="#" class="reply-link" data-comment-id="${data.comment.id}" data-author="${data.comment.user_name}">
                                                <i class="fa-solid fa-reply"></i> Reply
                                            </a>
                                        </div>
                                        <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>
                                        <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST" style="display: none;">
                                            @csrf
                                            <div class="d-flex flex-column">
                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                <div class="d-flex justify-content-between  mt-2">
                                                    <div id="comment-form-error" class="text-danger" style="display: none;">
                                                        Error: Reply cannot be empty
                                                    </div>
                                                    <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                </div>
                                            </div>
                                        </form>
                                        <div class="reply-list" style="display: none;"></div>
                                    </div>
                                </div>
                            </div>
                        `.replace(':commentId', data.comment.id);

                                commentList.insertAdjacentHTML('afterbegin', newCommentHtml);
                                this.reset();
                                initializeDropdowns();
                            }
                        } else {
                            // Display error messages
                            errorDiv.textContent = data.error || 'Your comment is empty';
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        errorDiv.textContent = 'Something went wrong';
                    });
            });

            // For submission of reply forms
            document.getElementById('comment-list')?.addEventListener('submit', function(event) {
                if (event.target.closest('.reply-form')) {
                    event.preventDefault();
                    const form = event.target;
                    const formData = new FormData(form);
                    const parentId = form.closest('.comment').dataset.commentId;
                    const errorDiv = form.querySelector('#comment-form-error');

                    // Reset error display
                    errorDiv.style.display = 'none';
                    errorDiv.textContent = '';

                    fetch(form.action.replace(':commentId', parentId), {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content')
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const replyList = form.closest('.reply-list') || form.closest(
                                    '.comment').querySelector('.reply-list');
                                if (replyList) {
                                    const newReplyHtml = `
                                <div class="comment reply" data-comment-id="${data.reply.id}">
                                    <div class="d-flex">
                                        <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                        <div class="w-100">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <div class="comment-author">${data.reply.user_name}</div>
                                                    <div class="comment-time">${data.reply.created_at}</div>
                                                </div>
                                                <div class="dropdown">
                                                    <button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton${data.reply.id}" data-bs-toggle="dropdown" aria-expanded="false">
                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                    </button>
                                                    <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.reply.id}">
                                                        <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.reply.id}">Edit</a></li>
                                                        <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.reply.id}">Delete</a></li>
                                                    </ul>
                                                </div>
                                            </div>
                                            <div class="comment-body">
                                                ${data.reply.parent_name ? `<a href="#" class="reply-mention">@${data.reply.parent_name}</a> ` : ''}
                                                <span class="reply-content">${data.reply.content}</span>
                                            </div>
                                            <div class="comment-actions">
                                                <a href="#" class="like-button" data-action="like" data-comment-id="${data.reply.id}">
                                                    <i class="fa-solid fa-thumbs-up"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.reply.id}">
                                                    <i class="fa-solid fa-thumbs-down"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="reply-link" data-comment-id="${data.reply.id}" data-author="${data.reply.user_name}">
                                                    <i class="fa-solid fa-reply"></i> Reply
                                                </a>
                                            </div>
                                            <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST" style="display: none;">
                                                @csrf
                                                    <div class="d-flex flex-column">
                                                        <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                        <div class="d-flex justify-content-between  mt-2">
                                                            <div id="comment-form-error" class="text-danger" style="display: none;">
                                                                Error: Reply cannot be empty
                                                            </div>
                                                            <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                        </div>
                                                    </div>
                                            </form>
                                            <div class="reply-list" style="display: none;"></div>
                                        </div>
                                    </div>
                                </div>
                                `.replace(':commentId', data.reply.id);

                                    replyList.insertAdjacentHTML('beforeend', newReplyHtml);
                                    form.reset();
                                    form.style.display =
                                        'none'; 

                                    // Ensure the replies are displayed
                                    const replyToggle = form.closest('.comment').querySelector(
                                        '.reply-toggle');
                                    if (replyToggle) {
                                        const replyList = replyToggle.nextElementSibling
                                            .nextElementSibling;
                                        replyList.style.display = 'block';
                                        replyToggle.textContent = 'Hide replies';
                                    }

                                    initializeDropdowns();
                                }
                            } else {
                                // Display error message
                                errorDiv.textContent = data.message || 'Error posting reply';
                                errorDiv.style.display = 'block';
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            // Display error message
                            errorDiv.textContent = 'Something went wrong';
                            errorDiv.style.display = 'block';
                        });
                }
            });

            // For reply link click to show reply form
            document.getElementById('comment-list')?.addEventListener('click', function(event) {
                if (event.target.closest('.reply-link')) {
                    event.preventDefault();
                    const replyForm = event.target.closest('.comment').querySelector('.reply-form');
                    if (replyForm) {
                        replyForm.style.display = replyForm.style.display === 'block' ? 'none' : 'block';
                    }
                }
            });
        });

        function initializeDropdowns() {
            const dropdowns = document.querySelectorAll('.dropdown-toggle:not(.initialized)');
            dropdowns.forEach(dropdown => {
                new bootstrap.Dropdown(dropdown);
                dropdown.classList.add('initialized');
            });
        }

        function toggleReplies(element) {
            const replyList = element.nextElementSibling.nextElementSibling;
            const isVisible = replyList.style.display === 'block';
            replyList.style.display = isVisible ? 'none' : 'block';
            element.textContent = isVisible ? 'View replies' : 'Hide replies';
        }
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.bookmark-toggle').forEach(function(button) {
                button.addEventListener('click', function() {
                    const fileId = this.getAttribute('data-file-id');
                    const button = this;

                    fetch("{{ route('bookmark.toggle') }}", {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({
                                file_id: fileId
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status === 'added') {
                                button.classList.add('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks-fill" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5z"/>
                                        <path d="M4.268 1A2 2 0 0 1 6 0h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L13 13.768V2a1 1 0 0 0-1-1z"/>
                                    </svg>`;
                            } else if (data.status === 'removed') {
                                button.classList.remove('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5zm2-1a1 1 0 0 0-1 1v10.566l3.723-2.482a.5.5 0 0 1 .554 0L11 14.566V4a1 1 0 0 0-1-1z"/>
                                        <path d="M4.268 1H12a1 1 0 0 1 1 1v11.768l.223.148A.5.5 0 0 0 14 13.5V2a2 2 0 0 0-2-2H6a2 2 0 0 0-1.732 1"/>
                                    </svg>`;
                            }
                        })
                        .catch(error => console.error('Error:', error));
                });
            });
        });
    </script>
@endsection
Embark on a lucrative journey with our turnkey vacation rental business – your golden ticket to making money while providing unforgettable travel experiences! Just like Airbnb, We at Appticz develop a vacation rental business that empowers you to transform your property into a revenue-generating oasis. Imagine waking up to a stream of bookings and delighted guests, all while enjoying the financial rewards of the booming vacation rental market. Get a free airbnb clone business quotation.
https://appticz.com/airbnb-clone
app.get('/auth/google',
  passport.authenticate('google', { scope: [ 'email', 'profile' ]
}));
app.get('/auth/google/callback', passport.authenticate( 'google', {
   successRedirect: '/dashboard',
   failureRedirect: '/login'
}));
1: Using Control Panel
control panel - programs - turn windows features on or off

2: Using the Command Prompt (admin)
bcdedit /set hypervisorlaunchtype off

The DISM Command
cmd (admin)
dism /online /disable-feature /featurename:Microsoft-hyper-v-all

3: Using PowerShell (admin)
Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All

4: Using BIOS
Configuration tab (or such - check)
select the Virtualization Technology - disable






echo var_export(something) die();
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler,StandardScaler,OneHotEncoder
from sklearn.preprocessing import LabelEncoder
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer

#Set Seed for reproducability
np.random.seed(42)
#Create synthetic dataset 
data={
    'Age':np.random.randint(29,77,size=200),
    'Sex':np.random.choice(['Male','Female'],size=200),
    'ChestPainType':np.random.choice(['ATA','NAP','ASY','TA'],size=200),
    'RestingBP':np.random.randint(94,200,size=200),
    'Cholesterol':np.random.randint(126,564,size=200),
    'FastingBS':np.random.choice([0,1],size=200),
    'RestingECG':np.random.choice(['Normal','ST','LVH'],size=200),
    'MaxHR':np.random.randint(71,202,size=200),
    'ExerciseAngina':np.random.choice(['N','Y'],size=200),
    'Oldpeak':np.random.uniform(0,6.2,size=200),
    'ST_Slope':np.random.choice(['Up','Flat','Down'],size=200),
    'HeartAttack':np.random.choice([0,1],size=200)
}

#Convert to DataFrame
df=pd.DataFrame(data)
df.head()
from sklearn.preprocessing import MinMaxScaler
scaler=MinMaxScaler()
columns_to_scale=['Age','Salary','Experience','Dependents','Rating']
df[columns_to_scale]=scaler.fit_transform(df[columns_to_scale])
df.head()
*******************************
  from sklearn.preprocessing import LabelEncoder,OneHotEncoder
from sklearn.compose import ColumnTransformer
l=LabelEncoder()
df['Purchased']=l.fit_transform(df['Purchased'])
ed_mapping={'Bachelor':1,'Master':2,'PhD':3}
df['Education']=df['Education'].map(ed_mapping)
df=pd.get_dummies(df,columns=['City','Product_Category'],drop_first=True)
df.head()
********************************
  from sklearn.decomposition import PCA
pca=PCA(n_components=2)
pca_f=pca.fit_transform(df[columns_to_scale])
pca_df=pd.DataFrame(pca_f,columns=['PCA1','PCA2'])
df=pd.concat([df,pca_df],axis=1)
df.head()
***********************
  df.drop('Name',axis=1,inplace=True)
df.head()
***************************
  import seaborn as sns
import matplotlib.pyplot as plt
corr_mat=df.corr()
plt.figure(figsize=(10,8))
sns.heatmap(corr_mat,annot=True,cmap="coolwarm")
plt.title("Correlation Matrix")
plt.show()
**********************************
  df.hist(bins=20,figsize=(20,15))
plt.show()
skewness=df.skew()
print(skewness)
**********************
  # prompt: plt.figure(figsize=(15,10))

plt.figure(figsize=(15,10))
sns.boxplot(data=df[['Age','Salary','Experience','Dependents','Rating']])
plt.title("Box Plots for Numerical Features")
plt.show()
*********************************
add_action('init', 'aovup_register_awaiting_dispatch_order_status');
function aovup_register_awaiting_dispatch_order_status() {
    register_post_status('wc-awaiting-dispatch', array(
        'label'                     => 'Awaiting Dispatch',
        'public'                    => true,
        'exclude_from_search'       => false,
        'show_in_admin_all_list'    => true,
        'show_in_admin_status_list' => true,
        'label_count'               => _n_noop('Awaiting Dispatch <span class="count">(%s)</span>', 'Awaiting Dispatch <span class="count">(%s)</span>')
    ));
}

add_filter('wc_order_statuses', 'aovup_add_awaiting_dispatch_to_order_statuses');
function aovup_add_awaiting_dispatch_to_order_statuses($order_statuses) {
    $order_statuses['wc-awaiting-dispatch'] = 'Awaiting Dispatch';
    return $order_statuses;
}

add_filter('bulk_actions-edit-shop_order', 'aovup_add_awaiting_dispatch_bulk_action');
function aovup_add_awaiting_dispatch_bulk_action($bulk_actions) {
    // Add a new bulk action named "Mark Awaiting Dispatch"
    $bulk_actions['mark_awaiting-dispatch'] = 'Mark Awaiting Dispatch';
    return $bulk_actions;
}

add_filter('handle_bulk_actions-edit-shop_order', 'aovup_handle_mark_awaiting_dispatch_bulk_action', 10, 3);
function aovup_handle_mark_awaiting_dispatch_bulk_action($redirect_to, $doaction, $post_ids) {
    if ($doaction !== 'mark_awaiting-dispatch') {
        return $redirect_to;
    }

    foreach ($post_ids as $post_id) {
        $order = wc_get_order($post_id);
        $order->update_status('awaiting-dispatch');
    }

    $redirect_to = add_query_arg('bulk_awaiting_dispatch_orders', count($post_ids), $redirect_to);
    return $redirect_to;
}
/**
 * Plugin Name
 *
 * @package           PluginPackage
 * @author            Your Name
 * @copyright         2019 Your Name or Company Name
 * @license           GPL-2.0-or-later
 *
 * @wordpress-plugin
 * Plugin Name:       Plugin Name
 * Plugin URI:        https://example.com/plugin-name
 * Description:       Description of the plugin.
 * Version:           1.0.0
 * Requires at least: 5.2
 * Requires PHP:      7.2
 * Author:            Your Name
 * Author URI:        https://example.com
 * Text Domain:       plugin-slug
 * License:           GPL v2 or later
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 * Update URI:        https://example.com/my-plugin/
 * Requires Plugins:  my-plugin, yet-another-plugin
 */
/*
 * Plugin Name:       My Basics Plugin
 * Plugin URI:        https://example.com/plugins/the-basics/
 * Description:       Handle the basics with this plugin.
 * Version:           1.10.3
 * Requires at least: 5.2
 * Requires PHP:      7.2
 * Author:            John Smith
 * Author URI:        https://author.example.com/
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Update URI:        https://example.com/my-plugin/
 * Text Domain:       my-basics-plugin
 * Domain Path:       /languages
 * Requires Plugins:  my-plugin, yet-another-plugin
 */
//html
<div class="container-fluid" style="margin-top: 60px;">
  <div class="row justify-content-start">
    <!-- Back Button -->
    <div class="col-6">
      <i class="bi bi-arrow-left-circle header-icon" (click)="goBack()"></i>
    </div>

    <!-- My Profile Heading -->
    <div class="col-6">
      <h2 class="text-left">My Profile</h2>
      <span style="float: right;">
        <a class="navbar-brand" href="#" data-bs-toggle="modal" data-bs-target="#helpModal">
            <i class="bi bi-info-circle-fill">Help</i>
          </a>
      </span>
    </div>

    <!-- Left Side Menu -->
    <div class="col-md-3">
      <div routerLink="/orders" *ngIf="userTypeID === 3">
        <h5 class="small-heading">
          <i class="bi bi-cart4"></i>
          Orders
        </h5>
      </div>  
      <br>
      <h5 class="small-heading">
        <i class="bi bi-bell-fill"></i>
        Notifications
      </h5>
      <!-- Notification placeholder -->
      <div class="card mt-3">
        <div class="card-body">
          <div *ngIf="unredeemedRewards.length === 0" class="notification-item">
            <span>No Notifications</span>
          </div>
          <div *ngFor="let reward of unredeemedRewards" class="notification-item">
            <span style="float:left">{{ reward.rewardTypeName }}</span>
            <span style="float: right"><button class="btn btn-sm btn-primary" (click)="openRedeemModal(reward)">Redeem</button></span>
          </div>
        </div>
      </div>
    </div>

    

    <!-- Vertical Line Separator -->
    <div class="col-md-1">
      <div class="vertical-line"></div>
    </div>

    <!-- Right Side Form -->
    <div class="col-md-6">
      <form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
        <h5 class="small-heading">
          <i class="bi bi-house-gear-fill"></i>
          Personal Details
        </h5>
        <div class="text-center mb-3">
          <div class="profile-photo-wrapper">
            <img [src]="userProfileImage" alt="Profile Photo" class="img-fluid rounded-circle profile-photo" *ngIf="userProfileImage">
            <div class="edit-photo-wrapper">
              <a href="#" (click)="enableEditMode($event)" class="edit-link">Edit</a>
              <label [class.disabled-icon]="!isEditMode" for="photoUpload" class="photo-upload-icon">
                <i class="bi bi-camera"></i>
              </label>
            </div>
            <input type="file" id="photoUpload" formControlName="photo" class="d-none" (change)="onPhotoChange($event)" [readonly]="!isEditMode" >
          </div>
        </div>
        

        <br>

      
        <div class="row">
          <div class="col-md-6 mb-3">
            <div class="form-group">
              <label for="name" class="form-label">Name</label>
              <input type="text" class="form-control" id="name" formControlName="name" [readonly]="!isEditMode" [ngClass]="{'disabled-input': !isEditMode}">
              <div *ngIf="profileForm.controls['name'].invalid && (profileForm.controls['name'].dirty || profileForm.controls['name'].touched)" class="alert">
                <div *ngIf="profileForm.controls['name'].errors?.['required']">Name is required.</div>
                <div *ngIf="profileForm.controls['name'].errors?.['minlength']">Name must be at least 2 characters long.</div>
                <div *ngIf="profileForm.controls['name'].errors?.['maxlength']">Name must be at most 20 characters long.</div>
              </div>
            </div>
          </div>

          <div class="col-md-6 mb-3">
            <div class="form-group">            
              <label for="surname" class="form-label">Surname</label>
              <input type="text" class="form-control" id="surname" formControlName="surname" [readonly]="!isEditMode" [ngClass]="{'disabled-input': !isEditMode}">
              <div *ngIf="profileForm.controls['surname'].invalid && (profileForm.controls['surname'].dirty || profileForm.controls['surname'].touched)" class="alert">
                <div *ngIf="profileForm.controls['surname'].errors?.['required']">Surname is required.</div>
                <div *ngIf="profileForm.controls['surname'].errors?.['minlength']">Surname must be at least 2 characters long.</div>
                <div *ngIf="profileForm.controls['surname'].errors?.['maxlength']">Surname must be at most 20 characters long.</div>
              </div>
            </div>
          </div>

          <div class="col-md-6 mb-3">
            <div class="form-group">
              <label for="email" class="form-label">Email Address</label>
              <input type="email" class="form-control" id="email" formControlName="email" [readonly]="!isEditMode" [ngClass]="{'disabled-input': !isEditMode}">
              <div *ngIf="profileForm.controls['email'].invalid && (profileForm.controls['email'].dirty || profileForm.controls['email'].touched)" class="alert">
                <div *ngIf="profileForm.controls['email'].errors?.['required']">Email is required.</div>
                <div *ngIf="profileForm.controls['email'].errors?.['email']">Email is invalid.</div>
              </div>
            </div>
          </div>

          <div class="col-md-6 mb-3">
            <div class="form-group">
              <label for="phoneNumber" class="form-label">Phone Number</label>
              <input type="text" class="form-control" id="phoneNumber" formControlName="phoneNumber" [readonly]="!isEditMode" [ngClass]="{'disabled-input': !isEditMode}">
              <div *ngIf="profileForm.controls['phoneNumber'].invalid && (profileForm.controls['phoneNumber'].dirty || profileForm.controls['phoneNumber'].touched)" class="alert">
                <div *ngIf="profileForm.controls['phoneNumber'].errors?.['required']">Phone Number is required.</div>
                <div *ngIf="profileForm.controls['phoneNumber'].errors?.['minlength']">Phone Number must be a valid 10-digit number.</div>
                <div *ngIf="profileForm.controls['phoneNumber'].errors?.['maxlength']">Phone Number must be a valid 10-digit number.</div>
              </div>
            </div>
          </div>

          <div class="col-md-6 mb-3">
            <div class="form-group">
              <label for="physical_Address" class="form-label">Physical Address</label>
              <input type="text" class="form-control" id="physical_Address" formControlName="physical_Address" [readonly]="!isEditMode" [ngClass]="{'disabled-input': !isEditMode}">
              <div *ngIf="profileForm.controls['physical_Address'].invalid && (profileForm.controls['physical_Address'].dirty || profileForm.controls['physical_Address'].touched)" class="alert">
                <div *ngIf="profileForm.controls['physical_Address'].errors?.['required']">Physical address is required.</div>
                <div *ngIf="profileForm.controls['physical_Address'].errors?.['minlength']">Physical Address must be at least 7 characters long.</div>
                <div *ngIf="profileForm.controls['physical_Address'].errors?.['maxlength']">Physical Address must be at most 100 characters long.</div>
              </div>
            </div>
          </div>
        </div>

        <div class="d-flex justify-content-end">
          <button type="button" class="btn btn-primary me-2" (click)="openSaveModal()" [disabled]="!isEditMode">Save</button>
          <button type="button" class="btn btn-info" (click)="changePassword()" [disabled]="!isEditMode">Change Password</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Save Confirmation Modal -->
<div class="modal fade" id="saveConfirmationModal" tabindex="-1" role="dialog" aria-labelledby="saveConfirmationModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="saveConfirmationModalTitle">Save Changes</h5>
      </div>
      <div class="modal-body">
        Are you sure you want to update your profile details?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" (click)="dismissModal()">Cancel</button>
        <button type="button" class="btn btn-primary" (click)="confirmSave()">Confirm</button>
      </div>
    </div>
  </div>
</div>

<!-- Error Modal -->
<div class="modal fade" id="errorModal" tabindex="-1" role="dialog" aria-labelledby="errorModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="errorModalTitle">Error</h5>
      </div>
      <div class="modal-body">
        Please enter a valid input for the following fields:
        <ul id="errorList"></ul>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" (click)="dismissErrorModal()">OK</button>
      </div>
    </div>
  </div>
</div>

<!-- Redeem Reward Modal -->
<div class="modal fade" id="redeemRewardModal" tabindex="-1" role="dialog" aria-labelledby="redeemRewardModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="redeemRewardModalTitle">Redeem Reward</h5>
      </div>
      <div class="modal-body">
        Are you sure you want to redeem the reward <strong>{{ selectedReward?.rewardTypeName }}</strong>?
        <br>
        <p>The reward criteria met: <strong>{{ selectedReward?.rewardCriteria }}</strong></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" (click)="dismissRedeemModal()">No</button>
        <button type="button" class="btn btn-primary" (click)="confirmRedeem()">Yes</button>
      </div>
    </div>
  </div>
</div>

<!-- Success Modal -->
<div class="modal fade" id="successModal" tabindex="-1" role="dialog" aria-labelledby="successModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <strong><h5 class="modal-title" id="successModalTitle">Congratulations</h5></strong>
      </div>
      <div class="modal-body">
        <strong>Congratulations!</strong> You've successfully redeemed this reward <strong>{{ selectedReward?.rewardTypeName }}</strong>. Please contact the gym and provide this code <strong>{{ verificationCode }}</strong> for further instructions.
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" (click)="dismissSuccessModal()">Close</button>
      </div>
    </div>
  </div>
</div>


<!-- help-modal.component.html -->
<div class="modal fade" id="helpModal" tabindex="-1" aria-labelledby="helpModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        <h5 class="modal-title mx-auto" id="helpModalLabel">Help Guide</h5>
        <div class="search-bar-container">
          <input type="text" class="form-control search-bar" placeholder="Search help" [(ngModel)]="searchTerm" (input)="filterHelpContent()">
        </div>
      </div>
      <div class="modal-body">
        <div *ngFor="let item of filteredContent">
          <h5>{{ item.title }}</h5>
          <p [innerHTML]="item.content"></p>
        </div>
      </div>
    </div>
  </div>
</div>

//ts
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormGroup, Validators, FormBuilder, FormsModule } from '@angular/forms';
import { UserService } from '../Services/userprofile.service';
import { Router, RouterLink } from '@angular/router';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';
import { Member, updateUser } from '../shared/update-user';
import { Subscription, catchError } from 'rxjs';
import { RewardRedeemViewModel, UnredeemedRewardModel } from '../shared/reward';
import { RewardService } from '../Services/reward.service';

declare var $: any; // Import jQuery

@Component({
  selector: 'app-profile-page',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, RouterLink, FormsModule],
  templateUrl: './profile-page.component.html',
  styleUrls: ['./profile-page.component.css']
})
export class ProfilePageComponent implements OnInit, OnDestroy {
  profileForm: FormGroup;
  user: updateUser | undefined;
  member: Member | undefined;
  isEditMode = false;
  errorMessage = '';  
  userProfileImage: string | null = null;
  photoFile: File | null = null;
  unredeemedRewards: UnredeemedRewardModel[] = [];
  selectedReward: UnredeemedRewardModel | null = null;
  verificationCode: string | null = null;
  userTypeID: number | null = null;
  helpContent: any[] = [];
  filteredContent: any[] = [];
  searchTerm: string = '';

  private userSubscription: Subscription | undefined;
  private memberSubscription: Subscription | undefined;
  private redeemSubscription: Subscription | undefined;
  
  constructor(
    private userService: UserService,
    private rewardService: RewardService,
    private router: Router,
    private fb: FormBuilder
  ) {
    this.profileForm = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      name: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      surname: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      phoneNumber: ['', [Validators.required, Validators.minLength(10), Validators.maxLength(10)]],
      physical_Address: ['', [Validators.required, Validators.minLength(7), Validators.maxLength(100)]],
      photo: ['']
    });
  }

  ngOnInit(): void {
    const userTypeId = JSON.parse(localStorage.getItem('User') || '{}').userTypeId;
    this.userTypeID = userTypeId;
    console.log('User Type ID',userTypeId);
    const userId = JSON.parse(localStorage.getItem('User') || '{}').userId;
    console.log('User ID from local storage:', userId);
    this.loadUserProfile(userId);
    this.isEditMode = false;    


    // Initialize help content
    this.helpContent = [
      {
        title: 'Profile Page Context-Sensitive Help',
        content: `
          <p><strong>Overview:</strong> The Profile Page allows users to view and update their personal information. This includes details such as username, email, and profile picture.</p>
          <p><strong>Elements and Features:</strong></p>`
      },
      {
        title: '1. Back Button',
        content: `
          <ul>
            <li><strong>Description:</strong> An arrow icon located in the header that allows you to return to the previous page.</li>
            <li><strong>Functionality:</strong> Clicking the back button navigates to the previous page you visited.</li>
            <li><strong>Helpful Tips:</strong>
              <ul>
                <li>Use the back button if you want to return to your previous page without losing your current context.</li>
              </ul>
            </li>
          </ul>`
      },
      {
        title: '2. Header Title',
        content: `
          <ul>
            <li><strong>Description:</strong> Displays the title "Profile" to indicate the purpose of the screen.</li>
            <li><strong>Functionality:</strong> Provides a clear indication of the current screen's functionality.</li>
          </ul>`
      },
      {
        title: '3. Profile Information',
        content: `
          <ul>
            <li><strong>Description:</strong> Displays your personal information such as username, email, and profile picture.</li>
            <li><strong>Functionality:</strong> Allows you to view and edit your personal details.</li>
          </ul>`
      },
      {
        title: '4. Change Password Button',
        content: `
          <ul>
            <li><strong>Description:</strong> A button that navigates you to the Change Password screen.</li>
            <li><strong>Functionality:</strong> Allows you to update your password securely.</li>
          </ul>`
      },
      {
        title: 'Technical Details:',
        content: `
          <ul>
            <li>Dynamic Data: The profile information is dynamically updated based on the data retrieved from the backend.</li>
            <li>Navigation: Utilizes Angular's Router for smooth transitions between different sections of the application.</li>
          </ul>`
      },
      {
        title: 'Common Questions:',
        content: `
          <p><strong>Q:</strong> How do I update my profile information?</p>
          <p><strong>A:</strong> Click on the edit button next to the information you want to update, make your changes, and click save.</p>
          <p><strong>Q:</strong> How do I change my password?</p>
          <p><strong>A:</strong> Click the "Change Password" button to navigate to the Change Password screen.</p>
          <p><strong>Q:</strong> What should I do if I encounter an error?</p>
          <p><strong>A:</strong> Refresh the page or contact support for assistance.</p>`
      },
      {
        title: 'Troubleshooting:',
        content: `
          <p><strong>Problem:</strong> The profile information is not loading.</p>
          <p><strong>Solution:</strong> Ensure you are connected to the internet and logged in. If the problem persists, try refreshing the page or contact technical support.</p>
          <p><strong>Problem:</strong> Unable to update profile information.</p>
          <p><strong>Solution:</strong> Check your internet connection and ensure all required fields are filled out correctly. If the issue continues, contact support.</p>`
      }
    ];

    // Initialize filtered content
    this.filteredContent = [...this.helpContent];
  }

  filterHelpContent(): void {
    const term = this.searchTerm.toLowerCase();
    this.filteredContent = this.helpContent.filter(item =>
      item.title.toLowerCase().includes(term) || item.content.toLowerCase().includes(term)
    );
  }

  ngOnDestroy(): void {
    // Clean up subscriptions
    if (this.userSubscription) {
      this.userSubscription.unsubscribe();
    }
    if (this.memberSubscription) {
      this.memberSubscription.unsubscribe();
    }
    if (this.redeemSubscription) {
      this.redeemSubscription.unsubscribe();
    }
  }

  loadUserProfile(userId: number): void {
    this.userSubscription = this.userService.getUserById(userId).pipe(
      catchError(error => {
        console.error('Error fetching user profile:', error);
        return [];
      })
    ).subscribe({
      next: (result) => {
        console.log('User data received:', result);
        this.user = result; 

        // Patch non-file form values
        this.profileForm.patchValue({
          email: this.user.email,
          name: this.user.name,
          surname: this.user.surname,
          phoneNumber: this.user.phoneNumber,
          physical_Address: this.user.physical_Address,
        });

        // Log photo to debug
        console.log('Photo:', this.user.photo);        
        // Set user profile image
        this.userProfileImage = `data:image/jpeg;base64,${this.user.photo}`;
        console.log('User:', this.user);

        const userTypeId = JSON.parse(localStorage.getItem('User') || '{}').userTypeId;
        this.userTypeID = userTypeId;
        if (this.userTypeID === 3) {
          this.loadMemberProfile(userId);
        }
      },
      complete: () => {
        console.log('getUserById subscription completed');
      }
    });
  }

  loadMemberProfile(userId: number): void {
    this.memberSubscription = this.userService.getMemberByUserId(userId).pipe(
      catchError(error => {
        console.error('Error fetching member profile:', error);
        return [];
      })
    ).subscribe({
      next: (result) => {
        this.member = result;
        if (this.member) {
          console.log('Member data received:', this.member); // Detailed debug statement
          console.log('Member ID:', this.member.member_ID); // Debug statement
          this.loadUnredeemedRewards(this.member.member_ID);
        }
      },
      complete: () => {
        console.log('getMemberByUserId subscription completed');
      }
    });
  }

  clearForm() {
    this.profileForm.reset();
  }

  enableEditMode(event: Event) {
    event.preventDefault();
    this.isEditMode = true;
    this.profileForm.enable();
  }

  openSaveModal() {
    if (this.profileForm.invalid) {
      this.showValidationErrors();
      $('#errorModal').modal('show');
      return;
    }
    $('#saveConfirmationModal').modal('show');
  }

  showValidationErrors() {
    const invalidFields: string[] = [];
    Object.keys(this.profileForm.controls).forEach(key => {
      const controlErrors = this.profileForm.get(key)?.errors;
      if (controlErrors) {
        Object.keys(controlErrors).forEach(errorKey => {
          invalidFields.push(`${key}: ${errorKey}`);
        });
      }
    });
    this.errorMessage = `Please enter a valid input: ${invalidFields.join(', ')}`;
  }

  dismissModal() {
    $('#saveConfirmationModal').modal('hide');
  }

  dismissErrorModal() {
    $('#errorModal').modal('hide');
  }

  confirmSave() {
    this.dismissModal();
    this.onSubmit();
    this.isEditMode = false; // Disable edit mode after confirmation
  }

  onSubmit() {
    if (this.profileForm.valid) {
        const userId = JSON.parse(localStorage.getItem('User')!).userId;
        const formValue = this.profileForm.value;

        // If no new photo is selected, use the existing photo
        let photoFile: File | null = this.photoFile;
        if (!photoFile && this.user?.photo) {
          // Ensure the Base64 string is valid
          const base64Prefix = 'data:image/jpeg;base64,';
          let base64String = this.user.photo;
          if (base64String.startsWith(base64Prefix)) {
            base64String = base64String.replace(base64Prefix, '');
          }
          try {
            const byteString = atob(base64String);
            const arrayBuffer = new ArrayBuffer(byteString.length);
            const intArray = new Uint8Array(arrayBuffer);
            for (let i = 0; i < byteString.length; i++) {
              intArray[i] = byteString.charCodeAt(i);
            }
            const blob = new Blob([intArray], { type: 'image/jpeg' });
            photoFile = new File([blob], 'photo.jpg', { type: 'image/jpeg' });
          } catch (e) {
            console.error('Invalid Base64 string:', e);
          }
        }

        // Create the user object
        const user: updateUser = {
            name: formValue.name,
            surname: formValue.surname,
            email: formValue.email,
            physical_Address: formValue.physical_Address,
            phoneNumber: formValue.phoneNumber,
            photo: this.user?.photo ?? '', // Ensure photo is included even if it's not updated
            user_Type_ID: this.user?.user_Type_ID ?? 0
        };

        this.userService.updateUser(userId, user, photoFile).subscribe({
            next: (result) => {
                console.log('User updated successfully:', result);
                this.router.navigateByUrl(`/ProfilePage/${userId}`);
                alert('Successfully updated profile');
            },
            error: (error) => {
                console.error('Error updating user profile:', error);
                alert('Error updating profile.');
            }
        });
    } else {
        console.warn('Form is invalid:', this.profileForm.errors);
    }
  }

  onPhotoChange(event: Event): void {
    if (!this.isEditMode) return;

    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
        const file = input.files[0];
        
        // Ensure file is an image
        if (!file.type.startsWith('image/')) {
            console.error('Selected file is not an image.');
            alert('Please select a valid image file.');
            return;
        }

        const reader = new FileReader();

        reader.onload = (e: any) => {
          if (e.target && e.target.result) {
              this.userProfileImage = e.target.result; // Update the image source for preview
              this.photoFile = file; // Set the file for form submission
              console.log('Base64 string of the image:', this.userProfileImage);
          }
      };

        reader.onerror = (e) => {
            console.error('Error reading file:', e);
            alert('There was an error reading the file. Please try again.');
        };

        reader.onabort = (e) => {
            console.warn('File read aborted:', e);
            alert('File read was aborted. Please try again.');
        };

        reader.onloadend = () => {
            console.log('File read completed.');
        };

        try {
            reader.readAsDataURL(file);
            this.photoFile = file; 
        } catch (error) {
            console.error('An error occurred while reading the file:', error);
            alert('An error occurred while reading the file. Please try again.');
        }
    } else {
        console.error('No file selected or input element is invalid.');
    }
  }


  goBack() {
    const userTypeId = JSON.parse(localStorage.getItem('User')!).userTypeId;
    const userId = JSON.parse(localStorage.getItem('User')!).userId;
    if (userTypeId === 1) {  // Ensure userTypeID is compared as string
      this.router.navigateByUrl(`/OwnerHome/${userId}`);
    } else if (userTypeId === 2) {
      this.router.navigateByUrl(`/EmployeeHome/${userId}`);
    } else if (userTypeId === 3) {
      this.router.navigateByUrl(`/Home/${userId}`);
    }
  }

  changePassword() {
    this.router.navigateByUrl('/ChangePasswordPage');
  }

  // Method to load rewards for the current user
  loadUnredeemedRewards(memberId: number): void {
    console.log('Loading unredeemed rewards for member ID:', memberId); 
    this.rewardService.getUnredeemedRewardsForMember(memberId).subscribe({
      next: rewards => {
        this.unredeemedRewards = rewards;
        console.log("reward", rewards)
      },
      error: error => {
        console.error('Error fetching unredeemed rewards:', error);
      },
      complete: () => {
        console.log('Fetching unredeemed rewards completed.');
      }
    });
  }

  // Method to open redeem modal for a reward
  openRedeemModal(reward: UnredeemedRewardModel): void {
    this.selectedReward = reward;
    $('#redeemRewardModal').modal('show');
  }

  // Method to dismiss redeem modal
  dismissRedeemModal(): void {
    $('#redeemRewardModal').modal('hide');
  }

  // Method to confirm redeeming a reward
  confirmRedeem(): void {
    if (!this.selectedReward) {
      return;
    }
    const redeemRequest = new RewardRedeemViewModel();
    redeemRequest.MemberId = this.member?.member_ID ?? 0;
    redeemRequest.RewardId = this.selectedReward.reward_ID;

    // Call backend service to redeem the reward
    this.redeemSubscription = this.rewardService.redeemReward(redeemRequest).subscribe({
      next: () => {
        // Show success modal on successful redemption
        this.verificationCode = this.generateSixDigitCode(); // Generate code when opening modal
        console.log('Generated verification code:', this.verificationCode); 
        $('#successModal').modal('show');
        // Remove redeemed reward from the list
        this.unredeemedRewards = this.unredeemedRewards.filter(r => r.reward_ID !== this.selectedReward?.reward_ID);
      },
      error: (error) => {
        console.error('Error redeeming reward:', error);
        // Handle error
      }
    });
    this.dismissRedeemModal();
  }

  // Method to dismiss success modal
  dismissSuccessModal(): void {
    $('#successModal').modal('hide');
  }

  generateSixDigitCode(): string {
    const code = Math.floor(100000 + Math.random() * 900000).toString();
    return `${code.slice(0, 3)}-${code.slice(3)}`;
  }
}
function cst_schema_field(){
    add_meta_box(
        'cft_metabox_field',
        'Add Schema',
        'cft_callback_func',
        array('page'),
        'normal',
        'high'
        );
}

add_action('add_meta_boxes','cst_schema_field');

function cft_callback_func($post){
    echo '<style>
        .schema_cft {
            width: 100%;
        }
    </style>';
    
    $meta_value = get_post_meta($post->ID, '_schema_cft', true);
    
    echo '<textarea name="schema_cft" class="schema_cft" rows="15">' . $meta_value . '</textarea>';
}

function cft_save_func($post_id){
    
    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if(!current_user_can('administrator', $post_id)) return;
    
    if(isset($_POST['schema_cft'])){
        update_post_meta($post_id, '_schema_cft', $_POST['schema_cft']);
    }
}

add_action('save_post','cft_save_func');

function display_schema_cft_in_head() {
    if (is_singular('page')) {
        $page_id = get_queried_object_id();
        
        $schema_cft_value = get_post_meta($page_id, '_schema_cft', true);

        if (!empty($schema_cft_value)) {
            echo $schema_cft_value;
        }
    }
}
// Add a column to the posts and pages list in the admin panel to display the last modified date
function add_last_modified_column($columns) {
    $columns['last_modified'] = 'Last Modified';
    return $columns;
}
add_filter('manage_posts_columns', 'add_last_modified_column');
add_filter('manage_pages_columns', 'add_last_modified_column');

// Populate the last modified column with the date and time
function display_last_modified_column($column, $post_id) {
    if ($column == 'last_modified') {
        $last_modified = get_post_modified_time('F j, Y, g:i a', false, $post_id);
        echo $last_modified;
    }
}
add_action('manage_posts_custom_column', 'display_last_modified_column', 10, 2);
add_action('manage_pages_custom_column', 'display_last_modified_column', 10, 2);

// Make the last modified column sortable
function make_last_modified_column_sortable($columns) {
    $columns['last_modified'] = 'last_modified';
    return $columns;
}
add_filter('manage_edit-post_sortable_columns', 'make_last_modified_column_sortable');
add_filter('manage_edit-page_sortable_columns', 'make_last_modified_column_sortable');

// Set the sorting logic for the last modified column
function sort_by_last_modified($vars) {
    if (isset($vars['orderby']) && 'last_modified' == $vars['orderby']) {
        $vars = array_merge($vars, array(
            'orderby' => 'modified'
        ));
    }
    return $vars;
}
add_filter('request', 'sort_by_last_modified');
@extends('new_layouts.app')
@section('styles')
    <style>
        .custom-table {
            border-collapse: collapse;
            border-radius: 1rem;
            border-style: hidden;
            box-shadow: 0 0 0 1px #e6ebef;
            overflow: hidden;
            text-align: left;
            width: 100%;
        }

        .badge-file-extension {
            background-color: #f25961;
            color: white;
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            border-radius: 0.375rem;
            margin-left: 0.5rem;
        }

        .bookmark-active svg {
            fill: #FF9800;
        }

        .description-text {
            font-size: 1.1rem;
            color: #555;
            margin-top: 0.5rem;
        }

        .comment {
            margin-top: 1rem;
            margin-bottom: 1rem;
        }

        .comment-section {
            border: 1px solid #e9ebee;
            border-radius: 1rem;
            padding: 1.5rem;
            background-color: #ffffff;
            /* box-shadow: 0 0 1rem rgba(0, 0, 0, 0.1); */
        }

        .comment-header {
            border-bottom: 1px solid #e9ebee;
            padding-bottom: 0.75rem;
            margin-bottom: 1rem;
        }

        .comment-avatar {
            height: 48px;
            width: 48px;
            border-radius: 50%;
            margin-right: 1rem;
        }

        .comment-author {
            font-size: 1rem;
            font-weight: 600;
        }

        .comment-time {
            font-size: 0.875rem;
            color: #90949c;
        }

        .comment-body {
            margin: 0.75rem 0;
            font-size: 1rem;
        }

        .comment-actions a {
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-right: 1rem;
        }

        .comment-actions i {
            margin-right: 0.5rem;
        }

        .reply-list {
            margin-top: 1rem;
            padding-left: 2rem;
        }

        .reply-list .comment {
            border-left: 1px dotted #d3d6db;
            padding-left: 1rem;
            margin-top: 1rem;
        }

        .reply-toggle {
            cursor: pointer;
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-top: 1rem;
            display: block;
        }

        .reply-form {
            display: none;
            position: relative;
            z-index: 10;
        }

        .comment-input {
            border-radius: 0.5rem;
        }

        .like-button.active i {
            color: #4caf50;
        }

        .dislike-button.active i {
            color: #dc3545;
        }


        /* Dropdown Styles */
        .dropdown-toggle::after {
            display: none;
            /* Remove the default arrow */
        }

        .dropdown-menu {
            right: 0;
            left: auto;
        }
    </style>
@endsection
@section('content')
    <div class="container">
        <div class="mt-4 comment-section">
            <h3>Comments ( {{ $comments->count() }} )</h3>
            <div class="comment-header d-flex justify-content-between align-items-center">
            </div>
            <div class="comment-body">
                <div class="d-flex mb-3">
                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                        class="comment-avatar">
                    <div class="w-100">
                        <form id="comment-form" action="{{ route('comments.store', $material) }}" method="POST">
                            @csrf
                            <div class="d-flex flex-column">
                                <textarea name="content" class="form-control comment-input" placeholder="Write a comment..." rows="3"></textarea>
                                <div class="d-flex justify-content-between mt-2">
                                    <div id="comment-form-error" class="text-danger"></div>
                                    <button type="submit" class="btn btn-primary">Post Comment</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div id="comment-list" class="comment-list">
                    @foreach ($comments as $comment)
                        <div class="comment" data-comment-id="{{ $comment->id }}">
                            <div class="d-flex">
                                <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                                    class="comment-avatar">
                                <div class="w-100">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <div class="comment-author">{{ $comment->user->name }}</div>
                                            <div class="comment-time">{{ $comment->created_at->diffForHumans() }}</div>
                                        </div>
                                        @if ($comment->user_id === auth()->id())
                                            <div class="dropdown">
                                                <button class="btn btn-link dropdown-toggle" type="button"
                                                    id="dropdownMenuButton{{ $comment->id }}" data-bs-toggle="dropdown"
                                                    aria-expanded="false">
                                                    <i class="fa-solid fa-ellipsis-vertical"></i>
                                                </button>
                                                <ul class="dropdown-menu"
                                                    aria-labelledby="dropdownMenuButton{{ $comment->id }}">
                                                    <li><a class="dropdown-item" href="#" data-action="edit"
                                                            data-comment-id="{{ $comment->id }}">Edit</a></li>
                                                    <li><a class="dropdown-item text-danger" href="#"
                                                            data-action="delete"
                                                            data-comment-id="{{ $comment->id }}">Delete</a></li>
                                                </ul>
                                            </div>
                                        @endif
                                    </div>
                                    <div class="comment-body">{{ $comment->content }}</div>
                                    <div class="comment-actions">
                                        <a href="#"
                                            class="like-button {{ $comment->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="like" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-up"></i>
                                            <span class="like-dislike-count">{{ $comment->likes }}</span>
                                        </a>
                                        <a href="#"
                                            class="dislike-button {{ $comment->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="dislike" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-down"></i>
                                            <span class="like-dislike-count">{{ $comment->dislikes }}</span>
                                        </a>
                                        <a href="#" class="reply-link" data-comment-id="{{ $comment->id }}"
                                            data-author="{{ $comment->user->name }}">
                                            <i class="fa-solid fa-reply"></i> Reply
                                        </a>
                                    </div>
                                    <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>

                                    <form class="reply-form" action="{{ route('replies.store', $comment) }}"
                                        method="POST">
                                        @csrf
                                        <div class="d-flex flex-column">
                                            <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                            <div class="d-flex justify-content-between mt-2">
                                                <div id="comment-form-error" class="text-danger" style="display: none;">
                                                    Error: Reply cannot be empty
                                                </div>
                                                <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                            </div>
                                        </div>

                                    </form>
                                    <div class="reply-list" style="display: none;">
                                        @foreach ($comment->replies as $reply)
                                            <div class="comment reply" data-comment-id="{{ $reply->id }}">
                                                <div class="d-flex">
                                                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg"
                                                        alt="avatar" class="comment-avatar">
                                                    <div class="w-100">
                                                        <div class="d-flex justify-content-between align-items-start">
                                                            <div>
                                                                <div class="comment-author">{{ $reply->user->name }}</div>
                                                                <div class="comment-time">
                                                                    {{ $reply->created_at->diffForHumans() }}</div>
                                                            </div>
                                                            @if ($reply->user_id === auth()->id())
                                                                <div class="dropdown">
                                                                    <button class="btn btn-link dropdown-toggle"
                                                                        type="button"
                                                                        id="dropdownMenuButton{{ $reply->id }}"
                                                                        data-bs-toggle="dropdown" aria-expanded="false">
                                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                                    </button>
                                                                    <ul class="dropdown-menu"
                                                                        aria-labelledby="dropdownMenuButton{{ $reply->id }}">
                                                                        <li><a class="dropdown-item" href="#"
                                                                                data-action="edit"
                                                                                data-comment-id="{{ $reply->id }}">Edit</a>
                                                                        </li>
                                                                        <li><a class="dropdown-item text-danger"
                                                                                href="#" data-action="delete"
                                                                                data-comment-id="{{ $reply->id }}">Delete</a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            @endif
                                                        </div>
                                                        <div class="comment-body">
                                                            @if ($reply->parent)
                                                                <a href="#"
                                                                    class="reply-mention">{{ '@' . $reply->parent->user->name }}</a>
                                                            @endif
                                                            <span class="reply-content">{{ $reply->content }}</span>
                                                        </div>
                                                        <div class="comment-actions">
                                                            <a href="#"
                                                                class="like-button {{ $reply->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="like" data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-up"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->likes }}</span>
                                                            </a>
                                                            <a href="#"
                                                                class="dislike-button {{ $reply->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="dislike"
                                                                data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-down"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->dislikes }}</span>
                                                            </a>
                                                            <a href="#" class="reply-link"
                                                                data-comment-id="{{ $reply->id }}"
                                                                data-author="{{ $reply->user->name }}">
                                                                <i class="fa-solid fa-reply"></i> Reply
                                                            </a>
                                                        </div>
                                                        <form class="reply-form"
                                                            action="{{ route('replies.store', $reply) }}" method="POST">
                                                            @csrf
                                                            <div class="d-flex flex-column">
                                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                                <div class="d-flex justify-content-between mt-2">
                                                                    <div id="comment-form-error" class="text-danger"
                                                                        style="display: none;">
                                                                        Error: Reply cannot be empty
                                                                    </div>
                                                                    <button type="submit"
                                                                        class="btn btn-primary ms-auto">Post Reply</button>
                                                                </div>
                                                            </div>

                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                            @include('materials.comment', ['replies' => $reply->replies])
                                        @endforeach
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const commentList = document.getElementById('comment-list');

            // Handle edit button click
            commentList.addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="edit"]');
                if (button) {
                    event.preventDefault();
                    const commentId = button.getAttribute('data-comment-id');
                    const commentElement = document.querySelector(
                        `.comment[data-comment-id="${commentId}"]`);
                    const commentBodyElement = commentElement.querySelector('.comment-body');

                    // Extract mention and content
                    const mentionElement = commentBodyElement.querySelector('.reply-mention');
                    const mention = mentionElement ? mentionElement.innerText.trim() : '';
                    const contentElement = mentionElement ? mentionElement.nextElementSibling :
                        commentBodyElement;
                    const content = contentElement.innerText.trim();

                    // Store original content for cancel action
                    commentBodyElement.dataset.originalContent = commentBodyElement.innerHTML;

                    const editForm = `
                <form class="edit-comment-form" data-comment-id="${commentId}">
                    ${mention ? `<span class="reply-mention">${mention}</span>` : ''}
                    <textarea class="form-control">${content}</textarea>
                    <button type="submit" class="btn btn-primary mt-2">Save</button>
                    <button type="button" class="btn btn-secondary mt-2 cancel-edit">Cancel</button>
                </form>
            `;

                    commentBodyElement.innerHTML = editForm;
                    attachEditFormListeners(commentId);
                }
            });

            function attachEditFormListeners(commentId) {
                const editForm = document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"]`);

                editForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    const textarea = this.querySelector('textarea');
                    const content = textarea.value;
                    const mention = this.querySelector('.reply-mention') ? this.querySelector(
                        '.reply-mention').innerText.trim() : '';

                    fetch(`/comments/${commentId}`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content')
                            },
                            body: JSON.stringify({
                                content
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const commentBodyElement = document.querySelector(
                                    `.comment[data-comment-id="${commentId}"] .comment-body`);
                                const mentionElement = mention ?
                                    `<a href="#" class="reply-mention">${mention}</a>` : '';
                                commentBodyElement.innerHTML =
                                    `${mentionElement} <span class="reply-content">${data.content}</span>`;
                            } else {
                                alert('Error updating comment.');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                        });
                });

                editForm.querySelector('.cancel-edit').addEventListener('click', function() {
                    const originalContent = document.querySelector(
                            `.comment[data-comment-id="${commentId}"] .comment-body`).dataset
                        .originalContent;
                    document.querySelector(`.comment[data-comment-id="${commentId}"] .comment-body`)
                        .innerHTML = originalContent;
                });
            }
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {

            // for delete 
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="delete"]');
                if (button) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');

                    if (confirm('Are you sure you want to delete this comment?')) {
                        fetch(`/comments/${commentId}`, {
                                method: 'DELETE',
                                headers: {
                                    'X-Requested-With': 'XMLHttpRequest',
                                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                        .getAttribute('content'),
                                    'Content-Type': 'application/json',
                                }
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    const commentElement = document.querySelector(
                                        `.comment[data-comment-id="${commentId}"]`);
                                    if (commentElement) {
                                        commentElement.remove();
                                    }
                                } else {
                                    alert(data.message || 'Error deleting comment');
                                }
                            })
                            .catch(error => {
                                console.error('Error:', error);
                                alert('Something went wrong');
                            });
                    }
                }
            });

            // for like and dislike
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a');
                if (button && (button.classList.contains('like-button') || button.classList.contains(
                        'dislike-button'))) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');
                    const action = button.getAttribute('data-action');

                    fetch(`/comments/${commentId}/${action}`, {
                            method: 'POST',
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content'),
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                _method: 'POST'
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const commentElement = document.querySelector(
                                    `.comment[data-comment-id="${commentId}"]`);
                                const likeCount = commentElement.querySelector(
                                    '.like-button .like-dislike-count');
                                const dislikeCount = commentElement.querySelector(
                                    '.dislike-button .like-dislike-count');

                                likeCount.textContent = data.comment.likes;
                                dislikeCount.textContent = data.comment.dislikes;

                                if (action === 'like') {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.dislike-button').classList.remove(
                                        'active');
                                } else {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.like-button').classList.remove(
                                        'active');
                                }
                            } else {
                                alert(data.message || 'Error updating like/dislike');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('Something went wrong');
                        });
                }
            });

            // For submission of the main comment form
            document.getElementById('comment-form')?.addEventListener('submit', function(event) {
                event.preventDefault();
                const formData = new FormData(this);
                const errorDiv = document.getElementById('comment-form-error');
                errorDiv.textContent = ''; // Clear previous errors

                fetch(this.action, {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                .getAttribute('content')
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const commentList = document.getElementById('comment-list');
                            if (commentList) {
                                const newCommentHtml = `
                            <div class="comment" data-comment-id="${data.comment.id}">
                                <div class="d-flex">
                                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                    <div class="w-100">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <div class="comment-author">${data.comment.user_name}</div>
                                                <div class="comment-time">${data.comment.created_at}</div>
                                            </div>
                                            <div class="dropdown">
                                                <button class="btn btn-link dropdown-toggle" type="button"
                                                    id="dropdownMenuButton${data.comment.id}" data-bs-toggle="dropdown"
                                                    aria-expanded="false">
                                                    <i class="fa-solid fa-ellipsis-vertical"></i>
                                                </button>
                                                <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.comment.id}">
                                                    <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.comment.id}">Edit</a></li>
                                                    <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.comment.id}">Delete</a></li>
                                                </ul>
                                            </div>
                                        </div>
                                        <div class="comment-body">${data.comment.content}</div>
                                        <div class="comment-actions">
                                            <a href="#" class="like-button" data-action="like" data-comment-id="${data.comment.id}">
                                                <i class="fa-solid fa-thumbs-up"></i>
                                                <span class="like-dislike-count">0</span>
                                            </a>
                                            <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.comment.id}">
                                                <i class="fa-solid fa-thumbs-down"></i>
                                                <span class="like-dislike-count">0</span>
                                            </a>
                                            <a href="#" class="reply-link" data-comment-id="${data.comment.id}" data-author="${data.comment.user_name}">
                                                <i class="fa-solid fa-reply"></i> Reply
                                            </a>
                                        </div>
                                        <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>
                                        <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST" style="display: none;">
                                            @csrf
                                            <div class="d-flex flex-column">
                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                <div class="d-flex justify-content-between  mt-2">
                                                    <div id="comment-form-error" class="text-danger" style="display: none;">
                                                        Error: Reply cannot be empty
                                                    </div>
                                                    <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                </div>
                                            </div>
                                        </form>
                                        <div class="reply-list" style="display: none;"></div>
                                    </div>
                                </div>
                            </div>
                        `.replace(':commentId', data.comment.id);

                                commentList.insertAdjacentHTML('afterbegin', newCommentHtml);
                                this.reset();
                                initializeDropdowns();
                            }
                        } else {
                            // Display error messages
                            errorDiv.textContent = data.error || 'Your comment is empty';
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        errorDiv.textContent = 'Something went wrong';
                    });
            });

            // For submission of reply forms
            document.getElementById('comment-list')?.addEventListener('submit', function(event) {
                if (event.target.closest('.reply-form')) {
                    event.preventDefault();
                    const form = event.target;
                    const formData = new FormData(form);
                    const parentId = form.closest('.comment').dataset.commentId;
                    const errorDiv = form.querySelector('#comment-form-error');

                    // Reset error display
                    errorDiv.style.display = 'none';
                    errorDiv.textContent = '';

                    fetch(form.action.replace(':commentId', parentId), {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content')
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const replyList = form.closest('.reply-list') || form.closest(
                                    '.comment').querySelector('.reply-list');
                                if (replyList) {
                                    const newReplyHtml = `
                                <div class="comment reply" data-comment-id="${data.reply.id}">
                                    <div class="d-flex">
                                        <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                        <div class="w-100">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <div class="comment-author">${data.reply.user_name}</div>
                                                    <div class="comment-time">${data.reply.created_at}</div>
                                                </div>
                                                <div class="dropdown">
                                                    <button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton${data.reply.id}" data-bs-toggle="dropdown" aria-expanded="false">
                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                    </button>
                                                    <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.reply.id}">
                                                        <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.reply.id}">Edit</a></li>
                                                        <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.reply.id}">Delete</a></li>
                                                    </ul>
                                                </div>
                                            </div>
                                            <div class="comment-body">
                                                ${data.reply.parent_name ? `<a href="#" class="reply-mention">@${data.reply.parent_name}</a> ` : ''}
                                                <span class="reply-content">${data.reply.content}</span>
                                            </div>
                                            <div class="comment-actions">
                                                <a href="#" class="like-button" data-action="like" data-comment-id="${data.reply.id}">
                                                    <i class="fa-solid fa-thumbs-up"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.reply.id}">
                                                    <i class="fa-solid fa-thumbs-down"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="reply-link" data-comment-id="${data.reply.id}" data-author="${data.reply.user_name}">
                                                    <i class="fa-solid fa-reply"></i> Reply
                                                </a>
                                            </div>
                                            <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST" style="display: none;">
                                                @csrf
                                                    <div class="d-flex flex-column">
                                                        <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                        <div class="d-flex justify-content-between  mt-2">
                                                            <div id="comment-form-error" class="text-danger" style="display: none;">
                                                                Error: Reply cannot be empty
                                                            </div>
                                                            <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                        </div>
                                                    </div>
                                            </form>
                                            <div class="reply-list" style="display: none;"></div>
                                        </div>
                                    </div>
                                </div>
                                `.replace(':commentId', data.reply.id);

                                    replyList.insertAdjacentHTML('beforeend', newReplyHtml);
                                    form.reset();
                                    form.style.display =
                                    'none'; // Hide the reply form after successful submission

                                    // Ensure the replies are displayed
                                    const replyToggle = form.closest('.comment').querySelector(
                                        '.reply-toggle');
                                    if (replyToggle) {
                                        const replyList = replyToggle.nextElementSibling
                                            .nextElementSibling;
                                        replyList.style.display = 'block';
                                        replyToggle.textContent = 'Hide replies';
                                    }

                                    initializeDropdowns();
                                }
                            } else {
                                // Display error message
                                errorDiv.textContent = data.message || 'Error posting reply';
                                errorDiv.style.display = 'block';
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            // Display error message
                            errorDiv.textContent = 'Something went wrong';
                            errorDiv.style.display = 'block';
                        });
                }
            });

            // For reply link click to show reply form
            document.getElementById('comment-list')?.addEventListener('click', function(event) {
                if (event.target.closest('.reply-link')) {
                    event.preventDefault();
                    const replyForm = event.target.closest('.comment').querySelector('.reply-form');
                    if (replyForm) {
                        replyForm.style.display = replyForm.style.display === 'block' ? 'none' : 'block';
                    }
                }
            });
        });

        function initializeDropdowns() {
            const dropdowns = document.querySelectorAll('.dropdown-toggle:not(.initialized)');
            dropdowns.forEach(dropdown => {
                new bootstrap.Dropdown(dropdown);
                dropdown.classList.add('initialized');
            });
        }

        function toggleReplies(element) {
            const replyList = element.nextElementSibling.nextElementSibling;
            const isVisible = replyList.style.display === 'block';
            replyList.style.display = isVisible ? 'none' : 'block';
            element.textContent = isVisible ? 'View replies' : 'Hide replies';
        }
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.bookmark-toggle').forEach(function(button) {
                button.addEventListener('click', function() {
                    const fileId = this.getAttribute('data-file-id');
                    const button = this;

                    fetch("{{ route('bookmark.toggle') }}", {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({
                                file_id: fileId
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status === 'added') {
                                button.classList.add('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks-fill" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5z"/>
                                        <path d="M4.268 1A2 2 0 0 1 6 0h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L13 13.768V2a1 1 0 0 0-1-1z"/>
                                    </svg>`;
                            } else if (data.status === 'removed') {
                                button.classList.remove('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5zm2-1a1 1 0 0 0-1 1v10.566l3.723-2.482a.5.5 0 0 1 .554 0L11 14.566V4a1 1 0 0 0-1-1z"/>
                                        <path d="M4.268 1H12a1 1 0 0 1 1 1v11.768l.223.148A.5.5 0 0 0 14 13.5V2a2 2 0 0 0-2-2H6a2 2 0 0 0-1.732 1"/>
                                    </svg>`;
                            }
                        })
                        .catch(error => console.error('Error:', error));
                });
            });
        });
    </script>
@endsection
@extends('new_layouts.app')
@section('styles')
    <style>
        .custom-table {
            border-collapse: collapse;
            border-radius: 1rem;
            border-style: hidden;
            box-shadow: 0 0 0 1px #e6ebef;
            overflow: hidden;
            text-align: left;
            width: 100%;
        }

        .badge-file-extension {
            background-color: #f25961;
            color: white;
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            border-radius: 0.375rem;
            margin-left: 0.5rem;
        }

        .bookmark-active svg {
            fill: #FF9800;
        }

        .description-text {
            font-size: 1.1rem;
            color: #555;
            margin-top: 0.5rem;
        }

        .comment {
            margin-top: 1rem;
            margin-bottom: 1rem;
        }

        .comment-section {
            border: 1px solid #e9ebee;
            border-radius: 1rem;
            padding: 1.5rem;
            background-color: #ffffff;
            /* box-shadow: 0 0 1rem rgba(0, 0, 0, 0.1); */
        }

        .comment-header {
            border-bottom: 1px solid #e9ebee;
            padding-bottom: 0.75rem;
            margin-bottom: 1rem;
        }

        .comment-avatar {
            height: 48px;
            width: 48px;
            border-radius: 50%;
            margin-right: 1rem;
        }

        .comment-author {
            font-size: 1rem;
            font-weight: 600;
        }

        .comment-time {
            font-size: 0.875rem;
            color: #90949c;
        }

        .comment-body {
            margin: 0.75rem 0;
            font-size: 1rem;
        }

        .comment-actions a {
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-right: 1rem;
        }

        .comment-actions i {
            margin-right: 0.5rem;
        }

        .reply-list {
            margin-top: 1rem;
            padding-left: 2rem;
        }

        .reply-list .comment {
            border-left: 1px dotted #d3d6db;
            padding-left: 1rem;
            margin-top: 1rem;
        }

        .reply-toggle {
            cursor: pointer;
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-top: 1rem;
            display: block;
        }

        .reply-form {
            display: none;
            position: relative;
            z-index: 10;
        }

        .comment-input {
            border-radius: 0.5rem;
        }

        .like-button.active i {
            color: #4caf50;
        }

        .dislike-button.active i {
            color: #dc3545;
        }


        /* Dropdown Styles */
        .dropdown-toggle::after {
            display: none;
            /* Remove the default arrow */
        }

        .dropdown-menu {
            right: 0;
            left: auto;
        }
    </style>
@endsection
@section('content')
    <div class="container">
        <div class="mt-4 comment-section">
            <h3>Comments ( {{ $comments->count() }} )</h3>
            <div class="comment-header d-flex justify-content-between align-items-center">
            </div>
            <div class="comment-body">
                <div class="d-flex mb-3">
                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                        class="comment-avatar">
                    <div class="w-100">
                        <form id="comment-form" action="{{ route('comments.store', $material) }}" method="POST">
                            @csrf
                            <div class="d-flex flex-column">
                                <textarea name="content" class="form-control comment-input" placeholder="Write a comment..." rows="3"></textarea>
                                <div class="d-flex justify-content-between mt-2">
                                    <div id="comment-form-error" class="text-danger"></div>
                                    <button type="submit" class="btn btn-primary">Post Comment</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div id="comment-list" class="comment-list">
                    @foreach ($comments as $comment)
                        <div class="comment" data-comment-id="{{ $comment->id }}">
                            <div class="d-flex">
                                <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                                    class="comment-avatar">
                                <div class="w-100">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <div class="comment-author">{{ $comment->user->name }}</div>
                                            <div class="comment-time">{{ $comment->created_at->diffForHumans() }}</div>
                                        </div>
                                        @if ($comment->user_id === auth()->id())
                                            <div class="dropdown">
                                                <button class="btn btn-link dropdown-toggle" type="button"
                                                    id="dropdownMenuButton{{ $comment->id }}" data-bs-toggle="dropdown"
                                                    aria-expanded="false">
                                                    <i class="fa-solid fa-ellipsis-vertical"></i>
                                                </button>
                                                <ul class="dropdown-menu"
                                                    aria-labelledby="dropdownMenuButton{{ $comment->id }}">
                                                    <li><a class="dropdown-item" href="#" data-action="edit"
                                                            data-comment-id="{{ $comment->id }}">Edit</a></li>
                                                    <li><a class="dropdown-item text-danger" href="#"
                                                            data-action="delete"
                                                            data-comment-id="{{ $comment->id }}">Delete</a></li>
                                                </ul>
                                            </div>
                                        @endif
                                    </div>
                                    <div class="comment-body">{{ $comment->content }}</div>
                                    <div class="comment-actions">
                                        <a href="#"
                                            class="like-button {{ $comment->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="like" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-up"></i>
                                            <span class="like-dislike-count">{{ $comment->likes }}</span>
                                        </a>
                                        <a href="#"
                                            class="dislike-button {{ $comment->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="dislike" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-down"></i>
                                            <span class="like-dislike-count">{{ $comment->dislikes }}</span>
                                        </a>
                                        <a href="#" class="reply-link" data-comment-id="{{ $comment->id }}"
                                            data-author="{{ $comment->user->name }}">
                                            <i class="fa-solid fa-reply"></i> Reply
                                        </a>
                                    </div>
                                    <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>

                                    <form class="reply-form" action="{{ route('replies.store', $comment) }}"
                                        method="POST">
                                        @csrf
                                        <div class="d-flex flex-column">
                                            <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                            <div class="d-flex justify-content-between mt-2">
                                                <div id="comment-form-error" class="text-danger" style="display: none;">
                                                    Error: Reply cannot be empty
                                                </div>
                                                <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                            </div>
                                        </div>

                                    </form>
                                    <div class="reply-list" style="display: none;">
                                        @foreach ($comment->replies as $reply)
                                            <div class="comment reply" data-comment-id="{{ $reply->id }}">
                                                <div class="d-flex">
                                                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg"
                                                        alt="avatar" class="comment-avatar">
                                                    <div class="w-100">
                                                        <div class="d-flex justify-content-between align-items-start">
                                                            <div>
                                                                <div class="comment-author">{{ $reply->user->name }}</div>
                                                                <div class="comment-time">
                                                                    {{ $reply->created_at->diffForHumans() }}</div>
                                                            </div>
                                                            @if ($reply->user_id === auth()->id())
                                                                <div class="dropdown">
                                                                    <button class="btn btn-link dropdown-toggle"
                                                                        type="button"
                                                                        id="dropdownMenuButton{{ $reply->id }}"
                                                                        data-bs-toggle="dropdown" aria-expanded="false">
                                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                                    </button>
                                                                    <ul class="dropdown-menu"
                                                                        aria-labelledby="dropdownMenuButton{{ $reply->id }}">
                                                                        <li><a class="dropdown-item" href="#"
                                                                                data-action="edit"
                                                                                data-comment-id="{{ $reply->id }}">Edit</a>
                                                                        </li>
                                                                        <li><a class="dropdown-item text-danger"
                                                                                href="#" data-action="delete"
                                                                                data-comment-id="{{ $reply->id }}">Delete</a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            @endif
                                                        </div>
                                                        <div class="comment-body">
                                                            @if ($reply->parent)
                                                                <a href="#"
                                                                    class="reply-mention">{{ '@' . $reply->parent->user->name }}</a>
                                                            @endif
                                                            <span class="reply-content">{{ $reply->content }}</span>
                                                        </div>
                                                        <div class="comment-actions">
                                                            <a href="#"
                                                                class="like-button {{ $reply->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="like" data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-up"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->likes }}</span>
                                                            </a>
                                                            <a href="#"
                                                                class="dislike-button {{ $reply->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="dislike"
                                                                data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-down"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->dislikes }}</span>
                                                            </a>
                                                            <a href="#" class="reply-link"
                                                                data-comment-id="{{ $reply->id }}"
                                                                data-author="{{ $reply->user->name }}">
                                                                <i class="fa-solid fa-reply"></i> Reply
                                                            </a>
                                                        </div>
                                                        <form class="reply-form"
                                                            action="{{ route('replies.store', $reply) }}" method="POST">
                                                            @csrf
                                                            <div class="d-flex flex-column">
                                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                                <div class="d-flex justify-content-between mt-2">
                                                                    <div id="comment-form-error" class="text-danger"
                                                                        style="display: none;">
                                                                        Error: Reply cannot be empty
                                                                    </div>
                                                                    <button type="submit"
                                                                        class="btn btn-primary ms-auto">Post Reply</button>
                                                                </div>
                                                            </div>

                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                            @include('materials.comment', ['replies' => $reply->replies])
                                        @endforeach
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const commentList = document.getElementById('comment-list');

            // Handle edit button click
            commentList.addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="edit"]');
                if (button) {
                    event.preventDefault();
                    const commentId = button.getAttribute('data-comment-id');
                    const commentElement = document.querySelector(
                        `.comment[data-comment-id="${commentId}"]`);
                    const commentBodyElement = commentElement.querySelector('.comment-body');

                    // Extract mention and content
                    const mentionElement = commentBodyElement.querySelector('.reply-mention');
                    const mention = mentionElement ? mentionElement.innerText.trim() : '';
                    const contentElement = mentionElement ? mentionElement.nextElementSibling :
                        commentBodyElement;
                    const content = contentElement.innerText.trim();

                    // Store original content for cancel action
                    commentBodyElement.dataset.originalContent = commentBodyElement.innerHTML;

                    const editForm = `
                <form class="edit-comment-form" data-comment-id="${commentId}">
                    ${mention ? `<span class="reply-mention">${mention}</span>` : ''}
                    <textarea class="form-control">${content}</textarea>
                    <button type="submit" class="btn btn-primary mt-2">Save</button>
                    <button type="button" class="btn btn-secondary mt-2 cancel-edit">Cancel</button>
                </form>
            `;

                    commentBodyElement.innerHTML = editForm;
                    attachEditFormListeners(commentId);
                }
            });

            function attachEditFormListeners(commentId) {
                const editForm = document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"]`);

                editForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    const textarea = this.querySelector('textarea');
                    const content = textarea.value;
                    const mention = this.querySelector('.reply-mention') ? this.querySelector(
                        '.reply-mention').innerText.trim() : '';

                    fetch(`/comments/${commentId}`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content')
                            },
                            body: JSON.stringify({
                                content
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const commentBodyElement = document.querySelector(
                                    `.comment[data-comment-id="${commentId}"] .comment-body`);
                                const mentionElement = mention ?
                                    `<a href="#" class="reply-mention">${mention}</a>` : '';
                                commentBodyElement.innerHTML =
                                    `${mentionElement} <span class="reply-content">${data.content}</span>`;
                            } else {
                                alert('Error updating comment.');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                        });
                });

                editForm.querySelector('.cancel-edit').addEventListener('click', function() {
                    const originalContent = document.querySelector(
                            `.comment[data-comment-id="${commentId}"] .comment-body`).dataset
                        .originalContent;
                    document.querySelector(`.comment[data-comment-id="${commentId}"] .comment-body`)
                        .innerHTML = originalContent;
                });
            }
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {

            // for delete 
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="delete"]');
                if (button) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');

                    if (confirm('Are you sure you want to delete this comment?')) {
                        fetch(`/comments/${commentId}`, {
                                method: 'DELETE',
                                headers: {
                                    'X-Requested-With': 'XMLHttpRequest',
                                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                        .getAttribute('content'),
                                    'Content-Type': 'application/json',
                                }
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    const commentElement = document.querySelector(
                                        `.comment[data-comment-id="${commentId}"]`);
                                    if (commentElement) {
                                        commentElement.remove();
                                    }
                                } else {
                                    alert(data.message || 'Error deleting comment');
                                }
                            })
                            .catch(error => {
                                console.error('Error:', error);
                                alert('Something went wrong');
                            });
                    }
                }
            });

            // for like and dislike
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a');
                if (button && (button.classList.contains('like-button') || button.classList.contains(
                        'dislike-button'))) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');
                    const action = button.getAttribute('data-action');

                    fetch(`/comments/${commentId}/${action}`, {
                            method: 'POST',
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content'),
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                _method: 'POST'
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const commentElement = document.querySelector(
                                    `.comment[data-comment-id="${commentId}"]`);
                                const likeCount = commentElement.querySelector(
                                    '.like-button .like-dislike-count');
                                const dislikeCount = commentElement.querySelector(
                                    '.dislike-button .like-dislike-count');

                                likeCount.textContent = data.comment.likes;
                                dislikeCount.textContent = data.comment.dislikes;

                                if (action === 'like') {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.dislike-button').classList.remove(
                                        'active');
                                } else {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.like-button').classList.remove(
                                        'active');
                                }
                            } else {
                                alert(data.message || 'Error updating like/dislike');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('Something went wrong');
                        });
                }
            });

            // for submission of the main comment form
            document.getElementById('comment-form')?.addEventListener('submit', function(event) {
                event.preventDefault();
                const formData = new FormData(this);
                const errorDiv = document.getElementById('comment-form-error');
                errorDiv.textContent = ''; // Clear previous errors

                fetch(this.action, {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                .getAttribute('content')
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const commentList = document.getElementById('comment-list');
                            if (commentList) {
                                const newCommentHtml = `
                                <div class="comment" data-comment-id="${data.comment.id}">
                                    <div class="d-flex">
                                        <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                        <div class="w-100">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <div class="comment-author">${data.comment.user_name}</div>
                                                    <div class="comment-time">${data.comment.created_at}</div>
                                                </div>
                                                <div class="dropdown">
                                                    <button class="btn btn-link dropdown-toggle" type="button"
                                                        id="dropdownMenuButton${data.comment.id}" data-bs-toggle="dropdown"
                                                        aria-expanded="false">
                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                    </button>
                                                    <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.comment.id}">
                                                        <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.comment.id}">Edit</a></li>
                                                        <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.comment.id}">Delete</a></li>
                                                    </ul>
                                                </div>
                                            </div>
                                            <div class="comment-body">${data.comment.content}</div>
                                            <div class="comment-actions">
                                                <a href="#" class="like-button" data-action="like" data-comment-id="${data.comment.id}">
                                                    <i class="fa-solid fa-thumbs-up"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.comment.id}">
                                                    <i class="fa-solid fa-thumbs-down"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="reply-link" data-comment-id="${data.comment.id}" data-author="${data.comment.user_name}">
                                                    <i class="fa-solid fa-reply"></i> Reply
                                                </a>
                                            </div>
                                            <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>
                                            <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST">
                                                @csrf
                                            <div class="d-flex flex-column">
                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                <div class="d-flex justify-content-between  mt-2">
                                                    <div id="comment-form-error" class="text-danger" style="display: none;">
                                                        Error: Reply cannot be empty
                                                    </div>
                                                    <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                </div>
                                            </div>
                                            </form>
                                            <div class="reply-list" style="display: none;"></div>
                                        </div>
                                    </div>
                                </div>
                            `.replace(':commentId', data.comment.id);

                                commentList.insertAdjacentHTML('afterbegin', newCommentHtml);
                                this.reset();
                                initializeDropdowns();
                            }
                        } else {
                            // Display error messages
                            errorDiv.textContent = data.error || 'Your comment is empty';
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        errorDiv.textContent = 'Something went wrong';
                    });
            });

            // for submission of reply forms
            document.getElementById('comment-list')?.addEventListener('submit', function(event) {
                if (event.target.closest('.reply-form')) {
                    event.preventDefault();
                    const form = event.target;
                    const formData = new FormData(form);
                    const parentId = form.closest('.comment').dataset.commentId;
                    const errorDiv = form.querySelector('#comment-form-error');

                    // Reset error display
                    errorDiv.style.display = 'none';
                    errorDiv.textContent = '';

                    fetch(form.action.replace(':commentId', parentId), {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content')
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const replyList = form.closest('.reply-list') || form.closest(
                                    '.comment').querySelector('.reply-list');
                                if (replyList) {
                                    const newReplyHtml = `
                                    <div class="comment reply" data-comment-id="${data.reply.id}">
                                        <div class="d-flex">
                                            <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                            <div class="w-100">
                                                <div class="d-flex justify-content-between align-items-start">
                                                    <div>
                                                        <div class="comment-author">${data.reply.user_name}</div>
                                                        <div class="comment-time">${data.reply.created_at}</div>
                                                    </div>
                                                    <div class="dropdown">
                                                        <button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton${data.reply.id}" data-bs-toggle="dropdown" aria-expanded="false">
                                                            <i class="fa-solid fa-ellipsis-vertical"></i>
                                                        </button>
                                                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.reply.id}">
                                                            <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.reply.id}">Edit</a></li>
                                                            <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.reply.id}">Delete</a></li>
                                                        </ul>
                                                    </div>
                                                </div>
                                                <div class="comment-body">
                                                    ${data.reply.parent_name ? `<a href="#" class="reply-mention">@${data.reply.parent_name}</a> ` : ''}
                                                    <span class="reply-content">${data.reply.content}</span>
                                                </div>
                                                <div class="comment-actions">
                                                    <a href="#" class="like-button" data-action="like" data-comment-id="${data.reply.id}">
                                                        <i class="fa-solid fa-thumbs-up"></i>
                                                        <span class="like-dislike-count">0</span>
                                                    </a>
                                                    <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.reply.id}">
                                                        <i class="fa-solid fa-thumbs-down"></i>
                                                        <span class="like-dislike-count">0</span>
                                                    </a>
                                                    <a href="#" class="reply-link" data-comment-id="${data.reply.id}" data-author="${data.reply.user_name}">
                                                        <i class="fa-solid fa-reply"></i> Reply
                                                    </a>
                                                </div>
                                                <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST">
                                                    @csrf
                                                        <div class="d-flex flex-column">
                                                            <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                            <div class="d-flex justify-content-between  mt-2">
                                                                <div id="comment-form-error" class="text-danger" style="display: none;">
                                                                    Error: Reply cannot be empty
                                                                </div>
                                                                <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                            </div>
                                                        </div>
                                                </form>
                                                <div class="reply-list" style="display: none;"></div>
                                            </div>
                                        </div>
                                    </div>
                                    `.replace(':commentId', data.reply.id);

                                    replyList.insertAdjacentHTML('beforeend', newReplyHtml);
                                    form.reset();
                                    initializeDropdowns();
                                }
                            } else {
                                // Display error message
                                errorDiv.textContent = data.message || 'Error posting reply';
                                errorDiv.style.display = 'block';
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            // Display error message
                            errorDiv.textContent = 'Something went wrong';
                            errorDiv.style.display = 'block';
                        });
                }
            });

            // for reply link click to show reply form
            document.getElementById('comment-list')?.addEventListener('click', function(event) {
                if (event.target.closest('.reply-link')) {
                    event.preventDefault();
                    const replyForm = event.target.closest('.comment').querySelector('.reply-form');
                    if (replyForm) {
                        replyForm.style.display = replyForm.style.display === 'block' ? 'none' : 'block';
                    }
                }
            });
        });

        function initializeDropdowns() {
            const dropdowns = document.querySelectorAll('.dropdown-toggle:not(.initialized)');
            dropdowns.forEach(dropdown => {
                new bootstrap.Dropdown(dropdown);
                dropdown.classList.add('initialized');
            });
        }

        function toggleReplies(element) {
            const replyList = element.nextElementSibling.nextElementSibling;
            const isVisible = replyList.style.display === 'block';
            replyList.style.display = isVisible ? 'none' : 'block';
            element.textContent = isVisible ? 'View replies' : 'Hide replies';
        }
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.bookmark-toggle').forEach(function(button) {
                button.addEventListener('click', function() {
                    const fileId = this.getAttribute('data-file-id');
                    const button = this;

                    fetch("{{ route('bookmark.toggle') }}", {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({
                                file_id: fileId
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status === 'added') {
                                button.classList.add('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks-fill" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5z"/>
                                        <path d="M4.268 1A2 2 0 0 1 6 0h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L13 13.768V2a1 1 0 0 0-1-1z"/>
                                    </svg>`;
                            } else if (data.status === 'removed') {
                                button.classList.remove('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5zm2-1a1 1 0 0 0-1 1v10.566l3.723-2.482a.5.5 0 0 1 .554 0L11 14.566V4a1 1 0 0 0-1-1z"/>
                                        <path d="M4.268 1H12a1 1 0 0 1 1 1v11.768l.223.148A.5.5 0 0 0 14 13.5V2a2 2 0 0 0-2-2H6a2 2 0 0 0-1.732 1"/>
                                    </svg>`;
                            }
                        })
                        .catch(error => console.error('Error:', error));
                });
            });
        });
    </script>
@endsection


@foreach ($replies as $reply)
    <div class="comment reply" data-comment-id="{{ $reply->id }}">
        <div class="d-flex">
            <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
            <div class="w-100">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="comment-author">{{ $reply->user->name }}</div>
                        <div class="comment-time">{{ $reply->created_at->diffForHumans() }}</div>
                    </div>
                    @if ($reply->user_id === auth()->id())
                        <div class="dropdown">
                            <button class="btn btn-link dropdown-toggle" type="button"
                                id="dropdownMenuButton{{ $reply->id }}" data-bs-toggle="dropdown"
                                aria-expanded="false">
                                <i class="fa-solid fa-ellipsis-vertical"></i>
                            </button>
                            <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton{{ $reply->id }}">
                                <li><a class="dropdown-item" href="#" data-action="edit"
                                        data-comment-id="{{ $reply->id }}">Edit</a>
                                </li>
                                <li><a class="dropdown-item text-danger" href="#" data-action="delete"
                                        data-comment-id="{{ $reply->id }}">Delete</a>
                                </li>
                            </ul>
                        </div>
                    @endif
                </div>
                <div class="comment-body">
                    @if ($reply->parent)
                        <a href="#" class="reply-mention">{{ '@' . $reply->parent->user->name }}</a>
                    @endif
                    <span class="reply-content">{{ $reply->content }}</span>
                </div>
                <div class="comment-actions">
                    <a href="#"
                        class="like-button {{ $reply->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                        data-action="like" data-comment-id="{{ $reply->id }}">
                        <i class="fa-solid fa-thumbs-up"></i>
                        <span class="like-dislike-count">{{ $reply->likes }}</span>
                    </a>
                    <a href="#"
                        class="dislike-button {{ $reply->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                        data-action="dislike" data-comment-id="{{ $reply->id }}">
                        <i class="fa-solid fa-thumbs-down"></i>
                        <span class="like-dislike-count">{{ $reply->dislikes }}</span>
                    </a>
                    <a href="#" class="reply-link" data-comment-id="{{ $reply->id }}"
                        data-author="{{ $reply->user->name }}">
                        <i class="fa-solid fa-reply"></i> Reply
                    </a>
                </div>
                <form class="reply-form" action="{{ route('replies.store', $reply) }}" method="POST">
                    @csrf
                    <div class="d-flex flex-column">
                        <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                        <div class="d-flex justify-content-between  mt-2">
                            <div id="comment-form-error" class="text-danger" style="display: none;">
                                Error: Reply cannot be empty
                            </div>
                            <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                        </div>
                    </div>

                </form>
                <div id="edit-comment-template" style="display: none;">
                    <div class="edit-comment-form">
                        <textarea class="form-control edit-comment-input" rows="3"></textarea>
                        <div class="text-end mt-2">
                            <button type="button" class="btn btn-primary save-edit-button">Save</button>
                            <button type="button" class="btn btn-secondary cancel-edit-button">Cancel</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @include('materials.comment', ['replies' => $reply->replies])
@endforeach
localStorage.ampConfig = `{"amp":{"services":{"fitprofile":{"url":"http://127.0.0.1:5500/fitpredictor/demo/dist/loader.js","enabled":"true"},"fitprofilepreview":{"url":"http://127.0.0.1:5500/fitpredictor/demo/dist/fitProfilePreviewLoader.js","enabled":"true"}}}}`
<script src="https://unpkg.com/lenis@1.1.9/dist/lenis.min.js"></script>
<script>
const lenis = new Lenis()

lenis.on('scroll', (e) => {
  console.log(e)
})

function raf(time) {
  lenis.raf(time)
  requestAnimationFrame(raf)
}

requestAnimationFrame(raf)
</script>
@extends('new_layouts.app')
@section('styles')
    <style>
        .custom-table {
            border-collapse: collapse;
            border-radius: 1rem;
            border-style: hidden;
            box-shadow: 0 0 0 1px #e6ebef;
            overflow: hidden;
            text-align: left;
            width: 100%;
        }

        .badge-file-extension {
            background-color: #f25961;
            color: white;
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            border-radius: 0.375rem;
            margin-left: 0.5rem;
        }

        .bookmark-active svg {
            fill: #FF9800;
        }

        .description-text {
            font-size: 1.1rem;
            color: #555;
            margin-top: 0.5rem;
        }

        .comment {
            margin-top: 1rem;
            margin-bottom: 1rem;
        }

        .comment-section {
            border: 1px solid #e9ebee;
            border-radius: 1rem;
            padding: 1.5rem;
            background-color: #ffffff;
            /* box-shadow: 0 0 1rem rgba(0, 0, 0, 0.1); */
        }

        .comment-header {
            border-bottom: 1px solid #e9ebee;
            padding-bottom: 0.75rem;
            margin-bottom: 1rem;
        }

        .comment-avatar {
            height: 48px;
            width: 48px;
            border-radius: 50%;
            margin-right: 1rem;
        }

        .comment-author {
            font-size: 1rem;
            font-weight: 600;
        }

        .comment-time {
            font-size: 0.875rem;
            color: #90949c;
        }

        .comment-body {
            margin: 0.75rem 0;
            font-size: 1rem;
        }

        .comment-actions a {
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-right: 1rem;
        }

        .comment-actions i {
            margin-right: 0.5rem;
        }

        .reply-list {
            margin-top: 1rem;
            padding-left: 2rem;
        }

        .reply-list .comment {
            border-left: 1px dotted #d3d6db;
            padding-left: 1rem;
            margin-top: 1rem;
        }

        .reply-toggle {
            cursor: pointer;
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-top: 1rem;
            display: block;
        }

        .reply-form {
            display: none;
            position: relative;
            z-index: 10;
        }

        .comment-input {
            border-radius: 0.5rem;
        }

        .like-button.active i {
            color: #4caf50;
        }

        .dislike-button.active i {
            color: #dc3545;
        }


        /* Dropdown Styles */
        .dropdown-toggle::after {
            display: none;
            /* Remove the default arrow */
        }

        .dropdown-menu {
            right: 0;
            left: auto;
        }
    </style>
@endsection
@section('content')
    <div class="container">
        <div class="mt-4 comment-section">
            <h3>Comments ( {{ $comments->count() }} )</h3>
            <div class="comment-header d-flex justify-content-between align-items-center">
            </div>
            <div class="comment-body">
                <div class="d-flex mb-3">
                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                        class="comment-avatar">
                    <div class="w-100">
                        <form id="comment-form" action="{{ route('comments.store', $material) }}" method="POST">
                            @csrf
                            <div class="d-flex flex-column">
                                <textarea name="content" class="form-control comment-input" placeholder="Write a comment..." rows="3"></textarea>
                                <div class="d-flex justify-content-between mt-2">
                                    <div id="comment-form-error" class="text-danger"></div>
                                    <button type="submit" class="btn btn-primary">Post Comment</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div id="comment-list" class="comment-list">
                    @foreach ($comments as $comment)
                        <div class="comment" data-comment-id="{{ $comment->id }}">
                            <div class="d-flex">
                                <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                                    class="comment-avatar">
                                <div class="w-100">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <div class="comment-author">{{ $comment->user->name }}</div>
                                            <div class="comment-time">{{ $comment->created_at->diffForHumans() }}</div>
                                        </div>
                                        @if ($comment->user_id === auth()->id())
                                            <div class="dropdown">
                                                <button class="btn btn-link dropdown-toggle" type="button"
                                                    id="dropdownMenuButton{{ $comment->id }}" data-bs-toggle="dropdown"
                                                    aria-expanded="false">
                                                    <i class="fa-solid fa-ellipsis-vertical"></i>
                                                </button>
                                                <ul class="dropdown-menu"
                                                    aria-labelledby="dropdownMenuButton{{ $comment->id }}">
                                                    <li><a class="dropdown-item" href="#" data-action="edit"
                                                            data-comment-id="{{ $comment->id }}">Edit</a></li>
                                                    <li><a class="dropdown-item text-danger" href="#"
                                                            data-action="delete"
                                                            data-comment-id="{{ $comment->id }}">Delete</a></li>
                                                </ul>
                                            </div>
                                        @endif
                                    </div>
                                    <div class="comment-body">{{ $comment->content }}</div>
                                    <div class="comment-actions">
                                        <a href="#"
                                            class="like-button {{ $comment->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="like" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-up"></i>
                                            <span class="like-dislike-count">{{ $comment->likes }}</span>
                                        </a>
                                        <a href="#"
                                            class="dislike-button {{ $comment->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="dislike" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-down"></i>
                                            <span class="like-dislike-count">{{ $comment->dislikes }}</span>
                                        </a>
                                        <a href="#" class="reply-link" data-comment-id="{{ $comment->id }}"
                                            data-author="{{ $comment->user->name }}">
                                            <i class="fa-solid fa-reply"></i> Reply
                                        </a>
                                    </div>
                                    <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>

                                    <form class="reply-form" action="{{ route('replies.store', $comment) }}"
                                        method="POST">
                                        @csrf
                                        <div class="d-flex flex-column">
                                            <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                            <div class="d-flex justify-content-between mt-2">
                                                <div id="comment-form-error" class="text-danger" style="display: none;">
                                                    Error: Reply cannot be empty
                                                </div>
                                                <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                            </div>
                                        </div>

                                    </form>
                                    <div class="reply-list" style="display: none;">
                                        @foreach ($comment->replies as $reply)
                                            <div class="comment reply" data-comment-id="{{ $reply->id }}">
                                                <div class="d-flex">
                                                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg"
                                                        alt="avatar" class="comment-avatar">
                                                    <div class="w-100">
                                                        <div class="d-flex justify-content-between align-items-start">
                                                            <div>
                                                                <div class="comment-author">{{ $reply->user->name }}</div>
                                                                <div class="comment-time">
                                                                    {{ $reply->created_at->diffForHumans() }}</div>
                                                            </div>
                                                            @if ($reply->user_id === auth()->id())
                                                                <div class="dropdown">
                                                                    <button class="btn btn-link dropdown-toggle"
                                                                        type="button"
                                                                        id="dropdownMenuButton{{ $reply->id }}"
                                                                        data-bs-toggle="dropdown" aria-expanded="false">
                                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                                    </button>
                                                                    <ul class="dropdown-menu"
                                                                        aria-labelledby="dropdownMenuButton{{ $reply->id }}">
                                                                        <li><a class="dropdown-item" href="#"
                                                                                data-action="edit"
                                                                                data-comment-id="{{ $reply->id }}">Edit</a>
                                                                        </li>
                                                                        <li><a class="dropdown-item text-danger"
                                                                                href="#" data-action="delete"
                                                                                data-comment-id="{{ $reply->id }}">Delete</a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            @endif
                                                        </div>
                                                        <div class="comment-body">
                                                            @if ($reply->parent)
                                                                <a href="#"
                                                                    class="reply-mention">{{ '@' . $reply->parent->user->name }}</a>
                                                            @endif
                                                            <span class="reply-content">{{ $reply->content }}</span>
                                                        </div>
                                                        <div class="comment-actions">
                                                            <a href="#"
                                                                class="like-button {{ $reply->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="like" data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-up"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->likes }}</span>
                                                            </a>
                                                            <a href="#"
                                                                class="dislike-button {{ $reply->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="dislike"
                                                                data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-down"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->dislikes }}</span>
                                                            </a>
                                                            <a href="#" class="reply-link"
                                                                data-comment-id="{{ $reply->id }}"
                                                                data-author="{{ $reply->user->name }}">
                                                                <i class="fa-solid fa-reply"></i> Reply
                                                            </a>
                                                        </div>
                                                        <form class="reply-form"
                                                            action="{{ route('replies.store', $reply) }}" method="POST">
                                                            @csrf
                                                            <div class="d-flex flex-column">
                                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                                <div class="d-flex justify-content-between mt-2">
                                                                    <div id="comment-form-error" class="text-danger"
                                                                        style="display: none;">
                                                                        Error: Reply cannot be empty
                                                                    </div>
                                                                    <button type="submit"
                                                                        class="btn btn-primary ms-auto">Post Reply</button>
                                                                </div>
                                                            </div>

                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                            @include('materials.comment', ['replies' => $reply->replies])
                                        @endforeach
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const commentList = document.getElementById('comment-list');

            // Handle edit button click
            commentList.addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="edit"]');
                if (button) {
                    event.preventDefault();
                    const commentId = button.getAttribute('data-comment-id');
                    const commentBodyElement = document.querySelector(
                        `.comment[data-comment-id="${commentId}"] .comment-body`
                    );
                    const contentElement = commentBodyElement.querySelector('.reply-content') ||
                        commentBodyElement;
                    const mentionElement = contentElement.querySelector('.reply-mention');
                    const mention = mentionElement ? mentionElement.innerText.trim() : '';
                    const content = contentElement.innerText.trim();

                    // Store original content for cancel action
                    commentBodyElement.dataset.originalContent = commentBodyElement.innerHTML;

                    const editForm = `
                <form class="edit-comment-form" data-comment-id="${commentId}">
                    ${mention ? `<span class="reply-mention">${mention}</span>` : ''}
                    <textarea class="form-control">${content}</textarea>
                    <button type="submit" class="btn btn-primary mt-2">Save</button>
                    <button type="button" class="btn btn-secondary mt-2 cancel-edit">Cancel</button>
                </form>
            `;

                    commentBodyElement.innerHTML = editForm;
                    attachEditFormListeners(commentId);
                }
            });

            function attachEditFormListeners(commentId) {
                const editForm = document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"]`);

                editForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    const content = this.querySelector('textarea').value;
                    const mention = this.querySelector('.reply-mention') ? this.querySelector(
                            '.reply-mention')
                        .innerText.trim() : '';

                    fetch(`/comments/${commentId}`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute(
                                        'content')
                            },
                            body: JSON.stringify({
                                content
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const commentBodyElement = document.querySelector(
                                    `.comment[data-comment-id="${commentId}"] .comment-body`);
                                const mentionElement = mention ?
                                    `<a href="#" class="reply-mention">${mention}</a>` : '';
                                commentBodyElement.innerHTML =
                                    `${mentionElement} <span class="reply-content">${data.content}</span>`;
                            } else {
                                alert('Error updating comment.');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                        });
                });

                editForm.querySelector('.cancel-edit').addEventListener('click', function() {
                    const originalContent = document.querySelector(
                            `.comment[data-comment-id="${commentId}"] .comment-body`).dataset
                        .originalContent;
                    document.querySelector(`.comment[data-comment-id="${commentId}"] .comment-body`)
                        .innerHTML =
                        originalContent;
                });
            }
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {

            // for delete 
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="delete"]');
                if (button) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');

                    if (confirm('Are you sure you want to delete this comment?')) {
                        fetch(`/comments/${commentId}`, {
                                method: 'DELETE',
                                headers: {
                                    'X-Requested-With': 'XMLHttpRequest',
                                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                        .getAttribute('content'),
                                    'Content-Type': 'application/json',
                                }
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    const commentElement = document.querySelector(
                                        `.comment[data-comment-id="${commentId}"]`);
                                    if (commentElement) {
                                        commentElement.remove();
                                    }
                                } else {
                                    alert(data.message || 'Error deleting comment');
                                }
                            })
                            .catch(error => {
                                console.error('Error:', error);
                                alert('Something went wrong');
                            });
                    }
                }
            });

            // for like and dislike
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a');
                if (button && (button.classList.contains('like-button') || button.classList.contains(
                        'dislike-button'))) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');
                    const action = button.getAttribute('data-action');

                    fetch(`/comments/${commentId}/${action}`, {
                            method: 'POST',
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content'),
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                _method: 'POST'
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const commentElement = document.querySelector(
                                    `.comment[data-comment-id="${commentId}"]`);
                                const likeCount = commentElement.querySelector(
                                    '.like-button .like-dislike-count');
                                const dislikeCount = commentElement.querySelector(
                                    '.dislike-button .like-dislike-count');

                                likeCount.textContent = data.comment.likes;
                                dislikeCount.textContent = data.comment.dislikes;

                                if (action === 'like') {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.dislike-button').classList.remove(
                                        'active');
                                } else {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.like-button').classList.remove(
                                        'active');
                                }
                            } else {
                                alert(data.message || 'Error updating like/dislike');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('Something went wrong');
                        });
                }
            });

            // for submission of the main comment form
            document.getElementById('comment-form')?.addEventListener('submit', function(event) {
                event.preventDefault();
                const formData = new FormData(this);
                const errorDiv = document.getElementById('comment-form-error');
                errorDiv.textContent = ''; // Clear previous errors

                fetch(this.action, {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                .getAttribute('content')
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const commentList = document.getElementById('comment-list');
                            if (commentList) {
                                const newCommentHtml = `
                                <div class="comment" data-comment-id="${data.comment.id}">
                                    <div class="d-flex">
                                        <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                        <div class="w-100">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <div class="comment-author">${data.comment.user_name}</div>
                                                    <div class="comment-time">${data.comment.created_at}</div>
                                                </div>
                                                <div class="dropdown">
                                                    <button class="btn btn-link dropdown-toggle" type="button"
                                                        id="dropdownMenuButton${data.comment.id}" data-bs-toggle="dropdown"
                                                        aria-expanded="false">
                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                    </button>
                                                    <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.comment.id}">
                                                        <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.comment.id}">Edit</a></li>
                                                        <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.comment.id}">Delete</a></li>
                                                    </ul>
                                                </div>
                                            </div>
                                            <div class="comment-body">${data.comment.content}</div>
                                            <div class="comment-actions">
                                                <a href="#" class="like-button" data-action="like" data-comment-id="${data.comment.id}">
                                                    <i class="fa-solid fa-thumbs-up"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.comment.id}">
                                                    <i class="fa-solid fa-thumbs-down"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="reply-link" data-comment-id="${data.comment.id}" data-author="${data.comment.user_name}">
                                                    <i class="fa-solid fa-reply"></i> Reply
                                                </a>
                                            </div>
                                            <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>
                                            <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST">
                                                @csrf
                                            <div class="d-flex flex-column">
                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                <div class="d-flex justify-content-between  mt-2">
                                                    <div id="comment-form-error" class="text-danger" style="display: none;">
                                                        Error: Reply cannot be empty
                                                    </div>
                                                    <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                </div>
                                            </div>
                                            </form>
                                            <div class="reply-list" style="display: none;"></div>
                                        </div>
                                    </div>
                                </div>
                            `.replace(':commentId', data.comment.id);

                                commentList.insertAdjacentHTML('afterbegin', newCommentHtml);
                                this.reset();
                                initializeDropdowns();
                            }
                        } else {
                            // Display error messages
                            errorDiv.textContent = data.error || 'Your comment is empty';
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        errorDiv.textContent = 'Something went wrong';
                    });
            });

            // for submission of reply forms
            document.getElementById('comment-list')?.addEventListener('submit', function(event) {
                if (event.target.closest('.reply-form')) {
                    event.preventDefault();
                    const form = event.target;
                    const formData = new FormData(form);
                    const parentId = form.closest('.comment').dataset.commentId;
                    const errorDiv = form.querySelector('#comment-form-error');

                    // Reset error display
                    errorDiv.style.display = 'none';
                    errorDiv.textContent = '';

                    fetch(form.action.replace(':commentId', parentId), {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content')
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const replyList = form.closest('.reply-list') || form.closest(
                                    '.comment').querySelector('.reply-list');
                                if (replyList) {
                                    const newReplyHtml = `
                                    <div class="comment reply" data-comment-id="${data.reply.id}">
                                        <div class="d-flex">
                                            <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                            <div class="w-100">
                                                <div class="d-flex justify-content-between align-items-start">
                                                    <div>
                                                        <div class="comment-author">${data.reply.user_name}</div>
                                                        <div class="comment-time">${data.reply.created_at}</div>
                                                    </div>
                                                    <div class="dropdown">
                                                        <button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton${data.reply.id}" data-bs-toggle="dropdown" aria-expanded="false">
                                                            <i class="fa-solid fa-ellipsis-vertical"></i>
                                                        </button>
                                                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.reply.id}">
                                                            <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.reply.id}">Edit</a></li>
                                                            <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.reply.id}">Delete</a></li>
                                                        </ul>
                                                    </div>
                                                </div>
                                                <div class="comment-body">${data.reply.parent_name ? '<a href="#">' + '@' + data.reply.parent_name + '</a> ' : ''}${data.reply.content}</div>
                                                <div class="comment-actions">
                                                    <a href="#" class="like-button" data-action="like" data-comment-id="${data.reply.id}">
                                                        <i class="fa-solid fa-thumbs-up"></i>
                                                        <span class="like-dislike-count">0</span>
                                                    </a>
                                                    <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.reply.id}">
                                                        <i class="fa-solid fa-thumbs-down"></i>
                                                        <span class="like-dislike-count">0</span>
                                                    </a>
                                                    <a href="#" class="reply-link" data-comment-id="${data.reply.id}" data-author="${data.reply.user_name}">
                                                        <i class="fa-solid fa-reply"></i> Reply
                                                    </a>
                                                </div>
                                                <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST">
                                                    @csrf
                                                        <div class="d-flex flex-column">
                                                            <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                            <div class="d-flex justify-content-between  mt-2">
                                                                <div id="comment-form-error" class="text-danger" style="display: none;">
                                                                    Error: Reply cannot be empty
                                                                </div>
                                                                <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                            </div>
                                                        </div>
                                                </form>
                                                <div class="reply-list" style="display: none;"></div>
                                            </div>
                                        </div>
                                    </div>
                                    `.replace(':commentId', data.reply.id);

                                    replyList.insertAdjacentHTML('beforeend', newReplyHtml);
                                    form.reset();
                                    initializeDropdowns();
                                }
                            } else {
                                // Display error message
                                errorDiv.textContent = data.message || 'Error posting reply';
                                errorDiv.style.display = 'block';
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            // Display error message
                            errorDiv.textContent = 'Something went wrong';
                            errorDiv.style.display = 'block';
                        });
                }
            });

            // for reply link click to show reply form
            document.getElementById('comment-list')?.addEventListener('click', function(event) {
                if (event.target.closest('.reply-link')) {
                    event.preventDefault();
                    const replyForm = event.target.closest('.comment').querySelector('.reply-form');
                    if (replyForm) {
                        replyForm.style.display = replyForm.style.display === 'block' ? 'none' : 'block';
                    }
                }
            });
        });

        function initializeDropdowns() {
            const dropdowns = document.querySelectorAll('.dropdown-toggle:not(.initialized)');
            dropdowns.forEach(dropdown => {
                new bootstrap.Dropdown(dropdown);
                dropdown.classList.add('initialized');
            });
        }

        function toggleReplies(element) {
            const replyList = element.nextElementSibling.nextElementSibling;
            const isVisible = replyList.style.display === 'block';
            replyList.style.display = isVisible ? 'none' : 'block';
            element.textContent = isVisible ? 'View replies' : 'Hide replies';
        }
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.bookmark-toggle').forEach(function(button) {
                button.addEventListener('click', function() {
                    const fileId = this.getAttribute('data-file-id');
                    const button = this;

                    fetch("{{ route('bookmark.toggle') }}", {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({
                                file_id: fileId
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status === 'added') {
                                button.classList.add('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks-fill" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5z"/>
                                        <path d="M4.268 1A2 2 0 0 1 6 0h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L13 13.768V2a1 1 0 0 0-1-1z"/>
                                    </svg>`;
                            } else if (data.status === 'removed') {
                                button.classList.remove('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5zm2-1a1 1 0 0 0-1 1v10.566l3.723-2.482a.5.5 0 0 1 .554 0L11 14.566V4a1 1 0 0 0-1-1z"/>
                                        <path d="M4.268 1H12a1 1 0 0 1 1 1v11.768l.223.148A.5.5 0 0 0 14 13.5V2a2 2 0 0 0-2-2H6a2 2 0 0 0-1.732 1"/>
                                    </svg>`;
                            }
                        })
                        .catch(error => console.error('Error:', error));
                });
            });
        });
    </script>
@endsection
@extends('new_layouts.app')
@section('styles')
    <style>
        .custom-table {
            border-collapse: collapse;
            border-radius: 1rem;
            border-style: hidden;
            box-shadow: 0 0 0 1px #e6ebef;
            overflow: hidden;
            text-align: left;
            width: 100%;
        }

        .badge-file-extension {
            background-color: #f25961;
            color: white;
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            border-radius: 0.375rem;
            margin-left: 0.5rem;
        }

        .bookmark-active svg {
            fill: #FF9800;
        }

        .description-text {
            font-size: 1.1rem;
            color: #555;
            margin-top: 0.5rem;
        }

        .comment {
            margin-top: 1rem;
            margin-bottom: 1rem;
        }

        .comment-section {
            border: 1px solid #e9ebee;
            border-radius: 1rem;
            padding: 1.5rem;
            background-color: #ffffff;
            /* box-shadow: 0 0 1rem rgba(0, 0, 0, 0.1); */
        }

        .comment-header {
            border-bottom: 1px solid #e9ebee;
            padding-bottom: 0.75rem;
            margin-bottom: 1rem;
        }

        .comment-avatar {
            height: 48px;
            width: 48px;
            border-radius: 50%;
            margin-right: 1rem;
        }

        .comment-author {
            font-size: 1rem;
            font-weight: 600;
        }

        .comment-time {
            font-size: 0.875rem;
            color: #90949c;
        }

        .comment-body {
            margin: 0.75rem 0;
            font-size: 1rem;
        }

        .comment-actions a {
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-right: 1rem;
        }

        .comment-actions i {
            margin-right: 0.5rem;
        }

        .reply-list {
            margin-top: 1rem;
            padding-left: 2rem;
        }

        .reply-list .comment {
            border-left: 1px dotted #d3d6db;
            padding-left: 1rem;
            margin-top: 1rem;
        }

        .reply-toggle {
            cursor: pointer;
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-top: 1rem;
            display: block;
        }

        .reply-form {
            display: none;
            position: relative;
            z-index: 10;
        }

        .comment-input {
            border-radius: 0.5rem;
        }

        .like-button.active i {
            color: #4caf50;
        }

        .dislike-button.active i {
            color: #dc3545;
        }


        /* Dropdown Styles */
        .dropdown-toggle::after {
            display: none;
            /* Remove the default arrow */
        }

        .dropdown-menu {
            right: 0;
            left: auto;
        }
    </style>
@endsection
@section('content')
    <div class="container">
        <div class="mt-4 comment-section">
            <h3>Comments ( {{ $comments->count() }} )</h3>
            <div class="comment-header d-flex justify-content-between align-items-center">
            </div>
            <div class="comment-body">
                <div class="d-flex mb-3">
                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                        class="comment-avatar">
                    <div class="w-100">
                        <form id="comment-form" action="{{ route('comments.store', $material) }}" method="POST">
                            @csrf
                            <div class="d-flex flex-column">
                                <textarea name="content" class="form-control comment-input" placeholder="Write a comment..." rows="3"></textarea>
                                <div class="d-flex justify-content-between mt-2">
                                    <div id="comment-form-error" class="text-danger"></div>
                                    <button type="submit" class="btn btn-primary">Post Comment</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div id="comment-list" class="comment-list">
                    @foreach ($comments as $comment)
                        <div class="comment" data-comment-id="{{ $comment->id }}">
                            <div class="d-flex">
                                <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                                    class="comment-avatar">
                                <div class="w-100">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <div class="comment-author">{{ $comment->user->name }}</div>
                                            <div class="comment-time">{{ $comment->created_at->diffForHumans() }}</div>
                                        </div>
                                        @if ($comment->user_id === auth()->id())
                                            <div class="dropdown">
                                                <button class="btn btn-link dropdown-toggle" type="button"
                                                    id="dropdownMenuButton{{ $comment->id }}" data-bs-toggle="dropdown"
                                                    aria-expanded="false">
                                                    <i class="fa-solid fa-ellipsis-vertical"></i>
                                                </button>
                                                <ul class="dropdown-menu"
                                                    aria-labelledby="dropdownMenuButton{{ $comment->id }}">
                                                    <li><a class="dropdown-item" href="#" data-action="edit"
                                                            data-comment-id="{{ $comment->id }}">Edit</a></li>
                                                    <li><a class="dropdown-item text-danger" href="#"
                                                            data-action="delete"
                                                            data-comment-id="{{ $comment->id }}">Delete</a></li>
                                                </ul>
                                            </div>
                                        @endif
                                    </div>
                                    <div class="comment-body">{{ $comment->content }}</div>
                                    <div class="comment-actions">
                                        <a href="#"
                                            class="like-button {{ $comment->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="like" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-up"></i>
                                            <span class="like-dislike-count">{{ $comment->likes }}</span>
                                        </a>
                                        <a href="#"
                                            class="dislike-button {{ $comment->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="dislike" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-down"></i>
                                            <span class="like-dislike-count">{{ $comment->dislikes }}</span>
                                        </a>
                                        <a href="#" class="reply-link" data-comment-id="{{ $comment->id }}"
                                            data-author="{{ $comment->user->name }}">
                                            <i class="fa-solid fa-reply"></i> Reply
                                        </a>
                                    </div>
                                    <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>

                                    <form class="reply-form" action="{{ route('replies.store', $comment) }}"
                                        method="POST">
                                        @csrf
                                        <div class="d-flex flex-column">
                                            <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                            <div class="d-flex justify-content-between mt-2">
                                                <div id="comment-form-error" class="text-danger" style="display: none;">
                                                    Error: Reply cannot be empty
                                                </div>
                                                <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                            </div>
                                        </div>

                                    </form>
                                    <div class="reply-list" style="display: none;">
                                        @foreach ($comment->replies as $reply)
                                            <div class="comment reply" data-comment-id="{{ $reply->id }}">
                                                <div class="d-flex">
                                                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg"
                                                        alt="avatar" class="comment-avatar">
                                                    <div class="w-100">
                                                        <div class="d-flex justify-content-between align-items-start">
                                                            <div>
                                                                <div class="comment-author">{{ $reply->user->name }}</div>
                                                                <div class="comment-time">
                                                                    {{ $reply->created_at->diffForHumans() }}</div>
                                                            </div>
                                                            @if ($reply->user_id === auth()->id())
                                                                <div class="dropdown">
                                                                    <button class="btn btn-link dropdown-toggle"
                                                                        type="button"
                                                                        id="dropdownMenuButton{{ $reply->id }}"
                                                                        data-bs-toggle="dropdown" aria-expanded="false">
                                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                                    </button>
                                                                    <ul class="dropdown-menu"
                                                                        aria-labelledby="dropdownMenuButton{{ $reply->id }}">
                                                                        <li><a class="dropdown-item" href="#"
                                                                                data-action="edit"
                                                                                data-comment-id="{{ $reply->id }}">Edit</a>
                                                                        </li>
                                                                        <li><a class="dropdown-item text-danger"
                                                                                href="#" data-action="delete"
                                                                                data-comment-id="{{ $reply->id }}">Delete</a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            @endif
                                                        </div>
                                                        <div class="comment-body">
                                                            @if ($reply->parent)
                                                                <a href="#"
                                                                    class="reply-mention">{{ '@' . $reply->parent->user->name }}</a>
                                                            @endif
                                                            <span class="reply-content">{{ $reply->content }}</span>
                                                        </div>
                                                        <div class="comment-actions">
                                                            <a href="#"
                                                                class="like-button {{ $reply->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="like" data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-up"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->likes }}</span>
                                                            </a>
                                                            <a href="#"
                                                                class="dislike-button {{ $reply->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="dislike"
                                                                data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-down"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->dislikes }}</span>
                                                            </a>
                                                            <a href="#" class="reply-link"
                                                                data-comment-id="{{ $reply->id }}"
                                                                data-author="{{ $reply->user->name }}">
                                                                <i class="fa-solid fa-reply"></i> Reply
                                                            </a>
                                                        </div>
                                                        <form class="reply-form"
                                                            action="{{ route('replies.store', $reply) }}" method="POST">
                                                            @csrf
                                                            <div class="d-flex flex-column">
                                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                                <div class="d-flex justify-content-between mt-2">
                                                                    <div id="comment-form-error" class="text-danger"
                                                                        style="display: none;">
                                                                        Error: Reply cannot be empty
                                                                    </div>
                                                                    <button type="submit"
                                                                        class="btn btn-primary ms-auto">Post Reply</button>
                                                                </div>
                                                            </div>

                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                            @include('materials.comment', ['replies' => $reply->replies])
                                        @endforeach
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const commentList = document.getElementById('comment-list');

            // Handle edit button click
            commentList.addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="edit"]');
                if (button) {
                    event.preventDefault();
                    const commentId = button.getAttribute('data-comment-id');
                    const commentBodyElement = document.querySelector(
                        `.comment[data-comment-id="${commentId}"] .comment-body`
                    );
                    const contentElement = commentBodyElement.querySelector('.reply-content') ||
                        commentBodyElement;
                    const mentionElement = contentElement.querySelector('.reply-mention');
                    const mention = mentionElement ? mentionElement.innerText.trim() : '';
                    const content = contentElement.innerText.trim();

                    // Store original content for cancel action
                    commentBodyElement.dataset.originalContent = commentBodyElement.innerHTML;

                    const editForm = `
                <form class="edit-comment-form" data-comment-id="${commentId}">
                    ${mention ? `<span class="reply-mention">${mention}</span>` : ''}
                    <textarea class="form-control">${content}</textarea>
                    <button type="submit" class="btn btn-primary mt-2">Save</button>
                    <button type="button" class="btn btn-secondary mt-2 cancel-edit">Cancel</button>
                </form>
            `;

                    commentBodyElement.innerHTML = editForm;
                    attachEditFormListeners(commentId);
                }
            });

            function attachEditFormListeners(commentId) {
                const editForm = document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"]`);

                editForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    const content = this.querySelector('textarea').value;
                    const mention = this.querySelector('.reply-mention') ? this.querySelector(
                            '.reply-mention')
                        .innerText.trim() : '';

                    fetch(`/comments/${commentId}`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute(
                                        'content')
                            },
                            body: JSON.stringify({
                                content
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const commentBodyElement = document.querySelector(
                                    `.comment[data-comment-id="${commentId}"] .comment-body`);
                                const mentionElement = mention ?
                                    `<a href="#" class="reply-mention">${mention}</a>` : '';
                                commentBodyElement.innerHTML =
                                    `${mentionElement} <span class="reply-content">${data.content}</span>`;
                            } else {
                                alert('Error updating comment.');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                        });
                });

                editForm.querySelector('.cancel-edit').addEventListener('click', function() {
                    const originalContent = document.querySelector(
                            `.comment[data-comment-id="${commentId}"] .comment-body`).dataset
                        .originalContent;
                    document.querySelector(`.comment[data-comment-id="${commentId}"] .comment-body`)
                        .innerHTML =
                        originalContent;
                });
            }
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {

            // for delete 
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="delete"]');
                if (button) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');

                    if (confirm('Are you sure you want to delete this comment?')) {
                        fetch(`/comments/${commentId}`, {
                                method: 'DELETE',
                                headers: {
                                    'X-Requested-With': 'XMLHttpRequest',
                                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                        .getAttribute('content'),
                                    'Content-Type': 'application/json',
                                }
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    const commentElement = document.querySelector(
                                        `.comment[data-comment-id="${commentId}"]`);
                                    if (commentElement) {
                                        commentElement.remove();
                                    }
                                } else {
                                    alert(data.message || 'Error deleting comment');
                                }
                            })
                            .catch(error => {
                                console.error('Error:', error);
                                alert('Something went wrong');
                            });
                    }
                }
            });

            // for like and dislike
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a');
                if (button && (button.classList.contains('like-button') || button.classList.contains(
                        'dislike-button'))) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');
                    const action = button.getAttribute('data-action');

                    fetch(`/comments/${commentId}/${action}`, {
                            method: 'POST',
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content'),
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                _method: 'POST'
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const commentElement = document.querySelector(
                                    `.comment[data-comment-id="${commentId}"]`);
                                const likeCount = commentElement.querySelector(
                                    '.like-button .like-dislike-count');
                                const dislikeCount = commentElement.querySelector(
                                    '.dislike-button .like-dislike-count');

                                likeCount.textContent = data.comment.likes;
                                dislikeCount.textContent = data.comment.dislikes;

                                if (action === 'like') {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.dislike-button').classList.remove(
                                        'active');
                                } else {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.like-button').classList.remove(
                                        'active');
                                }
                            } else {
                                alert(data.message || 'Error updating like/dislike');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('Something went wrong');
                        });
                }
            });

            // for submission of the main comment form
            document.getElementById('comment-form')?.addEventListener('submit', function(event) {
                event.preventDefault();
                const formData = new FormData(this);
                const errorDiv = document.getElementById('comment-form-error');
                errorDiv.textContent = ''; // Clear previous errors

                fetch(this.action, {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                .getAttribute('content')
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const commentList = document.getElementById('comment-list');
                            if (commentList) {
                                const newCommentHtml = `
                                <div class="comment" data-comment-id="${data.comment.id}">
                                    <div class="d-flex">
                                        <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                        <div class="w-100">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <div class="comment-author">${data.comment.user_name}</div>
                                                    <div class="comment-time">${data.comment.created_at}</div>
                                                </div>
                                                <div class="dropdown">
                                                    <button class="btn btn-link dropdown-toggle" type="button"
                                                        id="dropdownMenuButton${data.comment.id}" data-bs-toggle="dropdown"
                                                        aria-expanded="false">
                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                    </button>
                                                    <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.comment.id}">
                                                        <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.comment.id}">Edit</a></li>
                                                        <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.comment.id}">Delete</a></li>
                                                    </ul>
                                                </div>
                                            </div>
                                            <div class="comment-body">${data.comment.content}</div>
                                            <div class="comment-actions">
                                                <a href="#" class="like-button" data-action="like" data-comment-id="${data.comment.id}">
                                                    <i class="fa-solid fa-thumbs-up"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.comment.id}">
                                                    <i class="fa-solid fa-thumbs-down"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="reply-link" data-comment-id="${data.comment.id}" data-author="${data.comment.user_name}">
                                                    <i class="fa-solid fa-reply"></i> Reply
                                                </a>
                                            </div>
                                            <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>
                                            <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST">
                                                @csrf
                                            <div class="d-flex flex-column">
                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                <div class="d-flex justify-content-between  mt-2">
                                                    <div id="comment-form-error" class="text-danger" style="display: none;">
                                                        Error: Reply cannot be empty
                                                    </div>
                                                    <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                </div>
                                            </div>
                                            </form>
                                            <div class="reply-list" style="display: none;"></div>
                                        </div>
                                    </div>
                                </div>
                            `.replace(':commentId', data.comment.id);

                                commentList.insertAdjacentHTML('afterbegin', newCommentHtml);
                                this.reset();
                                initializeDropdowns();
                            }
                        } else {
                            // Display error messages
                            errorDiv.textContent = data.error || 'Your comment is empty';
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        errorDiv.textContent = 'Something went wrong';
                    });
            });

            // for submission of reply forms
            document.getElementById('comment-list')?.addEventListener('submit', function(event) {
                if (event.target.closest('.reply-form')) {
                    event.preventDefault();
                    const form = event.target;
                    const formData = new FormData(form);
                    const parentId = form.closest('.comment').dataset.commentId;
                    const errorDiv = form.querySelector('#comment-form-error');

                    // Reset error display
                    errorDiv.style.display = 'none';
                    errorDiv.textContent = '';

                    fetch(form.action.replace(':commentId', parentId), {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content')
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const replyList = form.closest('.reply-list') || form.closest(
                                    '.comment').querySelector('.reply-list');
                                if (replyList) {
                                    const newReplyHtml = `
                                    <div class="comment reply" data-comment-id="${data.reply.id}">
                                        <div class="d-flex">
                                            <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                            <div class="w-100">
                                                <div class="d-flex justify-content-between align-items-start">
                                                    <div>
                                                        <div class="comment-author">${data.reply.user_name}</div>
                                                        <div class="comment-time">${data.reply.created_at}</div>
                                                    </div>
                                                    <div class="dropdown">
                                                        <button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton${data.reply.id}" data-bs-toggle="dropdown" aria-expanded="false">
                                                            <i class="fa-solid fa-ellipsis-vertical"></i>
                                                        </button>
                                                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.reply.id}">
                                                            <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.reply.id}">Edit</a></li>
                                                            <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.reply.id}">Delete</a></li>
                                                        </ul>
                                                    </div>
                                                </div>
                                                <div class="comment-body">${data.reply.parent_name ? '<a href="#">' + '@' + data.reply.parent_name + '</a> ' : ''}${data.reply.content}</div>
                                                <div class="comment-actions">
                                                    <a href="#" class="like-button" data-action="like" data-comment-id="${data.reply.id}">
                                                        <i class="fa-solid fa-thumbs-up"></i>
                                                        <span class="like-dislike-count">0</span>
                                                    </a>
                                                    <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.reply.id}">
                                                        <i class="fa-solid fa-thumbs-down"></i>
                                                        <span class="like-dislike-count">0</span>
                                                    </a>
                                                    <a href="#" class="reply-link" data-comment-id="${data.reply.id}" data-author="${data.reply.user_name}">
                                                        <i class="fa-solid fa-reply"></i> Reply
                                                    </a>
                                                </div>
                                                <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST">
                                                    @csrf
                                                        <div class="d-flex flex-column">
                                                            <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                            <div class="d-flex justify-content-between  mt-2">
                                                                <div id="comment-form-error" class="text-danger" style="display: none;">
                                                                    Error: Reply cannot be empty
                                                                </div>
                                                                <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                            </div>
                                                        </div>
                                                </form>
                                                <div class="reply-list" style="display: none;"></div>
                                            </div>
                                        </div>
                                    </div>
                                    `.replace(':commentId', data.reply.id);

                                    replyList.insertAdjacentHTML('beforeend', newReplyHtml);
                                    form.reset();
                                    initializeDropdowns();
                                }
                            } else {
                                // Display error message
                                errorDiv.textContent = data.message || 'Error posting reply';
                                errorDiv.style.display = 'block';
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            // Display error message
                            errorDiv.textContent = 'Something went wrong';
                            errorDiv.style.display = 'block';
                        });
                }
            });

            // for reply link click to show reply form
            document.getElementById('comment-list')?.addEventListener('click', function(event) {
                if (event.target.closest('.reply-link')) {
                    event.preventDefault();
                    const replyForm = event.target.closest('.comment').querySelector('.reply-form');
                    if (replyForm) {
                        replyForm.style.display = replyForm.style.display === 'block' ? 'none' : 'block';
                    }
                }
            });
        });

        function initializeDropdowns() {
            const dropdowns = document.querySelectorAll('.dropdown-toggle:not(.initialized)');
            dropdowns.forEach(dropdown => {
                new bootstrap.Dropdown(dropdown);
                dropdown.classList.add('initialized');
            });
        }

        function toggleReplies(element) {
            const replyList = element.nextElementSibling.nextElementSibling;
            const isVisible = replyList.style.display === 'block';
            replyList.style.display = isVisible ? 'none' : 'block';
            element.textContent = isVisible ? 'View replies' : 'Hide replies';
        }
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.bookmark-toggle').forEach(function(button) {
                button.addEventListener('click', function() {
                    const fileId = this.getAttribute('data-file-id');
                    const button = this;

                    fetch("{{ route('bookmark.toggle') }}", {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({
                                file_id: fileId
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status === 'added') {
                                button.classList.add('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks-fill" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5z"/>
                                        <path d="M4.268 1A2 2 0 0 1 6 0h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L13 13.768V2a1 1 0 0 0-1-1z"/>
                                    </svg>`;
                            } else if (data.status === 'removed') {
                                button.classList.remove('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5zm2-1a1 1 0 0 0-1 1v10.566l3.723-2.482a.5.5 0 0 1 .554 0L11 14.566V4a1 1 0 0 0-1-1z"/>
                                        <path d="M4.268 1H12a1 1 0 0 1 1 1v11.768l.223.148A.5.5 0 0 0 14 13.5V2a2 2 0 0 0-2-2H6a2 2 0 0 0-1.732 1"/>
                                    </svg>`;
                            }
                        })
                        .catch(error => console.error('Error:', error));
                });
            });
        });
    </script>
@endsection
Convert a non-negative integer num to its English words representation.
@extends('new_layouts.app')
@section('styles')
    <style>
        .custom-table {
            border-collapse: collapse;
            border-radius: 1rem;
            border-style: hidden;
            box-shadow: 0 0 0 1px #e6ebef;
            overflow: hidden;
            text-align: left;
            width: 100%;
        }

        .badge-file-extension {
            background-color: #f25961;
            color: white;
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            border-radius: 0.375rem;
            margin-left: 0.5rem;
        }

        .bookmark-active svg {
            fill: #FF9800;
        }

        .description-text {
            font-size: 1.1rem;
            color: #555;
            margin-top: 0.5rem;
        }

        .comment {
            margin-top: 1rem;
            margin-bottom: 1rem;
        }

        .comment-section {
            border: 1px solid #e9ebee;
            border-radius: 1rem;
            padding: 1.5rem;
            background-color: #ffffff;
            /* box-shadow: 0 0 1rem rgba(0, 0, 0, 0.1); */
        }

        .comment-header {
            border-bottom: 1px solid #e9ebee;
            padding-bottom: 0.75rem;
            margin-bottom: 1rem;
        }

        .comment-avatar {
            height: 48px;
            width: 48px;
            border-radius: 50%;
            margin-right: 1rem;
        }

        .comment-author {
            font-size: 1rem;
            font-weight: 600;
        }

        .comment-time {
            font-size: 0.875rem;
            color: #90949c;
        }

        .comment-body {
            margin: 0.75rem 0;
            font-size: 1rem;
        }

        .comment-actions a {
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-right: 1rem;
        }

        .comment-actions i {
            margin-right: 0.5rem;
        }

        .reply-list {
            margin-top: 1rem;
            padding-left: 2rem;
        }

        .reply-list .comment {
            border-left: 1px dotted #d3d6db;
            padding-left: 1rem;
            margin-top: 1rem;
        }

        .reply-toggle {
            cursor: pointer;
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-top: 1rem;
            display: block;
        }

        .reply-form {
            display: none;
            position: relative;
            z-index: 10;
        }

        .comment-input {
            border-radius: 0.5rem;
        }

        .like-button.active i {
            color: #4caf50;
        }

        .dislike-button.active i {
            color: #dc3545;
        }


        /* Dropdown Styles */
        .dropdown-toggle::after {
            display: none;
            /* Remove the default arrow */
        }

        .dropdown-menu {
            right: 0;
            left: auto;
        }
    </style>
@endsection
@section('content')
    <div class="container">
        <div class="mt-4 comment-section">
            <h3>Comments ( {{ $comments->count() }} )</h3>
            <div class="comment-header d-flex justify-content-between align-items-center">
            </div>
            <div class="comment-body">
                <div class="d-flex mb-3">
                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                        class="comment-avatar">
                    <div class="w-100">
                        <form id="comment-form" action="{{ route('comments.store', $material) }}" method="POST">
                            @csrf
                            <div class="d-flex flex-column">
                                <textarea name="content" class="form-control comment-input" placeholder="Write a comment..." rows="3"></textarea>
                                <div class="d-flex justify-content-between mt-2">
                                    <div id="comment-form-error" class="text-danger"></div>
                                    <button type="submit" class="btn btn-primary">Post Comment</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div id="comment-list" class="comment-list">
                    @foreach ($comments as $comment)
                        <div class="comment" data-comment-id="{{ $comment->id }}">
                            <div class="d-flex">
                                <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                                    class="comment-avatar">
                                <div class="w-100">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <div class="comment-author">{{ $comment->user->name }}</div>
                                            <div class="comment-time">{{ $comment->created_at->diffForHumans() }}</div>
                                        </div>
                                        @if ($comment->user_id === auth()->id())
                                            <div class="dropdown">
                                                <button class="btn btn-link dropdown-toggle" type="button"
                                                    id="dropdownMenuButton{{ $comment->id }}" data-bs-toggle="dropdown"
                                                    aria-expanded="false">
                                                    <i class="fa-solid fa-ellipsis-vertical"></i>
                                                </button>
                                                <ul class="dropdown-menu"
                                                    aria-labelledby="dropdownMenuButton{{ $comment->id }}">
                                                    <li><a class="dropdown-item" href="#" data-action="edit"
                                                            data-comment-id="{{ $comment->id }}">Edit</a></li>
                                                    <li><a class="dropdown-item text-danger" href="#"
                                                            data-action="delete"
                                                            data-comment-id="{{ $comment->id }}">Delete</a></li>
                                                </ul>
                                            </div>
                                        @endif
                                    </div>
                                    <div class="comment-body">{{ $comment->content }}</div>
                                    <div class="comment-actions">
                                        <a href="#"
                                            class="like-button {{ $comment->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="like" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-up"></i>
                                            <span class="like-dislike-count">{{ $comment->likes }}</span>
                                        </a>
                                        <a href="#"
                                            class="dislike-button {{ $comment->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="dislike" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-down"></i>
                                            <span class="like-dislike-count">{{ $comment->dislikes }}</span>
                                        </a>
                                        <a href="#" class="reply-link" data-comment-id="{{ $comment->id }}"
                                            data-author="{{ $comment->user->name }}">
                                            <i class="fa-solid fa-reply"></i> Reply
                                        </a>
                                    </div>
                                    <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>

                                    <form class="reply-form" action="{{ route('replies.store', $comment) }}"
                                        method="POST">
                                        @csrf
                                        <div class="d-flex flex-column">
                                            <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                            <div class="d-flex justify-content-between mt-2">
                                                <div id="comment-form-error" class="text-danger" style="display: none;">
                                                    Error: Reply cannot be empty
                                                </div>
                                                <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                            </div>
                                        </div>

                                    </form>
                                    <div class="reply-list" style="display: none;">
                                        @foreach ($comment->replies as $reply)
                                            <div class="comment reply" data-comment-id="{{ $reply->id }}">
                                                <div class="d-flex">
                                                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg"
                                                        alt="avatar" class="comment-avatar">
                                                    <div class="w-100">
                                                        <div class="d-flex justify-content-between align-items-start">
                                                            <div>
                                                                <div class="comment-author">{{ $reply->user->name }}</div>
                                                                <div class="comment-time">
                                                                    {{ $reply->created_at->diffForHumans() }}</div>
                                                            </div>
                                                            @if ($reply->user_id === auth()->id())
                                                                <div class="dropdown">
                                                                    <button class="btn btn-link dropdown-toggle"
                                                                        type="button"
                                                                        id="dropdownMenuButton{{ $reply->id }}"
                                                                        data-bs-toggle="dropdown" aria-expanded="false">
                                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                                    </button>
                                                                    <ul class="dropdown-menu"
                                                                        aria-labelledby="dropdownMenuButton{{ $reply->id }}">
                                                                        <li><a class="dropdown-item" href="#"
                                                                                data-action="edit"
                                                                                data-comment-id="{{ $reply->id }}">Edit</a>
                                                                        </li>
                                                                        <li><a class="dropdown-item text-danger"
                                                                                href="#" data-action="delete"
                                                                                data-comment-id="{{ $reply->id }}">Delete</a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            @endif
                                                        </div>
                                                        <div class="comment-body">
                                                            @if ($reply->parent)
                                                                <a href="#"
                                                                    class="reply-mention">{{ '@' . $reply->parent->user->name }}</a>
                                                            @endif
                                                            <span class="reply-content">{{ $reply->content }}</span>
                                                        </div>
                                                        <div class="comment-actions">
                                                            <a href="#"
                                                                class="like-button {{ $reply->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="like" data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-up"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->likes }}</span>
                                                            </a>
                                                            <a href="#"
                                                                class="dislike-button {{ $reply->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="dislike"
                                                                data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-down"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->dislikes }}</span>
                                                            </a>
                                                            <a href="#" class="reply-link"
                                                                data-comment-id="{{ $reply->id }}"
                                                                data-author="{{ $reply->user->name }}">
                                                                <i class="fa-solid fa-reply"></i> Reply
                                                            </a>
                                                        </div>
                                                        <form class="reply-form"
                                                            action="{{ route('replies.store', $reply) }}" method="POST">
                                                            @csrf
                                                            <div class="d-flex flex-column">
                                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                                <div class="d-flex justify-content-between mt-2">
                                                                    <div id="comment-form-error" class="text-danger"
                                                                        style="display: none;">
                                                                        Error: Reply cannot be empty
                                                                    </div>
                                                                    <button type="submit"
                                                                        class="btn btn-primary ms-auto">Post Reply</button>
                                                                </div>
                                                            </div>

                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                            @include('materials.comment', ['replies' => $reply->replies])
                                        @endforeach
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Attach event listeners to all edit buttons
        document.querySelectorAll('[data-action="edit"]').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                const commentId = this.getAttribute('data-comment-id');
                const commentBodyElement = document.querySelector(
                    `.comment[data-comment-id="${commentId}"] .comment-body`
                );
                const contentElement = commentBodyElement.querySelector('.reply-content') || commentBodyElement;
                const mentionElement = contentElement.querySelector('.reply-mention');
                const mention = mentionElement ? mentionElement.innerText.trim() : '';
                const content = contentElement.innerText.trim();

                // Store original content for cancel action
                commentBodyElement.dataset.originalContent = commentBodyElement.innerHTML;

                const editForm = `
                    <form class="edit-comment-form" data-comment-id="${commentId}">
                        ${mention ? `<span class="reply-mention">${mention}</span>` : ''}
                        <textarea class="form-control">${content}</textarea>
                        <button type="submit" class="btn btn-primary mt-2">Save</button>
                        <button type="button" class="btn btn-secondary mt-2 cancel-edit">Cancel</button>
                    </form>
                `;

                commentBodyElement.innerHTML = editForm;
                attachEditFormListeners(commentId);
            });
        });
    });

    function attachEditFormListeners(commentId) {
        const editForm = document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"]`);
        
        editForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const content = this.querySelector('textarea').value;
            const mention = this.querySelector('.reply-mention') ? this.querySelector('.reply-mention').innerText.trim() : '';

            fetch(`/comments/${commentId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify({ content })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const commentBodyElement = document.querySelector(`.comment[data-comment-id="${commentId}"] .comment-body`);
                    const mentionElement = mention ? `<a href="#" class="reply-mention">${mention}</a>` : '';
                    commentBodyElement.innerHTML = `${mentionElement} <span class="reply-content">${data.content}</span>`;
                } else {
                    alert('Error updating comment.');
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
        });

        editForm.querySelector('.cancel-edit').addEventListener('click', function() {
            const originalContent = document.querySelector(`.comment[data-comment-id="${commentId}"] .comment-body`).dataset.originalContent;
            document.querySelector(`.comment[data-comment-id="${commentId}"] .comment-body`).innerHTML = originalContent;
        });
    }
</script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {

            // for delete 
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="delete"]');
                if (button) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');

                    if (confirm('Are you sure you want to delete this comment?')) {
                        fetch(`/comments/${commentId}`, {
                                method: 'DELETE',
                                headers: {
                                    'X-Requested-With': 'XMLHttpRequest',
                                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                        .getAttribute('content'),
                                    'Content-Type': 'application/json',
                                }
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    const commentElement = document.querySelector(
                                        `.comment[data-comment-id="${commentId}"]`);
                                    if (commentElement) {
                                        commentElement.remove();
                                    }
                                } else {
                                    alert(data.message || 'Error deleting comment');
                                }
                            })
                            .catch(error => {
                                console.error('Error:', error);
                                alert('Something went wrong');
                            });
                    }
                }
            });

            // for like and dislike
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a');
                if (button && (button.classList.contains('like-button') || button.classList.contains(
                        'dislike-button'))) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');
                    const action = button.getAttribute('data-action');

                    fetch(`/comments/${commentId}/${action}`, {
                            method: 'POST',
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content'),
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                _method: 'POST'
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const commentElement = document.querySelector(
                                    `.comment[data-comment-id="${commentId}"]`);
                                const likeCount = commentElement.querySelector(
                                    '.like-button .like-dislike-count');
                                const dislikeCount = commentElement.querySelector(
                                    '.dislike-button .like-dislike-count');

                                likeCount.textContent = data.comment.likes;
                                dislikeCount.textContent = data.comment.dislikes;

                                if (action === 'like') {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.dislike-button').classList.remove(
                                        'active');
                                } else {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.like-button').classList.remove(
                                        'active');
                                }
                            } else {
                                alert(data.message || 'Error updating like/dislike');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('Something went wrong');
                        });
                }
            });

            // for submission of the main comment form
            document.getElementById('comment-form')?.addEventListener('submit', function(event) {
                event.preventDefault();
                const formData = new FormData(this);
                const errorDiv = document.getElementById('comment-form-error');
                errorDiv.textContent = ''; // Clear previous errors

                fetch(this.action, {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                .getAttribute('content')
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const commentList = document.getElementById('comment-list');
                            if (commentList) {
                                const newCommentHtml = `
                                <div class="comment" data-comment-id="${data.comment.id}">
                                    <div class="d-flex">
                                        <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                        <div class="w-100">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <div class="comment-author">${data.comment.user_name}</div>
                                                    <div class="comment-time">${data.comment.created_at}</div>
                                                </div>
                                                <div class="dropdown">
                                                    <button class="btn btn-link dropdown-toggle" type="button"
                                                        id="dropdownMenuButton${data.comment.id}" data-bs-toggle="dropdown"
                                                        aria-expanded="false">
                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                    </button>
                                                    <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.comment.id}">
                                                        <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.comment.id}">Edit</a></li>
                                                        <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.comment.id}">Delete</a></li>
                                                    </ul>
                                                </div>
                                            </div>
                                            <div class="comment-body">${data.comment.content}</div>
                                            <div class="comment-actions">
                                                <a href="#" class="like-button" data-action="like" data-comment-id="${data.comment.id}">
                                                    <i class="fa-solid fa-thumbs-up"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.comment.id}">
                                                    <i class="fa-solid fa-thumbs-down"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="reply-link" data-comment-id="${data.comment.id}" data-author="${data.comment.user_name}">
                                                    <i class="fa-solid fa-reply"></i> Reply
                                                </a>
                                            </div>
                                            <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>
                                            <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST">
                                                @csrf
                                            <div class="d-flex flex-column">
                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                <div class="d-flex justify-content-between  mt-2">
                                                    <div id="comment-form-error" class="text-danger" style="display: none;">
                                                        Error: Reply cannot be empty
                                                    </div>
                                                    <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                </div>
                                            </div>
                                            </form>
                                            <div class="reply-list" style="display: none;"></div>
                                        </div>
                                    </div>
                                </div>
                            `.replace(':commentId', data.comment.id);

                                commentList.insertAdjacentHTML('afterbegin', newCommentHtml);
                                this.reset();
                                initializeDropdowns();
                            }
                        } else {
                            // Display error messages
                            errorDiv.textContent = data.error || 'Your comment is empty';
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        errorDiv.textContent = 'Something went wrong';
                    });
            });

            // for submission of reply forms
            document.getElementById('comment-list')?.addEventListener('submit', function(event) {
                if (event.target.closest('.reply-form')) {
                    event.preventDefault();
                    const form = event.target;
                    const formData = new FormData(form);
                    const parentId = form.closest('.comment').dataset.commentId;
                    const errorDiv = form.querySelector('#comment-form-error');

                    // Reset error display
                    errorDiv.style.display = 'none';
                    errorDiv.textContent = '';

                    fetch(form.action.replace(':commentId', parentId), {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content')
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const replyList = form.closest('.reply-list') || form.closest(
                                    '.comment').querySelector('.reply-list');
                                if (replyList) {
                                    const newReplyHtml = `
                                    <div class="comment reply" data-comment-id="${data.reply.id}">
                                        <div class="d-flex">
                                            <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                            <div class="w-100">
                                                <div class="d-flex justify-content-between align-items-start">
                                                    <div>
                                                        <div class="comment-author">${data.reply.user_name}</div>
                                                        <div class="comment-time">${data.reply.created_at}</div>
                                                    </div>
                                                    <div class="dropdown">
                                                        <button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton${data.reply.id}" data-bs-toggle="dropdown" aria-expanded="false">
                                                            <i class="fa-solid fa-ellipsis-vertical"></i>
                                                        </button>
                                                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.reply.id}">
                                                            <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.reply.id}">Edit</a></li>
                                                            <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.reply.id}">Delete</a></li>
                                                        </ul>
                                                    </div>
                                                </div>
                                                <div class="comment-body">${data.reply.parent_name ? '<a href="#">' + '@' + data.reply.parent_name + '</a> ' : ''}${data.reply.content}</div>
                                                <div class="comment-actions">
                                                    <a href="#" class="like-button" data-action="like" data-comment-id="${data.reply.id}">
                                                        <i class="fa-solid fa-thumbs-up"></i>
                                                        <span class="like-dislike-count">0</span>
                                                    </a>
                                                    <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.reply.id}">
                                                        <i class="fa-solid fa-thumbs-down"></i>
                                                        <span class="like-dislike-count">0</span>
                                                    </a>
                                                    <a href="#" class="reply-link" data-comment-id="${data.reply.id}" data-author="${data.reply.user_name}">
                                                        <i class="fa-solid fa-reply"></i> Reply
                                                    </a>
                                                </div>
                                                <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST">
                                                    @csrf
                                                        <div class="d-flex flex-column">
                                                            <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                            <div class="d-flex justify-content-between  mt-2">
                                                                <div id="comment-form-error" class="text-danger" style="display: none;">
                                                                    Error: Reply cannot be empty
                                                                </div>
                                                                <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                            </div>
                                                        </div>
                                                </form>
                                                <div class="reply-list" style="display: none;"></div>
                                            </div>
                                        </div>
                                    </div>
                                    `.replace(':commentId', data.reply.id);

                                    replyList.insertAdjacentHTML('beforeend', newReplyHtml);
                                    form.reset();
                                    initializeDropdowns();
                                }
                            } else {
                                // Display error message
                                errorDiv.textContent = data.message || 'Error posting reply';
                                errorDiv.style.display = 'block';
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            // Display error message
                            errorDiv.textContent = 'Something went wrong';
                            errorDiv.style.display = 'block';
                        });
                }
            });

            // for reply link click to show reply form
            document.getElementById('comment-list')?.addEventListener('click', function(event) {
                if (event.target.closest('.reply-link')) {
                    event.preventDefault();
                    const replyForm = event.target.closest('.comment').querySelector('.reply-form');
                    if (replyForm) {
                        replyForm.style.display = replyForm.style.display === 'block' ? 'none' : 'block';
                    }
                }
            });
        });

        function initializeDropdowns() {
            const dropdowns = document.querySelectorAll('.dropdown-toggle:not(.initialized)');
            dropdowns.forEach(dropdown => {
                new bootstrap.Dropdown(dropdown);
                dropdown.classList.add('initialized');
            });
        }

        function toggleReplies(element) {
            const replyList = element.nextElementSibling.nextElementSibling;
            const isVisible = replyList.style.display === 'block';
            replyList.style.display = isVisible ? 'none' : 'block';
            element.textContent = isVisible ? 'View replies' : 'Hide replies';
        }
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.bookmark-toggle').forEach(function(button) {
                button.addEventListener('click', function() {
                    const fileId = this.getAttribute('data-file-id');
                    const button = this;

                    fetch("{{ route('bookmark.toggle') }}", {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({
                                file_id: fileId
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status === 'added') {
                                button.classList.add('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks-fill" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5z"/>
                                        <path d="M4.268 1A2 2 0 0 1 6 0h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L13 13.768V2a1 1 0 0 0-1-1z"/>
                                    </svg>`;
                            } else if (data.status === 'removed') {
                                button.classList.remove('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5zm2-1a1 1 0 0 0-1 1v10.566l3.723-2.482a.5.5 0 0 1 .554 0L11 14.566V4a1 1 0 0 0-1-1z"/>
                                        <path d="M4.268 1H12a1 1 0 0 1 1 1v11.768l.223.148A.5.5 0 0 0 14 13.5V2a2 2 0 0 0-2-2H6a2 2 0 0 0-1.732 1"/>
                                    </svg>`;
                            }
                        })
                        .catch(error => console.error('Error:', error));
                });
            });
        });
    </script>
@endsection
LET vFieldCount = NoOfFields('LINK');


FOR i = 1 TO $(vFieldCount)
    LET vFieldName$(i) = FieldName($(i), 'LINK');
NEXT i;

// Step 2: Construct dynamic load script
SET vLoadScript = '';

set vSkipFields = 'el1#,el2#,el3#';

FOR i = 1 TO $(vFieldCount)


	trace TRACE field $(vFieldName$(i));
    
    
    	IF WildMatch(vSkipFields, '*$(vFieldName$(i))*')  THEN
        // If both match, log the result and continue
        TRACE Matched: $(vFieldName$(i)) and skipped;
        
        else
        
    
    
    	LET vLoadScript = '$(vLoadScript)' & '$(vFieldName$(i)),';
        
        ENDIF;
NEXT i;

LET vLoadScript = LEFT('$(vLoadScript)', LEN('$(vLoadScript)') - 1);  // Remove the trailing comma

exit script;
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome  to Android Studio"
        android:textSize="35dp"
        android:textColor="@color/design_default_color_secondary"
        android:textStyle="bold"
        
        
        />
    <TextView
        
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        android:text="My Name is write ur name"
        android:textColor="@color/purple_200"
        android:textSize="35dp"
        android:textStyle="italic"
        
        />
    <EditText
        android:id="@+id/firstnum"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:hint="Enter the First Number"
        
        
        />
    <EditText
        android:id="@+id/secondnum"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:hint="Enter the Second Number"


        />

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/Title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:text="Welcome to Android studioo"
        android:textSize="35dp"
        android:textColor="@color/purple_700"
        android:textStyle="italic"
        />
    <TextView
        android:id="@+id/Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="My name is Shankar"
        android:textColor="@color/black"
        android:textSize="35dp"
        android:textStyle="bold"/>
    <EditText
        android:id="@+id/firstname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enetr the first name"/>
    <EditText
        android:id="@+id/Second"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter second numb"/>

</LinearLayout>
function customRatingScoreHTML($productID)
{
  $product = wc_get_product($productID);
  $average      = $product->get_average_rating();
  $rating_whole = floor($average);
  $rating_fraction = $average - $rating_whole;
  $flug = 0;
  for ($i = 1; $i <= 5; $i++) {
    if ($i <= $rating_whole) {
      echo '<i class="fas fa-star"></i>';
    } else {
      if ($rating_fraction > 0 && $flug == 0) {
        echo '<i class="fas fa-star-half-alt"></i>';
        $flug = 1;
      } else {
        echo '<i class="far fa-star empty"></i>';
      }
    }
  }
}
<?php
//Team Post Type;
add_action('init', 'our_team_post_type_init');
function our_team_post_type_init()
{

    $labels = array(

        'name' => __('Team', 'post type general name', ''),
        'singular_name' => __('Our Team', 'post type singular name', ''),
        'add_new' => __('Add New', 'Our Team', ''),
        'add_new_item' => __('Add New Our Team', ''),
        'edit_item' => __('Edit Our Team', ''),
        'new_item' => __('New Our Team', ''),
        'view_item' => __('View Our Team', ''),
        'search_items' => __('Search Our Team', ''),
        'not_found' =>  __('No Our Team found', ''),
        'not_found_in_trash' => __('No Our Team found in Trash', ''),
        'parent_item_colon' => ''
    );
    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'rewrite' => true,
        'query_var' => true,
        'capability_type' => 'post',
        'hierarchical' => true,
        'public' => true,
        'has_archive' => true,
        'show_in_nav_menus' => true,
        'menu_position' => null,
        'rewrite' => array(
            'slug' => 'teams',
            'with_front' => true
        ),
        'supports' => array(
            'title',
            'editor',
            'thumbnail'
        )
    );

    register_post_type('team', $args);
}

// Add Shortcode [our_team];
add_shortcode('our_team', 'codex_our_team');
function codex_our_team()
{
    ob_start();
    wp_reset_postdata();
    ?>
    <div class="section__body">
  <div class="team-members">
    <ul>
			<?php
			$arg = array(
				'post_type' => 'team',
				'posts_per_page' => -1,
				'order' => 'ASC',
			);
			$po = new WP_Query($arg);
			?>
			<?php if ($po->have_posts()) : ?>
				<?php while ($po->have_posts()) : ?>
					<?php $po->the_post(); ?>
            <li>
              <div class="team-member">
                <a href="<?php the_permalink(); ?>">
                  <div class="team__image image-fit js-image-fit">
                      <?php echo get_the_post_thumbnail( get_the_ID(), 'full' );?>
                  </div>
                  <!-- /.team__image -->
                  <div class="team__content">
                    <h5><?php the_title(); ?>   </h5>
                    <!-- <p>Principal</p> -->
                  </div>
                  <!-- /.team__content -->
                </a>
              </div>
              <!-- /.team-member -->
            </li>
					
				<?php endwhile; ?>
			<?php endif; ?>
				</ul>
  </div>
  <!-- /.team-members -->
</div>
<?php
    wp_reset_postdata();
    return '' . ob_get_clean();
}



/*********************** SINGLE PAGE TEAM SECTION ***********************/
<?php get_header(); ?>

<div class="section-blog-member">
  <div class="shell">
    <div class="section__inner">
      <div class="section__head">
        <figure class="section__image">
          <img src="<?php the_field('featured_member_banner'); ?>" alt="<?php the_permalink(); ?>">                 
        </figure>
        <!-- /.section__image -->
        <div class="section__content">
          <div class="section__name">
            <h1><?php the_title(); ?></h1>
          </div>
          <!-- /.section__name -->
          <div class="section__job">
            <!-- <h2 class="h1">Principal</h2> -->
          </div>
          <!-- /.section__job -->
        </div>
        <!-- /.section__content -->
      </div>
      <!-- /.section__head -->
      <div class="section__body">
        <div class="section__entry">
          <?php the_content(); ?>
        </div>
        <!-- /.section__entry -->
      </div>
      <!-- /.section__body -->
    </div>
    <!-- /.section__inner -->
  </div>
  <!-- /.shell -->
</div>
<!-- /.section-blog-member -->
<?php get_footer(); ?>



/*********************** CSS FOR TEAM SECTION ***********************/
/*OUR TEAM*/
.team-members > ul { display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; margin: 0 0; list-style: none; padding: 0; }
.team-members > ul > li { width: 50%; padding: 0; }
.team-member { text-align: center; text-transform: uppercase; }
.team-member > a { display: block; text-decoration: none; }
.team-member .team__image { margin-bottom: 44px; }
.team-member .team__image { -webkit-transition: opacity .4s; -o-transition: opacity .4s; transition: opacity .4s; }
.image-fit { overflow: hidden; position: relative; background-size: cover; background-position: 50%; }
.team-member > a:hover .team__image { opacity: .3; -webkit-transition: opacity .4s; -o-transition: opacity .4s; transition: opacity .4s; }
.team-member .team__image img { height: 600px; object-fit: cover; }
.team-member h5 { font-size: 24px; line-height: 30px; font-family: 'Questrial', sans-serif; }

/*TEAM SINGLE*/
.section-blog-member { font-size: 20px; line-height: 30px; color: #000; font-weight: 400; font-family: "Questrial", sans-serif; }
.section-blog-member .section__image { margin: 0; position: relative; margin-left: calc(-50vw + 50%); width: 100vw }
.section-blog-member .section__image img { width: 100%; display: block }
.section-blog-member .section__content { position: absolute; left: 51.6%; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); z-index: 1 }
.section-blog-member .section__job { font-style: italic }
.section-blog-member .section__head { position: relative }
.section-blog-member .section__head:not(:last-child) { margin-bottom: 80px; }
.section-blog-member .section__body { max-width: 750px; margin-inline: auto }
.section-blog-member .section__name h1 { font-size: 64px; font-family: 'Questrial', sans-serif; line-height: 40px; }
.section-blog-member .section__entry p { margin-bottom: 1.5em; }
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate]
"ProductVersion"="Windows 10"
"TargetReleaseVersion"=dword:00000001
"TargetReleaseVersionInfo"="22H2"
@extends('new_layouts.app')
@section('styles')
    <style>
        .custom-table {
            border-collapse: collapse;
            border-radius: 1rem;
            border-style: hidden;
            box-shadow: 0 0 0 1px #e6ebef;
            overflow: hidden;
            text-align: left;
            width: 100%;
        }

        .badge-file-extension {
            background-color: #f25961;
            color: white;
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            border-radius: 0.375rem;
            margin-left: 0.5rem;
        }

        .bookmark-active svg {
            fill: #FF9800;
        }

        .description-text {
            font-size: 1.1rem;
            color: #555;
            margin-top: 0.5rem;
        }

        .comment {
            margin-top: 1rem;
            margin-bottom: 1rem;
        }

        .comment-section {
            border: 1px solid #e9ebee;
            border-radius: 1rem;
            padding: 1.5rem;
            background-color: #ffffff;
            /* box-shadow: 0 0 1rem rgba(0, 0, 0, 0.1); */
        }

        .comment-header {
            border-bottom: 1px solid #e9ebee;
            padding-bottom: 0.75rem;
            margin-bottom: 1rem;
        }

        .comment-avatar {
            height: 48px;
            width: 48px;
            border-radius: 50%;
            margin-right: 1rem;
        }

        .comment-author {
            font-size: 1rem;
            font-weight: 600;
        }

        .comment-time {
            font-size: 0.875rem;
            color: #90949c;
        }

        .comment-body {
            margin: 0.75rem 0;
            font-size: 1rem;
        }

        .comment-actions a {
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-right: 1rem;
        }

        .comment-actions i {
            margin-right: 0.5rem;
        }

        .reply-list {
            margin-top: 1rem;
            padding-left: 2rem;
        }

        .reply-list .comment {
            border-left: 1px dotted #d3d6db;
            padding-left: 1rem;
            margin-top: 1rem;
        }

        .reply-toggle {
            cursor: pointer;
            font-size: 0.875rem;
            color: #4267b2;
            text-decoration: none;
            margin-top: 1rem;
            display: block;
        }

        .reply-form {
            display: none;
            position: relative;
            z-index: 10;
        }

        .comment-input {
            border-radius: 0.5rem;
        }

        .like-button.active i {
            color: #4caf50;
        }

        .dislike-button.active i {
            color: #dc3545;
        }


        /* Dropdown Styles */
        .dropdown-toggle::after {
            display: none;
            /* Remove the default arrow */
        }

        .dropdown-menu {
            right: 0;
            left: auto;
        }
    </style>
@endsection
@section('content')
    <div class="container">
        <div class="mt-4 comment-section">
            <h3>Comments ( {{ $comments->count() }} )</h3>
            <div class="comment-header d-flex justify-content-between align-items-center">
            </div>
            <div class="comment-body">
                <div class="d-flex mb-3">
                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                        class="comment-avatar">
                    <div class="w-100">
                        <form id="comment-form" action="{{ route('comments.store', $material) }}" method="POST">
                            @csrf
                            <div class="d-flex flex-column">
                                <textarea name="content" class="form-control comment-input" placeholder="Write a comment..." rows="3"></textarea>
                                <div class="d-flex justify-content-between mt-2">
                                    <div id="comment-form-error" class="text-danger"></div>
                                    <button type="submit" class="btn btn-primary">Post Comment</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div id="comment-list" class="comment-list">
                    @foreach ($comments as $comment)
                        <div class="comment" data-comment-id="{{ $comment->id }}">
                            <div class="d-flex">
                                <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar"
                                    class="comment-avatar">
                                <div class="w-100">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <div class="comment-author">{{ $comment->user->name }}</div>
                                            <div class="comment-time">{{ $comment->created_at->diffForHumans() }}</div>
                                        </div>
                                        @if ($comment->user_id === auth()->id())
                                            <div class="dropdown">
                                                <button class="btn btn-link dropdown-toggle" type="button"
                                                    id="dropdownMenuButton{{ $comment->id }}" data-bs-toggle="dropdown"
                                                    aria-expanded="false">
                                                    <i class="fa-solid fa-ellipsis-vertical"></i>
                                                </button>
                                                <ul class="dropdown-menu"
                                                    aria-labelledby="dropdownMenuButton{{ $comment->id }}">
                                                    <li><a class="dropdown-item" href="#" data-action="edit"
                                                            data-comment-id="{{ $comment->id }}">Edit</a></li>
                                                    <li><a class="dropdown-item text-danger" href="#"
                                                            data-action="delete"
                                                            data-comment-id="{{ $comment->id }}">Delete</a></li>
                                                </ul>
                                            </div>
                                        @endif
                                    </div>
                                    <div class="comment-body">{{ $comment->content }}</div>
                                    <div class="comment-actions">
                                        <a href="#"
                                            class="like-button {{ $comment->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="like" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-up"></i>
                                            <span class="like-dislike-count">{{ $comment->likes }}</span>
                                        </a>
                                        <a href="#"
                                            class="dislike-button {{ $comment->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                            data-action="dislike" data-comment-id="{{ $comment->id }}">
                                            <i class="fa-solid fa-thumbs-down"></i>
                                            <span class="like-dislike-count">{{ $comment->dislikes }}</span>
                                        </a>
                                        <a href="#" class="reply-link" data-comment-id="{{ $comment->id }}"
                                            data-author="{{ $comment->user->name }}">
                                            <i class="fa-solid fa-reply"></i> Reply
                                        </a>
                                    </div>
                                    <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>

                                    <form class="reply-form" action="{{ route('replies.store', $comment) }}"
                                        method="POST">
                                        @csrf
                                        <div class="d-flex flex-column">
                                            <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                            <div class="d-flex justify-content-between mt-2">
                                                <div id="comment-form-error" class="text-danger" style="display: none;">
                                                    Error: Reply cannot be empty
                                                </div>
                                                <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                            </div>
                                        </div>

                                    </form>
                                    <div class="reply-list" style="display: none;">
                                        @foreach ($comment->replies as $reply)
                                            <div class="comment reply" data-comment-id="{{ $reply->id }}">
                                                <div class="d-flex">
                                                    <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg"
                                                        alt="avatar" class="comment-avatar">
                                                    <div class="w-100">
                                                        <div class="d-flex justify-content-between align-items-start">
                                                            <div>
                                                                <div class="comment-author">{{ $reply->user->name }}</div>
                                                                <div class="comment-time">
                                                                    {{ $reply->created_at->diffForHumans() }}</div>
                                                            </div>
                                                            @if ($reply->user_id === auth()->id())
                                                                <div class="dropdown">
                                                                    <button class="btn btn-link dropdown-toggle"
                                                                        type="button"
                                                                        id="dropdownMenuButton{{ $reply->id }}"
                                                                        data-bs-toggle="dropdown" aria-expanded="false">
                                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                                    </button>
                                                                    <ul class="dropdown-menu"
                                                                        aria-labelledby="dropdownMenuButton{{ $reply->id }}">
                                                                        <li><a class="dropdown-item" href="#"
                                                                                data-action="edit"
                                                                                data-comment-id="{{ $reply->id }}">Edit</a>
                                                                        </li>
                                                                        <li><a class="dropdown-item text-danger"
                                                                                href="#" data-action="delete"
                                                                                data-comment-id="{{ $reply->id }}">Delete</a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            @endif
                                                        </div>
                                                        <div class="comment-body">
                                                            @if ($reply->parent)
                                                                <a href="#"
                                                                    class="reply-mention">{{ '@' . $reply->parent->user->name }}</a>
                                                            @endif
                                                            <span class="reply-content">{{ $reply->content }}</span>
                                                        </div>
                                                        <div class="comment-actions">
                                                            <a href="#"
                                                                class="like-button {{ $reply->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="like" data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-up"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->likes }}</span>
                                                            </a>
                                                            <a href="#"
                                                                class="dislike-button {{ $reply->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                                                                data-action="dislike"
                                                                data-comment-id="{{ $reply->id }}">
                                                                <i class="fa-solid fa-thumbs-down"></i>
                                                                <span
                                                                    class="like-dislike-count">{{ $reply->dislikes }}</span>
                                                            </a>
                                                            <a href="#" class="reply-link"
                                                                data-comment-id="{{ $reply->id }}"
                                                                data-author="{{ $reply->user->name }}">
                                                                <i class="fa-solid fa-reply"></i> Reply
                                                            </a>
                                                        </div>
                                                        <form class="reply-form"
                                                            action="{{ route('replies.store', $reply) }}" method="POST">
                                                            @csrf
                                                            <div class="d-flex flex-column">
                                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                                <div class="d-flex justify-content-between mt-2">
                                                                    <div id="comment-form-error" class="text-danger"
                                                                        style="display: none;">
                                                                        Error: Reply cannot be empty
                                                                    </div>
                                                                    <button type="submit"
                                                                        class="btn btn-primary ms-auto">Post Reply</button>
                                                                </div>
                                                            </div>

                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                            @include('materials.comment', ['replies' => $reply->replies])
                                        @endforeach
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('[data-action="edit"]').forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    const commentId = this.getAttribute('data-comment-id');
                    const commentBodyElement = document.querySelector(
                        `.comment[data-comment-id="${commentId}"] .comment-body`);
                    const mentionElement = commentBodyElement.querySelector('.reply-mention');
                    const mention = mentionElement ? mentionElement.innerText.trim() : '';
                    const content = commentBodyElement.querySelector('.reply-content').innerText
                        .trim();

                    // Store original content for cancel action
                    commentBodyElement.dataset.originalContent = commentBodyElement.innerHTML;

                    const editForm = `
                    <form class="edit-comment-form" data-comment-id="${commentId}">
                        ${mention ? `<span class="reply-mention">${mention}</span>` : ''}
                        <textarea class="form-control">${content}</textarea>
                        <button type="submit" class="btn btn-primary mt-2">Save</button>
                        <button type="button" class="btn btn-secondary mt-2 cancel-edit">Cancel</button>
                    </form>
                `;

                    commentBodyElement.innerHTML = editForm;
                    attachEditFormListeners(commentId);
                });
            });
        });

        function attachEditFormListeners(commentId) {
            document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"]`).addEventListener('submit',
                function(e) {
                    e.preventDefault();
                    const content = this.querySelector('textarea').value;
                    const mention = this.querySelector('.reply-mention') ? this.querySelector('.reply-mention')
                        .innerText.trim() : '';

                    fetch(`/comments/${commentId}`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute(
                                    'content')
                            },
                            body: JSON.stringify({
                                content
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const commentBodyElement = document.querySelector(
                                    `.comment[data-comment-id="${commentId}"] .comment-body`);
                                const mentionElement = mention ?
                                    `<a href="#" class="reply-mention">${mention}</a>` : '';
                                commentBodyElement.innerHTML =
                                    `${mentionElement} <span class="reply-content">${data.content}</span>`;
                            } else {
                                alert('Error updating comment.');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                        });
                });

            document.querySelector(`.edit-comment-form[data-comment-id="${commentId}"] .cancel-edit`).addEventListener(
                'click',
                function() {
                    const originalContent = document.querySelector(
                        `.comment[data-comment-id="${commentId}"] .comment-body`).dataset.originalContent;
                    document.querySelector(`.comment[data-comment-id="${commentId}"] .comment-body`).innerHTML =
                        originalContent;
                });
        }
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {

            // for delete 
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a[data-action="delete"]');
                if (button) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');

                    if (confirm('Are you sure you want to delete this comment?')) {
                        fetch(`/comments/${commentId}`, {
                                method: 'DELETE',
                                headers: {
                                    'X-Requested-With': 'XMLHttpRequest',
                                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                        .getAttribute('content'),
                                    'Content-Type': 'application/json',
                                }
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    const commentElement = document.querySelector(
                                        `.comment[data-comment-id="${commentId}"]`);
                                    if (commentElement) {
                                        commentElement.remove();
                                    }
                                } else {
                                    alert(data.message || 'Error deleting comment');
                                }
                            })
                            .catch(error => {
                                console.error('Error:', error);
                                alert('Something went wrong');
                            });
                    }
                }
            });

            // for like and dislike
            document.getElementById('comment-list').addEventListener('click', function(event) {
                const button = event.target.closest('a');
                if (button && (button.classList.contains('like-button') || button.classList.contains(
                        'dislike-button'))) {
                    event.preventDefault();

                    const commentId = button.getAttribute('data-comment-id');
                    const action = button.getAttribute('data-action');

                    fetch(`/comments/${commentId}/${action}`, {
                            method: 'POST',
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content'),
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                _method: 'POST'
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const commentElement = document.querySelector(
                                    `.comment[data-comment-id="${commentId}"]`);
                                const likeCount = commentElement.querySelector(
                                    '.like-button .like-dislike-count');
                                const dislikeCount = commentElement.querySelector(
                                    '.dislike-button .like-dislike-count');

                                likeCount.textContent = data.comment.likes;
                                dislikeCount.textContent = data.comment.dislikes;

                                if (action === 'like') {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.dislike-button').classList.remove(
                                        'active');
                                } else {
                                    button.classList.toggle('active');
                                    commentElement.querySelector('.like-button').classList.remove(
                                        'active');
                                }
                            } else {
                                alert(data.message || 'Error updating like/dislike');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert('Something went wrong');
                        });
                }
            });

            // for submission of the main comment form
            document.getElementById('comment-form')?.addEventListener('submit', function(event) {
                event.preventDefault();
                const formData = new FormData(this);
                const errorDiv = document.getElementById('comment-form-error');
                errorDiv.textContent = ''; // Clear previous errors

                fetch(this.action, {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                .getAttribute('content')
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const commentList = document.getElementById('comment-list');
                            if (commentList) {
                                const newCommentHtml = `
                                <div class="comment" data-comment-id="${data.comment.id}">
                                    <div class="d-flex">
                                        <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                        <div class="w-100">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <div class="comment-author">${data.comment.user_name}</div>
                                                    <div class="comment-time">${data.comment.created_at}</div>
                                                </div>
                                                <div class="dropdown">
                                                    <button class="btn btn-link dropdown-toggle" type="button"
                                                        id="dropdownMenuButton${data.comment.id}" data-bs-toggle="dropdown"
                                                        aria-expanded="false">
                                                        <i class="fa-solid fa-ellipsis-vertical"></i>
                                                    </button>
                                                    <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.comment.id}">
                                                        <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.comment.id}">Edit</a></li>
                                                        <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.comment.id}">Delete</a></li>
                                                    </ul>
                                                </div>
                                            </div>
                                            <div class="comment-body">${data.comment.content}</div>
                                            <div class="comment-actions">
                                                <a href="#" class="like-button" data-action="like" data-comment-id="${data.comment.id}">
                                                    <i class="fa-solid fa-thumbs-up"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.comment.id}">
                                                    <i class="fa-solid fa-thumbs-down"></i>
                                                    <span class="like-dislike-count">0</span>
                                                </a>
                                                <a href="#" class="reply-link" data-comment-id="${data.comment.id}" data-author="${data.comment.user_name}">
                                                    <i class="fa-solid fa-reply"></i> Reply
                                                </a>
                                            </div>
                                            <div class="reply-toggle" onclick="toggleReplies(this)">View replies</div>
                                            <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST">
                                                @csrf
                                            <div class="d-flex flex-column">
                                                <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                <div class="d-flex justify-content-between  mt-2">
                                                    <div id="comment-form-error" class="text-danger" style="display: none;">
                                                        Error: Reply cannot be empty
                                                    </div>
                                                    <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                </div>
                                            </div>
                                            </form>
                                            <div class="reply-list" style="display: none;"></div>
                                        </div>
                                    </div>
                                </div>
                            `.replace(':commentId', data.comment.id);

                                commentList.insertAdjacentHTML('afterbegin', newCommentHtml);
                                this.reset();
                                initializeDropdowns();
                            }
                        } else {
                            // Display error messages
                            errorDiv.textContent = data.error || 'Your comment is empty';
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        errorDiv.textContent = 'Something went wrong';
                    });
            });


            // for submission of reply forms
            document.getElementById('comment-list')?.addEventListener('submit', function(event) {
                if (event.target.closest('.reply-form')) {
                    event.preventDefault();
                    const form = event.target;
                    const formData = new FormData(form);
                    const parentId = form.closest('.comment').dataset.commentId;
                    const errorDiv = form.querySelector('#comment-form-error');

                    // Reset error display
                    errorDiv.style.display = 'none';
                    errorDiv.textContent = '';

                    fetch(form.action.replace(':commentId', parentId), {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content')
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const replyList = form.closest('.reply-list') || form.closest(
                                    '.comment').querySelector('.reply-list');
                                if (replyList) {
                                    const newReplyHtml = `
                                    <div class="comment reply" data-comment-id="${data.reply.id}">
                                        <div class="d-flex">
                                            <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
                                            <div class="w-100">
                                                <div class="d-flex justify-content-between align-items-start">
                                                    <div>
                                                        <div class="comment-author">${data.reply.user_name}</div>
                                                        <div class="comment-time">${data.reply.created_at}</div>
                                                    </div>
                                                    <div class="dropdown">
                                                        <button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton${data.reply.id}" data-bs-toggle="dropdown" aria-expanded="false">
                                                            <i class="fa-solid fa-ellipsis-vertical"></i>
                                                        </button>
                                                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton${data.reply.id}">
                                                            <li><a class="dropdown-item" href="#" data-action="edit" data-comment-id="${data.reply.id}">Edit</a></li>
                                                            <li><a class="dropdown-item text-danger" href="#" data-action="delete" data-comment-id="${data.reply.id}">Delete</a></li>
                                                        </ul>
                                                    </div>
                                                </div>
                                                <div class="comment-body">${data.reply.parent_name ? '<a href="#">' + '@' + data.reply.parent_name + '</a> ' : ''}${data.reply.content}</div>
                                                <div class="comment-actions">
                                                    <a href="#" class="like-button" data-action="like" data-comment-id="${data.reply.id}">
                                                        <i class="fa-solid fa-thumbs-up"></i>
                                                        <span class="like-dislike-count">0</span>
                                                    </a>
                                                    <a href="#" class="dislike-button" data-action="dislike" data-comment-id="${data.reply.id}">
                                                        <i class="fa-solid fa-thumbs-down"></i>
                                                        <span class="like-dislike-count">0</span>
                                                    </a>
                                                    <a href="#" class="reply-link" data-comment-id="${data.reply.id}" data-author="${data.reply.user_name}">
                                                        <i class="fa-solid fa-reply"></i> Reply
                                                    </a>
                                                </div>
                                                <form class="reply-form" action="{{ route('replies.store', ':commentId') }}" method="POST">
                                                    @csrf
                                                        <div class="d-flex flex-column">
                                                            <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                                                            <div class="d-flex justify-content-between  mt-2">
                                                                <div id="comment-form-error" class="text-danger" style="display: none;">
                                                                    Error: Reply cannot be empty
                                                                </div>
                                                                <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                                                            </div>
                                                        </div>
                                                </form>
                                                <div class="reply-list" style="display: none;"></div>
                                            </div>
                                        </div>
                                    </div>
                                    `.replace(':commentId', data.reply.id);

                                    replyList.insertAdjacentHTML('beforeend', newReplyHtml);
                                    form.reset();
                                    initializeDropdowns();
                                }
                            } else {
                                // Display error message
                                errorDiv.textContent = data.message || 'Error posting reply';
                                errorDiv.style.display = 'block';
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            // Display error message
                            errorDiv.textContent = 'Something went wrong';
                            errorDiv.style.display = 'block';
                        });
                }
            });




            // for reply link click to show reply form
            document.getElementById('comment-list')?.addEventListener('click', function(event) {
                if (event.target.closest('.reply-link')) {
                    event.preventDefault();
                    const replyForm = event.target.closest('.comment').querySelector('.reply-form');
                    if (replyForm) {
                        replyForm.style.display = replyForm.style.display === 'block' ? 'none' : 'block';
                    }
                }
            });
        });

        function initializeDropdowns() {
            const dropdowns = document.querySelectorAll('.dropdown-toggle:not(.initialized)');
            dropdowns.forEach(dropdown => {
                new bootstrap.Dropdown(dropdown);
                dropdown.classList.add('initialized');
            });
        }

        function toggleReplies(element) {
            const replyList = element.nextElementSibling.nextElementSibling;
            const isVisible = replyList.style.display === 'block';
            replyList.style.display = isVisible ? 'none' : 'block';
            element.textContent = isVisible ? 'View replies' : 'Hide replies';
        }
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.bookmark-toggle').forEach(function(button) {
                button.addEventListener('click', function() {
                    const fileId = this.getAttribute('data-file-id');
                    const button = this;

                    fetch("{{ route('bookmark.toggle') }}", {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '{{ csrf_token() }}'
                            },
                            body: JSON.stringify({
                                file_id: fileId
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status === 'added') {
                                button.classList.add('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks-fill" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5z"/>
                                        <path d="M4.268 1A2 2 0 0 1 6 0h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L13 13.768V2a1 1 0 0 0-1-1z"/>
                                    </svg>`;
                            } else if (data.status === 'removed') {
                                button.classList.remove('bookmark-active');
                                button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                                        class="bi bi-bookmarks" viewBox="0 0 16 16">
                                        <path d="M2 4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v11.5a.5.5 0 0 1-.777.416L7 13.101l-4.223 2.815A.5.5 0 0 1 2 15.5zm2-1a1 1 0 0 0-1 1v10.566l3.723-2.482a.5.5 0 0 1 .554 0L11 14.566V4a1 1 0 0 0-1-1z"/>
                                        <path d="M4.268 1H12a1 1 0 0 1 1 1v11.768l.223.148A.5.5 0 0 0 14 13.5V2a2 2 0 0 0-2-2H6a2 2 0 0 0-1.732 1"/>
                                    </svg>`;
                            }
                        })
                        .catch(error => console.error('Error:', error));
                });
            });
        });
    </script>
@endsection


@foreach ($replies as $reply)
    <div class="comment reply" data-comment-id="{{ $reply->id }}">
        <div class="d-flex">
            <img src="https://static.xx.fbcdn.net/rsrc.php/v1/yi/r/odA9sNLrE86.jpg" alt="avatar" class="comment-avatar">
            <div class="w-100">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="comment-author">{{ $reply->user->name }}</div>
                        <div class="comment-time">{{ $reply->created_at->diffForHumans() }}</div>
                    </div>
                    @if ($reply->user_id === auth()->id())
                        <div class="dropdown">
                            <button class="btn btn-link dropdown-toggle" type="button"
                                id="dropdownMenuButton{{ $reply->id }}" data-bs-toggle="dropdown"
                                aria-expanded="false">
                                <i class="fa-solid fa-ellipsis-vertical"></i>
                            </button>
                            <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton{{ $reply->id }}">
                                <li><a class="dropdown-item" href="#" data-action="edit"
                                        data-comment-id="{{ $reply->id }}">Edit</a>
                                </li>
                                <li><a class="dropdown-item text-danger" href="#" data-action="delete"
                                        data-comment-id="{{ $reply->id }}">Delete</a>
                                </li>
                            </ul>
                        </div>
                    @endif
                </div>
                <div class="comment-body">
                    @if ($reply->parent)
                        <a href="#" class="reply-mention">{{ '@' . $reply->parent->user->name }}</a>
                    @endif
                    <span class="reply-content">{{ $reply->content }}</span>
                </div>
                <div class="comment-actions">
                    <a href="#"
                        class="like-button {{ $reply->likes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                        data-action="like" data-comment-id="{{ $reply->id }}">
                        <i class="fa-solid fa-thumbs-up"></i>
                        <span class="like-dislike-count">{{ $reply->likes }}</span>
                    </a>
                    <a href="#"
                        class="dislike-button {{ $reply->dislikes()->where('user_id', auth()->id())->exists() ? 'active' : '' }}"
                        data-action="dislike" data-comment-id="{{ $reply->id }}">
                        <i class="fa-solid fa-thumbs-down"></i>
                        <span class="like-dislike-count">{{ $reply->dislikes }}</span>
                    </a>
                    <a href="#" class="reply-link" data-comment-id="{{ $reply->id }}"
                        data-author="{{ $reply->user->name }}">
                        <i class="fa-solid fa-reply"></i> Reply
                    </a>
                </div>
                <form class="reply-form" action="{{ route('replies.store', $reply) }}" method="POST">
                    @csrf
                    <div class="d-flex flex-column">
                        <textarea name="content" class="form-control comment-input" placeholder="Write a reply..." rows="2"></textarea>
                        <div class="d-flex justify-content-between  mt-2">
                            <div id="comment-form-error" class="text-danger" style="display: none;">
                                Error: Reply cannot be empty
                            </div>
                            <button type="submit" class="btn btn-primary ms-auto">Post Reply</button>
                        </div>
                    </div>

                </form>
                <div id="edit-comment-template" style="display: none;">
                    <div class="edit-comment-form">
                        <textarea class="form-control edit-comment-input" rows="3"></textarea>
                        <div class="text-end mt-2">
                            <button type="button" class="btn btn-primary save-edit-button">Save</button>
                            <button type="button" class="btn btn-secondary cancel-edit-button">Cancel</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @include('materials.comment', ['replies' => $reply->replies])
@endforeach
Harness the power of next-gen asset tokenization platform development with Maticz. A trusted asset tokenization platform development company like Maticz helps business convert their illiquid asset into a tradable digital token. Tokenization of high-value assets through blockchain offers a secured transaction with transparency. This also offers a fragmented property ownership of a large asset. Fuel your business growth by digitalizing your high-value asset with Maticz.
function woo_checkout_custom_coupon_form(){
	if ( ! wc_coupons_enabled() ) { // @codingStandardsIgnoreLine.
		return;
	}
?>
<div class="mini-cart-nm-coupon">
	<div class="mini-cart-nm-coupon-heading">Enter your discount code</div>
    <div class="nm-coupon" style="display: flex;">
       <input type="text" id="nm-coupon-code" class="input-text nm-coupon-code" name="nm_coupon_code" value="" placeholder="">
       <button type="button" id="nm-apply-coupon-btn" class="button" name="nm_apply_coupon" value="" onclick="applyCoupon(this)" style="white-space: nowrap;"><?php esc_html_e( 'ACTIVATE', 'woocommerce' ); ?></button>
    </div>
    <div class="nm-coupon-notify" style="display: none; color: #FF0000;"></div>
</div>
<script type="text/javascript">
function applyCoupon(button) {
    let form = button.closest('.nm-coupon');
	button.innerText = 'ACTIVATE...';
    let couponCode = form.querySelector(".nm-coupon-code").value;
    let ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    
    jQuery.ajax({
        type: "GET",
        url: ajaxurl,
        dataType: 'json',
        data: 'coupon_code=' + couponCode + '&action=custom_apply_coupon',
        success: function (data) {
            if (data.status === 'success') {
                jQuery(document.body).trigger('wc_fragment_refresh');
                
            } else if (data.status === 'already_used') {
                jQuery('.nm-coupon-notify').html('Coupon already used!');
                jQuery('.nm-coupon-notify').show();
            } else {
                jQuery('.nm-coupon-notify').html('Coupon is not valid!');
                jQuery('.nm-coupon-notify').show();
            }
			if (jQuery('body').hasClass('woocommerce-checkout'))
                    jQuery(document.body).trigger('update_checkout');
        },
    });
}
// Remove coupon script
(function($) {
    $('body').on('click', '.woocommerce-remove-coupon', function(e) {
        e.preventDefault();
        let ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
        var coupon = $(this).data('coupon');
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'remove_coupon',
                coupon: coupon,
            },
            success: function(response) {
                jQuery(document.body).trigger('wc_fragment_refresh');
            },
            error: function(error) {
                console.log('Error:', error);
            }
        });
    });
})(jQuery);	
</script>
<?php    
}
add_action( 'woo_custom_checkout_coupon_form', 'woo_checkout_custom_coupon_form',10 );

add_action('wp_ajax_custom_apply_coupon', 'custom_apply_coupon');
add_action('wp_ajax_nopriv_custom_apply_coupon', 'custom_apply_coupon');

function custom_apply_coupon() {
    $coupon_code = isset($_GET['coupon_code']) ? $_GET['coupon_code'] : '';
    $coupon_code = sanitize_text_field($coupon_code);

    // Check if the coupon is already applied
    if (WC()->cart->has_discount($coupon_code)) {
        echo json_encode(array('status' => 'already_used'));
    } else {
        // Apply coupon
        $applied = WC()->cart->apply_coupon($coupon_code);
        if ($applied) {
            echo json_encode(array('status' => 'success'));
        } else {
            echo json_encode(array('status' => 'invalid'));
        }
    }
    wp_die();
}

add_action('wp_ajax_remove_coupon', 'remove_coupon_from_cart');
add_action('wp_ajax_nopriv_remove_coupon', 'remove_coupon_from_cart');

function remove_coupon_from_cart() {
    if (isset($_POST['coupon'])) {
        $coupon_code = sanitize_text_field($_POST['coupon']);
        WC()->cart->remove_coupon($coupon_code);
        wc_clear_notices(); 
        
        wp_send_json_success();
    } else {
        wp_send_json_error('Coupon code not provided.');
    }
}
.parent-container{
  //defining a grid container
  display: grid;
  //defining rows and columns
  grid-template: 50px 50px / 50px 50px;
  //defining a row and column gap
  gap: 20px 50px;
  
  
}

When we use the grid-template propertie, we are explicitly defining grid tracks to lay out our grid items. But when the grid needs more tracks for extra content, it will implicitly define new grid tracks. Additionally, the size values established from our grid-template propertie are not carried over into these implicit grid tracks. But we can define values for the implicit grid tracks.

Let’s say we want any new rows to stay the same value as our explicit row track sizes:

.parent-container {
  display: grid;
  grid-template: 50px 50px;
  grid-auto-rows: 50px;
}
// Driver function
        for(int i = 0; i < V; i++){
            if(!vis[i]) {
                if(cycleBFS(i, vis, adj)) return true;
            }
        }



// cycle check fun by BFS
    bool cycleBFS(int src, vector<int> &vis, vector<int> adj[]){
        queue<pair<int,int>> q;
        vis[src] = 1;
        q.push({src,-1});
        
        while(!q.empty()){
            int node = q.front().first;
            int parent = q.front().second;
            q.pop();
            
            for(auto it: adj[node]){
                if(!vis[it]){
                    vis[it] = 1;
                    q.push({it, node});
                }
                else if(parent != it){
                    return true;
                }
            }
        }
        return false;
    }




add_action('init', 'aovup_register_awaiting_dispatch_order_status');
function aovup_register_awaiting_dispatch_order_status() {
    register_post_status('wc-awaiting-dispatch', array(
        'label'                     => 'Awaiting Dispatch',
        'public'                    => true,
        'exclude_from_search'       => false,
        'show_in_admin_all_list'    => true,
        'show_in_admin_status_list' => true,
        'label_count'               => _n_noop('Awaiting Dispatch <span class="count">(%s)</span>', 'Awaiting Dispatch <span class="count">(%s)</span>')
    ));
}

add_filter('wc_order_statuses', 'aovup_add_awaiting_dispatch_to_order_statuses');
function aovup_add_awaiting_dispatch_to_order_statuses($order_statuses) {
    $order_statuses['wc-awaiting-dispatch'] = 'Awaiting Dispatch';
    return $order_statuses;
}

add_filter('bulk_actions-edit-shop_order', 'aovup_add_awaiting_dispatch_bulk_action');
function aovup_add_awaiting_dispatch_bulk_action($bulk_actions) {
    // Add a new bulk action named "Mark Awaiting Dispatch"
    $bulk_actions['mark_awaiting-dispatch'] = 'Mark Awaiting Dispatch';
    return $bulk_actions;
}

add_filter('handle_bulk_actions-edit-shop_order', 'aovup_handle_mark_awaiting_dispatch_bulk_action', 10, 3);
function aovup_handle_mark_awaiting_dispatch_bulk_action($redirect_to, $doaction, $post_ids) {
    if ($doaction !== 'mark_awaiting-dispatch') {
        return $redirect_to;
    }

    foreach ($post_ids as $post_id) {
        $order = wc_get_order($post_id);
        $order->update_status('awaiting-dispatch');
    }

    $redirect_to = add_query_arg('bulk_awaiting_dispatch_orders', count($post_ids), $redirect_to);
    return $redirect_to;
}
add_filter( 'wc_order_statuses', 'wc_renaming_order_status' );
function wc_renaming_order_status( $order_statuses ) {
    foreach ( $order_statuses as $key => $status ) {
        if ( 'wc-completed' === $key ) 
            $order_statuses['wc-completed'] = _x( 'Order Received', 'Order status', 'woocommerce' );
    }
    return $order_statuses;
}

/**configure your WordPress site to send emails via the Brevo API**/

function send_email_via_brevo($to, $subject, $message, $headers = '', $attachments = []) {
    $api_url = 'https://api.brevo.com/v3/smtp/email';
    $api_key = '123'; // Your Brevo API key

    // Email data structure
    $email_data = [
        'sender' => [
            'email' => 'contact@example.com', // Your email address
            'name' => 'Your Name' // Your name
        ],
        'to' => [
            [
                'email' => $to, // Recipient's email
                'name' => '' // Recipient's name (optional)
            ]
        ],
        'subject' => $subject,
        'htmlContent' => $message
    ];

    // Headers for the API request
    $request_headers = [
        'Content-Type: application/json',
        'api-key: ' . $api_key
    ];

    // Arguments for the API request
    $args = [
        'body' => json_encode($email_data),
        'headers' => $request_headers,
        'method' => 'POST',
        'data_format' => 'body'
    ];

    // Send the API request
    $response = wp_remote_post($api_url, $args);

    // Handle any errors
    if (is_wp_error($response)) {
        error_log('Email sending failed: ' . $response->get_error_message());
        return false;
    }

    // Log the response
    $response_body = wp_remote_retrieve_body($response);
    error_log('Email sent response: ' . $response_body);

    return true;
}

function override_wp_mail($args) {
    return send_email_via_brevo($args['to'], $args['subject'], $args['message'], $args['headers'], $args['attachments']);
}

add_filter('wp_mail', 'override_wp_mail', 10, 1);

MID({!$Flow.FaultMessage}, FIND('FIELD_CUSTOM_VALIDATION_EXCEPTION: ', {!$Flow.FaultMessage}) + LEN('FIELD_CUSTOM_VALIDATION_EXCEPTION: '), FIND('. Você pode consultar valores de ExceptionCode', {!$Flow.FaultMessage}) - FIND('FIELD_CUSTOM_VALIDATION_EXCEPTION: ', {!$Flow.FaultMessage}) - LEN('FIELD_CUSTOM_VALIDATION_EXCEPTION: '))
git clone https://github.com/yourusername/route-optimization.git
cd route-optimization
pip install -r requirements.txt
#include <bits/stdc++.h>
#include <iostream>
using namespace std;

#define MOD 1000000007
#define ll long long int
#define fr(i, a, b) for (int i = a; i < b; i++)

inline int binaryExponentiation(ll base, int exp, int mod = MOD) {
    ll result = 1;
    while (exp) {
        if (exp & 1) result = (result * base) % mod;
        base = (base * base) % mod;
        exp >>= 1;
    }
    return (int)result;
}

void solve() {
    int n;
    cin >> n;
    ll answer = 0;
    fr(i, 1, n) {
        ll current = binaryExponentiation(2, n - i - 1);
        current = (2 * current * (n - i)) % MOD;
        current = (current * i) % MOD;
        current = (current * i) % MOD;
        answer = (answer + current) % MOD;
    }
    cout << answer << endl;
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    int t;
    cin >> t;
    while (t--) solve();
    return 0;
}
#include<bits/stdc++.h>
#define ll long long
using namespace std;


bool is_valid(int x,int y,int r,int c,vector<vector<char>>&v){
    if(x<1 || x>r || y<1 || y>c || v[x][y]=='#') return false;
    return true;
}


void dfs(int &x,int &y,vector<vector<char>>&v,string &s,int r,int c,int &idx,int l){
    if(idx<l && s[idx]=='U' && is_valid(x,y,r,c,v)){
       dfs(x-1,y,v,s,r,c,idx+1);
    }
    if(idx<l && s[idx]=='L' && is_valid(x,y,r,c,v)){
       dfs(x,y-1,v,s,r,c,idx+1);
    }
    
    if(idx<l && s[idx]=='R' && is_valid(x,y,r,c,v)){
       dfs(x,y+1,v,s,r,c,idx+1);
    }
    
    if(idx<l && s[idx]=='D' && is_valid(x,y,r,c,v)){
       dfs(x+1,y,v,s,r,c,idx+1);
    }
    return;
}


int main(){
    int r,c,x,y;
    cin>>r>>c>>x>>y;
    vector<vector<char>>v(r,vector<char>(c));
    for(int i=0;i<r;i++){
        for(int j=0;j<c;j++){
            cin>>a[i][j];
        }
    }
    string s;
    cin>>s;
    int l=s.length();
    
    dfs(x,y,v,s,r,c,0,l);
    cout<<x<<" "<<y;
    return 0;
    
}
@media (max-width: 600px) {
    nav ul {
        text-align: center;
    }

    nav ul li {
        display: block;
        margin: 0.5rem 0;
    }
}
<tts service="android" speed="1.0" voice="en-US" style="display: none">{{En}}</tts>
star

Thu Aug 08 2024 15:54:40 GMT+0000 (Coordinated Universal Time)

@zily

star

Thu Aug 08 2024 15:54:06 GMT+0000 (Coordinated Universal Time)

@zily

star

Thu Aug 08 2024 15:54:06 GMT+0000 (Coordinated Universal Time)

@zily

star

Thu Aug 08 2024 15:52:03 GMT+0000 (Coordinated Universal Time)

@zily

star

Thu Aug 08 2024 15:14:30 GMT+0000 (Coordinated Universal Time)

@Sayed

star

Thu Aug 08 2024 13:06:35 GMT+0000 (Coordinated Universal Time) https://medium.com/@prashantramnyc/how-to-implement-google-authentication-in-node-js-using-passport-js-9873f244b55e

@abhi_550

star

Thu Aug 08 2024 11:37:34 GMT+0000 (Coordinated Universal Time) https://www.rginfotech.com/games/poker-game-development/

@kishanrg ##poker ##pokergame ##pokergamedevelopment ##gameapp

star

Thu Aug 08 2024 11:12:41 GMT+0000 (Coordinated Universal Time) https://www.guidingtech.com/how-to-disable-hyper-v-windows/

@Curable1600 #windows

star

Thu Aug 08 2024 10:38:45 GMT+0000 (Coordinated Universal Time) https://www.beleaftechnologies.com/crypto-casino-game-development

@smithtaylor ##crypto #casino ##game

star

Thu Aug 08 2024 08:09:55 GMT+0000 (Coordinated Universal Time)

@Merel1988 #php

star

Thu Aug 08 2024 05:28:45 GMT+0000 (Coordinated Universal Time)

@signup

star

Thu Aug 08 2024 04:21:05 GMT+0000 (Coordinated Universal Time)

@signup

star

Thu Aug 08 2024 03:10:01 GMT+0000 (Coordinated Universal Time) https://aovup.com/woocommerce/custom-order-status/

@mediasolutions

star

Wed Aug 07 2024 22:25:04 GMT+0000 (Coordinated Universal Time) https://developer.wordpress.org/plugins/plugin-basics/header-requirements/

@mediasolutions #php

star

Wed Aug 07 2024 22:24:53 GMT+0000 (Coordinated Universal Time) https://developer.wordpress.org/plugins/plugin-basics/header-requirements/

@mediasolutions #php

star

Wed Aug 07 2024 22:24:32 GMT+0000 (Coordinated Universal Time) https://developer.wordpress.org/plugins/plugin-basics/header-requirements/

@mediasolutions #php

star

Wed Aug 07 2024 21:31:35 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Wed Aug 07 2024 21:00:10 GMT+0000 (Coordinated Universal Time)

@wasim_mm1

star

Wed Aug 07 2024 20:45:12 GMT+0000 (Coordinated Universal Time)

@wasim_mm1

star

Wed Aug 07 2024 18:11:55 GMT+0000 (Coordinated Universal Time)

@Sayed

star

Wed Aug 07 2024 17:49:48 GMT+0000 (Coordinated Universal Time)

@Sayed

star

Wed Aug 07 2024 16:25:03 GMT+0000 (Coordinated Universal Time)

@kblanka #javascript

star

Wed Aug 07 2024 15:43:25 GMT+0000 (Coordinated Universal Time) https://github.com/darkroomengineering/lenis

@zily

star

Wed Aug 07 2024 15:24:15 GMT+0000 (Coordinated Universal Time)

@Sayed

star

Wed Aug 07 2024 15:24:14 GMT+0000 (Coordinated Universal Time)

@Sayed

star

Wed Aug 07 2024 13:51:35 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/integer-to-english-words/?envType

@0541 #java

star

Wed Aug 07 2024 12:07:12 GMT+0000 (Coordinated Universal Time)

@Sayed

star

Wed Aug 07 2024 10:07:59 GMT+0000 (Coordinated Universal Time) https://www.reddit.com/r/Windows11/comments/15txhve/comment/jwr1l87/

@Curable1600 #windows #ntlite

star

Wed Aug 07 2024 10:05:12 GMT+0000 (Coordinated Universal Time) https://htm-rapportage.eu.qlikcloud.com/dataloadeditor/app/7cead63c-b08c-4c31-831d-fb32b17f8310

@bogeyboogaard

star

Wed Aug 07 2024 09:00:03 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed Aug 07 2024 08:50:14 GMT+0000 (Coordinated Universal Time)

@signup

star

Wed Aug 07 2024 02:12:07 GMT+0000 (Coordinated Universal Time)

@quanganh141220 #php #single #product

star

Tue Aug 06 2024 17:42:28 GMT+0000 (Coordinated Universal Time)

@wasim_mm1

star

Tue Aug 06 2024 14:05:29 GMT+0000 (Coordinated Universal Time) https://www.ntlite.com/community/index.php?threads/content-delivery-manager-vs-automatic-installation-of-sponsored-apps.4684/#post-45667

@Curable1600 #windows #ntlite

star

Tue Aug 06 2024 13:32:00 GMT+0000 (Coordinated Universal Time)

@Sayed

star

Tue Aug 06 2024 11:44:03 GMT+0000 (Coordinated Universal Time) https://maticz.com/asset-tokenization-platform-development

@carolinemax ##maticz ##usa #assettokenization platform development

star

Tue Aug 06 2024 11:00:28 GMT+0000 (Coordinated Universal Time)

@ngoctran #php

star

Tue Aug 06 2024 09:40:50 GMT+0000 (Coordinated Universal Time)

@NoFox420 #javascript

star

Tue Aug 06 2024 06:35:19 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/problems/detect-cycle-in-an-undirected-graph/1

@w3yogesh #c++

star

Tue Aug 06 2024 05:45:33 GMT+0000 (Coordinated Universal Time) https://aovup.com/woocommerce/custom-order-status/

@mediasolutions

star

Tue Aug 06 2024 01:50:25 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/37790855/renaming-woocommerce-order-status

@mediasolutions

star

Mon Aug 05 2024 19:53:31 GMT+0000 (Coordinated Universal Time)

@peron97 #html

star

Mon Aug 05 2024 17:57:38 GMT+0000 (Coordinated Universal Time)

@tanushahaha

star

Mon Aug 05 2024 17:05:19 GMT+0000 (Coordinated Universal Time) https://www.codechef.com/problems/SQING

@utp #c++

star

Mon Aug 05 2024 16:57:34 GMT+0000 (Coordinated Universal Time)

@rohan_112d

star

Mon Aug 05 2024 16:16:34 GMT+0000 (Coordinated Universal Time)

@ibn_shakeerah

star

Mon Aug 05 2024 15:32:50 GMT+0000 (Coordinated Universal Time)

@trvndng #javascript

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension