@extends('layouts.app')

@section('main')
    <!-- Content Hea                                                    <span class="info-box-text">Total Accessories</span>
                            <span class="info-box-number" id="total-accessories">
                                {{ \App\Models\Product::where('tenant_id', app('tenant')->id)->where('type', 'Accessories')->count() }}
                            </span>              <span class="info-box-text">Total Phones</span>
                            <span class="info-box-number" id="total-phones">
                                {{ \App\Models\Product::where('tenant_id', app('tenant')->id)->where('type', 'Phone')->count() }}
                            </span>              <span class="info-box-text">Total Products</span>
                            <span class="info-box-number" id="total-records">
                                {{ \App\Models\Product::where('tenant_id', app('tenant')->id)->count() }}
                            </span>r (Page header) -->
    <section class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1><i class="fas fa-cube"></i> Products Management</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="{{ route('home') }}">Home</a></li>
                        <li class="breadcrumb-item active">Products</li>
                    </ol>
                </div>
            </div>
        </div>
        
        @if (session('success'))
            <div class="alert alert-success alert-dismissible fade show">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                <i class="fas fa-check-circle"></i> {{ session('success') }}
            </div>
        @endif
        @if (session('error'))
            <div class="alert alert-danger alert-dismissible fade show">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
            </div>
        @endif
    </section>

    <!-- Main content -->
    <section class="content">
        <x-admin-table 
            title="All Products"
            :create-route="route('product.create')"
            create-text="Add Product"
            :ajax-url="route('product.index')"
            table-id="products-table"
            :show-search="true"
            :show-date-filter="true"
            :show-export="true"
            :columns="[
                ['title' => '<input type=\"checkbox\" id=\"select-all-products\" title=\"Select All\">', 'field' => 'checkbox', 'orderable' => false, 'searchable' => false],
                ['title' => 'SL', 'field' => 'sl', 'orderable' => false],
                ['title' => 'Type', 'field' => 'type'],
                ['title' => 'Name', 'field' => 'name'],
                ['title' => 'Brand', 'field' => 'brand'],
                ['title' => 'Model', 'field' => 'model'],
                ['title' => 'IMEI/SN', 'field' => 'imei_or_sn'],
                ['title' => 'Condition', 'field' => 'condition'],
                ['title' => 'Stock', 'field' => 'stock'],
                ['title' => 'Buy Price', 'field' => 'buy_price'],
                ['title' => 'Sell Price', 'field' => 'sell_price'],
                ['title' => 'Added Date', 'field' => 'created_at'],
                ['title' => 'Actions', 'field' => 'actions', 'orderable' => false, 'searchable' => false]
            ]"
        >
            <x-slot name="customInfoBoxes">
                <div class="row mb-3">
                    <div class="col-md-4">
                        <div class="info-box">
                            <span class="info-box-icon bg-info"><i class="fas fa-cube"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">Total Products</span>
                                <span class="info-box-number" id="total-records">{{ $totalProducts ?? 0 }}</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="info-box">
                            <span class="info-box-icon bg-primary"><i class="fas fa-warehouse"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">Stock Phones</span>
                                <span class="info-box-number" id="stock-phones">{{ $stockPhones ?? 0 }}</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="info-box">
                            <span class="info-box-icon bg-secondary"><i class="fas fa-box"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">Stock Accessories</span>
                                <span class="info-box-number" id="stock-accessories">{{ $stockAccessories ?? 0 }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </x-slot>

            <x-slot name="extraFilters">
                <div class="col-md-3">
                    <label for="condition_filter" class="form-label">Condition</label>
                    <select class="form-control" id="condition_filter" name="condition_filter">
                        <option value="">All Conditions</option>
                        @foreach($conditions as $condition)
                            <option value="{{ $condition }}">{{ ucfirst($condition) }}</option>
                        @endforeach
                    </select>
                </div>
                
                <div class="col-md-3">
                    <label for="stock_filter" class="form-label">Stock Status</label>
                    <select class="form-control" id="stock_filter" name="stock_filter">
                        <option value="">All Stock</option>
                        <option value="in_stock">In Stock</option>
                        <option value="low_stock">Low Stock (≤5)</option>
                        <option value="out_of_stock">Out of Stock</option>
                    </select>
                </div>
            </x-slot>


        </x-admin-table>

        <!-- Bulk Actions Panel -->
        <div class="row mb-3" id="bulk-actions-panel" style="display: none;">
            <div class="col-12">
                <div class="alert alert-info d-flex justify-content-between align-items-center">
                    <div>
                        <i class="fas fa-check-square"></i>
                        <strong><span id="selected-count">0</span> product(s) selected</strong>
                        <span id="selected-products-preview" class="ml-2 text-muted"></span>
                    </div>
                    <div class="btn-group">
                        <button type="button" class="btn btn-sm btn-danger" id="bulk-delete-btn">
                            <i class="fas fa-trash"></i> Delete Selected
                        </button>
                        <button type="button" class="btn btn-sm btn-secondary" id="clear-selection-btn">
                            <i class="fas fa-times"></i> Clear Selection
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </section>

@push('style')
<style>
    /* Bulk Actions Panel Styling */
    #bulk-actions-panel {
        position: sticky;
        top: 0;
        z-index: 100;
        margin-top: -15px;
        margin-bottom: 15px;
    }
    
    #bulk-actions-panel .alert {
        margin-bottom: 0;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        animation: slideDown 0.3s ease-out;
    }
    
    @keyframes slideDown {
        from {
            opacity: 0;
            transform: translateY(-10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    /* Checkbox styling */
    .product-checkbox, #select-all-products {
        transform: scale(1.2);
        margin: 0;
    }
    
    /* Table row highlight when selected */
    .product-row-selected {
        background-color: rgba(0, 123, 255, 0.1) !important;
    }
    
    /* Action buttons hover effects */
    .btn-group .btn {
        transition: all 0.2s ease;
    }
    
    .btn-group .btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    }
    
    /* Selected products preview styling */
    #selected-products-preview {
        font-style: italic;
        font-size: 0.9em;
    }
    
    /* Bulk action buttons */
    #bulk-delete-btn {
        background: linear-gradient(45deg, #dc3545, #c82333);
        border: none;
        transition: all 0.3s ease;
    }
    
    #bulk-delete-btn:hover {
        background: linear-gradient(45deg, #c82333, #a71e2a);
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(220, 53, 69, 0.3);
    }
    
    #clear-selection-btn {
        transition: all 0.3s ease;
    }
    
    #clear-selection-btn:hover {
        transform: translateY(-1px);
    }
</style>
@endpush

@push('script')
    <script>
        // Edit Product Function
        function editProduct(id) {
            if (!id) {
                alert('Error: Product ID is required for editing');
                return;
            }

            console.log('Editing product with ID:', id);
            
            // Show loading feedback
            var button = event.target.closest('.btn-primary');
            if (button) {
                var originalHTML = button.innerHTML;
                button.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
                button.disabled = true;
                
                // Restore button after a short delay in case of slow redirect
                setTimeout(function() {
                    button.innerHTML = originalHTML;
                    button.disabled = false;
                }, 3000);
            }

            // Redirect to edit page
            window.location.href = '{{ route("product.index") }}/' + id + '/edit';
        }

        // Delete Product Function
        function deleteProduct(id) {
            if (!id) {
                alert('Error: Product ID is required for deletion');
                return;
            }

            console.log('Attempting to delete product with ID:', id);

            // Confirm deletion
            var confirmMessage = 'Are you sure you want to delete this product?\n\n' +
                                'This action cannot be undone and will permanently remove:\n' +
                                '• Product information\n' +
                                '• Stock data\n' +
                                '• All related records\n\n' +
                                'Click OK to delete or Cancel to abort.';
                                
            if (confirm(confirmMessage)) {
                console.log('User confirmed deletion');
                
                // Show loading feedback
                var button = event.target.closest('.btn-danger');
                if (button) {
                    var originalHTML = button.innerHTML;
                    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
                    button.disabled = true;
                }

                // Create a form to submit DELETE request
                var form = document.createElement('form');
                form.method = 'POST';
                form.action = '{{ route("product.index") }}/' + id;
                form.style.display = 'none';

                // Add CSRF token
                var csrfInput = document.createElement('input');
                csrfInput.type = 'hidden';
                csrfInput.name = '_token';
                csrfInput.value = '{{ csrf_token() }}';
                form.appendChild(csrfInput);

                // Add DELETE method
                var methodInput = document.createElement('input');
                methodInput.type = 'hidden';
                methodInput.name = '_method';
                methodInput.value = 'DELETE';
                form.appendChild(methodInput);

                // Submit the form
                document.body.appendChild(form);
                console.log('Submitting delete form for product ID:', id);
                form.submit();
            } else {
                console.log('User cancelled deletion');
            }
        }

        // Bulk Selection Functions
        function updateBulkActionsPanel() {
            var selectedCheckboxes = $('.product-checkbox:checked');
            var selectedCount = selectedCheckboxes.length;
            
            if (selectedCount > 0) {
                $('#bulk-actions-panel').show();
                $('#selected-count').text(selectedCount);
                
                // Show preview of selected products (max 3)
                var productNames = [];
                selectedCheckboxes.slice(0, 3).each(function() {
                    productNames.push($(this).data('product-name'));
                });
                
                var previewText = productNames.join(', ');
                if (selectedCount > 3) {
                    previewText += ` and ${selectedCount - 3} more`;
                }
                $('#selected-products-preview').text('(' + previewText + ')');
            } else {
                $('#bulk-actions-panel').hide();
                $('#selected-count').text('0');
                $('#selected-products-preview').text('');
            }
            
            // Update "Select All" checkbox state
            var totalCheckboxes = $('.product-checkbox').length;
            var allSelected = selectedCount === totalCheckboxes && totalCheckboxes > 0;
            var someSelected = selectedCount > 0 && selectedCount < totalCheckboxes;
            
            $('#select-all-products').prop('checked', allSelected);
            $('#select-all-products').prop('indeterminate', someSelected);
        }

        // Bulk Delete Function
        function bulkDeleteProducts() {
            var selectedCheckboxes = $('.product-checkbox:checked');
            var selectedIds = [];
            var productNames = [];
            
            selectedCheckboxes.each(function() {
                selectedIds.push($(this).val());
                productNames.push($(this).data('product-name'));
            });
            
            if (selectedIds.length === 0) {
                alert('Please select at least one product to delete.');
                return;
            }
            
            var confirmMessage = `Are you sure you want to delete ${selectedIds.length} selected product(s)?\n\n` +
                                'Products to be deleted:\n' +
                                productNames.slice(0, 5).join('\n') +
                                (productNames.length > 5 ? `\n... and ${productNames.length - 5} more` : '') +
                                '\n\nThis action cannot be undone!';
            
            if (confirm(confirmMessage)) {
                console.log('User confirmed bulk deletion of products:', selectedIds);
                
                // Show loading state
                $('#bulk-delete-btn').html('<i class="fas fa-spinner fa-spin"></i> Deleting...').prop('disabled', true);
                
                // Send AJAX request
                $.ajax({
                    url: '{{ route("product.bulkDelete") }}',
                    method: 'DELETE',
                    data: {
                        product_ids: selectedIds,
                        _token: '{{ csrf_token() }}'
                    },
                    success: function(response) {
                        if (response.success) {
                            // Show success message with details
                            var successMessage = `✅ Success!\n\nDeleted ${response.deleted_count} product(s):\n` +
                                                response.deleted_products.slice(0, 5).join('\n') +
                                                (response.deleted_products.length > 5 ? `\n... and ${response.deleted_products.length - 5} more` : '');
                            alert(successMessage);
                            
                            // Reload the DataTable to reflect changes
                            var table = $('#products-table').DataTable();
                            table.ajax.reload(function() {
                                console.log('DataTable reloaded after bulk deletion');
                                // Clear any remaining selections after reload
                                $('.product-checkbox').prop('checked', false);
                                $('#select-all-products').prop('checked', false).prop('indeterminate', false);
                                $('.product-row-selected').removeClass('product-row-selected');
                                updateBulkActionsPanel();
                            });
                            
                            console.log('Bulk deletion successful:', response);
                        } else {
                            alert('❌ Error: ' + response.message);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Bulk deletion failed:', xhr.responseText);
                        alert('Error deleting products. Please try again.');
                    },
                    complete: function() {
                        // Restore button state
                        $('#bulk-delete-btn').html('<i class="fas fa-trash"></i> Delete Selected').prop('disabled', false);
                    }
                });
            }
        }

        // Initialize when document is ready
        $(function() {
            console.log('✅ Product management page loaded successfully');
            console.log('✅ Edit, delete, and bulk delete functions are now available');
            
            // Select All checkbox functionality
            $(document).on('change', '#select-all-products', function() {
                var isChecked = $(this).prop('checked');
                $('.product-checkbox').prop('checked', isChecked);
                
                // Update row highlighting
                $('.product-checkbox').each(function() {
                    var $row = $(this).closest('tr');
                    if (isChecked) {
                        $row.addClass('product-row-selected');
                    } else {
                        $row.removeClass('product-row-selected');
                    }
                });
                
                updateBulkActionsPanel();
                console.log('Select all toggled:', isChecked);
            });
            
            // Individual checkbox change
            $(document).on('change', '.product-checkbox', function() {
                var $row = $(this).closest('tr');
                if ($(this).prop('checked')) {
                    $row.addClass('product-row-selected');
                } else {
                    $row.removeClass('product-row-selected');
                }
                updateBulkActionsPanel();
                console.log('Product checkbox changed, selected count:', $('.product-checkbox:checked').length);
            });
            
            // Bulk delete button click
            $(document).on('click', '#bulk-delete-btn', function() {
                bulkDeleteProducts();
            });
            
            // Clear selection button click
            $(document).on('click', '#clear-selection-btn', function() {
                $('.product-checkbox').prop('checked', false);
                $('#select-all-products').prop('checked', false).prop('indeterminate', false);
                $('.product-row-selected').removeClass('product-row-selected');
                updateBulkActionsPanel();
                console.log('Selection cleared');
            });
            
            // Add tooltips to action buttons for better UX
            $(document).on('mouseenter', '.btn-primary', function() {
                $(this).attr('title', 'Click to edit this product');
            });
            
            $(document).on('mouseenter', '.btn-danger', function() {
                $(this).attr('title', 'Click to delete this product (cannot be undone)');
            });

            // Add click event logging for debugging
            $(document).on('click', '.btn-primary', function() {
                console.log('Edit button clicked');
            });
            
            $(document).on('click', '.btn-danger', function() {
                console.log('Delete button clicked');
            });
        });
    </script>
@endpush

@endsection
