
<?php $__env->startSection('title', 'Items'); ?>
<?php $__env->startPush('plugin-styles'); ?>
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/datatables.net-bs5/dataTables.bootstrap5.css')); ?>">
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/flatpickr/flatpickr.min.css')); ?>">
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/sweetalert2/sweetalert2.min.css')); ?>">
<style>
.select2-container--bootstrap-5{
    width: 100% !important;
}
</style>
<?php $__env->stopPush(); ?>
<?php $__env->startSection('content'); ?>
<div class="accordion mb-3" id="grnFilterAccordion">
	<div class="accordion-item">
		<h2 class="accordion-header" id="grnFilterHeading">
			<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#grnFilterCollapse" aria-expanded="false" aria-controls="grnFilterCollapse">
				Filters
			</button>
		</h2>
		<div id="grnFilterCollapse" class="accordion-collapse collapse" aria-labelledby="grnFilterHeading" data-bs-parent="#grnFilterAccordion">
			<div class="accordion-body">

                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Type</label>
                        <select id="filterType" class="form-select">
                            <option value="">All Types</option>
                            <option value="52">Raw Material</option>
                            <option value="53">Finished Product</option>
                        </select>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Category</label>
                        <div>
                        <select id="filterCategory" class="form-select select2">
                            <option value="">All Categories</option>
                        </select>
                        </div>
                    </div>
                    
                </div>
                <div class="mt-3">
                    <button type="button" class="btn btn-primary" id="applyFilters">
                        <i class="fas fa-search me-2"></i>
                        Apply
                    </button>
                    <button type="button" class="btn btn-outline-secondary" id="clearFilters">
                        <i class="fas fa-times me-2"></i>
                        Clear
                    </button>
                    
                </div>
            </div>
		</div>
	</div>
</div>

<div class="card">
	<div class="card-body">
		<div class="d-flex justify-content-between align-items-center mb-3">
			<h6 class="card-title mb-0">Items</h6>
            <a href="<?php echo e(route('items.create')); ?>" class="btn btn-primary">
                <i class="fas fa-plus me-2"></i>
                Add Item
            </a>
		</div>
		<?php if(session('success')): ?><div class="alert alert-success"><?php echo e(session('success')); ?></div><?php endif; ?>
		<?php if($errors->any()): ?><div class="alert alert-danger"><?php echo e($errors->first()); ?></div><?php endif; ?>
		<div class="table-responsive">
			<table id="items-table" class="table table-hover">
                <thead class="table-light">
                    <tr>
                       <th>ID</th>
                    <th>Name</th>
                    <th>SKU</th>
                    
                    <th>Category</th>
                    <th>UNIT</th>
                    <th>Weighted Avg Price</th>
                    <th>Actions</th>
                    </tr>
                </thead>
            </table>
		</div>
	</div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('plugin-scripts'); ?>
<script src="<?php echo e(asset('theme/vendors/jquery/jquery.min.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/datatables.net/dataTables.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/datatables.net-bs5/dataTables.bootstrap5.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/sweetalert2/sweetalert2.min.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/select2/select2.min.js')); ?>"></script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // Minimal helpers
    const categorySelect = $('#filterCategory');
    const typeSelect = $('#filterType');

    function getTypeSuffix(){
        const t = (typeSelect.find('option:selected').text() || '').toLowerCase();
        return /finished/.test(t) ? ' - Finished Product' : ' - Raw Material';
    }

    function loadCategoriesForType(parentId){
        if (!parentId) { categorySelect.val('').trigger('change'); return; }
        const suffix = getTypeSuffix();
        $.get('<?php echo e(route('items.chart-account-children')); ?>', { parent_id: parentId })
            .done(function(data){
                // Re-init lightweight Select2 datasource by replacing options
                if (categorySelect.data('select2')) categorySelect.select2('destroy');
                categorySelect.empty();
                categorySelect.append(new Option('All Categories', '', false, false));
                (data.results || []).forEach(function(it){
                    categorySelect.append(new Option(it.text + suffix, it.id, false, false));
                });
                categorySelect.select2({ theme: 'bootstrap-5', placeholder: 'Select Category', allowClear: true });
            });
    }

    // Default Type selection to first non-empty option and load categories
    // Auto-select first type and load categories once
    // const firstType = typeSelect.find('option[value!=""]').first();
    // if (firstType.length && !typeSelect.val()) {
    //     typeSelect.val(firstType.val());
    // }
    loadCategoriesForType(typeSelect.val());

    // On change, load categories for new type
    typeSelect.on('change', function(){ loadCategoriesForType($(this).val()); });

    // Initialize DataTable
    const table = new DataTable('#items-table', {
        processing: true,
        serverSide: false,
        ajax: {
            url: 'items',
            data: function(d) {
                d.category = $('#filterCategory').val();
                d.type = $('#filterType').val();
                d.active = $('#filterActive').val();
                d.search = $('#filterSearch').val();
            }
        },
        order: [[0, 'desc']],
        columns: [
            {
                data: 'id',
                name: 'id',
                className: 'text-center'
            },
            {
                data: 'name',
                name: 'name',
                render: function(data, type, row) {
                    return `<div>
                        <strong>${data}</strong>
                        ${row.description ? `<br><small class="text-muted">${row.description}</small>` : ''}
                    </div>`;
                }
            },
            {
                data: 'sku',
                name: 'sku',
                className: 'text-center'
            },
            // {
            //     data: 'type',
            //     name: 'type',
            //     render: function(data) {
            //         const badges = {
            //             'raw_material': 'warning',
            //             'finished_product': 'success'
            //         };
            //         const labels = {
            //             'raw_material': 'Raw Material',
            //             'finished_product': 'Finished Product'
            //         };
            //         return `<span class="badge bg-${badges[data] || 'secondary'}">${labels[data] || data}</span>`;
            //     }
            // },
            {
                data: 'category_name',
                name: 'category_name',
                render: function(data) {
                    return data || '-';
                }
            },
            {
                data: 'uom',
                name: 'uom',
                render: function(data) {
                    return data || '-';
                }
            },
            {
                data: 'weighted_average_price',
                name: 'weighted_average_price',
                className: 'text-end',
                render: function(data) {
                    return data || '-';
                }
            },
            {
                data: 'actions',
                name: 'actions',
                orderable: false,
                searchable: false,
                className: 'text-center',
                render: function(data, type, row) {

                    let showBomButton = false;

        if (row.sku && row.sku.startsWith('FG')) {
            showBomButton = true;
        }

        let bomButton = '';
        if (showBomButton) {
            // console.log(row);
            if(row.bom){
           bomButton = `
    <a href="/manufacturing/boms/${row.bom.id}" 
       class="btn btn-sm btn-outline-secondary" 
       title="View BOMs">
        <i class="fas fa-cogs me-1"></i> BOMs
    </a>
`;
            }
        }

        return `

                    <div class="d-flex gap-2">
                        ${bomButton}
                        <a href="/items/${row.id}/edit" class="btn btn-sm btn-outline-primary" title="Edit">
                            <i class="fas fa-edit me-1"></i>Edit
                        </a>
                       
                    </div>`;

                    //  <form action="/items/${row.id}" method="POST" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this item?')">
                    //         <input type="hidden" name="_token" value="<?php echo e(csrf_token()); ?>">
                    //         <input type="hidden" name="_method" value="DELETE">
                    //         <button type="submit" class="btn btn-sm btn-outline-danger" title="Delete">
                    //             <i class="fas fa-trash me-1"></i>Delete
                    //         </button>
                    //     </form>
                }
            }
        ],
        language: {
            processing: '<div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div>',
            emptyTable: '<div class="text-center py-4"><i class="fas fa-inbox fa-3x text-muted mb-3"></i><p class="text-muted">No items found</p></div>',
            zeroRecords: '<div class="text-center py-4"><i class="fas fa-search fa-3x text-muted mb-3"></i><p class="text-muted">No matching items found</p></div>'
        }
    });

    // Filter functionality
    $('#applyFilters').on('click', function() {
        const category = $('#filterCategory').val();
        const type = $('#filterType').val();
        
        const params = new URLSearchParams();
        if (category) params.set('category', category);
        if (type) params.set('type', type);
        
        const newUrl = 'items?' + params.toString();
        
        table.ajax.url(newUrl).load();
    });

    // Clear filters — reload original URL
    $('#clearFilters').on('click', function() {
        $('#filterCategory, #filterType').val('').trigger('change');
        table.ajax.url('items').load();
    });

    // Search on enter
    $('#filterSearch').on('keypress', function(e) {
        if (e.which === 13) {
            table.draw();
        }
    });

    // Inline status update
    $(document).on('change', '.item-status-select', function() {
        const id = $(this).data('id');
        const status = $(this).val();
        $.ajax({
            url: `/items/${id}/toggle-status`,
            method: 'PATCH',
            data: { _token: '<?php echo e(csrf_token()); ?>', status: status },
        }).done(function() {
            table.draw(false);
        }).fail(function(xhr) {
            alert('Failed to update status');
            table.draw(false);
        });
    });

});
</script>
<?php $__env->stopPush(); ?>


<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\habibcables-ERP\resources\views/items/index.blade.php ENDPATH**/ ?>