@extends('layouts.app')
@section('title', 'Items')
@push('plugin-styles')
<link rel="stylesheet" href="{{ asset('theme/vendors/datatables.net-bs5/dataTables.bootstrap5.css') }}">
@endpush

@section('content')
<x-card
    title="Item Management"
    subtitle="Manage your inventory items, raw materials, and finished products"
    icon="fas fa-box"
    badge="{{ $itemsCount ?? 0 }}"
    badgeColor="info"
    :actions="[
        ['label' => 'Export CSV', 'url' => '#', 'icon' => 'fas fa-download'],
        ['label' => 'Import CSV', 'url' => '#', 'icon' => 'fas fa-upload'],
        ['label' => 'Bulk Actions', 'url' => '#', 'icon' => 'fas fa-tasks']
    ]"
    class="shadow-lg"
>
    <!-- Page Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h4 class="mb-1">Items</h4>
            <p class="text-muted mb-0">Manage all your inventory items in one place</p>
        </div>
        <div class="d-flex gap-2">
            <button class="btn btn-outline-primary" data-bs-toggle="collapse" data-bs-target="#filtersCollapse">
                <i class="fas fa-filter me-2"></i>
                Filters
            </button>
            <a href="{{ route('items.create') }}" class="btn btn-primary">
                <i class="fas fa-plus me-2"></i>
                Add Item
            </a>
        </div>
    </div>

    <!-- Success/Error Messages -->
    @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i>
            {{ session('success') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    @if($errors->any())
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            {{ $errors->first() }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    <!-- Filters Section -->
    <div class="collapse mb-4" id="filtersCollapse">
        <div class="card border-light">
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Category</label>
                        <select id="filterCategory" class="form-select">
                            <option value="">All Categories</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Type</label>
                        <select id="filterType" class="form-select">
                            <option value="">All Types</option>
                            <option value="raw_material">Raw Material</option>
                            <option value="finished_product">Finished Product</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Status</label>
                        <select id="filterActive" class="form-select">
                            <option value="">All Status</option>
                            <option value="1">Active</option>
                            <option value="0">Inactive</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Search</label>
                        <input type="text" class="form-control" id="filterSearch" placeholder="Search items...">
                    </div>
                </div>
                <div class="mt-3">
                    <button type="button" class="btn btn-primary" id="applyFilters">
                        <i class="fas fa-search me-2"></i>
                        Apply Filters
                    </button>
                    <button type="button" class="btn btn-outline-secondary" id="clearFilters">
                        <i class="fas fa-times me-2"></i>
                        Clear Filters
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- DataTable -->
    <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>Type</th>
                    <th>Category</th>
                    <th>UoM</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
        </table>
    </div>
</x-card>
@endsection

@push('plugin-scripts')
<script src="{{ asset('theme/vendors/jquery/jquery.min.js') }}"></script>
<script src="{{ asset('theme/vendors/datatables.net/dataTables.js') }}"></script>
<script src="{{ asset('theme/vendors/datatables.net-bs5/dataTables.bootstrap5.js') }}"></script>
<script src="{{ asset('theme/vendors/select2/select2.min.js') }}"></script>
<script src="{{ asset('theme/vendors/flatpickr/flatpickr.min.js') }}"></script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // Initialize Select2 for category filter
    const categorySelect = $('#filterCategory');
    categorySelect.select2({
        theme: 'bootstrap-5',
        placeholder: 'Select Category',
        allowClear: true,
        ajax: {
            url: '{{ route("item-categories.search") }}',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    q: params.term || '',
                    page: params.page || 1
                };
            },
            processResults: function (data, params) {
                params.page = params.page || 1;
                return {
                    results: data.data.map(function(item) {
                        return {
                            id: item.id,
                            text: item.name
                        };
                    }),
                    pagination: {
                        more: data.next_page_url != null
                    }
                };
            },
            cache: true
        }
    });

    // Initialize DataTable
    const table = new DataTable('#items-table', {
        processing: true,
        serverSide: true,
        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',
                className: 'text-center'
            },
            {
                data: 'is_active',
                name: 'is_active',
                render: function(data, type, row) {
                    const status = data == 1 ? 'Active' : 'Inactive';
                    const badgeClass = data == 1 ? 'success' : 'danger';
                    return `<span class="badge bg-${badgeClass}">${status}</span>`;
                }
            },
            {
                data: 'actions',
                name: 'actions',
                orderable: false,
                searchable: false,
                className: 'text-center',
                render: function(data, type, row) {
                    return `<div class="d-flex gap-2">
                        <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>
                        <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="{{ 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>
                    </div>`;
                }
            }
        ],
        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() {
        table.draw();
    });

    $('#clearFilters').on('click', function() {
        $('#filterCategory, #filterType, #filterActive').val('').trigger('change');
        $('#filterSearch').val('');
        table.draw();
    });

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


});
</script>
@endpush
