@extends('layouts.admin-simple')

@section('title', 'Indirect Goods - Adjustments')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item">Indirect Goods</li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.indirect-goods.inventory.index') }}">Inventory</a></li>
    <li class="breadcrumb-item active">Adjustments</li>
@endsection

@section('page-title')
    <div class="d-flex justify-content-between align-items-center w-100">
        <div class="page-title-left">
            <h3 class="mb-1">Inventory Adjustments</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Manual stock adjustments for indirect goods</p>
        </div>
        <a href="{{ route('warehouse.indirect-goods.inventory.index') }}" class="btn btn-sm btn-outline-secondary">
            <i class="material-icons mr-1" style="font-size: 16px;">arrow_back</i> Back to Inventory
        </a>
    </div>
@endsection

@section('content')
    @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show">
            {{ session('success') }}
            <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
        </div>
    @endif
    @if(session('error'))
        <div class="alert alert-danger alert-dismissible fade show">
            {{ session('error') }}
            <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
        </div>
    @endif

    <!-- Adjustment Form -->
    <div class="card mb-4">
        <div class="card-header">
            <h6 class="card-title mb-0"><i class="material-icons mr-2">tune</i>New Adjustment</h6>
        </div>
        <div class="card-body">
            <form action="{{ route('warehouse.indirect-goods.inventory.store-adjustment') }}" method="POST">
                @csrf
                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label class="font-weight-bold">Indirect Good <span class="text-danger">*</span></label>
                            <select name="indirect_good_id" id="adj-indirect-good" class="form-control select2" required>
                                <option value="">Select Item</option>
                                @foreach($indirectGoods as $ig)
                                    <option value="{{ $ig->id }}">{{ $ig->ig_code }} - {{ $ig->ig_description }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label class="font-weight-bold">Inventory Batch <span class="text-danger">*</span></label>
                            <select name="inventory_id" id="adj-inventory" class="form-control" required disabled>
                                <option value="">Select item first</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label class="font-weight-bold">Type <span class="text-danger">*</span></label>
                            <select name="adjustment_type" class="form-control" required>
                                <option value="add">Add (+)</option>
                                <option value="subtract">Subtract (-)</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label class="font-weight-bold">Quantity <span class="text-danger">*</span></label>
                            <input type="number" name="quantity" class="form-control" step="0.01" min="0.01" required>
                        </div>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary mb-3 w-100">
                            <i class="material-icons mr-1" style="font-size: 16px;">save</i> Apply
                        </button>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label class="font-weight-bold">Reason <span class="text-danger">*</span></label>
                            <input type="text" name="reason" class="form-control" placeholder="Reason for adjustment..." required maxlength="500">
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Recent Adjustments -->
    <div class="card">
        <div class="card-header">
            <h6 class="card-title mb-0"><i class="material-icons mr-2">history</i>Recent Adjustments</h6>
        </div>
        <div class="card-body">
            @if($adjustments->isEmpty())
                <div class="text-center py-4 text-muted">No adjustments recorded yet.</div>
            @else
                <div class="table-responsive">
                    <table class="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Date</th>
                                <th>Indirect Good</th>
                                <th>Invoice No.</th>
                                <th>Qty Before</th>
                                <th>Qty Moved</th>
                                <th>Qty After</th>
                                <th>By</th>
                                <th>Notes</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($adjustments as $index => $adj)
                                <tr>
                                    <td>{{ $adjustments->firstItem() + $index }}</td>
                                    <td>{{ $adj->created_at->format('d M Y H:i') }}</td>
                                    <td>{{ $adj->indirectGood ? $adj->indirectGood->ig_code . ' - ' . $adj->indirectGood->ig_description : '-' }}</td>
                                    <td>{{ $adj->invoice_number ?: '-' }}</td>
                                    <td class="text-right">{{ number_format($adj->quantity_before, 2) }}</td>
                                    <td class="text-right font-weight-bold">{{ number_format($adj->quantity_moved, 2) }}</td>
                                    <td class="text-right">{{ number_format($adj->quantity_after, 2) }}</td>
                                    <td>{{ $adj->user ? $adj->user->name : '-' }}</td>
                                    <td>{{ $adj->notes }}</td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
                <div class="mt-3">{{ $adjustments->links() }}</div>
            @endif
        </div>
    </div>
@endsection

@section('scripts')
<script>
$(document).ready(function() {
    $('.select2').select2({ theme: 'bootstrap4', width: '100%' });

    // Load inventory batches when item changes
    $('#adj-indirect-good').change(function() {
        var itemId = $(this).val();
        var $inv = $('#adj-inventory');
        $inv.html('<option value="">Loading...</option>').prop('disabled', true);

        if (!itemId) {
            $inv.html('<option value="">Select item first</option>');
            return;
        }

        $.get('{{ route("warehouse.indirect-goods.inventory.index") }}', {
            _token: '{{ csrf_token() }}',
            search: { value: '' },
            start: 0,
            length: 100,
            draw: 1
        }, function(response) {
            var options = '<option value="">Select batch</option>';
            if (response.data) {
                response.data.forEach(function(inv) {
                    if (inv.ig_code && inv.ig_code.indexOf($('#adj-indirect-good option:selected').text().split(' - ')[0]) > -1) {
                        options += '<option value="' + inv.id + '">Invoice: ' + inv.invoice_number + ' | Batch: ' + inv.batch_number + ' | Qty: ' + inv.quantity_available + '</option>';
                    }
                });
            }
            $inv.html(options).prop('disabled', false);
        });

        // Simpler approach - direct query
        $.ajax({
            url: '{{ route("warehouse.indirect-goods.inventory.index") }}',
            data: { draw: 1, start: 0, length: 100, search: { value: '' } },
            headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
            success: function(response) {
                var options = '<option value="">Select batch</option>';
                if (response.data) {
                    var igCode = $('#adj-indirect-good option:selected').text().split(' - ')[0].trim();
                    response.data.forEach(function(inv) {
                        if (inv.ig_code === igCode) {
                            options += '<option value="' + inv.id + '">Invoice: ' + inv.invoice_number + ' | Batch: ' + inv.batch_number + ' | Qty: ' + inv.quantity_available + '</option>';
                        }
                    });
                }
                $inv.html(options).prop('disabled', false);
            }
        });
    });
});
</script>
@endsection
