

<?php $__env->startSection('title', 'Edit Manufacturing BOM'); ?>

<?php $__env->startPush('plugin-styles'); ?>
    <style>
        .select2-container {
            border: 1px solid #ddd !important;
            border-radius: 8px !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>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Edit Manufacturing BOM: <?php echo e($manufacturingBom->name); ?></h3>
                    <div class="card-tools">
                        <a href="<?php echo e(route('manufacturing.boms.show', $manufacturingBom->id)); ?>" class="btn btn-info btn-sm">
                            <i class="fas fa-eye"></i> View
                        </a>
                        <a href="<?php echo e(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="<?php echo e(route('manufacturing.boms.update', $manufacturingBom->id)); ?>" method="POST">
                    <?php echo csrf_field(); ?>
                    <?php echo method_field('PUT'); ?>
                    <div class="card-body">
                        

                        <!-- 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>
                                    <input type="text" class="form-control"
                                           value="<?php echo e($manufacturingBom->finishedGoods ? $manufacturingBom->finishedGoods->name . ' (' . $manufacturingBom->finishedGoods->sku . ')' : 'No finished goods selected'); ?>"
                                           readonly>
                                    <input type="hidden" name="finished_goods_account_id" value="<?php echo e($manufacturingBom->finished_goods_account_id); ?>">
                                    <small class="form-text text-muted">Finished goods cannot be changed after BOM creation</small>
                                </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 <?php $__errorArgs = ['basic_unit_amount'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                           id="basic_unit_amount" name="basic_unit_amount"
                                           value="<?php echo e(old('basic_unit_amount', $manufacturingBom->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>
                                    <?php $__errorArgs = ['basic_unit_amount'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="basic_unit">Unit <span class="text-danger">*</span></label>
                                    

                                    
                                    <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">
                                            <?php if($manufacturingBom->finishedGoods && $manufacturingBom->finishedGoods->uom): ?>
                                                <?php echo e($manufacturingBom->finishedGoods->uom->name); ?>

                                            <?php else: ?>
                                                <?php echo e($manufacturingBom->basic_unit ?? 'No unit specified'); ?>

                                            <?php 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 <?php $__errorArgs = ['description'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                              id="description" name="description" rows="3"><?php echo e(old('description', $manufacturingBom->description)); ?></textarea>
                                    <?php $__errorArgs = ['description'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                </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">
                                        <?php if(old('ingredients')): ?>
                                            <?php $__currentLoopData = old('ingredients'); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $ingredient): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <?php
                                                    $selectedAccount = \App\Models\Account::find($ingredient['ingredient_account_id'] ?? null);
                                                ?>
                                                <tr id="ingredient-row-<?php echo e($index + 1); ?>">
                                                    <td>
                                                        <select class="form-control select2 ingredient-select" name="ingredients[<?php echo e($index + 1); ?>][ingredient_account_id]" required>
                                                            <option value="">Select Raw Material</option>
                                                            <?php if($selectedAccount): ?>
                                                                <option value="<?php echo e($selectedAccount->id); ?>" selected><?php echo e($selectedAccount->name); ?> (<?php echo e($selectedAccount->sku); ?>)</option>
                                                            <?php endif; ?>
                                                        </select>
                                                    </td>
                                                    <td>
                                                        <input type="number" class="form-control" name="ingredients[<?php echo e($index + 1); ?>][quantity_required]"
                                                               step="0.0001" min="0.0001" required placeholder="0.0000"
                                                               value="<?php echo e($ingredient['quantity_required'] ?? ''); ?>">
                                                    </td>
                                                    <td>
                                                        

                                                        
                                                        <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">
                                                                <?php if(isset($ingredient['ingredient_account_id']) && $ingredient['ingredient_account_id']): ?>
                                                                    <?php
                                                                        $selectedAccount = \App\Models\Account::with('uom')->find($ingredient['ingredient_account_id']);
                                                                    ?>
                                                                    <?php if($selectedAccount && $selectedAccount->uom): ?>
                                                                        <?php echo e($selectedAccount->uom->name); ?>

                                                                    <?php elseif(isset($ingredient['unit']) && $ingredient['unit']): ?>
                                                                        <?php echo e($ingredient['unit']); ?>

                                                                    <?php else: ?>
                                                                        No unit specified
                                                                    <?php endif; ?>
                                                                <?php else: ?>
                                                                    <?php echo e($ingredient['unit'] ?? 'No unit specified'); ?>

                                                                <?php endif; ?>
                                                            </span>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <select class="form-control" name="ingredients[<?php echo e($index + 1); ?>][wastage_type]">
                                                            <option value="percentage" <?php echo e(($ingredient['wastage_type'] ?? 'percentage') == 'percentage' ? 'selected' : ''); ?>>Percentage</option>
                                                            <option value="absolute" <?php echo e(($ingredient['wastage_type'] ?? '') == 'absolute' ? 'selected' : ''); ?>>Absolute</option>
                                                        </select>
                                                    </td>
                                                    <td>
                                                        <input type="number" class="form-control" name="ingredients[<?php echo e($index + 1); ?>][wastage_value]"
                                                               step="0.0001" min="0" value="<?php echo e($ingredient['wastage_value'] ?? '0'); ?>" placeholder="0.0000">
                                                    </td>
                                                    <td>
                                                        <button type="button" class="btn btn-danger btn-sm" onclick="removeIngredientRow(<?php echo e($index + 1); ?>)">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        <?php else: ?>
                                            <?php $__currentLoopData = $manufacturingBom->ingredients; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $ingredient): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <tr id="ingredient-row-<?php echo e($index + 1); ?>">
                                                    <td>
                                                        <select class="form-control select2 ingredient-select" name="ingredients[<?php echo e($index + 1); ?>][ingredient_account_id]" required>
                                                            <option value="">Select Raw Material</option>
                                                            <option value="<?php echo e($ingredient->ingredient->id); ?>" selected><?php echo e($ingredient->ingredient->name); ?> (<?php echo e($ingredient->ingredient->sku); ?>)</option>
                                                        </select>
                                                    </td>
                                                    <td>
                                                        <input type="number" class="form-control" name="ingredients[<?php echo e($index + 1); ?>][quantity_required]"
                                                               step="0.0001" min="0.0001" required placeholder="0.0000"
                                                               value="<?php echo e($ingredient->quantity_required); ?>">
                                                    </td>
                                                    <td>
                                                        

                                                        
                                                        <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">
                                                                <?php if($ingredient->ingredient && $ingredient->ingredient->uom): ?>
                                                                    <?php echo e($ingredient->ingredient->uom->name); ?>

                                                                <?php else: ?>
                                                                    <?php echo e($ingredient->unit ?? 'No unit specified'); ?>

                                                                <?php endif; ?>
                                                            </span>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <select class="form-control" name="ingredients[<?php echo e($index + 1); ?>][wastage_type]">
                                                            <option value="percentage" <?php echo e($ingredient->wastage_type == 'percentage' ? 'selected' : ''); ?>>Percentage</option>
                                                            <option value="absolute" <?php echo e($ingredient->wastage_type == 'absolute' ? 'selected' : ''); ?>>Absolute</option>
                                                        </select>
                                                    </td>
                                                    <td>
                                                        <input type="number" class="form-control" name="ingredients[<?php echo e($index + 1); ?>][wastage_value]"
                                                               step="0.0001" min="0" value="<?php echo e($ingredient->wastage_value); ?>" placeholder="0.0000">
                                                    </td>
                                                    <td>
                                                        <button type="button" class="btn btn-danger btn-sm" onclick="removeIngredientRow(<?php echo e($index + 1); ?>)">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <div class="card-footer">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Update BOM
                        </button>
                        <a href="<?php echo e(route('manufacturing.boms.show', $manufacturingBom->id)); ?>" class="btn btn-secondary">
                            <i class="fas fa-times"></i> Cancel
                        </a>
                    </div>
                </form>
            </div>
            </div>
        </div>
    </div>

    <!-- Steps Management -->
    

    <!-- Ingredients Management -->
    

</div>


<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
$(document).ready(function() {
    // Finished goods field is read-only in edit mode

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

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

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

    // Initialize Select2 for existing ingredient rows
    $('.ingredient-select').each(function() {
        $(this).select2({
            theme: 'bootstrap4',
            width: '100%',
            ajax: {
                url: "<?php echo e(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
        });
    });

    // Initialize raw materials Select2
    $('#ingredient_account_id').select2({
        theme: 'bootstrap4',
        width: '100%',
        ajax: {
            url: "<?php echo e(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
    $('#ingredient_account_id').on('select2:select', function (e) {
        var data = e.params.data;
        $('#unit').val(data.unit);
    });

    // Ingredient management functions
    let ingredientRowCount = <?php echo e($manufacturingBom->ingredients->count()); ?>;

    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>
                    

                    
                    <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: "<?php echo e(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 removeIngredientRow(rowId) {
        if (confirm('Are you sure you want to remove this ingredient?')) {
            $(`#ingredient-row-${rowId}`).remove();
        }
    }

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

    // Add Step Form
    $('#addStepForm').on('submit', function(e) {
        e.preventDefault();

        $.ajax({
            url: "<?php echo e(route('manufacturing.boms.add-step', $manufacturingBom->id)); ?>",
            type: 'POST',
            data: $(this).serialize(),
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert('Error: ' + response.message);
                }
            },
            error: function(xhr) {
                alert('Error adding step');
            }
        });
    });

    // Add Ingredient Form
    $('#addIngredientForm').on('submit', function(e) {
        e.preventDefault();

        $.ajax({
            url: "<?php echo e(route('manufacturing.boms.add-ingredient', $manufacturingBom->id)); ?>",
            type: 'POST',
            data: $(this).serialize(),
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert('Error: ' + response.message);
                }
            },
            error: function(xhr) {
                alert('Error adding ingredient');
            }
        });
    });
});

function removeStep(stepId) {
    if (confirm('Are you sure you want to remove this step?')) {
        $.ajax({
            url: "/manufacturing/boms/<?php echo e($manufacturingBom->id); ?>/steps/" + stepId,
            type: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert('Error: ' + response.message);
                }
            },
            error: function(xhr) {
                alert('Error removing step');
            }
        });
    }
}

function removeIngredient(ingredientId) {
    if (confirm('Are you sure you want to remove this ingredient?')) {
        $.ajax({
            url: "/manufacturing/boms/<?php echo e($manufacturingBom->id); ?>/ingredients/" + ingredientId,
            type: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert('Error: ' + response.message);
                }
            },
            error: function(xhr) {
                alert('Error removing ingredient');
            }
        });
    }
}
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\habibcables-ERP\resources\views\manufacturing\boms\edit.blade.php ENDPATH**/ ?>