@extends('layouts.app')

@section('title', 'Edit Manufacturing BOM')

@section('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: {{ $manufacturingBom->name }}</h3>
                    <div class="card-tools">
                        <a href="{{ route('manufacturing.boms.show', $manufacturingBom->id) }}" class="btn btn-info btn-sm">
                            <i class="fas fa-eye"></i> View
                        </a>
                        <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.update', $manufacturingBom->id) }}" method="POST">
                    @csrf
                    @method('PUT')
                    <div class="card-body">
                        {{-- <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', $manufacturingBom->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', $manufacturingBom->version) }}" 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', $manufacturingBom->is_active) == 1 ? 'selected' : '' }}>Active</option>
                                        <option value="0" {{ old('is_active', $manufacturingBom->is_active) == 0 ? 'selected' : '' }}>Inactive</option>
                                    </select>
                                    @error('is_active')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </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', $manufacturingBom->description) }}</textarea>
                                    @error('description')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </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="{{ route('manufacturing.boms.show', $manufacturingBom->id) }}" class="btn btn-secondary">
                            <i class="fas fa-times"></i> Cancel
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Steps Management -->
    {{-- <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Manage Steps</h3>
                    <div class="card-tools">
                        <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#addStepModal">
                            <i class="fas fa-plus"></i> Add Step
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    @if($manufacturingBom->steps->count() > 0)
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>Sequence</th>
                                        <th>Step Name</th>
                                        <th>Instruction</th>
                                        <th>Ingredients</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($manufacturingBom->steps as $step)
                                    <tr>
                                        <td>{{ $step->sequence_order }}</td>
                                        <td>{{ $step->step_name }}</td>
                                        <td>{{ Str::limit($step->instruction, 50) }}</td>
                                        <td>
                                            <span class="badge badge-info">{{ $step->ingredients->count() }}</span>
                                        </td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-warning" onclick="editStep({{ $step->id }})">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-danger" onclick="removeStep({{ $step->id }})">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @else
                        <p class="text-muted">No steps defined for this BOM.</p>
                    @endif
                </div>
            </div>
        </div>
    </div> --}}

    <!-- Ingredients Management -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Manage Ingredients</h3>
                    <div class="card-tools">
                        <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#addIngredientModal">
                            <i class="fas fa-plus"></i> Add Ingredient
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    @if($manufacturingBom->ingredients->count() > 0)
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>Ingredient</th>
                                        <th>SKU</th>
                                        <th>Quantity Required</th>
                                        <th>Unit</th>
                                        <th>Wastage</th>
                                        <th>Step</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($manufacturingBom->ingredients as $ingredient)
                                    <tr>
                                        <td>{{ $ingredient->ingredient->name }}</td>
                                        <td>{{ $ingredient->ingredient->sku }}</td>
                                        <td>{{ $ingredient->formatted_quantity }}</td>
                                        <td>{{ $ingredient->unit }}</td>
                                        <td>{{ $ingredient->formatted_wastage }}</td>
                                        <td>
                                            @if($ingredient->step)
                                                <span class="badge badge-info">{{ $ingredient->step->step_name }}</span>
                                            @else
                                                <span class="badge badge-secondary">Direct</span>
                                            @endif
                                        </td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-warning" onclick="editIngredient({{ $ingredient->id }})">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-danger" onclick="removeIngredient({{ $ingredient->id }})">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @else
                        <p class="text-muted">No ingredients defined for this BOM.</p>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Step Modal -->
<div class="modal fade" id="addStepModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Step</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form id="addStepForm">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="step_name">Step Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="step_name" name="step_name" required>
                    </div>
                    <div class="form-group">
                        <label for="instruction">Instruction</label>
                        <textarea class="form-control" id="instruction" name="instruction" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="sequence_order">Sequence Order <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="sequence_order" name="sequence_order" min="1" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Step</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Ingredient Modal -->
<div class="modal fade" id="addIngredientModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Ingredient</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form id="addIngredientForm">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="ingredient_account_id">Raw Material <span class="text-danger">*</span></label>
                        <select class="form-control select2" id="ingredient_account_id" name="ingredient_account_id" required>
                            <option value="">Select Raw Material</option>
                        </select>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="quantity_required">Quantity Required <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="quantity_required" name="quantity_required" step="0.0001" min="0.0001" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="unit">Unit <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="unit" name="unit" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="wastage_type">Wastage Type</label>
                                <select class="form-control" id="wastage_type" name="wastage_type">
                                    <option value="percentage">Percentage</option>
                                    <option value="absolute">Absolute</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="wastage_value">Wastage Value</label>
                                <input type="number" class="form-control" id="wastage_value" name="wastage_value" step="0.0001" min="0" value="0">
                            </div>
                        </div>
                    </div>
                    {{-- <div class="form-group">
                        <label for="manufacturing_bom_step_id">Assign to Step (Optional)</label>
                        <select class="form-control" id="manufacturing_bom_step_id" name="manufacturing_bom_step_id">
                            <option value="">Direct to BOM</option>
                            @foreach($manufacturingBom->steps as $step)
                                <option value="{{ $step->id }}">{{ $step->step_name }}</option>
                            @endforeach
                        </select>
                    </div> --}}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Ingredient</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
$(document).ready(function() {
    // Initialize Select2
    $('#is_active').select2({
        theme: 'bootstrap4',
        width: '100%'
    });

    // Initialize raw materials Select2
    $('#ingredient_account_id').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
    $('#ingredient_account_id').on('select2:select', function (e) {
        var data = e.params.data;
        $('#unit').val(data.unit);
    });

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

        $.ajax({
            url: "{{ 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: "{{ 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/{{ $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/{{ $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>
@endpush
