@extends('layouts.app')

@section('title', 'Create Manufacturing BOM')
@push('plugin-styles')
    <style>
        .select2-container {
            border: 1px solid #ddd !important;
            border-radius: 8px !important;
            /* width: 100% !important; */
        }
        .select2-selection__rendered{
            padding-top: 1.8% !important;
        }
        .select2-container .select2-selection--single{
            height: 45px !important;
        }

        /* BOM exists warning styles */
        .btn:disabled {
            cursor: not-allowed;
            opacity: 0.6;
        }

        .bom-exists-warning {
            border-left: 4px solid #ffc107;
        }

        .form-control.is-invalid {
            border-color: #dc3545;
            box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
        }
    </style>
@endpush
@section('content')
@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" aria-label="Close"></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>
				<strong>Please fix the following errors:</strong>
				<ul class="mb-0 mt-2">
					@foreach($errors->all() as $error)
						<li>{{ $error }}</li>
					@endforeach
				</ul>
				<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
			</div>
		@endif
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Create Manufacturing BOM</h3>
                    <div class="card-tools">
                        <a href="{{ route('manufacturing.boms.index') }}" class="btn btn-secondary btn-sm">
                            <i class="fas fa-arrow-left"></i> Back to BOMs
                        </a>
                    </div>
                </div>
                <form action="{{ route('manufacturing.boms.store') }}" method="POST" id="bomForm">
                    @csrf
                    <div class="card-body">
                        @if(session('error'))
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="fas fa-exclamation-triangle me-2"></i>{{ session('error') }}
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                        @endif
                        <!-- Basic BOM Information -->
                        {{-- <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="name">BOM Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control @error('name') is-invalid @enderror"
                                           id="name" name="name" value="{{ old('name') }}" required>
                                    @error('name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="version">Version <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control @error('version') is-invalid @enderror"
                                           id="version" name="version" value="{{ old('version', 1) }}" min="1" required>
                                    @error('version')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="is_active">Status</label>
                                    <select class="form-control @error('is_active') is-invalid @enderror"
                                            id="is_active" name="is_active">
                                        <option value="1" {{ old('is_active', 1) == 1 ? 'selected' : '' }}>Active</option>
                                        <option value="0" {{ old('is_active') == 0 ? 'selected' : '' }}>Inactive</option>
                                    </select>
                                    @error('is_active')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div> --}}

                        <!-- Finished Goods Selection -->
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="finished_goods_account_id">Finished Goods <span class="text-danger">*</span></label>
                                    <select class="form-control select2 @error('finished_goods_account_id') is-invalid @enderror"
                                            id="finished_goods_account_id" name="finished_goods_account_id" required>
                                        <option value="">Select Finished Goods</option>
                                        @if(old('finished_goods_account_id'))
                                            @php
                                                $selectedAccount = \App\Models\Account::find(old('finished_goods_account_id'));
                                            @endphp
                                            @if($selectedAccount)
                                                <option value="{{ $selectedAccount->id }}" selected>{{ $selectedAccount->name }} ({{ $selectedAccount->sku }})</option>
                                            @endif
                                        @endif
                                    </select>
                                    @error('finished_goods_account_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="basic_unit_amount">Basic Unit Amount <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control @error('basic_unit_amount') is-invalid @enderror"
                                           id="basic_unit_amount" name="basic_unit_amount" value="{{ old('basic_unit_amount') }}"
                                           step="0.0001" min="0.0001" required placeholder="e.g., 90">
                                    <small class="form-text text-muted">Amount of finished product (e.g., 90 for a coil of cable)</small>
                                    @error('basic_unit_amount')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="basic_unit">Unit <span class="text-danger">*</span></label>
                                    {{-- OLD: Unit select version - commented out
                                    @include('common.unit-select', [
                                        'name' => 'basic_unit',
                                        'class' => 'form-control',
                                        'selected' => old('basic_unit'),
                                        'required' => true,
                                        'placeholder' => 'Select Unit'
                                    ])
                                    --}}

                                    {{-- NEW: Text display for unit --}}
                                    <div class="form-control unit-display" style="background-color: #f8f9fa; border-color: #dee2e6; color: #495057; cursor: not-allowed; display: flex; align-items: center; height: 45px;">
                                        <span class="unit-text">
                                            @if(old('finished_goods_account_id'))
                                                @php
                                                    $selectedAccount = \App\Models\Account::with('uom')->find(old('finished_goods_account_id'));
                                                @endphp
                                                @if($selectedAccount && $selectedAccount->uom)
                                                    {{ $selectedAccount->uom->name }}
                                                @elseif($selectedAccount && $selectedAccount->unit_of_measure)
                                                    {{ $selectedAccount->unit_of_measure }}
                                                @else
                                                    No unit specified
                                                @endif
                                            @else
                                                Select finished goods first
                                            @endif
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-12">
                                <div class="form-group">
                                    <label for="description">Description</label>
                                    <textarea class="form-control @error('description') is-invalid @enderror"
                                              id="description" name="description" rows="3">{{ old('description') }}</textarea>
                                    @error('description')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <!-- Ingredients Section -->
                        <div class="row">
                            <div class="col-12">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <h5 class="mb-0">
                                        Ingredients <span class="text-danger">*</span>
                                    </h5>
                                    <button type="button" class="btn btn-success btn-sm" id="addIngredientRow">
                                        <i class="fas fa-plus"></i> Add Ingredient
                                    </button>
                                </div>

                                <div class="table-responsive">
                                    <table class="table table-bordered" id="ingredientsTable">
                                        <thead>
                                            <tr>
                                                <th>Raw Material</th>
                                                <th>Quantity Required</th>
                                                <th>Unit</th>
                                                <th>Scrap Type</th>
                                                <th>Scrap Value</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody id="ingredientsTableBody">
                                            @if(old('ingredients'))
                                                @foreach(old('ingredients') as $index => $ingredient)
                                                    @php
                                                        $selectedAccount = \App\Models\Account::with('uom')->find($ingredient['ingredient_account_id'] ?? null);
                                                    @endphp
                                                    <tr id="ingredient-row-{{ $index + 1 }}">
                                                        <td>
                                                            <select class="form-control select2 ingredient-select" name="ingredients[{{ $index + 1 }}][ingredient_account_id]" required>
                                                                <option value="">Select Raw Material</option>
                                                                @if($selectedAccount)
                                                                    <option value="{{ $selectedAccount->id }}" selected>{{ $selectedAccount->name }} ({{ $selectedAccount->sku }})</option>
                                                                @endif
                                                            </select>
                                                        </td>
                                                        <td>
                                                            <input type="number" class="form-control" name="ingredients[{{ $index + 1 }}][quantity_required]"
                                                                   step="0.0001" min="0.0001" required placeholder="0.0000"
                                                                   value="{{ $ingredient['quantity_required'] ?? '' }}">
                                                        </td>
                                                        <td>
                                                            {{-- OLD: Unit select version - commented out
                                                            @include('common.unit-select', [
                                                                'name' => 'ingredients[' . ($index + 1) . '][unit]',
                                                                'class' => 'form-control',
                                                                'selected' => $ingredient['unit'] ?? '',
                                                                'required' => true,
                                                                'placeholder' => 'Select Unit'
                                                            ])
                                                            --}}

                                                            {{-- NEW: Text display for unit --}}
                                                            <div class="form-control unit-display" style="background-color: #f8f9fa; border-color: #dee2e6; color: #495057; cursor: not-allowed; display: flex; align-items: center; height: 38px;">
                                                                <span class="unit-text">
                                                                    @if($selectedAccount && $selectedAccount->uom)
                                                                        {{ $selectedAccount->uom->name }}
                                                                    @elseif(isset($ingredient['unit']) && $ingredient['unit'])
                                                                        {{ $ingredient['unit'] }}
                                                                    @else
                                                                        Select raw material first
                                                                    @endif
                                                                </span>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <select class="form-control" name="ingredients[{{ $index + 1 }}][wastage_type]">
                                                                <option value="percentage" {{ ($ingredient['wastage_type'] ?? 'percentage') == 'percentage' ? 'selected' : '' }}>Percentage</option>
                                                                <option value="absolute" {{ ($ingredient['wastage_type'] ?? '') == 'absolute' ? 'selected' : '' }}>Absolute</option>
                                                            </select>
                                                        </td>
                                                        <td>
                                                            <input type="number" class="form-control" name="ingredients[{{ $index + 1 }}][wastage_value]"
                                                                   step="0.0001" min="0" value="{{ $ingredient['wastage_value'] ?? '0' }}" placeholder="0.0000">
                                                        </td>
                                                        <td>
                                                            <button type="button" class="btn btn-danger btn-sm" onclick="removeIngredientRow({{ $index + 1 }})">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        </td>
                                                    </tr>
                                                @endforeach
                                            @endif
                                        </tbody>
                                    </table>
                                </div>

                            </div>
                        </div>

                        <!-- Steps Section (Optional) -->
                        {{-- <div class="row mt-4">
                            <div class="col-12">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h5>Manufacturing Steps <small class="text-muted">(Optional)</small></h5>
                                    <button type="button" class="btn btn-primary btn-sm" id="addStepBtn">
                                        <i class="fas fa-plus"></i> Add Step
                                    </button>
                                </div>
                                <div id="stepsContainer">
                                    <!-- Dynamic steps will be added here -->
                                </div>
                            </div>
                        </div> --}}
                    </div>

                    <div class="card-footer">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Create BOM
                        </button>
                        <a href="{{ route('manufacturing.boms.index') }}" class="btn btn-secondary">
                            <i class="fas fa-times"></i> Cancel
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>

@endsection

@push('scripts')
<script>
$(document).ready(function() {
    let ingredientRowCount = {{ old('ingredients') ? count(old('ingredients')) : 0 }};
    let stepCount = 0;

    // Initialize Select2 for finished goods
    $('#finished_goods_account_id').select2({
        theme: 'bootstrap5',
        width: '100%',
        ajax: {
            url: "{{ route('manufacturing.boms.search-finished-goods') }}",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    q: params.term
                };
            },
            processResults: function (data) {
                console.log('Finished goods search results:', data);
                return {
                    results: data.results || []
                };
            },
            cache: true,
            error: function (xhr, status, error) {
                console.error('Error searching finished goods:', error);
                console.error('Response:', xhr.responseText);
                return {
                    results: []
                };
            }
        },
        placeholder: 'Search for finished goods...',
        minimumInputLength: 1
    });

    // Check for existing BOM when finished goods is selected
    $('#finished_goods_account_id').on('select2:select', function (e) {
        const finishedGoodsId = e.params.data.id;
        checkBOMExists(finishedGoodsId);

        // Update basic unit display
        updateBasicUnitDisplay(e.params.data);
    });

    // Handle when finished goods selection is cleared or changed
    $('#finished_goods_account_id').on('select2:clear', function (e) {
        clearBOMExistsWarning();
    });

    // Handle when finished goods selection changes
    $('#finished_goods_account_id').on('change', function (e) {
        const selectedValue = $(this).val();
        if (!selectedValue) {
            clearBOMExistsWarning();
        }
    });

    // Function to check if BOM already exists for selected finished good
    function checkBOMExists(finishedGoodsId) {
        if (!finishedGoodsId) return;

        $.ajax({
            url: "{{ route('manufacturing.boms.check-exists') }}",
            method: 'POST',
            data: {
                finished_goods_account_id: finishedGoodsId,
                _token: $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.exists) {
                    // Show warning message
                    showBOMExistsWarning(response);
                } else {
                    // Clear any existing warnings
                    clearBOMExistsWarning();
                }
            },
            error: function(xhr) {
                console.error('Error checking BOM existence:', xhr.responseText);
            }
        });
    }

    // Prevent form submission if BOM exists
    $('form').on('submit', function(e) {
        const submitBtn = $('button[type="submit"]');
        if (submitBtn.prop('disabled')) {
            e.preventDefault();
            alert('Cannot create BOM: A BOM already exists for the selected finished good. Please select a different finished good or edit the existing BOM.');
            return false;
        }
    });

    // Function to show BOM exists warning
    function showBOMExistsWarning(response) {
        // Remove existing warning if any
        $('.bom-exists-warning').remove();

        const warningHtml = `
            <div class="alert alert-warning bom-exists-warning mt-2">
                <i class="fas fa-exclamation-triangle"></i>
                <strong>Warning:</strong> ${response.message}
                <br>
                <small>Existing BOM: <strong>${response.bom_name}</strong> (ID: ${response.bom_id})</small>
                <br>
                <a href="/manufacturing/boms/${response.bom_id}/edit" class="btn btn-sm btn-outline-primary mt-1" target="_blank">
                    <i class="fas fa-edit"></i> Edit Existing BOM
                </a>
            </div>
        `;

        $('#finished_goods_account_id').closest('.form-group').after(warningHtml);

        // Add error class to the select
        $('#finished_goods_account_id').addClass('is-invalid');

        // Disable submit button
        disableSubmitButton();
    }

    // Function to clear BOM exists warning
    function clearBOMExistsWarning() {
        $('.bom-exists-warning').remove();
        $('#finished_goods_account_id').removeClass('is-invalid');

        // Enable submit button
        enableSubmitButton();
    }

    // Function to disable submit button
    function disableSubmitButton() {
        const submitBtn = $('button[type="submit"]');
        submitBtn.prop('disabled', true);
        submitBtn.addClass('btn-secondary').removeClass('btn-primary');
        submitBtn.html('<i class="fas fa-ban"></i> Cannot Create BOM - Already Exists');

        // Add tooltip
        submitBtn.attr('title', 'A BOM already exists for this finished good. Please select a different finished good or edit the existing BOM.');
    }

    // Function to enable submit button
    function enableSubmitButton() {
        const submitBtn = $('button[type="submit"]');
        submitBtn.prop('disabled', false);
        submitBtn.addClass('btn-primary').removeClass('btn-secondary');
        submitBtn.html('<i class="fas fa-save"></i> Create BOM');

        // Remove tooltip
        submitBtn.removeAttr('title');
    }

    // Initialize other Select2 elements
    $('#is_active, #basic_unit').select2({
        theme: 'bootstrap5',
        width: '100%'
    });

    // Add ingredient row
    $('#addIngredientRow').click(function() {
        addIngredientRow();
    });

    // Add step
    // $('#addStepBtn').click(function() {
    //     addStep();
    // });

    // Initialize Select2 for existing ingredient rows
    $('.ingredient-select').each(function() {
        $(this).select2({
            theme: 'bootstrap4',
            width: '100%',
            ajax: {
                url: "{{ route('manufacturing.boms.search-raw-materials') }}",
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        q: params.term
                    };
                },
                processResults: function (data) {
                    return {
                        results: data.results
                    };
                },
                cache: true
            },
            placeholder: 'Search for raw materials...',
            minimumInputLength: 1
        });
    });

    // Add first ingredient row by default only if no existing rows
    if (ingredientRowCount === 0) {
        addIngredientRow();
    }

    function addIngredientRow() {
        ingredientRowCount++;
        const row = `
            <tr id="ingredient-row-${ingredientRowCount}">
                <td>
                    <select class="form-control select2 ingredient-select" name="ingredients[${ingredientRowCount}][ingredient_account_id]" required>
                        <option value="">Select Raw Material</option>
                    </select>
                </td>
                <td>
                    <input type="number" class="form-control" name="ingredients[${ingredientRowCount}][quantity_required]"
                           step="0.0001" min="0.0001" required placeholder="0.0000">
                </td>
                <td>
                    {{-- OLD: Unit select version - commented out
                    <select class="form-control" name="ingredients[${ingredientRowCount}][unit]" required>
                        <option value="">Select Unit</option>
                        <option value="meters">Meters</option>
                        <option value="pieces">Pieces</option>
                        <option value="kg">Kilograms</option>
                        <option value="tons">Tons</option>
                        <option value="liters">Liters</option>
                        <option value="boxes">Boxes</option>
                        <option value="rolls">Rolls</option>
                        <option value="coils">Coils</option>
                        <option value="pcs">Pieces</option>
                        <option value="m">Meters</option>
                        <option value="l">Liters</option>
                        <option value="g">Grams</option>
                        <option value="mg">Milligrams</option>
                        <option value="cm">Centimeters</option>
                        <option value="mm">Millimeters</option>
                        <option value="ft">Feet</option>
                        <option value="in">Inches</option>
                        <option value="yd">Yards</option>
                        <option value="sqm">Square Meters</option>
                        <option value="cbm">Cubic Meters</option>
                        <option value="dozen">Dozen</option>
                        <option value="gross">Gross</option>
                        <option value="ream">Ream</option>
                        <option value="set">Set</option>
                        <option value="pair">Pair</option>
                        <option value="bundle">Bundle</option>
                        <option value="pack">Pack</option>
                        <option value="carton">Carton</option>
                        <option value="pallet">Pallet</option>
                        <option value="drum">Drum</option>
                        <option value="barrel">Barrel</option>
                        <option value="bag">Bag</option>
                        <option value="sack">Sack</option>
                        <option value="tube">Tube</option>
                        <option value="sheet">Sheet</option>
                        <option value="plate">Plate</option>
                        <option value="rod">Rod</option>
                        <option value="wire">Wire</option>
                        <option value="cable">Cable</option>
                        <option value="strand">Strand</option>
                        <option value="conductor">Conductor</option>
                        <option value="insulation">Insulation</option>
                        <option value="jacket">Jacket</option>
                        <option value="core">Core</option>
                        <option value="twist">Twist</option>
                        <option value="bunch">Bunch</option>
                        <option value="lay">Lay</option>
                        <option value="pitch">Pitch</option>
                        <option value="diameter">Diameter</option>
                        <option value="gauge">Gauge</option>
                        <option value="awg">AWG</option>
                        <option value="mm2">Square Millimeters</option>
                        <option value="cm2">Square Centimeters</option>
                        <option value="m2">Square Meters</option>
                        <option value="mm3">Cubic Millimeters</option>
                        <option value="cm3">Cubic Centimeters</option>
                        <option value="m3">Cubic Meters</option>
                    </select>
                    --}}

                    {{-- NEW: Text display for unit --}}
                    <div class="form-control unit-display" style="background-color: #f8f9fa; border-color: #dee2e6; color: #495057; cursor: not-allowed; display: flex; align-items: center; height: 38px;">
                        <span class="unit-text">Select raw material first</span>
                    </div>
                </td>
                <td>
                    <select class="form-control" name="ingredients[${ingredientRowCount}][wastage_type]">
                        <option value="percentage">Percentage</option>
                        <option value="absolute">Absolute</option>
                    </select>
                </td>
                <td>
                    <input type="number" class="form-control" name="ingredients[${ingredientRowCount}][wastage_value]"
                           step="0.0001" min="0" value="0" placeholder="0.0000">
                </td>
                <td>
                    <button type="button" class="btn btn-danger btn-sm" onclick="removeIngredientRow(${ingredientRowCount})">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            </tr>
        `;
        $('#ingredientsTableBody').append(row);

        // Initialize Select2 for the new ingredient select
        $(`#ingredient-row-${ingredientRowCount} .ingredient-select`).select2({
            theme: 'bootstrap4',
            width: '100%',
            ajax: {
                url: "{{ route('manufacturing.boms.search-raw-materials') }}",
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        q: params.term
                    };
                },
                processResults: function (data) {
                    return {
                        results: data.results
                    };
                },
                cache: true
            },
            placeholder: 'Search for raw materials...',
            minimumInputLength: 1
        });

        // Handle ingredient selection to auto-fill unit
        $(`#ingredient-row-${ingredientRowCount} .ingredient-select`).on('select2:select', function (e) {
            var data = e.params.data;
            updateIngredientUnitDisplay($(this).closest('tr'), data);
        });
    }

    // function addStep() {
    //     stepCount++;
    //     const stepHtml = `
    //         <div class="card mt-3" id="step-${stepCount}">
    //             <div class="card-header">
    //                 <h6 class="mb-0">Step ${stepCount}</h6>
    //                 <button type="button" class="btn btn-danger btn-sm float-right" onclick="removeStep(${stepCount})">
    //                     <i class="fas fa-trash"></i>
    //                 </button>
    //             </div>
    //             <div class="card-body">
    //                 <div class="form-group">
    //                     <label>Step Description</label>
    //                     <textarea class="form-control" name="steps[${stepCount}][description]" rows="2" placeholder="Describe this manufacturing step..."></textarea>
    //                 </div>
    //                 <div class="form-group">
    //                     <label>Step Ingredients</label>
    //                     <button type="button" class="btn btn-success btn-sm mb-2" onclick="addStepIngredient(${stepCount})">
    //                         <i class="fas fa-plus"></i> Add Ingredient to Step
    //                     </button>
    //                     <div class="table-responsive">
    //                         <table class="table table-sm table-bordered" id="step-ingredients-${stepCount}">
    //                             <thead>
    //                                 <tr>
    //                                     <th>Raw Material</th>
    //                                     <th>Quantity</th>
    //                                     <th>Unit</th>
    //                                     <th>Scrap Type</th>
    //                                     <th>Scrap Value</th>
    //                                     <th>Actions</th>
    //                                 </tr>
    //                             </thead>
    //                             <tbody>
    //                                 <!-- Step ingredients will be added here -->
    //                             </tbody>
    //                         </table>
    //                     </div>
    //                 </div>
    //             </div>
    //         </div>
    //     `;
    //     $('#stepsContainer').append(stepHtml);
    // }

    // Global functions for removing rows
    window.removeIngredientRow = function(rowId) {
        $(`#ingredient-row-${rowId}`).remove();
    };

    window.removeStep = function(stepId) {
        $(`#step-${stepId}`).remove();
    };

    // window.addStepIngredient = function(stepId) {
    //     const stepIngredientCount = $(`#step-ingredients-${stepId} tbody tr`).length + 1;
    //     const row = `
    //         <tr>
    //             <td>
    //                 <select class="form-control select2 step-ingredient-select" name="steps[${stepId}][ingredients][${stepIngredientCount}][ingredient_account_id]" required>
    //                     <option value="">Select Raw Material</option>
    //                 </select>
    //             </td>
    //             <td>
    //                 <input type="number" class="form-control" name="steps[${stepId}][ingredients][${stepIngredientCount}][quantity_required]"
    //                        step="0.0001" min="0.0001" required>
    //             </td>
    //             <td>
    //                 <select class="form-control" name="steps[${stepId}][ingredients][${stepIngredientCount}][unit]" required>
    //                     <option value="">Select Unit</option>
    //                     <option value="meters">Meters</option>
    //                     <option value="pieces">Pieces</option>
    //                     <option value="kg">Kilograms</option>
    //                     <option value="tons">Tons</option>
    //                     <option value="liters">Liters</option>
    //                     <option value="boxes">Boxes</option>
    //                     <option value="rolls">Rolls</option>
    //                     <option value="coils">Coils</option>
    //                     <option value="pcs">Pieces</option>
    //                     <option value="m">Meters</option>
    //                     <option value="l">Liters</option>
    //                     <option value="g">Grams</option>
    //                     <option value="mg">Milligrams</option>
    //                     <option value="cm">Centimeters</option>
    //                     <option value="mm">Millimeters</option>
    //                     <option value="ft">Feet</option>
    //                     <option value="in">Inches</option>
    //                     <option value="yd">Yards</option>
    //                     <option value="sqm">Square Meters</option>
    //                     <option value="cbm">Cubic Meters</option>
    //                     <option value="dozen">Dozen</option>
    //                     <option value="gross">Gross</option>
    //                     <option value="ream">Ream</option>
    //                     <option value="set">Set</option>
    //                     <option value="pair">Pair</option>
    //                     <option value="bundle">Bundle</option>
    //                     <option value="pack">Pack</option>
    //                     <option value="carton">Carton</option>
    //                     <option value="pallet">Pallet</option>
    //                     <option value="drum">Drum</option>
    //                     <option value="barrel">Barrel</option>
    //                     <option value="bag">Bag</option>
    //                     <option value="sack">Sack</option>
    //                     <option value="tube">Tube</option>
    //                     <option value="sheet">Sheet</option>
    //                     <option value="plate">Plate</option>
    //                     <option value="rod">Rod</option>
    //                     <option value="wire">Wire</option>
    //                     <option value="cable">Cable</option>
    //                     <option value="strand">Strand</option>
    //                     <option value="conductor">Conductor</option>
    //                     <option value="insulation">Insulation</option>
    //                     <option value="jacket">Jacket</option>
    //                     <option value="core">Core</option>
    //                     <option value="twist">Twist</option>
    //                     <option value="bunch">Bunch</option>
    //                     <option value="lay">Lay</option>
    //                     <option value="pitch">Pitch</option>
    //                     <option value="diameter">Diameter</option>
    //                     <option value="gauge">Gauge</option>
    //                     <option value="awg">AWG</option>
    //                     <option value="mm2">Square Millimeters</option>
    //                     <option value="cm2">Square Centimeters</option>
    //                     <option value="m2">Square Meters</option>
    //                     <option value="mm3">Cubic Millimeters</option>
    //                     <option value="cm3">Cubic Centimeters</option>
    //                     <option value="m3">Cubic Meters</option>
    //                 </select>
    //             </td>
    //             <td>
    //                 <select class="form-control" name="steps[${stepId}][ingredients][${stepIngredientCount}][wastage_type]">
    //                     <option value="percentage">Percentage</option>
    //                     <option value="absolute">Absolute</option>
    //                 </select>
    //             </td>
    //             <td>
    //                 <input type="number" class="form-control" name="steps[${stepId}][ingredients][${stepIngredientCount}][wastage_value]"
    //                        step="0.0001" min="0" value="0">
    //             </td>
    //             <td>
    //                 <button type="button" class="btn btn-danger btn-sm" onclick="$(this).closest('tr').remove()">
    //                     <i class="fas fa-trash"></i>
    //                 </button>
    //             </td>
    //         </tr>
    //     `;
    //     $(`#step-ingredients-${stepId} tbody`).append(row);

    //     // Initialize Select2 for step ingredient
    //     $(`#step-ingredients-${stepId} tbody tr:last .step-ingredient-select`).select2({
    //         theme: 'bootstrap4',
    //         width: '100%',
    //         ajax: {
    //             url: "{{ route('manufacturing.boms.search-raw-materials') }}",
    //             dataType: 'json',
    //             delay: 250,
    //             data: function (params) {
    //                 return {
    //                     q: params.term
    //                 };
    //             },
    //             processResults: function (data) {
    //                 return {
    //                     results: data.results
    //                 };
    //             },
    //             cache: true
    //         },
    //         placeholder: 'Search for raw materials...',
    //         minimumInputLength: 1
    //     });

    //     // Handle step ingredient selection
    //     $(`#step-ingredients-${stepId} tbody tr:last .step-ingredient-select`).on('select2:select', function (e) {
    //         var data = e.params.data;
    //         $(this).closest('tr').find('input[name*="[unit]"]').val(data.unit);
    //     });
    // };

    // Helper functions for unit display
    function updateBasicUnitDisplay(data) {
        const unitText = data.unit_name || data.unit || 'No unit specified';
        $('.unit-display .unit-text').text(unitText);
    }

    function updateIngredientUnitDisplay(row, data) {
        const unitText = data.unit_name || data.unit || 'No unit specified';
        row.find('.unit-display .unit-text').text(unitText);
    }
});
</script>
@endpush
