@extends('layouts.layoutapp')

@section('content')
        <div class="row">
        <div class="col-12">
            <div class="card me-2">
                    <div class="d-flex justify-content-between align-items-center p-2">
                        <h5 class="mb-0">Assemble Item</h5>
                        <span class="badge bg-secondary px-3 py-2 unit_price">Unit Price: ₹ 0</span>
                    </div>
                    <div class="card-body">
                        <form class="submit" action="{{route('manufacture-assemble-update',$assemble->id)}}" method="POST"
                            enctype="multipart/form-data">
                            @csrf
                            <input type="hidden" name="grand_total" class="grand_total">
                            <input type="hidden" name="per_unit_cost" class="per_unit_cost">
                            <div>
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label for="assembled_date">Assembled Date</label>
                                        <input type="date" name="assembled_date" id="assembled_date"
                                            class="form-control @error('assembled_date') is-invalid @enderror"
                                            value="{{ old('assembled_date', $assemble->assemble_date )}}" readonly>
                                        @error('assembled_date')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>

                                    <div class="col-md-4 mb-3">
                                        <label for="bom_id">Bill Of Material</label>
                                        <select name="bom_id" id="bom_id"
                                            class="form-select select2 bom_id @error('bom_id') is-invalid @enderror" disabled>
                                            <option value="">Select BOM</option>
                                            @foreach ($bom as $item)
                                                <option value="{{ $item->id }}" {{ old('bom_id',$assemble->bom_id) == $item->id ? 'selected' : '' }}>
                                                    {{ $item->assemble_item }}
                                                </option>
                                            @endforeach
                                        </select>
                                        @error('bom_id')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>

                                    <div class="col-md-4 mb-3">
                                        <label for="assembled_qty">Assembled Qty</label>
                                        <input type="number" name="assembled_qty" id="assembled_qty" min="1"
                                            class="form-control assembled_qty @error('assembled_qty') is-invalid @enderror" readonly
                                            placeholder="Enter Assembled Qty" value="{{ old('assembled_qty',$assemble->assembled_qty) }}">
                                        @error('assembled_qty')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>

                                    <div class="col-md-4 mb-3">
                                        <label for="code">Product Code</label>
                                        <input type="text" name="code" id="code"
                                            class="form-control @error('code') is-invalid @enderror"
                                            placeholder="Enter Product Code" value="{{ old('code',$assemble->product->code ?? '') }}" readonly>
                                        @error('code')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>

                                    <div class="col-md-4 mb-3">
                                        <label for="category_id">Product Category</label>
                                        <select name="category_id" id="category_id"
                                            class="form-select select2 @error('category_id') is-invalid @enderror" disabled>
                                            <option value="">Select Category</option>
                                            @foreach ($category as $item)
                                                <option value="{{ $item->id }}" {{ old('category_id',$assemble->product->category_id) == $item->id ? 'selected' : '' }}>
                                                    {{ $item->name }}
                                                </option>
                                            @endforeach
                                        </select>
                                        @error('category_id')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>

                                    <div class="col-md-4 mb-3">
                                        <label for="selling_price">Selling Price</label>
                                        <input type="number" name="selling_price" id="selling_price" min="1" readonly
                                            class="form-control @error('selling_price') is-invalid @enderror"
                                            placeholder="Enter Selling Price" value="{{ old('selling_price',$assemble->product->unit_price ?? '') }}">
                                        @error('selling_price')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>

                                    <div class="col-md-8 mb-3">
                                        <label for="remarks">Remarks</label>
                                        <textarea name="remarks" id="remarks" rows="1"
                                            class="form-control @error('remarks') is-invalid @enderror" readonly
                                            placeholder="Enter Remarks...">{{ old('remarks',$assemble->remarks) }}</textarea>
                                        @error('remarks')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>

                            </div>
                            <div class="table-responsive">
                                <table class="table table-bordered table-striped">
                                    <thead>
                                        <tr>
                                            <td class="text-center">#</td>
                                            <td class="text-center">Product Name</td>
                                            <td class="text-center">Quantity</td>
                                            <td class="text-center">Unit</td>
                                            <td class="text-center">Available Qty</td>
                                            <td class="text-center">Unit Cost</td>
                                            <td class="text-center">Total Amount</td>
                                        </tr>
                                    </thead>
                                    <tbody class="bom_items">

                                    </tbody>
                                </table>
                            </div>
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="text-start fw-bold" id="grand_total_display">
                                    Grand Total: ₹ 0.00
                                </div>
                                <div>
                                    {{-- <button type="submit" class="btn btn-primary btn-sm 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 () {
            let bomId = '';

             getProducts($('.bom_id').val());
            $('.bom_id').on('change', function () {
                bomId = $(this).val();
                getProducts(bomId);
            });

            $('.assembled_qty').on('input', function () {
                const assembled_qty = parseFloat($(this).val()) || 0;
                renderProductRows(assembled_qty);
            });
        });

        let currentBomItems = [];

        function getProducts(bomId) {
            if (bomId) {
                $.ajax({
                    url: '{{route('get-products')}}',
                    type: 'GET',
                    data: { bomId: bomId },
                    success: function (data) {
                        currentBomItems = data.bom_items || [];
                        const assembled_qty = parseFloat($('.assembled_qty').val()) || 0;
                        renderProductRows(assembled_qty);
                         let unitCost = data.unit_price ?? 0;
                        $('.unit_price').text('Unit Price: ₹' + unitCost);
                    },
                    error: function (xhr) {
                        console.error(xhr);
                        $('.bom_items').html(
                            '<tr><td colspan="7" class="text-center text-danger">Error loading items</td></tr>'
                        );
                    },
                });
            } else {
                $('.bom_items').html(
                    '<tr><td colspan="7" class="text-center">Select a Bill Of Material to view items</td></tr>'
                );
            }
        }

        function renderProductRows(assembled_qty) {
    $('.bom_items').empty();

    if (currentBomItems.length === 0) {
        $('.bom_items').html(
            '<tr><td colspan="7" class="text-center">No items found</td></tr>'
        );
        return;
    }

    let grandTotal = 0;
    
    currentBomItems.forEach(function (item, index) {
        let calculatedQty, unitCost, totalAmount;
        
            calculatedQty = (assembled_qty * item.qty).toFixed(2);
            unitCost = parseFloat(item.unit_cost).toFixed(2);
            totalAmount = (calculatedQty * unitCost).toFixed(2);     

        grandTotal += parseFloat(totalAmount);

        const row = `
            <tr>
                <td class="text-center">${index + 1}</td>
                <td class="text-center">
                    ${item.type !== 'product' ? 
                        `${item.cost_type.name || ''}
                         <input type="hidden" name="additional_costs[${index}][cost_type]" value="${item.type || ''}">
                         <input type="hidden" name="additional_costs[${index}][description]" value="${item.description || ''}">` : 
                        `${item.product?.name || ''} (${item.product?.code || ''})
                         <input type="hidden" name="bom_items[${index}][product_id]" value="${item.product_id}">`}
                </td>
                <td class="text-center">
                    ${item.type !== 'product' ? 
                        `${item.unit?.name || '-'}` : 
                        `${item.unit?.name || '-'}
                         <input type="hidden" name="bom_items[${index}][uom_id]" value="${item.uom_id}">`}
                </td>
                <td class="text-center">
                    ${calculatedQty}
                    <input type="hidden" name="${item.type !== 'product' ? 'additional_costs' : 'bom_items'}[${index}][qty]" value="${calculatedQty}">
                </td>
                <td class="text-center">
                    ${item.type === 'product' ? (item.product?.qty || 'N/A') : 'N/A'}
                </td>
                <td class="text-center">
                    ₹ ${unitCost}
                    <input type="hidden" name="${item.type !== 'product' ? 'additional_costs' : 'bom_items'}[${index}][unit_cost]" value="${unitCost}">
                </td>
                <td class="text-center">
                    ₹ ${totalAmount}
                    <input type="hidden" name="${item.type !== 'product' ? 'additional_costs' : 'bom_items'}[${index}][amount]" value="${totalAmount}">
                </td>
            </tr>
        `;
        
        $('.bom_items').append(row);
    });

    $('#grand_total_display').text(`Grand Total: ₹ ${grandTotal.toFixed(2)}`);
    $('.grand_total').val(grandTotal.toFixed(2));
    
    const perUnitCost = currentBomItems.reduce((sum, item) => {
        return sum + (item.type === 'product' ? parseFloat(item.amount || 0) : parseFloat(item.unit_cost || 0));
    }, 0);
    
    $('.per_unit_cost').val(perUnitCost.toFixed(2));
}    
    </script>

@endpush