@extends('layouts.layoutapp')

@section('content')
    <style>
        .form-control {
            padding-left: 15px !important;
        }       
    </style>
        <div class="row">
        <div class="col-12">
            <div class="card me-2">
                    <div class="card-header">
                        <h5> Bill Of Material</h5>
                    </div>
                    <div class="card-body">
                        <form class="submit" enctype="multipart/form-data">
                            @csrf
                            <div>
                                <h6> Bill Of Material Info </h6>
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label for="assembled_item">Assembled Item <span class="text-danger">*</span></label>
                                        <input type="text" name="assembled_item" id="assembled_item" value="{{ old('assembled_item', $bom->assemble_item ?? '') }}" class="form-control">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="remarks">Remarks</label>
                                        <textarea name="remarks" id="remarks" rows="1" class="form-control">{{ old('remarks', $bom->remarks) }}</textarea>
                                    </div>
                                </div>
                            </div>
                            <hr>
                            <div>
                                <div class="d-flex justify-content-between">
                                    <h6>Bill Of Material Items</h6>
                                    <div>
                                        <button type="button" class="btn btn-primary btn-sm" id="saveBomItem">
                                            Add Item
                                        </button>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label for="product_id">Product Name</label>
                                        <select id="product_id" class="form-select select2 product_id">
                                            <option value="">Select Product</option>
                                            @foreach ($product as $item)
                                                <option value="{{ $item->id }}" {{ old('product_id') == $item->id ? 'selected' : '' }}>
                                                    {{ $item->name }}({{ $item->code }})
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label for="unit">Unit</label>
                                        <input type="text" class="form-control unit" id="unit" readonly placeholder="UOM">
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label for="qty">Quantity</label>
                                        <input type="number" class="form-control qty" id="qty" step="0.01" placeholder="Quantity">
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label for="unit_cost">Unit Cost</label>
                                        <input type="number" class="form-control unit_cost" id="unit_cost" placeholder="Unit Cost">
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label for="total_amount">Total</label>
                                        <input type="number" class="form-control total_amount" id="total_amount" placeholder="Total">
                                    </div>
                                </div>
                                <hr>
                                <div class="d-flex justify-content-between">
                                    <h6>Additional Manufacturing Costs</h6>
                                    <div>
                                        <button type="button" class="btn btn-primary btn-sm" id="saveAdditionalCost">
                                            Add Cost
                                        </button>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label for="cost_type">Cost Type</label>
                                        <select id="cost_type" class="form-select select2 cost_type" placeholder="Enter Cost type">
                                            <option value="">Select Cost Type</option>
                                            @foreach ($costType as $item)
                                                <option value="{{ $item->id }}">{{ $item->name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label for="additional_unit">Unit</label>
                                        <select id="additional_unit" class="form-select additional_unit">
                                            <option value="" selected>Select Unit</option>
                                            @foreach ($unit as $item)
                                                <option value="{{ $item->id }}" data-unit_name="{{ $item->name }}">{{ $item->name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label for="additional_cost">Amount</label>
                                        <input type="number" class="form-control additional_cost" id="additional_cost" placeholder="Amount" step="0.01">
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label for="cost_description">Description</label>
                                        <input type="text" class="form-control cost_description" id="cost_description" placeholder="Description">
                                    </div>
                                </div>
                                <hr>
                                <div class="table-responsive">
                                    <table class="table table-bordered table-striped">
                                        <thead>
                                            <tr>
                                                <th class="text-center">#</th>
                                                <th class="text-center">Product Name</th>
                                                <th class="text-center">Unit</th>
                                                <th class="text-center">Quantity</th>
                                                <th class="text-center">Unit Cost</th>
                                                <th class="text-center">Total Amount</th>
                                                <th class="text-center"></th>
                                            </tr>
                                        </thead>
                                        <tbody class="added_product">
                                            @if(count($bom->bomItems) > 0)
                                                @foreach($bom->bomItems as $index => $item)
                                                    @if($item->type == 'product')
                                                        <tr data-type="product" data-index="{{ $index }}" data-row-number="{{ $loop->iteration }}">
                                                            <td class="text-center">{{ $loop->iteration }}</td>
                                                            <td class="text-center">
                                                                <input type="hidden" name="bom_items[{{ $index }}][product_id]" value="{{ $item->product_id }}" />
                                                                {{ ($item->product->name ?? '') . ' (' . ($item->product->code ?? '') . ')' }}
                                                            </td>
                                                            <td class="text-center">
                                                                <input type="hidden" name="bom_items[{{ $index }}][uom_id]" value="{{ $item->uom_id }}" />
                                                                {{ $item->unit->name ?? '-' }}
                                                            </td>
                                                            <td class="text-center">
                                                                <input type="hidden" name="bom_items[{{ $index }}][qty]" value="{{ $item->qty }}" />
                                                                {{ $item->qty }}
                                                            </td>
                                                            <td class="text-center">
                                                                <input type="hidden" name="bom_items[{{ $index }}][unit_cost]" value="{{ number_format($item->unit_cost, 2) }}" />
                                                                ₹ {{ number_format($item->unit_cost, 2) }}
                                                            </td>
                                                            <td class="text-center">
                                                                <input type="hidden" name="bom_items[{{ $index }}][amount]" value="{{ number_format($item->amount, 2) }}" />
                                                                ₹ {{ number_format($item->amount, 2) }}
                                                            </td>
                                                            <td class="text-center">
                                                                <a href="javascript:void(0)" class="remove-item text-danger"><i class="fa fa-trash"></i></a>
                                                            </td>
                                                        </tr>
                                                    @else
                                                        <tr data-type="additional_cost" data-index="{{ $index }}" data-row-number="{{ $loop->iteration }}">
                                                            <td class="text-center">{{ $loop->iteration }}</td>
                                                            <td class="text-center">
                                                                <input type="hidden" name="additional_costs[{{ $index }}][cost_type_id]" value="{{ $item->type ?? '' }}" />
                                                                <input type="hidden" name="additional_costs[{{ $index }}][cost_type_text]" value="{{ $item->costType->name ?? '' }}" />
                                                                <input type="hidden" name="additional_costs[{{ $index }}][description]" value="{{ $item->description ?? '' }}" />
                                                                {{ $item->costType->name ?? '' }}
                                                            </td>
                                                            <td class="text-center">
                                                                <input type="hidden" name="additional_costs[{{ $index }}][uom_id]" value="{{ $item->uom_id ?? '' }}" />
                                                                {{ $item->unit->name ?? '-' }}
                                                            </td>
                                                            <td class="text-center">1</td>
                                                            <td class="text-center">
                                                                <input type="hidden" name="additional_costs[{{ $index }}][amount]" value="{{ number_format($item->unit_cost, 2) }}" />
                                                                ₹ {{ number_format($item->unit_cost, 2) }}
                                                            </td>
                                                            <td class="text-center">
                                                                <input type="hidden" name="additional_costs[{{ $index }}][amount]" value="{{ number_format($item->amount, 2) }}" />
                                                                ₹ {{ number_format($item->amount, 2) }}
                                                            </td>
                                                            <td class="text-center">
                                                                <a href="javascript:void(0)" class="remove-item text-danger"><i class="fa fa-trash"></i></a>
                                                            </td>
                                                        </tr>
                                                    @endif
                                                @endforeach
                                            @else
                                                <tr class="first-row">
                                                    <td class="text-center" colspan="7">Enter BOM Items and add them...</td>
                                                </tr>
                                            @endif
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <td colspan="5" class="text-end"><strong>Total:</strong></td>
                                                <td class="text-center" id="grand_total">₹ {{ number_format($bom->total_amount ?? 0, 2) }}</td>
                                                <td></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                                <div class="text-end">
                                    <button type="button" class="btn btn-primary btn-sm saveItems me-2">Update</button>
                                    <a href="{{ route('manufacture-index') }}" class="btn btn-secondary btn-sm me-2">Cancel</a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
@endsection

@push('scripts')
<script>
    $(document).ready(function () {
        $('#cost_type').select2({
            placeholder: "Search or type a Cost Type",
            allowClear: true,
            tags: true,
            tokenSeparators: [',', ' '],
            width: '100%',
            createTag: function (params) {
                if (params.term.trim() === '') {
                    return null;
                }
                return {
                    id: params.term,
                    text: params.term
                };
            }
        });

        $('#product_id').select2({
            placeholder: "Select Product",
            allowClear: true,
            width: '100%'
        });

        const product = @json($product);
        const cost_type = @json($costType);
        let productData = '';
        let bomItemsCount = {{ count($bom->bomItems->where('type', 'product')) }};
        let additionalCostsCount = {{ count($bom->bomItems->where('type', '!=', 'product')) }};
        let unitId = 0;
        let totalRowCount = {{ count($bom->bomItems) }};

        $('.product_id').on('change', function () {
            let productId = $(this).val();
            productData = product.find(data => data.id == productId);

            let Unit = '';
            if (productData) {
                Unit = productData.category?.unit_of_mass?.name || '';
                unitId = productData.category?.uom || 0;
            }
            $('.unit').val(Unit);
        });

        $('.qty').on('input', function () {
            let qty = parseFloat($(this).val()) || 0;
            let marginPrice = parseFloat(productData?.margin_price) || 0;

            let total = qty * marginPrice;

            $('.unit_cost').val(marginPrice.toFixed(2));
            $('.total_amount').val(total.toFixed(2));
        });

        $('#saveBomItem').on('click', function () {
            const productId = $('#product_id').val();
            const productText = $('#product_id option:selected').text();
            const unit = $('#unit').val();
            const qty = $('#qty').val();
            const unitCost = $('#unit_cost').val();
            const total = $('#total_amount').val();

            clearValidationErrors();

            let hasError = false;

            if (!productId) {
                showInlineError('#product_id', 'Product is required.');
                hasError = true;
            }
            if (!qty || qty <= 0) {
                showInlineError('#qty', 'Valid quantity is required.');
                hasError = true;
            }
            if (!unitCost || unitCost <= 0) {
                showInlineError('#unit_cost', 'Valid unit cost is required.');
                hasError = true;
            }

            if (hasError) return;

            bomItemsCount++;
            totalRowCount++;

            $('.added_product .first-row').remove();

            $('.added_product').append(`
                <tr data-type="product" data-index="${bomItemsCount}" data-row-number="${totalRowCount}">
                    <td class="text-center">${totalRowCount}</td>
                    <td class="text-center">
                        <input type="hidden" name="bom_items[${bomItemsCount}][product_id]" value="${productId}" />
                        ${productText}
                    </td>                        
                    <td class="text-center">
                        <input type="hidden" name="bom_items[${bomItemsCount}][uom_id]" value="${unitId}" />
                        ${unit}
                    </td>
                    <td class="text-center">
                        <input type="hidden" name="bom_items[${bomItemsCount}][qty]" value="${qty}" />
                        ${qty}
                    </td>
                    <td class="text-center">
                        <input type="hidden" name="bom_items[${bomItemsCount}][unit_cost]" value="${unitCost}" />
                        ₹ ${unitCost}
                    </td>
                    <td class="text-center">
                        <input type="hidden" name="bom_items[${bomItemsCount}][amount]" value="${total}" />
                        ₹ ${total}
                    </td>
                    <td class="text-center">
                        <a href="javascript:void(0)" class="remove-item text-danger"><i class="fa fa-trash"></i></a>
                    </td>
                </tr>
            `);

            $('#product_id').val('').trigger('change');
            $('#unit').val('');
            $('#qty').val('');
            $('#unit_cost').val('');
            $('#total_amount').val('');
            updateGrandTotal();
        });

        $('#saveAdditionalCost').on('click', function () {
            const costTypeInput = $('#cost_type');
            let costType = costTypeInput.val();
            const costTypeText = costTypeInput.find('option:selected').text();
            const description = $('#cost_description').val();
            const additional_unit = $('#additional_unit').val();
            const additional_unit_name = $('#additional_unit option:selected').data('unit_name');
            const amount = $('#additional_cost').val();

            clearValidationErrors();

            let hasError = false;

            if (!costType) {
                showInlineError('#cost_type', 'Cost type is required.');
                hasError = true;
            }
            if (!additional_unit) {
                showInlineError('#additional_unit', 'Unit is required.');
                hasError = true;
            }
            if (!amount || amount <= 0) {
                showInlineError('#additional_cost', 'Valid amount is required.');
                hasError = true;
            }

            if (hasError) return;

            const isNewCostType = isNaN(costType) && costType !== '';

            if (isNewCostType) {
                saveCostType(costType, function(response) {
                    if (response && response.cost_type && response.cost_type.id) {
                        const newCostTypeId = response.cost_type.id;
                        const newCostTypeName = response.cost_type.name;
                        
                        additionalCostsCount++;
                        totalRowCount++;
                        addAdditionalCostRow(newCostTypeId, newCostTypeName);
                        resetFormFields();
                        updateGrandTotal();
                    }
                }, function(error) {
                    console.error('Failed to save cost type:', error);
                    alert('Failed to save new cost type');
                });
            } else {
                additionalCostsCount++;
                totalRowCount++;
                addAdditionalCostRow(costType, costTypeText);
                resetFormFields();
                updateGrandTotal();
            }
        });

        $('.saveItems').on('click', function () {
            let form = $('.submit');
            let formData = new FormData(form[0]);

            clearValidationErrors();

            const assembledItem = $('#assembled_item').val().trim();
            if (!assembledItem) {
                showInlineError('#assembled_item', 'Assembled Item is required.');
                return;
            }

            if ($('.added_product tr[data-type]').length === 0) {
                Swal.fire({
                    title: 'Error!',
                    text: 'Please add at least one BOM item or additional cost',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
                return;
            }

            $.ajax({
                url: '{{ route('manufacture-bom-update', $bom->id) }}',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function (data) {
                    Swal.fire({
                        title: 'Success!',
                        text: data.message || 'BOM updated successfully!',
                        icon: 'success',
                        confirmButtonText: 'OK',
                        timer: 2000,
                        timerProgressBar: true
                    }).then(() => {
                        window.location.href = "{{ route('manufacture-index') }}";
                    });
                },
                error: function (xhr) {
                    let message = 'An unexpected error occurred.';
                    if (xhr.status === 422 && xhr.responseJSON?.errors) {
                        const firstKey = Object.keys(xhr.responseJSON.errors)[0];
                        message = xhr.responseJSON.errors[firstKey][0];
                    } else if (xhr.responseJSON?.message) {
                        message = xhr.responseJSON.message;
                    }

                    Swal.fire({
                        title: 'Error!',
                        text: message,
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            });
        });

        function saveCostType(costType, successCallback, errorCallback) {
            $.ajax({
                url: '{{ route('save-costType') }}',
                type: 'POST',
                data: { 
                    costType: costType,
                    _token: '{{ csrf_token() }}'
                },
                dataType: 'json',
                success: function(response) {
                    if (response && response.cost_type && response.cost_type.id) {
                        const newOption = new Option(
                            response.cost_type.name, 
                            response.cost_type.id, 
                            false, 
                            true
                        );
                        $('#cost_type').append(newOption).trigger('change');
                        successCallback(response);
                    } else {
                        errorCallback('Invalid response format');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error:', error);
                    errorCallback(error);
                }
            });
        }

        function addAdditionalCostRow(costTypeId, displayText) {
            const amount = $('#additional_cost').val();
            const description = $('#cost_description').val();
            const additional_unit = $('#additional_unit').val();
            const additional_unit_name = $('#additional_unit option:selected').data('unit_name');

            $('.added_product .first-row').remove();

            $('.added_product').append(`
                <tr data-type="additional_cost" data-index="${additionalCostsCount}" data-row-number="${totalRowCount}" class="additional-cost-row">
                    <td class="text-center">${totalRowCount}</td>
                    <td class="text-center">
                        <input type="hidden" name="additional_costs[${additionalCostsCount}][cost_type_id]" value="${costTypeId}" />
                        <input type="hidden" name="additional_costs[${additionalCostsCount}][cost_type_text]" value="${displayText}" />
                        <input type="hidden" name="additional_costs[${additionalCostsCount}][description]" value="${description}" />
                        ${displayText}
                    </td>
                    <td class="text-center">
                        <input type="hidden" name="additional_costs[${additionalCostsCount}][uom_id]" value="${additional_unit}" />
                        ${additional_unit_name || ''}
                    </td>
                    <td class="text-center">1</td>
                    <td class="text-center">
                        <input type="hidden" name="additional_costs[${additionalCostsCount}][amount]" value="${amount}" />
                        ₹ ${amount}
                    </td>
                    <td class="text-center">
                        <input type="hidden" name="additional_costs[${additionalCostsCount}][amount]" value="${amount}" />
                        ₹ ${amount}
                    </td>
                    <td class="text-center">
                        <a href="javascript:void(0)" class="remove-item text-danger"><i class="fa fa-trash"></i></a>
                    </td>
                </tr>
            `);
        }

        function resetFormFields() {
            $('#cost_type').val('').trigger('change');
            $('#additional_unit').val('').trigger('change');
            $('#cost_description').val('');
            $('#additional_cost').val('');
        }

        function updateGrandTotal() {
            let total = 0;

            $('.added_product tr[data-type="product"]').each(function () {
                const amount = parseFloat($(this).find('input[name*="amount"]').val()) || 0;
                total += amount;
            });

            $('.added_product tr[data-type="additional_cost"]').each(function () {
                const amount = parseFloat($(this).find('input[name*="amount"]').val()) || 0;
                total += amount;
            });

            $('#grand_total').text('₹ ' + total.toFixed(2));
        }

        function clearValidationErrors() {
            $('.error-message').remove();
            $('.is-invalid').removeClass('is-invalid');
        }

        function showInlineError(selector, message) {
            const input = $(selector);
            input.addClass('is-invalid');

            const errorEl = $(`<small class="text-danger error-message">${message}</small>`);
            input.closest('.mb-3').append(errorEl);
        }

        $(document).on('click', '.remove-item', function () {
            const row = $(this).closest('tr');
            const rowType = row.data('type');
            const rowIndex = row.data('index');
            
            row.remove();
            totalRowCount--;

            if (rowType === 'product') {
                bomItemsCount--;
            } else if (rowType === 'additional_cost') {
                additionalCostsCount--;
            }

            $('.added_product tr[data-type]').each(function(index) {
                const newRowNumber = index + 1;
                $(this).attr('data-row-number', newRowNumber);
                $(this).find('td:first').text(newRowNumber);
            });

            if ($('.added_product tr[data-type]').length === 0) {
                $('.added_product').html(`
                    <tr><td class="text-center first-row" colspan="7">Enter BOM Items and add them...</td></tr>
                `);
                bomItemsCount = 0;
                additionalCostsCount = 0;
                totalRowCount = 0;
            }
            
            updateGrandTotal();
        });

        updateGrandTotal();
    });
</script>
@endpush