@extends(\'admin.layouts.app\') {{-- Assuming you have a main layout file --}}

@section(\'content\')
<div class="container-fluid">
    {{-- Changed RFQ to Inquiry --}}
    <h1>Edit Quotation #{{ $quotation->id }} for Inquiry #{{ $inquiry->id }}</h1>

    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <form action="{{ route(\'admin.quotations.update\', $quotation->id) }}" method="POST" id="quotation-form">
        @csrf
        @method(\'PUT\')
        {{-- Hidden fields to store calculated values and JSON --}}
        {{-- Changed rfq_id to inquiry_id --}}
        <input type="hidden" name="inquiry_id" value="{{ $inquiry->id }}"> 
        <input type="hidden" name="costing_details" id="costing_details_json">
        <input type="hidden" name="calculated_total_fabric_consumption" id="calculated_total_fabric_consumption_hidden">
        <input type="hidden" name="calculated_total_fabric_cost" id="calculated_total_fabric_cost_hidden">
        <input type="hidden" name="calculated_accessories_cost" id="calculated_accessories_cost_hidden">
        <input type="hidden" name="calculated_additional_costs_total" id="calculated_additional_costs_total_hidden">
        <input type="hidden" name="calculated_total_cost" id="calculated_total_cost_hidden">

        {{-- 1. Inquiry Details (Non-editable) --}}
        <div class="card mb-4">
            <div class="card-header bg-secondary text-white">
                 {{-- Changed RFQ to Inquiry --}}
                <h5 class="mb-0">Inquiry Details (Read Only)</h5>
            </div>
            <div class="card-body">
                 <div class="row">
                    {{-- Updated to use $inquiry and its relationships/fields --}}
                    <div class="col-md-4"><p><strong>Customer Name:</strong> {{ $inquiry->customer_name }}</p></div>
                    <div class="col-md-4"><p><strong>Item Description:</strong> {{ $inquiry->itemDescription->name ?? \'N/A\' }}</p></div>
                    <div class="col-md-4"><p><strong>Brand:</strong> {{ $inquiry->brand->name ?? \'N/A\' }}</p></div>
                    <div class="col-md-4"><p><strong>Size Range:</strong> {{ $inquiry->sizeRange->name ?? \'N/A\' }}</p></div>
                    <div class="col-md-4"><p><strong>Color:</strong> {{ $inquiry->color->name ?? \'N/A\' }}</p></div>
                    <div class="col-md-4"><p><strong>Order Quantity:</strong> {{ $inquiry->order_quantity }}</p></div>
                    <div class="col-md-4"><p><strong>Target Price:</strong> {{ $inquiry->target_price ? \'$\' . number_format($inquiry->target_price, 2) : \'N/A\' }}</p></div>
                    <div class="col-md-4"><p><strong>Fabric Composition:</strong> {{ $inquiry->fabricComposition->name ?? \'N/A\' }}</p></div>
                    <div class="col-md-4"><p><strong>Fabric Type:</strong> {{ $inquiry->fabricType->name ?? \'N/A\' }}</p></div>
                    <div class="col-md-4"><p><strong>Yarn Count:</strong> {{ $inquiry->yarnCount->name ?? \'N/A\' }}</p></div>
                    <div class="col-md-4"><p><strong>Fabric Weight:</strong> {{ $inquiry->fabricWeight->name ?? \'N/A\' }}</p></div>
                    <div class="col-md-4"><p><strong>Shipment Date:</strong> {{ $inquiry->shipment_date ? $inquiry->shipment_date->format(\'Y-m-d\') : \'N/A\' }}</p></div>
                    {{-- Add other Inquiry fields as needed --}}
                </div>
            </div>
        </div>

        {{-- Decode costing details for pre-filling form --}}
        @php
            $costingDetails = $quotation->costing_details ?? [];
            $fabricConsumptionInput = $costingDetails[\'fabric_consumption\'][\'input_body\'] ?? 0;
            $wastageId = $costingDetails[\'wastage\'][\'percentage_id\'] ?? \'\';
            $fabricPriceInput = $costingDetails[\'fabric_pricing\'][\'calculated_price_per_unit\'] ?? 0;
            $selectedAddons = $costingDetails[\'add_ons\'] ?? [];
            $selectedAccessories = $costingDetails[\'accessories\'] ?? [];
            $selectedAdditionalCosts = $costingDetails[\'additional_costs\'] ?? [];
            // Calculate initial total addon consumption for hidden field
            $initialAddonConsumption = 0;
            foreach($selectedAddons as $addon) {
                $initialAddonConsumption += ($addon[\'consumption\'] ?? 0);
            }
        @endphp

        {{-- 2. Costing Modules & Workflow --}}
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Costing Calculation</h5>
            </div>
            <div class="card-body">
                {{-- 2.1 Fabric Consumption Calculation --}}
                <fieldset class="mb-4 p-3 border">
                    <legend class="w-auto px-2">Fabric Consumption</legend>
                    <p><em>(Placeholder: Fabric consumption input fields/canvas based on Info Library formula)</em></p>
                    <div class="form-group">
                        <label for="fabric_consumption_input">Body Consumption (e.g., yards/pc)</label>
                        <input type="number" step="0.0001" id="fabric_consumption_input" class="form-control calculation-trigger" placeholder="Enter body consumption" value="{{ old(\'fabric_consumption_input\', $fabricConsumptionInput) }}">
                    </div>
                </fieldset>

                {{-- 2.2 Wastage Percentage --}}
                <fieldset class="mb-4 p-3 border">
                    <legend class="w-auto px-2">Wastage</legend>
                    <div class="form-group">
                        <label for="wastage_percentage_id">Wastage Percentage</label>
                        <select name="wastage_percentage_id" id="wastage_percentage_id" class="form-control calculation-trigger">
                            <option value="" data-percentage="0">Select Wastage % (from Info Library)</option>
                            {{-- @foreach($wastagePercentages as $wastage) --}}
                            {{-- <option value="{{ $wastage->id }}" data-percentage="{{ $wastage->percentage }}" {{ old(\'wastage_percentage_id\', $wastageId) == $wastage->id ? \'selected\' : \'\' }}>{{ $wastage->name }} ({{ $wastage->percentage }}%)</option> --}}
                            {{-- @endforeach --}}
                             <option value="1" data-percentage="5" {{ old(\'wastage_percentage_id\', $wastageId) == 1 ? \'selected\' : \'\' }}>Standard (5%)</option> {{-- Placeholder --}}
                            <option value="2" data-percentage="10" {{ old(\'wastage_percentage_id\', $wastageId) == 2 ? \'selected\' : \'\' }}>High (10%)</option> {{-- Placeholder --}}
                            <option value="3" data-percentage="0" {{ old(\'wastage_percentage_id\', $wastageId) == 3 ? \'selected\' : \'\' }}>None (0%)</option> {{-- Placeholder --}}
                        </select>
                    </div>
                     <p><small>Calculated Wastage Amount: <span id="wastage_amount_display">0.0000</span></small></p>
                </fieldset>

                {{-- 2.3 Add-ons (Collar, Cuff, Hood, etc.) --}}
                <fieldset class="mb-4 p-3 border">
                    <legend class="w-auto px-2">Fabric Add-ons</legend>
                     <p><em>(Select fabric add-ons like collars, cuffs, hoods with preset consumption values from Info Library)</em></p>
                     <table class="table table-sm" id="add-ons-table">
                        <thead>
                            <tr>
                                <th>Add-on (from Info Library)</th>
                                <th>Consumption (e.g., yards/pc)</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            {{-- Pre-fill selected add-ons based on $selectedAddons --}}
                            @foreach($selectedAddons as $index => $addon)
                            <tr>
                                <td><select name="addon_id[{{$index}}]" class="form-control form-control-sm"><option value="">Select Add-on</option><option value="{{ $addon[\'id\'] }}" selected>{{ $addon[\'name\'] ?? \'Add-on \' . $addon[\'id\'] }}</option><!-- Populate from Info Library --></select></td>
                                <td><input type="number" name="addon_consumption[{{$index}}]" class="form-control form-control-sm calculation-trigger" min="0" step="0.0001" value="{{ $addon[\'consumption\'] ?? 0 }}"></td>
                                <td><button type="button" class="btn btn-danger btn-sm remove-row">X</button></td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                    <button type="button" class="btn btn-sm btn-outline-primary" id="add-addon-button">+ Add Fabric Add-on</button>
                    <p class="mt-2"><small>Total Add-on Consumption: <span id="total_addon_consumption_display">{{ number_format($initialAddonConsumption, 4) }}</span></small></p>
                    <input type="hidden" id="total_addon_consumption_hidden" value="{{ $initialAddonConsumption }}">
                </fieldset>

                <div class="alert alert-info">
                    <strong>Total Fabric Consumption (Body + Wastage + Add-ons):</strong> 
                    <span id="total_fabric_consumption_display">{{ number_format($quotation->calculated_total_fabric_consumption ?? 0, 4) }}</span> yards/pc (example unit)
                </div>
            </div>
        </div>

        {{-- 3. Accessories Checklist --}}
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Accessories Cost</h5>
            </div>
            <div class="card-body">
                <p><em>(Select accessories from Info Library, input quantity and unit cost)</em></p>
                <table class="table table-sm" id="accessories-table">
                    <thead>
                        <tr>
                            <th>Accessory (from Info Library)</th>
                            <th>Quantity per Piece</th>
                            <th>Unit Cost ($)</th>
                            <th>Total Cost ($)</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        {{-- Pre-fill selected accessories based on $selectedAccessories --}}
                        @foreach($selectedAccessories as $index => $accessory)
                        <tr>
                             <td><select name="accessory_id[{{$index}}]" class="form-control form-control-sm"><option value="">Select Accessory</option><option value="{{ $accessory[\'id\'] }}" selected>{{ $accessory[\'name\'] ?? \'Accessory \' . $accessory[\'id\'] }}</option><!-- Populate from Info Library --></select></td>
                             <td><input type="number" name="accessory_quantity[{{$index}}]" class="form-control form-control-sm calculation-trigger" min="0" step="any" value="{{ $accessory[\'quantity\'] ?? 1 }}"></td>
                             <td><input type="number" name="accessory_unit_cost[{{$index}}]" class="form-control form-control-sm calculation-trigger" min="0" step="0.01" value="{{ $accessory[\'unit_cost\'] ?? 0 }}"></td>
                             <td>{{ number_format(($accessory[\'quantity\'] ?? 1) * ($accessory[\'unit_cost\'] ?? 0), 2) }}</td>
                             <td><button type="button" class="btn btn-danger btn-sm remove-row">X</button></td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
                <button type="button" class="btn btn-sm btn-outline-primary" id="add-accessory-button">+ Add Accessory</button>
                <div class="alert alert-info mt-3">
                    <strong>Total Accessories Cost:</strong> $<span id="total_accessories_cost_display">{{ number_format($quotation->calculated_accessories_cost ?? 0, 2) }}</span>
                </div>
            </div>
        </div>

        {{-- 4. Fabric Pricing Calculation --}}
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Fabric Cost</h5>
            </div>
            <div class="card-body">
                <p><em>(Calculate Fabric Price based on Info Library data: Yarn Price, Knitting, Dyeing, Finishing, etc.)</em></p>
                <div class="form-group">
                    <label for="fabric_price_input">Fabric Price per Unit (e.g., $/yard)</label>
                    <input type="number" step="0.01" id="fabric_price_input" class="form-control calculation-trigger" placeholder="Enter fabric price per unit" value="{{ old(\'fabric_price_input\', $fabricPriceInput) }}">
                </div>
                <div class="alert alert-info mt-3">
                    <strong>Total Fabric Cost (Total Consumption * Fabric Price):</strong> $<span id="total_fabric_cost_display">{{ number_format($quotation->calculated_total_fabric_cost ?? 0, 2) }}</span>
                </div>
            </div>
        </div>

        {{-- 5. Additional Costs --}}
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Additional Costs</h5>
            </div>
            <div class="card-body">
                 <p><em>(Select preset costs like CM, Printing, Embroidery, Washing, Commercial Cost, Service Charge, Commission, or add manually)</em></p>
                <table class="table table-sm" id="additional-costs-table">
                    <thead>
                        <tr>
                            <th>Cost Item</th>
                            <th>Cost ($)</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                         {{-- Pre-fill selected additional costs based on $selectedAdditionalCosts --}}
                         @foreach($selectedAdditionalCosts as $index => $cost)
                         <tr>
                            <td><input type="text" name="additional_cost_name[{{$index}}]" class="form-control form-control-sm" placeholder="Cost Item Name" value="{{ $cost[\'name\'] ?? \'\' }}"></td>
                            <td><input type="number" name="additional_cost_value[{{$index}}]" class="form-control form-control-sm calculation-trigger" min="0" step="0.01" value="{{ $cost[\'cost\'] ?? 0 }}"></td>
                            <td><button type="button" class="btn btn-danger btn-sm remove-row">X</button></td>
                         </tr>
                         @endforeach
                    </tbody>
                </table>
                <button type="button" class="btn btn-sm btn-outline-primary" id="add-additional-cost-button">+ Add Cost Item</button>
                 <div class="alert alert-info mt-3">
                    <strong>Total Additional Costs:</strong> $<span id="total_additional_costs_display">{{ number_format($quotation->calculated_additional_costs_total ?? 0, 2) }}</span>
                </div>
            </div>
        </div>

        {{-- 6. Final Summary --}}
        <div class="card mb-4">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0">Final Summary & Quotation</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <p><strong>Total Fabric Cost:</strong> $<span id="summary_fabric_cost">{{ number_format($quotation->calculated_total_fabric_cost ?? 0, 2) }}</span></p>
                        <p><strong>Total Accessories Cost:</strong> $<span id="summary_accessories_cost">{{ number_format($quotation->calculated_accessories_cost ?? 0, 2) }}</span></p>
                        <p><strong>Total Additional Costs:</strong> $<span id="summary_additional_costs">{{ number_format($quotation->calculated_additional_costs_total ?? 0, 2) }}</span></p>
                        <hr>
                        <p><strong>Calculated Total Cost:</strong> $<strong id="summary_total_cost">{{ number_format($quotation->calculated_total_cost ?? 0, 2) }}</strong></p>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="quoted_price"><strong>Final Quoted Price ($)</strong></label>
                            <input type="number" step="0.01" name="quoted_price" id="quoted_price" class="form-control form-control-lg" required min="0" value="{{ old(\'quoted_price\', $quotation->quoted_price) }}">
                        </div>
                        <div class="form-group">
                            <label for="remarks">Remarks</label>
                            <textarea name="remarks" id="remarks" class="form-control" rows="3">{{ old(\'remarks\', $quotation->remarks) }}</textarea>
                        </div>
                         <div class="form-group">
                            <label for="status">Status</label>
                            <select name="status" id="status" class="form-control">
                                <option value="draft" {{ old(\'status\', $quotation->status) == \'draft\' ? \'selected\' : \'\' }}>Draft</option>
                                <option value="submitted" {{ old(\'status\', $quotation->status) == \'submitted\' ? \'selected\' : \'\' }}>Submitted</option>
                                <option value="approved" {{ old(\'status\', $quotation->status) == \'approved\' ? \'selected\' : \'\' }}>Approved</option>
                                <option value="rejected" {{ old(\'status\', $quotation->status) == \'rejected\' ? \'selected\' : \'\' }}>Rejected</option>
                            </select>
                        </div>
                    </div>
                </div>
                 <p class="mt-3"><small><em>Note: Target Price from Inquiry was {{ $inquiry->target_price ? \'$\' . number_format($inquiry->target_price, 2) : \'N/A\' }}. Compare with Calculated Total Cost.</em></small></p>
            </div>
        </div>

        <div class="form-group text-center">
            <button type="submit" class="btn btn-primary btn-lg">Update Quotation</button>
            <a href="{{ route(\'admin.quotations.index\') }}" class="btn btn-secondary btn-lg">Cancel</a>
        </div>
    </form>
</div>

@endsection

@push(\'scripts\')
{{-- Include the same corrected JavaScript as in create.blade.php --}}
<script>
    document.addEventListener(\'DOMContentLoaded\', function() {
        console.log(\'Quotation Generator JS Initializing...\');

        // --- Helper Functions ---
        const getFloat = (elementId) => parseFloat(document.getElementById(elementId)?.value) || 0;
        const getSelectedData = (selectId, dataAttribute) => parseFloat(document.getElementById(selectId)?.selectedOptions[0]?.dataset[dataAttribute]) || 0;
        const setHtml = (elementId, value) => { 
            const el = document.getElementById(elementId);
            if (el) el.innerHTML = value; 
        };
        const setValue = (elementId, value) => { 
            const el = document.getElementById(elementId);
            if (el) el.value = value; 
        };
        const formatCurrency = (value) => typeof value === \'number\' ? value.toFixed(2) : \'0.00\';
        const formatConsumption = (value) => typeof value === \'number\' ? value.toFixed(4) : \'0.0000\';

        // --- Calculation Logic --- 
        function calculateAll() {
            console.log(\'Recalculating all costs...\');
            
            // 1. Fabric Consumption
            let bodyConsumption = getFloat(\'fabric_consumption_input\');
            let wastagePercentage = getSelectedData(\'wastage_percentage_id\', \'percentage\') / 100;
            let wastageAmount = bodyConsumption * wastagePercentage;
            setHtml(\'wastage_amount_display\', formatConsumption(wastageAmount));

            let totalAddonConsumption = 0;
            document.querySelectorAll(\'#add-ons-table tbody tr\').forEach(row => {
                totalAddonConsumption += parseFloat(row.querySelector(\'input[name^="addon_consumption"]\')?.value) || 0;
            });
            setValue(\'total_addon_consumption_hidden\', totalAddonConsumption);
            setHtml(\'total_addon_consumption_display\', formatConsumption(totalAddonConsumption));

            let totalFabricConsumption = bodyConsumption + wastageAmount + totalAddonConsumption;
            setHtml(\'total_fabric_consumption_display\', formatConsumption(totalFabricConsumption));
            setValue(\'calculated_total_fabric_consumption_hidden\', formatConsumption(totalFabricConsumption));

            // 2. Accessories Cost
            let totalAccessoriesCost = 0;
            document.querySelectorAll(\'#accessories-table tbody tr\').forEach(row => {
                let quantity = parseFloat(row.querySelector(\'input[name^="accessory_quantity"]\')?.value) || 0;
                let unitCost = parseFloat(row.querySelector(\'input[name^="accessory_unit_cost"]\')?.value) || 0;
                let rowTotal = quantity * unitCost;
                const totalCell = row.querySelector(\'td:nth-child(4)\');
                if(totalCell) totalCell.textContent = formatCurrency(rowTotal);
                totalAccessoriesCost += rowTotal;
            });
            setHtml(\'total_accessories_cost_display\', formatCurrency(totalAccessoriesCost));
            setValue(\'calculated_accessories_cost_hidden\', formatCurrency(totalAccessoriesCost));

            // 3. Fabric Cost
            let fabricPrice = getFloat(\'fabric_price_input\');
            let totalFabricCost = totalFabricConsumption * fabricPrice;
            setHtml(\'total_fabric_cost_display\', formatCurrency(totalFabricCost));
            setValue(\'calculated_total_fabric_cost_hidden\', formatCurrency(totalFabricCost));

            // 4. Additional Costs
            let totalAdditionalCosts = 0;
            document.querySelectorAll(\'#additional-costs-table tbody tr\').forEach(row => {
                totalAdditionalCosts += parseFloat(row.querySelector(\'input[name^="additional_cost_value"]\')?.value) || 0;
            });
            setHtml(\'total_additional_costs_display\', formatCurrency(totalAdditionalCosts));
            setValue(\'calculated_additional_costs_total_hidden\', formatCurrency(totalAdditionalCosts));

            // 5. Final Summary
            let calculatedTotalCost = totalFabricCost + totalAccessoriesCost + totalAdditionalCosts;
            setHtml(\'summary_fabric_cost\', formatCurrency(totalFabricCost));
            setHtml(\'summary_accessories_cost\', formatCurrency(totalAccessoriesCost));
            setHtml(\'summary_additional_costs\', formatCurrency(totalAdditionalCosts));
            setHtml(\'summary_total_cost\', formatCurrency(calculatedTotalCost));
            setValue(\'calculated_total_cost_hidden\', formatCurrency(calculatedTotalCost));

            // Update JSON data
            updateCostingDetailsJson();
        }

        // --- Event Listeners --- 
        // Trigger calculation on relevant input changes
        document.querySelectorAll(".calculation-trigger").forEach(element => {
            element.addEventListener(\'change\', calculateAll);
            element.addEventListener(\'keyup\', calculateAll);
        });

        // Add Add-on Row
        document.getElementById(\'add-addon-button\")?.addEventListener(\'click\', function() {
            const tableBody = document.querySelector(\'#add-ons-table tbody\');
            if (!tableBody) return;
            const rowCount = Date.now(); // Unique index
            const newRow = tableBody.insertRow();
            newRow.innerHTML = `
                <td><select name="addon_id[${rowCount}]" class="form-control form-control-sm"><option value=\"\">Select Add-on</option><!-- Populate from Info Library --></select></td>
                <td><input type="number" name="addon_consumption[${rowCount}]" class="form-control form-control-sm calculation-trigger" min="0" step="0.0001" value="0"></td>
                <td><button type="button" class="btn btn-danger btn-sm remove-row">X</button></td>
            `;
            // Re-attach listeners to new elements
            newRow.querySelectorAll(".calculation-trigger").forEach(el => {
                 el.addEventListener(\'change\', calculateAll);
                 el.addEventListener(\'keyup\', calculateAll);
            });
        });

        // Add Accessory Row
        document.getElementById(\'add-accessory-button\")?.addEventListener(\'click\', function() {
            const tableBody = document.querySelector(\'#accessories-table tbody\');
             if (!tableBody) return;
            const rowCount = Date.now(); // Unique index
            const newRow = tableBody.insertRow();
            newRow.innerHTML = `
                <td><select name="accessory_id[${rowCount}]" class="form-control form-control-sm"><option value=\"\">Select Accessory</option><!-- Populate from Info Library --></select></td>
                <td><input type="number" name="accessory_quantity[${rowCount}]" class="form-control form-control-sm calculation-trigger" min="0" step="any" value="1"></td>
                <td><input type="number" name="accessory_unit_cost[${rowCount}]" class="form-control form-control-sm calculation-trigger" min="0" step="0.01" value="0"></td>
                <td>0.00</td>
                <td><button type="button" class="btn btn-danger btn-sm remove-row">X</button></td>
            `;
            // Re-attach listeners to new elements
            newRow.querySelectorAll(".calculation-trigger").forEach(el => {
                 el.addEventListener(\'change\', calculateAll);
                 el.addEventListener(\'keyup\', calculateAll);
            });
        });
        
        // Add Additional Cost Row
        document.getElementById(\'add-additional-cost-button\")?.addEventListener(\'click\', function() {
            const tableBody = document.querySelector(\'#additional-costs-table tbody\');
             if (!tableBody) return;
            const rowCount = Date.now(); // Unique index
            const newRow = tableBody.insertRow();
            newRow.innerHTML = `
                <td><input type="text" name="additional_cost_name[${rowCount}]" class="form-control form-control-sm" placeholder="Cost Item Name"></td>
                <td><input type="number" name="additional_cost_value[${rowCount}]" class="form-control form-control-sm calculation-trigger" min="0" step="0.01" value="0"></td>
                <td><button type="button" class="btn btn-danger btn-sm remove-row">X</button></td>
            `;
             // Re-attach listeners to new elements
            newRow.querySelectorAll(".calculation-trigger").forEach(el => {
                 el.addEventListener(\'change\', calculateAll);
                 el.addEventListener(\'keyup\', calculateAll);
            });
        });

        // Remove Row Logic (Event Delegation for dynamically added rows)
        document.addEventListener(\'click\', function(e) {
            if (e.target && e.target.classList.contains(\'remove-row\')) {
                e.target.closest(\'tr\")?.remove();
                calculateAll(); // Recalculate after removing a row
            }
        });

        // --- JSON Update --- 
        function updateCostingDetailsJson() {
            const costingDetails = {
                fabric_consumption: {
                    input_body: getFloat(\'fabric_consumption_input\'),
                    calculated_wastage: getFloat(\'fabric_consumption_input\') * (getSelectedData(\'wastage_percentage_id\', \'percentage\') / 100),
                    calculated_addons: getFloat(\'total_addon_consumption_hidden\'),
                    total: getFloat(\'calculated_total_fabric_consumption_hidden\')
                },
                wastage: {
                    percentage_id: document.getElementById(\'wastage_percentage_id\")?.value,
                    percentage_value: getSelectedData(\'wastage_percentage_id\', \'percentage\'),
                },
                add_ons: [],
                accessories: [],
                fabric_pricing: {
                    // Add components like yarn_price, knitting etc. if calculated/inputted here
                    calculated_price_per_unit: getFloat(\'fabric_price_input\'),
                },
                additional_costs: [],
            };

            // Populate Add-ons Array
            document.querySelectorAll(\'#add-ons-table tbody tr\').forEach((row) => {
                const addonSelect = row.querySelector(`select[name^="addon_id"]`);
                const addonConsumptionInput = row.querySelector(`input[name^="addon_consumption"]`);
                if (!addonSelect || !addonConsumptionInput) return;
                const addonId = addonSelect.value;
                const addonName = addonSelect.options[addonSelect.selectedIndex]?.textContent || \'\';
                const addonConsumption = parseFloat(addonConsumptionInput.value) || 0;
                if (addonId && addonConsumption > 0) {
                     costingDetails.add_ons.push({
                        id: addonId,
                        name: addonName, // Store name for easier display
                        consumption: addonConsumption,
                    });
                }
            });

            // Populate Accessories Array
            document.querySelectorAll(\'#accessories-table tbody tr\').forEach((row) => {
                const accessorySelect = row.querySelector(`select[name^="accessory_id"]`);
                const quantityInput = row.querySelector(`input[name^="accessory_quantity"]`);
                const unitCostInput = row.querySelector(`input[name^="accessory_unit_cost"]`);
                if (!accessorySelect || !quantityInput || !unitCostInput) return;
                const accessoryId = accessorySelect.value;
                const accessoryName = accessorySelect.options[accessorySelect.selectedIndex]?.textContent || \'\';
                const quantity = parseFloat(quantityInput.value) || 0;
                const unitCost = parseFloat(unitCostInput.value) || 0;
                if (accessoryId) {
                     costingDetails.accessories.push({
                        id: accessoryId,
                        name: accessoryName, // Store name for easier display
                        quantity: quantity,
                        unit_cost: unitCost,
                        total: quantity * unitCost
                    });
                }
            });

            // Populate Additional Costs Array
             document.querySelectorAll(\'#additional-costs-table tbody tr\').forEach((row) => {
                const nameInput = row.querySelector(`input[name^="additional_cost_name"]`);
                const valueInput = row.querySelector(`input[name^="additional_cost_value"]`);
                if (!nameInput || !valueInput) return;
                const costName = nameInput.value;
                const costValue = parseFloat(valueInput.value) || 0;
                if (costName && costValue > 0) {
                    costingDetails.additional_costs.push({
                        name: costName,
                        cost: costValue,
                    });
                }
            });
            
            setValue(\'costing_details_json\', JSON.stringify(costingDetails));
            console.log(\'Updated Costing Details JSON:\', JSON.stringify(costingDetails, null, 2));
        }

        // Initial calculation on page load
        calculateAll();

        // Update JSON before form submission
        const form = document.getElementById(\'quotation-form\');
        if (form) {
            form.addEventListener(\'submit\', function(e) {
                console.log(\'Form submitting, ensuring JSON is updated...\');
                updateCostingDetailsJson();
                // Optionally add frontend validation here before allowing submit
            });
        }

    });
</script>
@endpush
