@extends('admin.layouts.app')

@section('title', $title)

@section('content')
    <div class="col-md-12">
        @include('admin.layouts.notifications')

        <!-- Page Heading & Search Area -->
        <div class="row mb-3">
            <div class="col-md-9">
                <h4 class="c-grey-900">{{ $title }} <a class="btn btn-primary" href="{{ route('ch-admin.blog.categories.create') }}"><i class="ti-plus"></i></a></h4>
            </div>
            <div class="col-md-3">
                <form method="GET" action="{{ route('ch-admin.blog.categories.index') }}">
                    <div class="input-group">
                        <input type="text" name="search" class="form-control" placeholder="Search…" aria-label="Search" value="{{ request('search') }}">
                        <button class="btn btn-info" type="submit"><i class="ti ti-search"></i></button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Main Content -->
        <div class="row">
            <div class="bgc-white bd bdrs-3 p-20 mB-20">
                <!-- Bulk Delete Button -->
                <div class="row mb-3">
                    <div class="col-md-12">
                        <button class="btn btn-danger" id="delete-categories"><i class="ti-trash"></i> Delete</button>
                    </div>
                </div>

                <!-- Categories Table -->
                <div class="row">
                    <table class="table table-striped">
                        <thead>
                        <tr>
                            <th><input type="checkbox" id="select-all" class="form-check-input"></th>
                            <th>Name</th>
                            <th>Description</th>
                            <th>Posts Count</th>
                            <th>Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        @if($categories->isEmpty())
                            <tr><td colspan="5" class="text-center">No records found.</td></tr>
                        @else
                            @foreach($categories as $category)
                                <tr>
                                    <td><input type="checkbox" class="form-check-input select-category" value="{{ $category->id }}"></td>
                                    <td>{{ $category->name }}</td>
                                    <td>{!! nl2br($category->description) !!}</td>
                                    <td>{{ $category->posts->count() }}</td>
                                    <td class="d-flex flex-row">
                                        <a href="{{ route('ch-admin.blog.categories.edit', $category->id) }}" class="btn btn-sm btn-primary me-1"><i class="ti-pencil"></i></a>
                                        <button type="button" class="btn btn-sm btn-danger delete-category" data-category-id="{{ $category->id }}"><i class="ti-trash"></i></button>
                                    </td>
                                </tr>
                            @endforeach
                        @endif
                        </tbody>
                    </table>

                    @if($categories->hasPages())
                        <div class="mt-4">
                            {{ $categories->links() }}
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>

    <!-- Delete Category Modal -->
    <div class="modal fade" id="deleteCategoryModal" tabindex="-1" role="dialog" aria-labelledby="deleteCategoryModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteCategoryModalLabel">Delete Category</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <div class="modal-body">
                    <p>Do you also want to delete the associated posts?</p>

                    <div class="form-group" id="category-dropdown" style="display: none;">
                        <p>Choose a category to move the associated posts.</p>
                        <label for="category-select">Select Category</label>
                        <select name="category-select" id="category-select" class="form-control" required>
                            <option value="" disabled selected>Select a Category</option>
                            @foreach($allCategories as $category)
                                <option value="{{ $category->id }}">{{ $category->name }}</option>
                            @endforeach
                        </select>
                        <button type="button" class="btn btn-danger mt-3" id="delete-category-without-posts-done">Delete &amp; Move</button>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" id="delete-categories-with-posts">Yes</button>
                    <button type="button" class="btn btn-danger" id="delete-categories-without-posts">No</button>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script src="{{url('assets/custom/js/axios.min.js')}}"></script>
    <script>
        const selectAllCheckbox = document.getElementById('select-all');
        const categoryCheckboxes = document.querySelectorAll('.select-category');
        const bulkDeleteButton = document.getElementById('delete-categories');
        const singleDeleteButton = document.querySelectorAll('.delete-category');

        function toggleBulkDeleteButton() {
            bulkDeleteButton.disabled = !Array.from(categoryCheckboxes).some(checkbox => checkbox.checked);
        }

        selectAllCheckbox.addEventListener('click', function () {
            const isChecked = this.checked;
            categoryCheckboxes.forEach(checkbox => {
                checkbox.checked = isChecked;
            });
            toggleBulkDeleteButton();
        });

        categoryCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function () {
                const allChecked = [...categoryCheckboxes].every(checkbox => checkbox.checked);
                selectAllCheckbox.checked = allChecked;
                toggleBulkDeleteButton();
            });
        });

        toggleBulkDeleteButton();

        // Function to get selected categories for bulk delete
        function getSelectedCategories() {
            const selectedCategories = [];
            document.querySelectorAll('.select-category:checked').forEach(function (checkbox) {
                selectedCategories.push(checkbox.value);
            });
            return selectedCategories;
        }

        // New Code for Category Deletion
        let categoryIds = [];
        let singleDelete = null;

        const deleteCategoryModal = new bootstrap.Modal(document.getElementById('deleteCategoryModal'));

        // Reset Modal when it is open
        deleteCategoryModal._element.addEventListener('hide.bs.modal', function () {
            categoryIds = [];
            singleDelete = null;
            categorySelect.value = "";
            categoryDropdown.style.display = 'none';
            deleteCategoriesWithPostsButton.style.display = 'inline-block';
            deleteCategoriesWithoutPostsButton.style.display = 'inline-block';
            deleteCategoryWithoutPostsWithoutMovingCategoryId.disabled = true;
            updateCategoryDropdown();
        });

        const deleteCategoriesWithPostsButton = document.getElementById('delete-categories-with-posts');
        const deleteCategoriesWithoutPostsButton = document.getElementById('delete-categories-without-posts');
        const categoryDropdown = document.getElementById('category-dropdown');
        const deleteCategoryWithoutPostsWithoutMovingCategoryId = document.getElementById('delete-category-without-posts-done');
        const categorySelect = document.getElementById('category-select');

        deleteCategoryWithoutPostsWithoutMovingCategoryId.disabled = true;

        categorySelect.addEventListener('change', function () {
            if (categorySelect.value) {
                deleteCategoryWithoutPostsWithoutMovingCategoryId.disabled = false;
            } else {
                deleteCategoryWithoutPostsWithoutMovingCategoryId.disabled = true;
            }
        });

        // Remove the selected Category from Dropdown in the Modal
        function updateCategoryDropdown() {
            const options = categorySelect.options;

            for (let i = 0; i < options.length; i++) {
                const option = options[i];

                if (categoryIds.includes(option.value)) {
                    option.style.display = 'none';
                } else {
                    option.style.display = 'block';
                }
            }
        }

        // Event listener for the single delete button
        singleDeleteButton.forEach(button => {
            button.addEventListener('click', function () {
                singleDelete = true;
                categoryIds = [];
                let categoryId = button.getAttribute('data-category-id');
                categoryIds.push(categoryId);

                updateCategoryDropdown();
                deleteCategoryModal.show();
            });
        });

        // Multiple Categories Delete Button Event
        bulkDeleteButton.addEventListener('click', function () {
            singleDelete = false;
            categoryIds = [];
            categoryIds = getSelectedCategories();
            updateCategoryDropdown();
            deleteCategoryModal.show();
        });

        // Method for delete Categories with Posts
        deleteCategoriesWithPostsButton.addEventListener('click', function () {
            httpClient.delete('{{ route("ch-admin.blog.categories.destroy") }}', {
                data: {
                    categoryIds: categoryIds,
                    deletePosts: true,
                    singleDelete: singleDelete,
                }
            })
                .then((response) => {
                    if (response.data.success) {
                        window.location.href = '{{ route("ch-admin.blog.categories.index") }}';
                    } else {
                        alert('Failed to delete categories and posts.');
                    }
                })
                .catch((error) => {
                    console.error(error);
                    alert('An error occurred. Please try again.');
                });
        });

        // Categories without Posts Button Action
        deleteCategoriesWithoutPostsButton.addEventListener('click', function () {
            categoryDropdown.style.display = 'block';
            deleteCategoriesWithPostsButton.style.display = 'none';
            deleteCategoriesWithoutPostsButton.style.display = 'none';
        });

        // Method for delete Categories without Posts with MovingCategoryId
        deleteCategoryWithoutPostsWithoutMovingCategoryId.addEventListener('click', function () {
            const movingCategoryId = categorySelect.value;

            httpClient.delete('{{ route("ch-admin.blog.categories.destroy") }}', {
                data: {
                    categoryIds: categoryIds,
                    deletePosts: false,
                    singleDelete: singleDelete,
                    movingCategoryId: movingCategoryId,
                }
            })
                .then((response) => {
                    if (response.data.success) {
                        window.location.href = '{{ route("ch-admin.blog.categories.index") }}';
                    } else {
                        alert('Failed to delete categories and move posts.');
                    }
                })
                .catch((error) => {
                    console.error(error);
                    alert('An error occurred. Please try again.');
                });
        });
    </script>
@endpush

