@include('admin.header')

<div class="container-fluid">
    <h1>Create Quotation 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.store') }}" method="POST" id="quotation-form">
        @csrf
        <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_other_costs_total" id="calculated_other_costs_total_hidden">
        <input type="hidden" name="calculated_commercial_rates_total" id="calculated_commercial_rates_total_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">
                <h5 class="mb-0">Inquiry Details (Read Only)</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4"><p><strong>Customer Name:</strong> {{ $inquiry->buyer->company_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>
                    @if($inquiry->images)
                        <img src="{{ asset('inquiries/'.$inquiry->images) }}" style="max-width: 150px;" alt="">
                    @endif
                </div>
            </div>
        </div>

        {{-- 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">
                {{-- =================================================================
                == 1. TOP FABRIC CONSUMPTION
                ================================================================= --}}
                <fieldset class="mb-4 p-3 border">
                    <legend class="w-auto px-2" style="font-size: 1.1rem; font-weight: bold;">1. Top Fabrics Consumption</legend>
                    <p><em>(Select fabric Consumption like Body Length, Sleeve, Chest Length etc)</em></p>

                    <table class="table table-sm" id="top-fabric-table">
                        <thead>
                            <tr>
                                <th>Fabric Name (from Info Library)</th>
                                <th>Consumption</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                    <button type="button" class="btn btn-sm btn-outline-primary" id="add-top-fabric-button">+ Add Top Fabric</button>

                    <div class="form-group mt-2">
                        <label for="top_fabric_gsm">GSM</label>
                        <input type="number" class="form-control form-control-sm calculation-trigger" id="top_fabric_gsm" value="{{ $inquiry->fabricWeight->name ?? 0 }}">
                    </div>
                    <div class="form-group mt-2">
                        <label for="top_wastage_percentage">Wastage / Extra Percentage (%)</label>
                        <input type="number" class="form-control form-control-sm calculation-trigger" id="top_wastage_percentage" value="0" min="0" step="0.01">
                    </div>
                </fieldset>

                <fieldset class="mb-4 p-3 border">
                    <legend class="w-auto px-2" style="font-size: 1.1rem; font-weight: bold;">Top Fabric Add-ons</legend>
                    <p><em>(Select Add-ons like Collar, Cuffs, Placket etc)</em></p>
                    <table class="table table-sm" id="top-fabric-addons-table">
                        <thead>
                            <tr>
                                <th>Add-on Name</th>
                                <th>Consumption</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                    <button type="button" class="btn btn-sm btn-outline-success" id="add-top-fabric-addon-button">+ Add Top Fabric Add-on</button>
                    <p class="mt-2"><small>Total Top Consumption (Fabric + Wastage + Addons): <span id="total_top_consumption_display">0.0000</span></small></p>
                </fieldset>

                {{-- =================================================================
                == 2. BOTTOM FABRIC CONSUMPTION
                ================================================================= --}}
                <fieldset class="mb-4 p-3 border">
                    <legend class="w-auto px-2" style="font-size: 1.1rem; font-weight: bold;">2. Bottom Fabric Consumption</legend>
                    <p><em>(Select fabric components like ½ Thigh/Hip Width, Total Length etc)</em></p>

                    <table class="table table-sm" id="bottom-fabric-table">
                        <thead>
                            <tr>
                                <th>Fabric Component</th>
                                <th>Value (cm)</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                    <button type="button" class="btn btn-sm btn-outline-primary" id="add-bottom-fabric-button">+ Add Bottom Fabric</button>

                    <div class="form-group mt-2">
                        <label for="bottom_fabric_gsm">GSM</label>
                        <input type="number" class="form-control form-control-sm calculation-trigger" id="bottom_fabric_gsm" value="{{ $inquiry->fabricWeight->name ?? 0 }}">
                    </div>
                    <div class="form-group mt-2">
                        <label for="bottom_wastage_percentage">Wastage / Extra Percentage (%)</label>
                        <input type="number" class="form-control form-control-sm calculation-trigger" id="bottom_wastage_percentage" value="0" min="0" step="0.01">
                    </div>
                </fieldset>

                <fieldset class="mb-4 p-3 border">
                    <legend class="w-auto px-2" style="font-size: 1.1rem; font-weight: bold;">Bottom Fabric Add-ons</legend>
                    <p><em>(Select Add-ons like Pockets, Waistband, etc)</em></p>
                     <table class="table table-sm" id="bottom-fabric-addons-table">
                        <thead>
                            <tr>
                                <th>Add-on Name</th>
                                <th>Consumption</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                    <button type="button" class="btn btn-sm btn-outline-success" id="add-bottom-fabric-addon-button">+ Add Bottom Fabric Add-on</button>
                    <p class="mt-2"><small>Total Bottom Consumption (Fabric + Wastage + Addons): <span id="total_bottom_consumption_display">0.0000</span></small></p>
                </fieldset>

                {{-- GRAND TOTAL FABRIC CONSUMPTION --}}
                <div class="alert alert-info">
                    <strong>Total Fabric Consumption (Top + Bottom):</strong>
                    <span id="total_fabric_consumption_display">0.0000</span> kg
                </div>

                {{-- =================================================================
                == 3. FABRIC COST SECTION
                ================================================================= --}}
                <fieldset class="mb-4 p-3 border">
                    <legend class="w-auto px-2" style="font-size: 1.1rem; font-weight: bold;">3. Fabric Cost</legend>
                    <p><em>(Select Yarn Type, Knitting Type, Dyeing Type with their values)</em></p>

                    <table class="table table-sm" id="fabric-cost-table">
                        <thead>
                            <tr>
                                <th>Cost Type</th>
                                <th>Value ($)</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                    <button type="button" class="btn btn-sm btn-outline-primary" id="add-fabric-cost-button">+ Add Fabric Cost</button>
                </fieldset>

                <fieldset class="mb-4 p-3 border">
               <!--      <legend class="w-auto px-2" style="font-size: 1.1rem; font-weight: bold;">Fabric Cost Add-ons</legend>
                    <p><em>(Select additional fabric cost add-ons)</em></p>
                    <table class="table table-sm" id="fabric-cost-addons-table">
                        <thead>
                            <tr>
                                <th>Add-on Name</th>
                                <th>Cost ($)</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                    <button type="button" class="btn btn-sm btn-outline-success" id="add-fabric-cost-addon-button">+ Add Fabric Cost Add-on</button> -->
                    <p class="mt-2"><small>Total Fabric Cost per Unit: $<span id="total_fabric_cost_per_unit_display">0.00</span></small></p>
                </fieldset>

                {{-- TOTAL FABRICS COST DZN --}}
                <div class="alert alert-success">
                    <strong>Total Fabrics Cost DZN (Consumption × Fabric Cost per Unit):</strong>
                    $<span id="total_fabrics_cost_dzn_display">0.00</span>
                </div>

                {{-- =================================================================
                == 4. ACCESSORY COST SECTION
                ================================================================= --}}
                <fieldset class="mb-4 p-3 border">
                    <legend class="w-auto px-2" style="font-size: 1.1rem; font-weight: bold;">4. Accessory Cost</legend>
                    <p><em>(Select accessories from Info Library with Rate, Quantity, and Consumption per Unit)</em></p>

                    <table class="table table-sm" id="accessory-cost-table">
                        <thead>
                            <tr>
                                <th>Item Name</th>
                                <th>Rate ($)</th>
                                <th>Quantity</th>
                                <th>Consumption per Unit</th>
                                <th>Total Cost ($)</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                    <button type="button" class="btn btn-sm btn-outline-primary" id="add-accessory-button">+ Add Accessory</button>
                    <p class="mt-2"><small>Total Accessory Cost: $<span id="total_accessory_cost_display">0.00</span></small></p>
                </fieldset>

                {{-- =================================================================
                == 5. OTHER COSTS SECTION - HIERARCHICAL LAYOUT
                ================================================================= --}}
                <fieldset class="mb-4 p-3 border">
                    <legend class="w-auto px-2" style="font-size: 1.1rem; font-weight: bold;"></legend>
                    <p><em>(Categories and their related cost items)</em></p>

                    <div id="other-costs-container">
                        @foreach($other as $otherCost)
                            <div class="category-section mb-4 p-3 border rounded bg-light">
                                <h6 class="mb-3 text-dark" style="font-size:18px;">{{ $otherCost->name }}</h6>
                                <div class="cost-items-list">
                                    @foreach($cost as $costItem)
                                        @if($costItem->other_cost_id == $otherCost->id)
                                            <div class="cost-item-row d-flex align-items-center mb-2">
                                                <div class="flex-grow-1 mr-2">
                                                    <input type="text" class="form-control form-control-sm" value="{{ $costItem->name }}" readonly>
                                                </div>
                                                <div class="mr-2" style="width: 120px;">
                                                    <input type="number" class="form-control form-control-sm other-cost-amount calculation-trigger" 
                                                           value="{{ $costItem->amount }}" min="0" step="0.01" 
                                                           data-cost-id="{{ $costItem->id }}" data-category-id="{{ $otherCost->id }}">
                                                </div>
                                            </div>
                                        @endif
                                    @endforeach
                                </div>
                            </div>
                        @endforeach
                    </div>
                    <p class="mt-2"><small>Total Other Costs: $<span id="total_other_costs_display">0.00</span></small></p>
                </fieldset>

                {{-- =================================================================
                == 6. COMMERCIAL RATES SECTION
                ================================================================= --}}
                <fieldset class="mb-4 p-3 border">
                    <legend class="w-auto px-2" style="font-size: 1.1rem; font-weight: bold;">6. Commercial Rates</legend>
                    <p><em>(Select commercial rates from Info Library with their percentage values)</em></p>

                    <table class="table table-sm" id="commercial-rates-table">
                        <thead>
                            <tr>
                                <th>Rate Name</th>
                                <th>Percentage (%)</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                    <button type="button" class="btn btn-sm btn-outline-primary" id="add-commercial-rate-button">+ Add Commercial Rate</button>
                    <p class="mt-2"><small>Total Commercial Rates: $<span id="total_commercial_rates_display">0.00</span></small></p>
                </fieldset>

                {{-- Hidden options for dropdowns --}}
                <div id="garments-options" style="display: none;">
                    @foreach($garments as $garment)
                        <option value="{{ $garment->id }}" data-type="{{ strtolower(str_contains($garment->name, 'Body') ? 'body' : (str_contains($garment->name, 'Sleeve') ? 'sleeve' : (str_contains($garment->name, 'Chest') ? 'chest' : 'other'))) }}">{{ $garment->name }}</option>
                    @endforeach
                </div>

                {{-- Fabric cost options (yarn, knitting, dyeing) --}}
                <div id="fabric-cost-options" style="display: none;">
                    @foreach($yarn as $yarnType)
                        <option value="{{ $yarnType->id }}" data-cost="{{ $yarnType->price }}">{{ $yarnType->name }}</option>
                    @endforeach
                    @foreach($knitting as $knittingType)
                        <option value="{{ $knittingType->id }}" data-cost="{{ $knittingType->price }}">{{ $knittingType->name }}</option>
                    @endforeach
                    @foreach($dyeing as $dyeingType)
                        <option value="{{ $dyeingType->id }}" data-cost="{{ $dyeingType->price }}">{{ $dyeingType->name }}</option>
                    @endforeach
                </div>

                {{-- Accessory options --}}
                <div id="accessory-options" style="display: none;">
                    @foreach($accessories as $accessory)
                        <option value="{{ $accessory->id }}" data-rate="{{ $accessory->default_rate }}" data-quantity="{{ $accessory->unit }}" data-consumption="{{ $accessory->consumption_per_unit }}">{{ $accessory->name }}</option>
                    @endforeach
                </div>

                {{-- Commercial rates options --}}
                <div id="commercial-rates-options" style="display: none;">
                    @foreach($commercial as $commercialRate)
                        <option value="{{ $commercialRate->id }}" data-percentage="{{ $commercialRate->percentage }}">{{ $commercialRate->name }}</option>
                    @endforeach
                </div>

                {{-- Bottom fabric component options --}}
                <div id="bottom-fabric-options" style="display: none;">
                    <option value="half_thigh" data-type="half_thigh">½ Thigh/Hip Width</option>
                    <option value="total_length" data-type="total_length">Total Length</option>
                    <option value="waistbelt_height" data-type="waistbelt_height">Waistbelt Height</option>
                    <option value="front_rise" data-type="front_rise">Front Rise</option>
                    <option value="back_rise" data-type="back_rise">Back Rise</option>
                    <option value="in_seam" data-type="in_seam">In/Out Seam</option>
                    <option value="out_seam" data-type="out_seam">Out Seam (Override)</option>
                </div>

                <div id="fabric-addon-options" style="display: none;">
                    @foreach($fabric as $addon)
                        <option value="{{ $addon->id }}" data-consumption="{{ $addon->price }}">{{ $addon->name }}</option>
                    @endforeach
                </div>
            </div>
        </div>

        {{-- 3. Other 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></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">0.00</span>
                </div>
            </div>
        </div>

        {{-- 4. 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 Fabrics Cost DZN:</strong> $<span id="summary_fabrics_cost_dzn">0.00</span></p>
                        <p><strong>Total Accessory Cost:</strong> $<span id="summary_accessory_cost">0.00</span></p>
                        <p><strong>Total Other Costs:</strong> $<span id="summary_other_costs">0.00</span></p>
                        <p><strong>Total Commercial Rates:</strong> $<span id="summary_commercial_rates">0.00</span></p>
                        <p><strong>Total Additional Costs:</strong> $<span id="summary_additional_costs">0.00</span></p>
                        <hr>
                        <p><strong>Calculated Total Cost:</strong> $<strong id="summary_total_cost">0.00</strong></p>
                        <p><strong>FOB Cost Per Piece:</strong> $<span id="summary_fob_cost_per_piece">0.00</span></p>
                        <p><strong>Target Price:</strong> {{ $inquiry->target_price ? '$' . number_format($inquiry->target_price, 2) : 'N/A' }}</p>
                        <p><strong>Difference (Target - FOB):</strong> $<span id="summary_difference">0.00</span></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', 0) }}">
                        </div>
                        <div class="form-group">
                            <label for="remarks">Remarks</label>
                            <textarea name="remarks" id="remarks" class="form-control" rows="3">{{ old('remarks') }}</textarea>
                        </div>
                         <div class="form-group">
                            <label for="status">Status</label>
                            <select name="status" id="status" class="form-control">
                                <option value="draft" selected>Draft</option>
                                <option value="submitted">Submitted</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">Save Quotation</button>
            <a href="{{ route('admin.inquiries.index') }}" class="btn btn-secondary btn-lg">Cancel</a>
        </div>
    </form>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
    // --- Generic function to add a row to a table ---
    function addRow(tableBody, rowContent, calculationCallback) {
        const newRow = document.createElement("tr");
        newRow.innerHTML = rowContent;
        tableBody.appendChild(newRow);

        // Attach event listeners to new row elements
        newRow.querySelectorAll('.calculation-trigger, .garment-select, .addon-select, .consumption-input, .bottom-component-select, .bottom-value-input, .fabric-cost-select, .fabric-cost-value, .other-cost-select, .other-cost-value, .commercial-rate-select, .commercial-rate-percentage').forEach(el => {
            el.addEventListener('input', calculationCallback);
            el.addEventListener("change", calculationCallback);
        });

        newRow.querySelector(".remove-row").addEventListener("click", function () {
            newRow.remove();
            calculationCallback();
        });

        // For bottom fabric components, ensure the value input is updated when selection changes
        if (tableBody.id === "bottom-fabric-table") {
            const selectElement = newRow.querySelector(".bottom-component-select");
            const valueInput = newRow.querySelector(".bottom-value-input");
            if (selectElement && valueInput) {
                selectElement.addEventListener("change", function() {
                    // Clear the value when the component type changes
                    valueInput.value = ""; 
                    calculationCallback();
                });
            }
        }
    }
    
    // --- Generic function to add an addon row ---
    function addAddonRow(tableBody, optionsHTML, calculationCallback) {
        const newRow = document.createElement("tr");
        newRow.innerHTML = `
            <td>
                <select class="form-control form-control-sm addon-select calculation-trigger">
                    <option value="">Select Add-on</option>
                    ${optionsHTML}
                </select>
            </td>
            <td><input type="number" class="form-control form-control-sm addon-consumption" readonly></td>
            <td><button type="button" class="btn btn-danger btn-sm remove-row">X</button></td>
        `;
        tableBody.appendChild(newRow);
        
        const select = newRow.querySelector(".addon-select");
        const input = newRow.querySelector(".addon-consumption");

        select.addEventListener("change", function () {
            const selected = select.options[select.selectedIndex];
            input.value = selected.getAttribute("data-consumption") || 0;
            calculationCallback();
        });
        
        newRow.querySelector(".remove-row").addEventListener("click", function () {
            newRow.remove();
            calculationCallback();
        });
    }

    // --- Event Listeners for Add Buttons ---
    const garmentsOptions = document.getElementById("garments-options").innerHTML;
    const fabricCostOptions = document.getElementById("fabric-cost-options").innerHTML;
    const accessoryOptions = document.getElementById("accessory-options").innerHTML;
    const commercialRatesOptions = document.getElementById("commercial-rates-options").innerHTML;
    const bottomFabricOptions = document.getElementById("bottom-fabric-options").innerHTML;
    const fabricAddonOptions = document.getElementById("fabric-addon-options").innerHTML;

    // Top Fabric
    document.getElementById("add-top-fabric-button").addEventListener("click", () => {
        const rowContent = `
            <td>
                <select class="form-control form-control-sm garment-select calculation-trigger">
                    <option value="">Select Fabric</option>${garmentsOptions}
                </select>
            </td>
            <td><input type="number" class="form-control form-control-sm consumption-input calculation-trigger" min="0" step="0.0001"></td>
            <td><button type="button" class="btn btn-danger btn-sm remove-row">X</button></td>
        `;
        addRow(document.querySelector("#top-fabric-table tbody"), rowContent, calculateAll);
    });

    // Fabric Cost
    document.getElementById("add-fabric-cost-button").addEventListener("click", () => {
        const rowContent = `
            <td>
                <select class="form-control form-control-sm fabric-cost-select calculation-trigger">
                    <option value="">Select Cost Type</option>${fabricCostOptions}
                </select>
            </td>
            <td><input type="number" class="form-control form-control-sm fabric-cost-value" readonly></td>
            <td><button type="button" class="btn btn-danger btn-sm remove-row">X</button></td>
        `;
        
        const newRow = document.createElement("tr");
        newRow.innerHTML = rowContent;
        document.querySelector("#fabric-cost-table tbody").appendChild(newRow);
        
        const select = newRow.querySelector(".fabric-cost-select");
        const input = newRow.querySelector(".fabric-cost-value");

        select.addEventListener("change", function () {
            const selected = select.options[select.selectedIndex];
            input.value = selected.getAttribute("data-cost") || 0;
            calculateAll();
        });
        
        newRow.querySelector(".remove-row").addEventListener("click", function () {
            newRow.remove();
            calculateAll();
        });
    });

    // Accessory Cost
    document.getElementById("add-accessory-button").addEventListener("click", () => {
        const rowContent = `
            <td>
                <select class="form-control form-control-sm accessory-select calculation-trigger">
                    <option value="">Select Accessory</option>${accessoryOptions}
                </select>
            </td>
            <td><input type="number" class="form-control form-control-sm accessory-rate calculation-trigger" min="0" step="0.01" placeholder="Rate"></td>
            <td><input type="number" class="form-control form-control-sm accessory-quantity calculation-trigger" min="0" step="1" placeholder="Quantity"></td>
            <td><input type="number" class="form-control form-control-sm accessory-consumption calculation-trigger" min="0" step="0.01" placeholder="Consumption per Unit"></td>
            <td><span class="accessory-total-cost">0.00</span></td>
            <td><button type="button" class="btn btn-danger btn-sm remove-row">X</button></td>
        `;
        
        const newRow = document.createElement("tr");
        newRow.innerHTML = rowContent;
        document.querySelector("#accessory-cost-table tbody").appendChild(newRow);
        
        const select = newRow.querySelector(".accessory-select");
        const rateInput = newRow.querySelector(".accessory-rate");
        const quantityInput = newRow.querySelector(".accessory-quantity");
        const consumptionInput = newRow.querySelector(".accessory-consumption");
        const totalCostSpan = newRow.querySelector(".accessory-total-cost");

        select.addEventListener("change", function () {
            const selected = select.options[select.selectedIndex];
            rateInput.value = selected.getAttribute("data-rate") || 0;
            quantityInput.value = selected.getAttribute("data-quantity") || 0;
            consumptionInput.value = selected.getAttribute("data-consumption") || 0;
            calculateAccessoryRowTotal(newRow);
            calculateAll();
        });

        [rateInput, quantityInput, consumptionInput].forEach(input => {
            input.addEventListener("input", function () {
                calculateAccessoryRowTotal(newRow);
                calculateAll();
            });
        });
        
        newRow.querySelector(".remove-row").addEventListener("click", function () {
            newRow.remove();
            calculateAll();
        });
    });

    // Commercial Rates
    document.getElementById("add-commercial-rate-button").addEventListener("click", () => {
        const rowContent = `
            <td>
                <select class="form-control form-control-sm commercial-rate-select calculation-trigger">
                    <option value="">Select Commercial Rate</option>${commercialRatesOptions}
                </select>
            </td>
            <td><input type="number" class="form-control form-control-sm commercial-rate-percentage calculation-trigger" min="0" step="0.01" placeholder="Percentage"></td>
            <td><button type="button" class="btn btn-danger btn-sm remove-row">X</button></td>
        `;
        
        const newRow = document.createElement("tr");
        newRow.innerHTML = rowContent;
        document.querySelector("#commercial-rates-table tbody").appendChild(newRow);
        
        const select = newRow.querySelector(".commercial-rate-select");
        const percentageInput = newRow.querySelector(".commercial-rate-percentage");

        select.addEventListener("change", function () {
            const selected = select.options[select.selectedIndex];
            percentageInput.value = selected.getAttribute("data-percentage") || 0;
            calculateAll();
        });

        percentageInput.addEventListener("input", function () {
            calculateAll();
        });
        
        newRow.querySelector(".remove-row").addEventListener("click", function () {
            newRow.remove();
            calculateAll();
        });
    });
    
    // Bottom Fabric
    document.getElementById("add-bottom-fabric-button").addEventListener("click", () => {
        const rowContent = `
            <td>
                <select class="form-control form-control-sm bottom-component-select calculation-trigger">
                    <option value="">Select Component</option>${bottomFabricOptions}
                </select>
            </td>
            <td><input type="number" class="form-control form-control-sm bottom-value-input calculation-trigger" min="0" step="0.0001" placeholder="Enter value in cm"></td>
            <td><button type="button" class="btn btn-danger btn-sm remove-row">X</button></td>
        `;
        addRow(document.querySelector("#bottom-fabric-table tbody"), rowContent, calculateAll);
    });
    
    // Top Addons
    document.getElementById("add-top-fabric-addon-button").addEventListener("click", () => {
        addAddonRow(document.querySelector("#top-fabric-addons-table tbody"), fabricAddonOptions, calculateAll);
    });

    // Bottom Addons
    document.getElementById("add-bottom-fabric-addon-button").addEventListener("click", () => {
        addAddonRow(document.querySelector("#bottom-fabric-addons-table tbody"), fabricAddonOptions, calculateAll);
    });

    // Additional Costs
    document.getElementById("add-additional-cost-button").addEventListener("click", () => {
        const rowContent = `
            <td><input type="text" class="form-control form-control-sm additional-cost-name" placeholder="Cost Name"></td>
            <td><input type="number" class="form-control form-control-sm additional-cost-amount calculation-trigger" min="0" step="0.01" placeholder="Amount"></td>
            <td><button type="button" class="btn btn-danger btn-sm remove-row">X</button></td>
        `;
        addRow(document.querySelector("#additional-costs-table tbody"), rowContent, calculateAll);
    });

    // Attach listeners to all initial calculation-triggering fields
    document.querySelectorAll('.calculation-trigger').forEach(el => {
        el.addEventListener('input', calculateAll);
        el.addEventListener('change', calculateAll);
    });

    // --- Function to calculate individual accessory row total ---
    function calculateAccessoryRowTotal(row) {
        const rate = parseFloat(row.querySelector(".accessory-rate").value) || 0;
        const quantity = parseFloat(row.querySelector(".accessory-quantity").value) || 0;
        const consumption = parseFloat(row.querySelector(".accessory-consumption").value) || 0;
        const total = rate * quantity * consumption;
        row.querySelector(".accessory-total-cost").textContent = total.toFixed(2);
    }

    // --- Main Calculation Function ---
    function calculateAll() {
        // --- 1. Calculate Top Consumption ---
        const topGsm = parseFloat(document.getElementById("top_fabric_gsm").value) || 0;
        let bodyLength = 0, sleeveLength = 0, chestLength = 0;

        document.querySelectorAll("#top-fabric-table tbody tr").forEach(row => {
            const select = row.querySelector(".garment-select");
            const value = parseFloat(row.querySelector(".consumption-input").value) || 0;
            const type = select.options[select.selectedIndex]?.getAttribute("data-type");

            if (type === "body") bodyLength += value;
            else if (type === "sleeve") sleeveLength += value;
            else if (type === "chest") chestLength += value;
        });

        const totalBodySleeveLength = bodyLength + sleeveLength + 10;
        const totalChestLength = chestLength + 4;
        let topConsumption = (totalBodySleeveLength * totalChestLength * 2 * 12 * topGsm) / 10000000;

        const topWastagePerc = parseFloat(document.getElementById("top_wastage_percentage").value) || 0;
        topConsumption += (topConsumption * topWastagePerc) / 100;

        let topAddonTotal = 0;
        document.querySelectorAll("#top-fabric-addons-table tbody tr").forEach(row => {
            topAddonTotal += parseFloat(row.querySelector(".addon-consumption").value) || 0;
        });
        
        const totalTopConsumption = topConsumption + topAddonTotal;
        document.getElementById("total_top_consumption_display").textContent = totalTopConsumption.toFixed(4);

        // --- 2. Calculate Bottom Consumption ---
        const bottomGsm = parseFloat(document.getElementById("bottom_fabric_gsm").value) || 0;
        
        // Collect bottom fabric component values
        let halfThigh = 0, totalLength = 0, waistbeltHeight = 0, frontRise = 0, backRise = 0, inSeam = 0, outSeam = 0;
        
        document.querySelectorAll("#bottom-fabric-table tbody tr").forEach(row => {
            const select = row.querySelector(".bottom-component-select");
            const value = parseFloat(row.querySelector(".bottom-value-input").value) || 0;
            const type = select.options[select.selectedIndex]?.getAttribute("data-type");

            switch(type) {
                case "half_thigh": halfThigh = value; break;
                case "total_length": totalLength = value; break;
                case "waistbelt_height": waistbeltHeight = value; break;
                case "front_rise": frontRise = value; break;
                case "back_rise": backRise = value; break;
                case "in_seam": inSeam = value; break;
                case "out_seam": outSeam = value; break;
            }
        });

        // Calculate Total Length using preset formulas if not directly provided
        if (totalLength === 0) {
            if (outSeam > 0) {
                totalLength = outSeam;
            } else {
                const totalWaistbelt = (waistbeltHeight * 2) + 2;
                const halfRise = (frontRise + backRise) / 2;
                const inSeamWithAllowance = inSeam > 0 ? inSeam + 8 : 0;
                totalLength = totalWaistbelt + halfRise + inSeamWithAllowance;
            }
        }
        
        // Apply bottom fabric consumption formula
        let bottomConsumption = 0;
        if (halfThigh > 0 && totalLength > 0) {
            bottomConsumption = (halfThigh * totalLength * 4 * 12 * bottomGsm) / 10000000;
        }

        const bottomWastagePerc = parseFloat(document.getElementById("bottom_wastage_percentage").value) || 0;
        bottomConsumption += (bottomConsumption * bottomWastagePerc) / 100;
        
        let bottomAddonTotal = 0;
        document.querySelectorAll("#bottom-fabric-addons-table tbody tr").forEach(row => {
            bottomAddonTotal += parseFloat(row.querySelector(".addon-consumption").value) || 0;
        });

        const totalBottomConsumption = bottomConsumption + bottomAddonTotal;
        document.getElementById("total_bottom_consumption_display").textContent = totalBottomConsumption.toFixed(4);

        // --- 3. Grand Total Consumption ---
        const grandTotalConsumption = totalTopConsumption + totalBottomConsumption;
        document.getElementById("total_fabric_consumption_display").textContent = grandTotalConsumption.toFixed(4);
        document.getElementById("calculated_total_fabric_consumption_hidden").value = grandTotalConsumption.toFixed(4);

        // --- 4. Calculate Fabric Cost per Unit ---
        let fabricCostPerUnit = 0;
        document.querySelectorAll("#fabric-cost-table tbody tr").forEach(row => {
            fabricCostPerUnit += parseFloat(row.querySelector(".fabric-cost-value").value) || 0;
        });

        const totalFabricCostPerUnit = fabricCostPerUnit;
        document.getElementById("total_fabric_cost_per_unit_display").textContent = totalFabricCostPerUnit.toFixed(2);

        // --- 5. Calculate Total Fabrics Cost DZN ---
        const totalFabricsCostDzn = grandTotalConsumption * totalFabricCostPerUnit;
        document.getElementById('total_fabrics_cost_dzn_display').textContent = totalFabricsCostDzn.toFixed(2);
        document.getElementById('summary_fabrics_cost_dzn').textContent = totalFabricsCostDzn.toFixed(2);
        document.getElementById('calculated_total_fabric_cost_hidden').value = totalFabricsCostDzn.toFixed(2);

        // --- 6. Calculate Accessory Cost ---
        let totalAccessoryCost = 0;
        document.querySelectorAll("#accessory-cost-table tbody tr").forEach(row => {
            const rate = parseFloat(row.querySelector(".accessory-rate").value) || 0;
            const quantity = parseFloat(row.querySelector(".accessory-quantity").value) || 0;
            const consumption = parseFloat(row.querySelector(".accessory-consumption").value) || 0;
            totalAccessoryCost += rate * quantity * consumption;
        });

        document.getElementById("total_accessory_cost_display").textContent = totalAccessoryCost.toFixed(2);
        document.getElementById("summary_accessory_cost").textContent = totalAccessoryCost.toFixed(2);
        document.getElementById("calculated_accessories_cost_hidden").value = totalAccessoryCost.toFixed(2);

        // --- 7. Calculate Other Costs (Hierarchical layout) ---
        let totalOtherCosts = 0;
        document.querySelectorAll(".other-cost-amount").forEach(input => {
            totalOtherCosts += parseFloat(input.value) || 0;
        });

        document.getElementById("total_other_costs_display").textContent = totalOtherCosts.toFixed(2);
        document.getElementById("summary_other_costs").textContent = totalOtherCosts.toFixed(2);
        document.getElementById("calculated_other_costs_total_hidden").value = totalOtherCosts.toFixed(2);

        // --- 8. Calculate Commercial Rates ---
        const subtotal = totalFabricsCostDzn + totalAccessoryCost + totalOtherCosts;
        let totalCommercialRates = 0;
        
        document.querySelectorAll("#commercial-rates-table tbody tr").forEach(row => {
            const percentage = parseFloat(row.querySelector(".commercial-rate-percentage").value) || 0;
            totalCommercialRates += (subtotal * percentage) / 100;
        });

        document.getElementById("total_commercial_rates_display").textContent = totalCommercialRates.toFixed(2);
        document.getElementById("summary_commercial_rates").textContent = totalCommercialRates.toFixed(2);
        document.getElementById("calculated_commercial_rates_total_hidden").value = totalCommercialRates.toFixed(2);

        // --- 9. Calculate Additional Costs ---
        let totalAdditionalCosts = 0;
        document.querySelectorAll("#additional-costs-table tbody tr").forEach(row => {
            const amount = parseFloat(row.querySelector(".additional-cost-amount").value) || 0;
            totalAdditionalCosts += amount;
        });

        document.getElementById("total_additional_costs_display").textContent = totalAdditionalCosts.toFixed(2);
        document.getElementById("summary_additional_costs").textContent = totalAdditionalCosts.toFixed(2);
        document.getElementById("calculated_additional_costs_total_hidden").value = totalAdditionalCosts.toFixed(2);

        // --- 10. Calculate Grand Total ---
        const grandTotal = totalFabricsCostDzn + totalAccessoryCost + totalOtherCosts + totalCommercialRates + totalAdditionalCosts;
        document.getElementById("summary_total_cost").textContent = grandTotal.toFixed(2);
        document.getElementById("calculated_total_cost_hidden").value = grandTotal.toFixed(2);

        // --- 11. Calculate FOB Cost Per Piece ---
        const orderQuantity = {{ $inquiry->order_quantity ?? 1 }};
        const fobCostPerPiece = grandTotal / orderQuantity;
        document.getElementById("summary_fob_cost_per_piece").textContent = fobCostPerPiece.toFixed(2);

        // --- 12. Calculate Difference ---
        const targetPrice = {{ $inquiry->target_price ?? 0 }};
        const difference = targetPrice - fobCostPerPiece;
        document.getElementById("summary_difference").textContent = difference.toFixed(2);
const differenceElement = document.getElementById("summary_difference");

if (difference > 0) {
    differenceElement.style.background = "green";
        differenceElement.style.color = "white";
         differenceElement.style.padding = "5px";


} else if (difference < 0) {
    differenceElement.style.background = "red";
            differenceElement.style.color = "white";
         differenceElement.style.padding = "5px";
} else {
    differenceElement.style.color = "black";
}
        // --- 13. Update costing details JSON ---
        const costingDetails = {
            fabric_consumption: grandTotalConsumption,
            fabric_cost: totalFabricsCostDzn,
            accessory_cost: totalAccessoryCost,
            other_costs: totalOtherCosts,
            commercial_rates: totalCommercialRates,
            additional_costs: totalAdditionalCosts,
            total_cost: grandTotal
        };
        
        document.getElementById("costing_details_json").value = JSON.stringify(costingDetails);
    }

    // Initial calculation
    calculateAll();
});
</script>

@include('admin.footer')

