@extends('layouts.app')

@section('title', 'Warehouse Ledger')

@push('plugin-style')
<style>
    .filter-section {
        background-color: #f8f9fa;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
    }
    .filter-row {
        margin-bottom: 15px;
    }
    .filter-row:last-child {
        margin-bottom: 0;
    }
</style>
@endpush

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">Warehouse Ledger (IGP History)</h4>
                    <p class="card-subtitle">Track all Inward Gate Pass (IGP) transactions and warehouse movements</p>
                </div>
                <div class="card-body">
                    <!-- Filters -->
                    <div class="filter-section">
                        <div class="row filter-row">
                            <div class="col-md-2">
                                <label for="item_filter" class="form-label">Item</label>
                                @include('common.item-select', [
                                    'name' => 'item_filter',
                                    'id' => 'item_filter',
                                    'label' => 'Item',
                                    'class' => 'form-select',
                                    'placeholder' => 'All Items',
                                    'allowClear' => true
                                ])
                            </div>
                            <div class="col-md-2">
                                <label for="warehouse_filter" class="form-label">Warehouse</label>
                                <select id="warehouse_filter" class="form-select">
                                    <option value="">All Warehouses</option>
                                    @foreach($warehouses as $warehouse)
                                        <option value="{{ $warehouse->id }}">{{ $warehouse->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="txn_type_filter" class="form-label">Transaction Type</label>
                                <select id="txn_type_filter" class="form-select">
                                    <option value="">All Types</option>
                                    <option value="igp">IGP</option>
                                    <option value="transfer">Transfer</option>
                                    <option value="adjustment">Adjustment</option>
                                    <option value="production_receipt">Production Receipt</option>
                                    <option value="production_issue">Production Issue</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="date_from_filter" class="form-label">Date From</label>
                                <input type="date" id="date_from_filter" class="form-control">
                            </div>
                            <div class="col-md-2">
                                <label for="date_to_filter" class="form-label">Date To</label>
                                <input type="date" id="date_to_filter" class="form-control">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">&nbsp;</label>
                                <div>
                                    <button id="apply_filters" class="btn btn-primary btn-sm">
                                        <i class="fas fa-filter"></i> Apply Filters
                                    </button>
                                    <button id="clear_filters" class="btn btn-secondary btn-sm">
                                        <i class="fas fa-times"></i> Clear
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- DataTable -->
                    <div class="table-responsive">
                        <table id="warehouse_ledger_table" class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Type</th>
                                    <th>Item</th>
                                    <th>Warehouse</th>
                                    <th>Bin</th>
                                    <th>Qty In</th>
                                    <th>Qty Out</th>
                                    <th>Unit Cost</th>
                                    <th>Reference</th>
                                </tr>
                            </thead>
                        </table>
                    </div>

                    <!-- Test table for debugging -->
                    <div class="mt-4">
                        <h6>Debug Info:</h6>
                        <div id="debug-info"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('plugin-scripts')
<script>
$(document).ready(function() {
    console.log('Initializing Warehouse Ledger DataTable...');

    // Update debug info
    $('#debug-info').html('<p>Page loaded, checking libraries...</p>');

    // Check if jQuery is loaded
    if (typeof $ === 'undefined') {
        console.error('jQuery is not loaded!');
        $('#debug-info').html('<p style="color: red;">Error: jQuery is not loaded!</p>');
        alert('Error: jQuery is not loaded.');
        return;
    }

    $('#debug-info').append('<p>jQuery loaded successfully</p>');

    // Check if DataTables is loaded
    if (typeof $.fn.DataTable === 'undefined') {
        console.error('DataTables is not loaded!');
        $('#debug-info').append('<p style="color: red;">Error: DataTables is not loaded!</p>');
        alert('Error: DataTables library is not loaded. Please refresh the page.');
        return;
    }

    $('#debug-info').append('<p>DataTables loaded successfully</p>');

    console.log('jQuery version:', $.fn.jquery);
    console.log('DataTables version:', $.fn.dataTable.version);

    $('#debug-info').append('<p>jQuery version: ' + $.fn.jquery + '</p>');
    $('#debug-info').append('<p>DataTables version: ' + $.fn.dataTable.version + '</p>');

    // Test DataTables with a simple table first
    console.log('Testing DataTables functionality...');
    $('#debug-info').append('<p>Testing DataTables functionality...</p>');

    // Initialize DataTable
    try {
        var table = $('#warehouse_ledger_table').DataTable({
            processing: true,
            serverSide: false,
            ajax: {
                url: '{{ route("wms.index") }}',
                data: function(d) {
                    d.item_id = $('#item_filter').val();
                    d.warehouse_id = $('#warehouse_filter').val();
                    d.txn_type = $('#txn_type_filter').val();
                    d.date_from = $('#date_from_filter').val();
                    d.date_to = $('#date_to_filter').val();
                    d.ajax = true;
                    console.log('Sending data:', d);
                    $('#debug-info').append('<p>Sending AJAX request...</p>');
                },
                error: function(xhr, error, thrown) {
                    console.error('DataTables AJAX error:', error, thrown);
                    console.log('Response:', xhr.responseText);
                    $('#debug-info').append('<p style="color: red;">AJAX Error: ' + error + '</p>');
                    alert('Error loading data. Please check the console for details.');
                },
                success: function(data) {
                    console.log('DataTables AJAX success:', data);
                    $('#debug-info').append('<p style="color: green;">AJAX Success: ' + (data.data ? data.data.length : 0) + ' records loaded</p>');
                }
            },
            columns: [
                { data: 'formatted_date', name: 'occurred_at' },
                { data: 'txn_type_badge', name: 'txn_type' },
                { data: 'item_name', name: 'item.name' },
                { data: 'warehouse_name', name: 'bin.warehouse.name' },
                { data: 'bin_code', name: 'bin.code' },
                { data: 'formatted_qty_in', name: 'qty_in' },
                { data: 'formatted_qty_out', name: 'qty_out' },
                { data: 'formatted_unit_cost', name: 'unit_cost' },
                { data: 'ref_no', name: 'ref_no' }
            ],
            order: [[0, 'desc']],
            pageLength: 25,
            initComplete: function(settings, json) {
                console.log('DataTable initialization complete:', settings, json);
                $('#debug-info').append('<p style="color: green;">DataTable initialization complete</p>');
            }
        });

        $('#debug-info').append('<p style="color: green;">DataTable object created successfully</p>');

    } catch (error) {
        console.error('Error creating DataTable:', error);
        $('#debug-info').append('<p style="color: red;">Error creating DataTable: ' + error.message + '</p>');
    }

    // Apply filters
    $('#apply_filters').click(function() {
        console.log('Applying filters...');
        $('#debug-info').append('<p>Applying filters...</p>');
        table.ajax.reload();
    });

    // Clear filters
    $('#clear_filters').click(function() {
        console.log('Clearing filters...');
        $('#debug-info').append('<p>Clearing filters...</p>');
        $('#item_filter').val('');
        $('#warehouse_filter').val('');
        $('#txn_type_filter').val('');
        $('#date_from_filter').val('');
        $('#date_to_filter').val('');
        table.ajax.reload();
    });

    // Auto-apply filters on change
    $('#item_filter, #warehouse_filter, #txn_type_filter').change(function() {
        console.log('Filter changed:', $(this).attr('id'), $(this).val());
        $('#debug-info').append('<p>Filter changed: ' + $(this).attr('id') + ' = ' + $(this).val() + '</p>');
        table.ajax.reload();
    });

    // Auto-apply date filters
    $('#date_from_filter, #date_to_filter').change(function() {
        console.log('Date filter changed:', $(this).attr('id'), $(this).val());
        $('#debug-info').append('<p>Date filter changed: ' + $(this).attr('id') + ' = ' + $(this).val() + '</p>');
        table.ajax.reload();
    });

    // Debug: Log table initialization
    console.log('Warehouse Ledger DataTable initialized successfully');
    $('#debug-info').append('<p style="color: green;">Warehouse Ledger DataTable initialized successfully</p>');
});
</script>
@endpush
