@extends('admin.layouts.app')

@section('content')
    <div class="page-header">
        <div class="row">
            <div class="col-sm-12">
                <h3 class="page-title">Edit Master Formulation</h3>
                <ul class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('master-formulations.index') }}">Master Formulations</a>
                    </li>
                    <li class="breadcrumb-item active">Edit Master Formulation</li>
                </ul>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-12">
            <div class="card">
                <div class="card-body">
                    <form action="{{ route('master-formulations.update', $masterFormulation->id) }}" method="POST"
                        class="needs-validation" novalidate>
                        @csrf
                        @method('PUT')
                        <div class="form-row row">
                            <div class="mb-3 col-md-4">
                                <label for="brand_name">Brand<span class="text-danger">*</span></label>
                                <select class="js-example-basic-single select2" name="brand_name" id="brand_name" required>
                                    <option value="">Select Brand</option>
                                    @foreach ($brandNames as $brand)
                                        <option value="{{ $brand }}"
                                            {{ old('brand_name', $masterFormulation->brand_name ?? '') == $brand ? 'selected' : '' }}>
                                            {{ $brand }}</option>
                                    @endforeach
                                </select>
                                @error('brand_name')
                                    <div class="text-danger">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="mb-3 col-md-4">
                                <label for="product_name">Product (manual)<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="product_name" id="product_name"
                                    placeholder="Enter product name" required
                                    value="{{ old('product_name', $masterFormulation->product_name ?? '') }}">
                                @error('product_name')
                                    <div class="text-danger">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="mb-3 col-md-4">
                                <label for="batch_size">Batch Size<span class="text-danger">*</span></label>
                                <input type="number" class="form-control" name="batch_size" id="batch_size"
                                    placeholder="Batch Size" required
                                    value="{{ old('batch_size', $masterFormulation->batch_size) }}" step="0.01"
                                    min="0.01">
                                @error('batch_size')
                                    <div class="text-danger">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>

                        {{-- @forelse ($masterFormulation->mfItems as $item) --}}
                        <div class="col-md-12">
                            <div class="card border-0 mb-0" id="item-group">
                                @php
                                    $mfItems = $masterFormulation->mfItems->toArray();
                                    $count = count($mfItems);
                                @endphp
                                @for ($i = 0; $i < $count; $i++)
                                    <div class="item-set">
                                        @php
                                            $item = $mfItems[$i];
                                        @endphp
                                        <div
                                            class="card-header bg-white py-2 d-flex justify-content-between align-items-center">
                                            <h4 class="card-title mb-0">Item {{ $i + 1 }}</h4>
                                            @if ($i > 0)
                                                <button type="button" onclick="removeItem(this)"
                                                    class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></button>
                                            @endif
                                        </div>
                                        <div class="card-body px-0 pb-0">
                                            <div class="row">
                                                <div class="mb-3 col-md-4">
                                                    <label for="">Raw Material Items<span
                                                            class="text-danger">*</span></label>
                                                    <select name="items[{{ $i }}][raw_material_item]"
                                                        class="js-example-basic-single select2 " required>
                                                        <option value="">Select Raw Material</option>
                                                        @foreach ($rawMaterialItems as $rawMaterialItem)
                                                            <option value="{{ $rawMaterialItem->id }}"
                                                                {{ old("items.$i.raw_material_item") == $rawMaterialItem->id ? 'selected' : ' ' }}
                                                                @selected(!is_null($item) && $item['raw_material_item_id'] == $rawMaterialItem->id)>
                                                                {{ $rawMaterialItem->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>


                                                <div class="mb-3 col-md-4">
                                                    <label>Quantity</label>
                                                    <input type="number" class="form-control quantity"
                                                        name="items[{{ $i }}][quantity]"
                                                        placeholder="Product Quantity" required
                                                        value="{{ $item['quantity'] ?? old("items.$i.quantity") }}">
                                                </div>

                                            </div>
                                        </div>
                                    </div>
                                @endfor
                            </div>
                            <div class="mb-3 text-end">
                                <button type="button" onclick="addItem()" class="btn btn-primary">Add Item</button>
                            </div>
                        </div>



                        <button class="btn btn-primary" type="submit">Update</button>
                        <a class="btn btn-secondary" href="{{ route('master-formulations.index') }}">Cancel</a>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        const itemSets = document.querySelectorAll('#item-group .item-set');
        let itemIndex = itemSets.length;

        function addItem() {
            var html = `
                <div class="item-set">
                    <div class="card-header bg-white py-2 d-flex justify-content-between align-items-center">
                        <h4 class="card-title mb-0">Item ${ itemIndex + 1 }</h4>
                        @if ($i > 0)
                            <button type="button" onclick="removeItem(this)" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></button>
                        @endif
                    </div>
                    <div class="card-body px-0 pb-0">
                        <div class="row">
                             <div class="mb-3 col-md-4">
                                                    <label for="">Raw Material Items<span
                                                            class="text-danger">*</span></label>
                                                    <select name="items[${ itemIndex }][raw_material_item]"
                                                        class="js-example-basic-single select2 " required>
                                                        <option value="">Select Raw Material</option>
                                                        @foreach ($rawMaterialItems as $rawMaterialItem)
                                                            <option value="{{ $rawMaterialItem->id }}"  {{ old("items.$i.raw_material_item") == $rawMaterialItem->id ? 'selected' : ' ' }}>
                                                                {{ $rawMaterialItem->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                          
                        
                            <div class="mb-3 col-md-4">
                                <label>Quantity</label>
                                <input type="number" class="form-control quantity" name="items[${ itemIndex }][quantity]"
                                    placeholder="Product Quantity" required value="{{ old("items.$i.quantity") }}" oninput="calculateSingleProductAmount()">
                            </div>
                      
                        </div>
                    </div>
                </div>
            `;
            $("#item-group").append(html);
            const firstDropdownOptions = $(".product_variations_dropdown:first").children().clone();
            $(`#item-group .item-set:last .product_variations_dropdown`).append(firstDropdownOptions);
            itemIndex++;
            $('.js-example-basic-single').select2({});
        }

        function removeItem(button) {
            const itemSets = document.querySelectorAll('#item-group .item-set');
            // Find the closest parent .item-set of the clicked button and remove it
            if (itemSets && itemSets.length > 1) {
                const item = button.closest('.item-set');
                if (item) {
                    item.remove();
                    itemIndex--; // Decrement itemIndex to ensure consistency
                }
            }
        }
    </script>
@endsection
