@extends('admin.layouts.app')

@section('title', $title)

@section('content')
    <div class="col-md-12">
        <!-- 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.products.create') }}"><i class="ti-plus"></i></a></h4>
            </div>
            <div class="col-md-3">
                <form method="GET" action="{{ route('ch-admin.products.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>
                    <!-- Include current filter values as hidden inputs -->
                    <input type="hidden" name="category_id" value="{{ request('category_id') }}">
                </form>
            </div>
        </div>

        <!-- Main Content -->
        <div class="row">
            <div class="bgc-white bd bdrs-3 p-20 mB-20">
                <!-- Filters Section -->
                <div class="row mb-3">
                    <form method="GET" action="{{ route('ch-admin.products.index') }}" class="d-flex align-items-center gap-3 w-100">
                        <!-- Filter by Categories -->
                        <div class="flex-shrink-0">
                            <select name="category_id" class="form-control">
                                <option value="">All Categories</option>
                                @foreach($categories as $category)
                                    <option value="{{ $category->id }}" {{ request('category_id') == $category->id ? 'selected' : '' }}>{{ $category->name }}</option>
                                @endforeach
                            </select>
                        </div>

                        <!-- Action Buttons -->
                        <div class="flex-shrink-0">
                            <button type="submit" class="btn btn-info">Apply Filters</button>
                            @if(request('category_id') || request('search'))
                                <a href="{{ route('ch-admin.products.index') }}" class="btn btn-secondary">Reset</a>
                            @endif
                            <button class="btn btn-danger" id="delete-bulk-btn" type="button"><i class="ti-trash"></i> Delete</button>
                        </div>
                        <input type="hidden" name="search" value="{{ request('search') }}">
                    </form>
                </div>

                <!-- Products Table -->
                <div class="row">
                    <table class="table table-striped">
                        <thead>
                        <tr>
                            <th><input type="checkbox" id="select-all" class="form-check-input"></th>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Category</th>
                            <th>Total Plans</th>
                            <th>Total Addons</th>
                            <th>Starting price/Price</th>
                            <th>Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        @forelse($products as $product)
                            <tr>
                                <td><input type="checkbox" class="form-check-input select-product" value="{{ $product->id }}"></td>
                                <th>{{ $product->id }}</th>
                                <td>{{ $product->name }}</td>
                                <td>{{ $product->category->name }}</td>
                                <td>{{ $product->plans->count() }}</td>
                                <td>{{ $product->addons->count() }}</td>
                                <td>
                                    @if($product->plans->count() > 0 && $product->plans->first()->pricingTiers->count() > 0)
                                        {{ $product->plans->first()->pricingTiers->first()->price }}
                                    @else
                                        N/A
                                    @endif
                                </td>
                                <td class="d-flex flex-row">
                                    <a href="{{ route('ch-admin.products.edit', $product->id) }}" class="btn btn-sm btn-primary me-1">
                                        <i class="ti-pencil"></i>
                                    </a>
                                    <form action="{{ route('ch-admin.products.destroy', $product->id) }}" method="POST" style="display: inline;">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this product?')">
                                            <i class="ti-trash"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        @empty
                            <tr><td colspan="8" class="text-center">No records found.</td></tr>
                        @endforelse
                        </tbody>
                    </table>

                    <!-- Pagination Links -->
                    @if($products->hasPages())
                        <div class="mt-4">
                            {{ $products->links() }}
                        </div>
                    @endif
                </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 productCheckboxes = document.querySelectorAll('.select-product');
        const deleteBulkBtn = document.getElementById('delete-bulk-btn');

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

        productCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('click', function() {
                const allChecked = [...productCheckboxes].every(checkbox => checkbox.checked);
                selectAllCheckbox.checked = allChecked;

                if (!this.checked) {
                    selectAllCheckbox.checked = false;
                }

                toggleDeleteButton();
            });
        });

        function toggleDeleteButton() {
            const isChecked = [...productCheckboxes].some(checkbox => checkbox.checked);
            deleteBulkBtn.style.display = isChecked ? 'inline-block' : 'none';
        }

        function updateSelectAllCheckbox() {
            const allChecked = [...productCheckboxes].every(checkbox => checkbox.checked);
            selectAllCheckbox.checked = allChecked;
        }

        function getSelectedProducts() {
            const selectedProducts = [];
            document.querySelectorAll('.select-product:checked').forEach(function (checkbox) {
                selectedProducts.push(checkbox.value);
            });
            return selectedProducts;
        }

        deleteBulkBtn.addEventListener('click', function () {
            const selectedProducts = getSelectedProducts();

            if (selectedProducts.length === 0) {
                alert('Please select at least one product.');
                return;
            }

            if (!confirm('Are you sure you want to delete the selected products?')) {
                return;
            }

            httpClient.delete('{{ route("ch-admin.products.bulk.destroy") }}', {
                data: {
                    product_ids: selectedProducts,
                }
            })
                .then((response) => {
                    if (response.data.success) {
                        window.location.href = '{{ route("ch-admin.products.index") }}';
                    } else {
                        alert('Failed to delete products.');
                    }
                })
                .catch((error) => {
                    console.error(error);
                    alert('An error occurred. Please try again.');
                });
        });

        toggleDeleteButton();
    </script>
@endpush
