@extends('layouts.admin-simple')

@section('title', 'Record Consumption')

@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.consumption.index') }}">Consumption</a></li>
    <li class="breadcrumb-item active">Record</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">Record Consumption / Write-Off</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Deduct indirect goods from project inventory</p>
        </div>
    </div>
@endsection

@section('content')
    @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

    <form action="{{ route('warehouse.indirect-goods.consumption.store') }}" method="POST">
        @csrf
        <div class="card">
            <div class="card-header">
                <h6 class="card-title mb-0"><i class="material-icons mr-2">delete_sweep</i>Consumption Details</h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="font-weight-bold">Consumption Date <span class="text-danger">*</span></label>
                            <input type="date" name="consumption_date" class="form-control @error('consumption_date') is-invalid @enderror" value="{{ old('consumption_date', date('Y-m-d')) }}" required>
                            @error('consumption_date') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="font-weight-bold">Project <span class="text-danger">*</span></label>
                            <select name="project_id" id="project_id" class="form-control warehouse-select2 @error('project_id') is-invalid @enderror" data-placeholder="Select Project" required>
                                <option value="">Select Project</option>
                                @foreach($projects as $project)
                                    <option value="{{ $project->id }}" {{ old('project_id') == $project->id ? 'selected' : '' }}>{{ $project->project_number }} - {{ $project->project_name }}</option>
                                @endforeach
                            </select>
                            @error('project_id') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="font-weight-bold">Consumption Type <span class="text-danger">*</span></label>
                            <select name="consumption_type" class="form-control warehouse-select2 @error('consumption_type') is-invalid @enderror" data-placeholder="Select Type" required>
                                <option value="">Select Type</option>
                                <option value="consumed" {{ old('consumption_type') == 'consumed' ? 'selected' : '' }}>Consumed</option>
                                <option value="written_off" {{ old('consumption_type') == 'written_off' ? 'selected' : '' }}>Written Off</option>
                                <option value="damaged" {{ old('consumption_type') == 'damaged' ? 'selected' : '' }}>Damaged</option>
                                <option value="expired" {{ old('consumption_type') == 'expired' ? 'selected' : '' }}>Expired</option>
                            </select>
                            @error('consumption_type') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="font-weight-bold">Indirect Good <span class="text-danger">*</span></label>
                            <select name="indirect_good_id" id="indirect_good_id" class="form-control warehouse-select2 @error('indirect_good_id') is-invalid @enderror" data-placeholder="Select Indirect Good" required disabled>
                                <option value="">Select project first</option>
                            </select>
                            @error('indirect_good_id') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="font-weight-bold">Invoice Number <span class="text-danger">*</span></label>
                            <select name="invoice_number" id="invoice_number" class="form-control warehouse-select2 @error('invoice_number') is-invalid @enderror" data-placeholder="Select Invoice" required disabled>
                                <option value="">Select item first</option>
                            </select>
                            @error('invoice_number') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="font-weight-bold">Quantity to Consume <span class="text-danger">*</span></label>
                            <input type="number" name="quantity_consumed" id="quantity_consumed" class="form-control @error('quantity_consumed') is-invalid @enderror" value="{{ old('quantity_consumed') }}" step="0.01" min="0.01" required>
                            <small class="text-muted" id="available-qty-text">Available: -</small>
                            @error('quantity_consumed') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label class="font-weight-bold">Reason / Notes</label>
                            <textarea name="reason" class="form-control @error('reason') is-invalid @enderror" rows="3" placeholder="Provide reason for consumption/write-off...">{{ old('reason') }}</textarea>
                            @error('reason') <div class="invalid-feedback">{{ $message }}</div> @enderror
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-footer text-right">
                <a href="{{ route('warehouse.indirect-goods.consumption.index') }}" class="btn btn-secondary mr-2">Cancel</a>
                <button type="submit" class="btn btn-primary">
                    <i class="material-icons mr-1" style="font-size: 16px;">save</i>
                    Record Consumption
                </button>
            </div>
        </div>
    </form>
@endsection

@push('styles')
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    <style>
        .select2-container--bootstrap-5 .select2-selection {
            min-height: 38px;
            border: 1px solid #ced4da;
        }
        .select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered {
            line-height: 36px;
        }
        .select2-container--bootstrap-5 .select2-selection--single .select2-selection__arrow {
            height: 36px;
        }
        .select2-container {
            width: 100% !important;
        }
    </style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    var projectItemsUrlTemplate = @json(route('warehouse.indirect-goods.consumption.api.project-items', ['projectId' => '__PROJECT_ID__']));
    var itemInvoicesUrlTemplate = @json(route('warehouse.indirect-goods.consumption.api.item-invoices', ['projectId' => '__PROJECT_ID__', 'indirectGoodId' => '__ITEM_ID__']));

    $('.warehouse-select2').select2({
        theme: 'bootstrap-5',
        allowClear: true,
        width: '100%',
        placeholder: function() {
            return $(this).data('placeholder') || 'Select...';
        }
    });

    // Load items when project changes
    $('#project_id').change(function() {
        var projectId = $(this).val();
        var $itemSelect = $('#indirect_good_id');
        var $invoiceSelect = $('#invoice_number');
        $itemSelect.html('<option value="">Loading...</option>').prop('disabled', true).trigger('change.select2');
        $invoiceSelect.html('<option value="">Select item first</option>').prop('disabled', true).trigger('change.select2');
        $('#available-qty-text').text('Available: -');

        if (!projectId) {
            $itemSelect.html('<option value="">Select project first</option>').trigger('change.select2');
            return;
        }

        var url = projectItemsUrlTemplate.replace('__PROJECT_ID__', encodeURIComponent(projectId));

        $.get(url, function(data) {
            var options = '<option value="">Select Indirect Good</option>';
            if (data.length === 0) {
                options = '<option value="">No indirect goods available for this project</option>';
                $itemSelect.html(options).prop('disabled', true).trigger('change.select2');
                return;
            }

            data.forEach(function(item) {
                options += '<option value="' + item.id + '">' + item.text + ' (Available: ' + item.total_available + ')</option>';
            });
            $itemSelect.html(options).prop('disabled', false).trigger('change.select2');
        }).fail(function() {
            $itemSelect.html('<option value="">Unable to load indirect goods</option>').prop('disabled', true).trigger('change.select2');
        });
    });

    // Load invoices when item changes
    $('#indirect_good_id').change(function() {
        var projectId = $('#project_id').val();
        var itemId = $(this).val();
        var $invoiceSelect = $('#invoice_number');
        $invoiceSelect.html('<option value="">Loading...</option>').prop('disabled', true).trigger('change.select2');
        $('#available-qty-text').text('Available: -');

        if (!itemId || !projectId) {
            $invoiceSelect.html('<option value="">Select item first</option>').trigger('change.select2');
            return;
        }

        var url = itemInvoicesUrlTemplate
            .replace('__PROJECT_ID__', encodeURIComponent(projectId))
            .replace('__ITEM_ID__', encodeURIComponent(itemId));

        $.get(url, function(data) {
            var options = '<option value="">Select Invoice</option>';
            if (data.length === 0) {
                options = '<option value="">No invoices available for this item</option>';
                $invoiceSelect.html(options).prop('disabled', true).trigger('change.select2');
                return;
            }

            data.forEach(function(inv) {
                options += '<option value="' + inv.invoice_number + '" data-available="' + inv.quantity_available + '">'
                    + inv.invoice_number + ' (Available: ' + parseFloat(inv.quantity_available).toFixed(2) + ')</option>';
            });
            $invoiceSelect.html(options).prop('disabled', false).trigger('change.select2');
        }).fail(function() {
            $invoiceSelect.html('<option value="">Unable to load invoices</option>').prop('disabled', true).trigger('change.select2');
        });
    });

    // Show available quantity when invoice selected
    $('#invoice_number').change(function() {
        var selected = $(this).find(':selected');
        var available = selected.data('available');
        if (available !== undefined) {
            $('#available-qty-text').text('Available: ' + parseFloat(available).toFixed(2));
            $('#quantity_consumed').attr('max', available);
        } else {
            $('#available-qty-text').text('Available: -');
        }
    });
});
</script>
@endpush
