@extends('layouts.dashboard.adminapp')

@section('title', 'Edit Quotation')

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

<x-layout.page-header title="UEPL / Edit Quotation" icon="file-invoice" iconColor="warning" />

<form class="row quotation-page-content" id="quotationContent" method="POST"
    action="{{ route('admin.quotation.update', $quotation->id) }}">
    @csrf
    @method('POST')
    <div class="col-lg-12">
        <div class="quotation-form mb-5">
            <div class="umbrey-logo"><img src="{{ asset('cbimage.png') }}" alt="Company Logo" /></div>
            <h1>Edit Quotation</h1>
            <br>
            <!-- Company and Client Information -->
            <div class="company-info">

                @php
                $customerObj = $customers
                ->where('id', $quotation->customer_id ?? $quotation->customer_name)
                ->first();
                @endphp
                <!-- Row 1: Customer Name & RFQ No -->
                <div class="row">
                    <div class="col-md-6">
                        <label for="customerName">Customer Details <span class="required" title="required">*</span></label>
                        <input type="text" id="customerName" name="customer_id" value="{{ $customerObj->company ?? '' }}" readonly>
                        <input type="hidden" id="customerId" name="customer_name" value="{{ $quotation->customer_name }}" readonly>
                    </div>
                    <div class="col-md-6">
                        <label for="rfqNo">RFQ No</label>
                        <select id="rfqNo" name="rfq_no" class="form-control">
                            <option value="">Select RFQ No</option>
                            @foreach ($unassignedRfqs as $rfq)
                                <option value="{{ $rfq->id }}" @if ($quotation->rfq_no == $rfq->id) selected @endif>
                                    {{ $rfq->rfq_no }}
                                </option>
                            @endforeach
                            @if ($quotation->rfq_no && !$unassignedRfqs->contains('id', $quotation->rfq_no))
                                <option value="{{ $quotation->rfq_no }}" selected>{{ $quotation->rfq_no }}</option>
                            @endif
                        </select>
                    </div>
                </div><br>
                
                <!-- Row 2: Address & RFQ Date -->
                <div class="row">
                    <div class="col-md-6">
                        <label for="address">Address</label>
                        <textarea id="address" name="address" rows="1" placeholder="Address" required>{{ $quotation->address }}</textarea>
                    </div>
                    <div class="col-md-6">
                        <label for="rfqDate">RFQ Date</label>
                        <input type="date" id="rfqDate" name="rfq_date" value="{{ $quotation->rfq_date }}">
                    </div>
                </div><br>
                
                <!-- Row 3: GST & Quotation ID -->
                <div class="row">
                    <div class="col-md-6">
                        <label for="gst">GST</label>
                        <input type="text" id="gst" name="gst" placeholder="Enter valid GST number" required value="{{ $quotation->gst }}">
                    </div>
                    <div class="col-md-6">
                        <label for="quotationNo">Quotation ID <span class="required" title="required">*</span></label>
                        <input type="text" id="quotationNo" name="quotation_no" readonly required value="{{ $quotation->quotation_no }}">
                    </div>
                </div><br>
                
                <!-- Row 4: Contact Number & Quotation Date -->
                <div class="row">
                    <div class="col-md-6">
                        <label for="phone">Contact Number</label>
                        <input type="tel" id="phone" name="phone" placeholder="Enter 10-digit number" required value="{{ $quotation->phone }}">
                    </div>
                    <div class="col-md-6">
                        <label for="quotationDate">Quotation Date <span class="required" title="required">*</span></label>
                        <input type="date" id="quotationDate" name="quotation_date" required value="{{ $quotation->quotation_date }}">
                    </div>
                </div><br>
                
                <!-- Row 5: Email & Customer Reference No -->
                <div class="row">
                    <div class="col-md-6">
                        <label for="email">Email</label>
                        <input type="text" id="email" name="email" placeholder="Email" required value="{{ $quotation->email }}">
                    </div>
                    <div class="col-md-6">
                        <label for="custRefNo">Customer Reference No</label>
                        <input type="text" id="custRefNo" name="cust_ref_no" placeholder="Reference No" value="{{ $quotation->cust_ref_no }}">
                    </div>
                </div><br>
                
                <!-- Row 6: Part No & Project Material No -->
                <div class="row">
                    <div class="col-md-6">
                        <label for="partNo">Part No</label>
                        <input type="text" id="partNo" name="part_no" value="{{ $quotation->part_no }}">
                    </div>
                    <div class="col-md-6">
                        <label for="project-materialNo">Project Material No</label>
                        <input type="text" id="project-materialNo" name="project_material_no" placeholder="Project Material No" value="{{ $quotation->project_material_no }}">
                    </div>
                </div><br>
                
                <!-- Row 7: Drawing No & Drawing Revision -->
                <div class="row">
                    <div class="col-md-6">
                        <label for="drawingNo">Drawing No</label>
                        <input type="text" id="drawingNo" name="drawing_no" value="{{ $quotation->drawing_no }}">
                    </div>
                    <div class="col-md-6">
                        <label for="drawingRev">Drawing Revision</label>
                        <input type="text" id="drawingRev" name="drawing_rev" value="{{ $quotation->drawing_rev }}">
                    </div>
                </div><br>
                
                <!-- Row 8: Quantity & Unit of Measurement -->
                <div class="row">
                    <div class="col-md-6">
                        <label for="quantity">Quantity</label>
                        <input type="number" id="quantity" name="quantity" value="{{ $quotation->quantity }}">
                    </div>
                    <div class="col-md-6">
                        <label for="uom">Unit of Measurement</label>
                        <input type="text" id="quantityUOM" name="quantity_uom" value="{{ $quotation->quantity_uom }}">
                    </div>
                </div><br>
                
                <!-- Row 9: Product Type & Description -->
                <div class="row">
                    <div class="col-md-6 product-selection">
                        <label for="productType">Product Type <span class="required" title="required">*</span></label>
                        <input type="text" id="productType" name="product_type" placeholder="Product Type" required value="{{ $quotation->product_type }}">
                    </div>
                    <div class="col-md-6">
                        <label for="description">Description</label>
                        <textarea id="description" name="description" rows="2" placeholder="Project Description">{{ $quotation->description }}</textarea>
                    </div>
                </div><br>


                <hr>

                <!-- ======== DYNAMIC TABLES ======== -->
                <div class="tables">
                    <!-- RAW MATERIAL CHARGES -->
                    <div class="row">
                        <div class="col-md-4">
                            <label><input type="checkbox" id="checkbox1" onclick="toggleTable(1)" checked> Raw
                                Material
                                Charges</label>
                        </div>
                    </div>
                    <div class="rawmaterial-table">
                        <table id="table1" class="product-table RMtable">
                            <thead>
                                <tr>
                                    <th>Sl.No</th>
                                    <th>Raw Material</th>
                                    <th>Rate(₹/kg)</th>
                                    <th>Scrap Rate(₹/kg)</th>
                                    <th>Finish Weight(kg)</th>
                                    <th>RM Type</th>
                                    <th>Quantity</th>
                                    <th>Size 1(mm)</th>
                                    <th>Size 2(mm)</th>
                                    <th>Size 3(mm)</th>
                                    <th>RM Cost(₹)</th>
                                    <th>Value(₹)</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody id="rm-tbody">
                                @php
                                $rawMaterials = $quotation->raw_materials
                                ? json_decode($quotation->raw_materials, true)
                                : [];
                                @endphp

                                @foreach ($rawMaterials as $i => $rm)
                                <tr>
                                    <td>{{ $i + 1 }}</td>
                                    <td><select name="raw_material[{{ $i }}][material_id]" class="rm-material form-control">
                                            <option value="">Select Raw Material</option>

                                            @foreach ($allRawMaterials as $rawMaterial)
                                            <option value="{{ $rawMaterial->id }}"
                                                {{ (
        (isset($rm['material_id']) && $rm['material_id'] == $rawMaterial->id) ||
        (isset($rm['material']) && $rm['material'] == $rawMaterial->id)
    ) ? 'selected' : '' }}>
                                                {{ $rawMaterial->name }}
                                            </option>
                                            @endforeach
                                        </select></td>
                                    <td><input type="number" name="raw_material[{{ $i }}][rate]"
                                            class="rm-rate" placeholder="Rate" step="0.01"
                                            value="{{ $rm['rate'] ?? '' }}"></td>
                                    <td><input type="number"
                                            name="raw_material[{{ $i }}][scrap_rate]"
                                            class="rm-scrap-rate" placeholder="Scrap Rate" step="0.01"
                                            value="{{ $rm['scrap_rate'] ?? '' }}"></td>
                                    <td><input type="number"
                                            name="raw_material[{{ $i }}][finish_weight]"
                                            class="rm-finish-weight" placeholder="Finish Weight" step="0.01"
                                            value="{{ $rm['finish_weight'] ?? '' }}"></td>
                                    <td>
                                        <select name="raw_material[{{ $i }}][type]">
                                            <option value="" disabled>Type</option>
                                            <option value="Rod"
                                                {{ ($rm['type'] ?? '') == 'Rod' ? 'selected' : '' }}>Rod</option>
                                            <option value="Plate"
                                                {{ ($rm['type'] ?? '') == 'Plate' ? 'selected' : '' }}>Plate
                                            </option>
                                            <option value="Pipe"
                                                {{ ($rm['type'] ?? '') == 'Pipe' ? 'selected' : '' }}>Pipe</option>
                                            <option value="Other"
                                                {{ ($rm['type'] ?? '') == 'Other' ? 'selected' : '' }}>Other
                                            </option>
                                        </select>
                                    </td>
                                    <td><input type="number" name="raw_material[{{ $i }}][quantity]"
                                            class="rm-quantity" placeholder="Quantity" min="1"
                                            value="{{ $rm['quantity'] ?? '' }}"></td>
                                    <td><input type="number" name="raw_material[{{ $i }}][size1]"
                                            placeholder="Size 1" value="{{ $rm['size1'] ?? '' }}"></td>
                                    <td><input type="number" name="raw_material[{{ $i }}][size2]"
                                            placeholder="Size 2" value="{{ $rm['size2'] ?? '' }}"></td>
                                    <td><input type="number" name="raw_material[{{ $i }}][size3]"
                                            placeholder="Size 3" value="{{ $rm['size3'] ?? '' }}"></td>
                                    <td><input type="number" name="raw_material[{{ $i }}][rm_cost]"
                                            class="rm-cost" placeholder="RM Cost" step="0.01"
                                            value="{{ $rm['rm_cost'] ?? '' }}"></td>
                                    <td><input type="text" name="raw_material[{{ $i }}][value]"
                                            class="rm-value" placeholder="Value" readonly
                                            value="{{ $rm['value'] ?? '' }}"></td>
                                    <td>
                                        <button type="button" class="btn btn-danger" onclick="deleteRow(this)">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                    <div class="row col-md-2" id="add-row-1">
                        <br>
                        <button type="button" id="addRowRM">Add Row</button>
                    </div>
                    <hr>
                    <!-- CONVERSION COST -->
                    <div class="row">
                        <div class="col-md-4">
                            <label><input type="checkbox" id="checkbox2" onclick="toggleTable(2)" checked> Conversion
                                Cost</label>
                        </div>
                    </div>
                    <table id="table2" class="product-table">
                        <thead>
                            <tr>
                                <th>Sl.No</th>
                                <th>Description</th>
                                <th>Quantity</th>
                                <th>Unit</th>
                                <th>Rate(INR)</th>
                                <th>Value</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody id="cc-tbody">
                            @php
                            $conversionCosts = $quotation->conversion_costs
                            ? json_decode($quotation->conversion_costs, true)
                            : [];
                            @endphp
                            @foreach ($conversionCosts as $i => $cc)
                            <tr>
                                <td>{{ $i + 1 }}</td>
                                <td>
                                    <input list="conversionCost-options"
                                        name="conversion_cost[{{ $i }}][desc]"
                                        placeholder="Select an option" value="{{ $cc['desc'] ?? '' }}">
                                    <datalist id="conversionCost-options">
                                        @foreach ($conversionprocesses as $cost)
                                        <option value="{{ $cost }}"></option>
                                        @endforeach
                                    </datalist>
                                </td>
                                <td><input type="number" name="conversion_cost[{{ $i }}][quantity]"
                                        class="cc-quantity" placeholder="Quantity" min="1"
                                        value="{{ $cc['quantity'] ?? '' }}"></td>
                                <td><input type="text" name="conversion_cost[{{ $i }}][unit]"
                                        placeholder="Unit" value="{{ $cc['unit'] ?? '' }}"></td>
                                <td><input type="number" name="conversion_cost[{{ $i }}][rate]"
                                        class="cc-rate" placeholder="Rate" min="0" step="0.01"
                                        value="{{ $cc['rate'] ?? '' }}"></td>
                                <td><input type="text" name="conversion_cost[{{ $i }}][value]"
                                        class="cc-value" placeholder="Value" readonly
                                        value="{{ $cc['value'] ?? '' }}"></td>
                                <td>
                                    <button type="button" class="btn btn-danger" onclick="deleteRow(this)">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                    <div class="row col-md-2" id="add-row-2">
                        <br>
                        <button type="button" id="addRowCC">Add Row</button>
                    </div>
                    <hr>
                    <!-- PACKING CHARGES -->
                    <div class="row">
                        <div class="col-md-4">
                            <label><input type="checkbox" id="checkbox3" onclick="toggleTable(3)" checked> Packing
                                Charges</label>
                        </div>
                    </div>
                    <table id="table3" class="product-table">
                        <thead>
                            <tr>
                                <th>Sl.No</th>
                                <th>Description</th>
                                <th>Quantity</th>
                                <th>Unit</th>
                                <th>Rate(INR)</th>
                                <th>Value</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody id="pc-tbody">
                            @php
                            $packingCharges = $quotation->packing_charges
                            ? json_decode($quotation->packing_charges, true)
                            : [];
                            @endphp
                            @foreach ($packingCharges as $i => $pc)
                            <tr>
                                <td>{{ $i + 1 }}</td>
                                <td><input type="text" name="packing[{{ $i }}][desc]"
                                        placeholder="Description" value="{{ $pc['desc'] ?? '' }}"></td>
                                <td><input type="number" name="packing[{{ $i }}][quantity]"
                                        class="pc-quantity" placeholder="Quantity" min="1"
                                        value="{{ $pc['quantity'] ?? '' }}"></td>
                                <td><input type="text" name="packing[{{ $i }}][unit]"
                                        placeholder="Unit" value="{{ $pc['unit'] ?? '' }}"></td>
                                <td><input type="number" name="packing[{{ $i }}][rate]"
                                        class="pc-rate" placeholder="Rate" min="0" step="0.01"
                                        value="{{ $pc['rate'] ?? '' }}"></td>
                                <td><input type="text" name="packing[{{ $i }}][value]"
                                        class="pc-value" placeholder="Value" readonly
                                        value="{{ $pc['value'] ?? '' }}"></td>
                                <td>
                                    <button type="button" class="btn btn-danger" onclick="deleteRow(this)">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                    <div class="row col-md-2" id="add-row-3">
                        <br>
                        <button type="button" id="addRowPC">Add Row</button>
                    </div>
                </div>
                <hr>
                <div class="col-md-12">
                    <label for="quoteNote">Note</label>
                    <textarea name="note" id="quoteNote" placeholder="Note">{{ $quotation->note }}</textarea>
                </div>
                <!-- Totals and GST Calculation -->
                <hr>
                <div class="row total-fields">
                    <div class="col-md-6">
                        <label for="INR">Indian Rupees</label>
                        <input type="text" id="GT-in-letters" readonly value="{{ $quotation->grand_total }}">
                    </div>
                    <div class="col-md-6">
                        <div class="totals align-self-lg-end">
                            <div class="row">
                                <div class="col-md-3">
                                    <label for="totalAmount">SUB TOTAL</label>
                                </div>
                                <div class="col-md-9">
                                    <input type="text" name="sub_total" id="totalAmount" readonly
                                        value="{{ $quotation->sub_total }}">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-3">
                                    <label for="discount">Discount (%)</label>
                                </div>
                                <div class="col-md-9">
                                    <input type="number" id="qt-discount" name="discount"
                                        oninput="calculateTotals()" value="{{ $quotation->discount }}">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-3">
                                    <label for="roundUp">RoundUp Amount</label>
                                </div>
                                <div class="col-md-9">
                                    <input type="text" id="roundUp" name="round_up" readonly
                                        value="{{ $quotation->round_up }}">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-3">
                                    <label for="grandTotal">Grand Total</label>
                                </div>
                                <div class="col-md-9">
                                    <input type="text" id="grandTotal" name="grand_total" readonly
                                        value="{{ $quotation->grand_total }}">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <hr>
                <div class="row mt-5 mb-5">
                    <div class="col-xl-3">
                        <button type="submit" class="btn btn-primary">Update</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

@endsection
@push('scripts')
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    window.allRawMaterials = @json($allRawMaterials);
    $(function() {
        // --- Autofill today's date if blank
        let today = new Date();
        let yyyy = today.getFullYear();
        let mm = String(today.getMonth() + 1).padStart(2, '0');
        let dd = String(today.getDate()).padStart(2, '0');
        let todayStr = `${yyyy}-${mm}-${dd}`;
        if (!$('#quotationDate').val()) $('#quotationDate').val(todayStr);

        // --- Quotation No (if needed to autofill)
        $.get("{{ url('admin/max-quotation-id') }}", function(data) {
            if (!$('#quotationNo').val()) $('#quotationNo').val(data.newQuotationNo);
        });

        // --- Toggle dynamic tables (show/hide)
        window.toggleTable = function(num) {
            $("#table" + num).toggleClass('hidden');
            $("#add-row-" + num).toggle();
        };

        // --- Add/Remove Row Logic
        let rmRow = $('#rm-tbody tr').length || 1,
            ccRow = $('#cc-tbody tr').length || 1,
            pcRow = $('#pc-tbody tr').length || 1;

        $('#addRowRM').click(function() {
            let idx = rmRow++;
            $('#rm-tbody').append(rawMaterialRow(idx));
        });

        $('#addRowCC').click(function() {
            let idx = ccRow++;
            $('#cc-tbody').append(conversionCostRow(idx));
        });

        $('#addRowPC').click(function() {
            let idx = pcRow++;
            $('#pc-tbody').append(packingChargeRow(idx));
        });

        window.deleteRow = function(btn) {
            $(btn).closest('tr').remove();
            calculateTotals();
        };

        // --- Placeholders for RM types
        $(document).on('change', 'select[name^="raw_material"][name$="[type]"]', function() {
            updateSizePlaceholders(this);
            // Also re-calc RM Cost (if needed)
            calculateRMCost($(this).closest('tr')[0]);
        });

        // --- Recalculate RM cost on relevant input
        $(document).on('input change', `
        input[name^="raw_material"][name$="[rate]"],
        input[name^="raw_material"][name$="[scrap_rate]"],
        input[name^="raw_material"][name$="[finish_weight]"],
        input[name^="raw_material"][name$="[size1]"],
        input[name^="raw_material"][name$="[size2]"],
        input[name^="raw_material"][name$="[size3]"],
        select[name^="raw_material"][name$="[type]"],
        input[name^="raw_material"][name$="[material]"]
    `, function() {
            calculateRMCost($(this).closest('tr')[0]);
        });

        // --- Calculate row values for RM/CC/PC tables
        $(document).on('input', '.rm-rate, .rm-quantity, .rm-cost', function() {
            $(this).closest('tr').find('.rm-value').val(
                (
                    (parseFloat($(this).closest('tr').find('.rm-rate').val()) || 0) *
                    (parseFloat($(this).closest('tr').find('.rm-quantity').val()) || 0) +
                    (parseFloat($(this).closest('tr').find('.rm-cost').val()) || 0)
                ).toFixed(2)
            );
            calculateTotals();
        });
        $(document).on('input', '.cc-rate, .cc-quantity', function() {
            $(this).closest('tr').find('.cc-value').val(
                ((parseFloat($(this).closest('tr').find('.cc-rate').val()) || 0) *
                    (parseFloat($(this).closest('tr').find('.cc-quantity').val()) || 0)).toFixed(2)
            );
            calculateTotals();
        });
        $(document).on('input', '.pc-rate, .pc-quantity', function() {
            $(this).closest('tr').find('.pc-value').val(
                ((parseFloat($(this).closest('tr').find('.pc-rate').val()) || 0) *
                    (parseFloat($(this).closest('tr').find('.pc-quantity').val()) || 0)).toFixed(2)
            );
            calculateTotals();
        });

        // --- Totals & Indian Rupees in words
        window.calculateTotals = function() {
            let subtotal = 0;
            $('.rm-value, .cc-value, .pc-value').each(function() {
                subtotal += parseFloat($(this).val()) || 0;
            });
            $('#totalAmount').val(subtotal.toFixed(2));
            let discount = parseFloat($('#qt-discount').val()) || 0;
            let afterDiscount = subtotal - (subtotal * discount / 100);
            let roundUp = Math.round(afterDiscount) - afterDiscount;
            $('#roundUp').val(roundUp.toFixed(2));
            let grandTotal = afterDiscount + roundUp;
            $('#grandTotal').val(grandTotal.toFixed(2));
            $('#GT-in-letters').val(convertNumberToWords(Math.round(grandTotal)) + ' Rupees');
        };
        $(document).on('input', '.rm-value, .cc-value, .pc-value, #qt-discount', calculateTotals);
        // Trigger once on load
        calculateTotals();

        // --- Number to Words (INR)
        function convertNumberToWords(amount) {
            var words = [];
            words[0] = '';
            words[1] = 'One';
            words[2] = 'Two';
            words[3] = 'Three';
            words[4] = 'Four';
            words[5] = 'Five';
            words[6] = 'Six';
            words[7] = 'Seven';
            words[8] = 'Eight';
            words[9] = 'Nine';
            words[10] = 'Ten';
            words[11] = 'Eleven';
            words[12] = 'Twelve';
            words[13] = 'Thirteen';
            words[14] = 'Fourteen';
            words[15] = 'Fifteen';
            words[16] = 'Sixteen';
            words[17] = 'Seventeen';
            words[18] = 'Eighteen';
            words[19] = 'Nineteen';
            words[20] = 'Twenty';
            words[30] = 'Thirty';
            words[40] = 'Forty';
            words[50] = 'Fifty';
            words[60] = 'Sixty';
            words[70] = 'Seventy';
            words[80] = 'Eighty';
            words[90] = 'Ninety';
            if (amount === 0) return 'Zero';
            if (amount > 999999999) return 'Overflow';
            var crore = Math.floor(amount / 10000000);
            amount -= crore * 10000000;
            var lakh = Math.floor(amount / 100000);
            amount -= lakh * 100000;
            var thousand = Math.floor(amount / 1000);
            amount -= thousand * 1000;
            var hundred = Math.floor(amount / 100);
            amount -= hundred * 100;
            var ten = Math.floor(amount / 10);
            var one = amount % 10;
            var str = '';
            if (crore > 0) str += convertNumberToWords(crore) + ' Crore ';
            if (lakh > 0) str += convertNumberToWords(lakh) + ' Lakh ';
            if (thousand > 0) str += convertNumberToWords(thousand) + ' Thousand ';
            if (hundred > 0) str += convertNumberToWords(hundred) + ' Hundred ';
            if (ten > 1) str += words[ten * 10] + ' ';
            if (ten == 1) str += words[ten * 10 + one] + ' ';
            else if (one > 0) str += words[one] + ' ';
            return str.trim();
        }

        // --- RM Type Placeholders
        function updateSizePlaceholders(selectElement) {
            const row = $(selectElement).closest('tr');
            const size1Input = row.find('input[name$="[size1]"]')[0];
            const size2Input = row.find('input[name$="[size2]"]')[0];
            const size3Input = row.find('input[name$="[size3]"]')[0];
            const rmCostInput = row.find('input[name$="[rm_cost]"]')[0];
            const selectedType = $(selectElement).val();
            if (selectedType === 'Rod') {
                size1Input.placeholder = 'Rod Diameter';
                size2Input.placeholder = 'Rod Length';
                size3Input.placeholder = '';
                size1Input.readOnly = false;
                size2Input.readOnly = false;
                size3Input.readOnly = true;
                rmCostInput.readOnly = true;
            } else if (selectedType === 'Plate') {
                size1Input.placeholder = 'Plate Thickness';
                size2Input.placeholder = 'Plate Length';
                size3Input.placeholder = 'Plate Width';
                size1Input.readOnly = false;
                size2Input.readOnly = false;
                size3Input.readOnly = false;
                rmCostInput.readOnly = true;
            } else if (selectedType === 'Pipe') {
                size1Input.placeholder = 'Outer Diameter';
                size2Input.placeholder = 'Inner Diameter';
                size3Input.placeholder = 'Pipe Length';
                size1Input.readOnly = false;
                size2Input.readOnly = false;
                size3Input.readOnly = false;
                rmCostInput.readOnly = true;
            } else {
                size1Input.placeholder = 'Size 1';
                size2Input.placeholder = 'Size 2';
                size3Input.placeholder = 'Size 3';
                size1Input.readOnly = true;
                size2Input.readOnly = true;
                size3Input.readOnly = true;
                rmCostInput.readOnly = false;
            }
        }

        // --- RM Cost Calculation (based on type)
        function calculateRMCost(row) {
            row = $(row);
            const rawMaterial = row.find('input[name$="[material]"]').val() || '';
            const materialName = rawMaterial.split('-')[0].trim();
            const rmRate = parseFloat(row.find('input[name$="[rate]"]').val()) || 0;
            const scrapRate = parseFloat(row.find('input[name$="[scrap_rate]"]').val()) || 0;
            const finishWeight = parseFloat(row.find('input[name$="[finish_weight]"]').val()) || 0;
            const size1 = (parseFloat(row.find('input[name$="[size1]"]').val()) || 0) * 0.001;
            const size2 = (parseFloat(row.find('input[name$="[size2]"]').val()) || 0) * 0.001;
            const size3 = (parseFloat(row.find('input[name$="[size3]"]').val()) || 0) * 0.001;
            const rmType = row.find('select[name$="[type]"]').val();
            const rmCostInput = row.find('input[name$="[rm_cost]"]')[0];
            const density = parseFloat(row.find('input[name$="[density]"]').val()) || 0;
            let rmWeight = 0,
                scrapWeight = 0,
                rmCost = 0;
            if (rmType === 'Rod') {
                rmWeight = 3.142 * Math.pow(size1 / 2, 2) * size2 * density; // πr²h*density
                scrapWeight = rmWeight - finishWeight;
                if (rmWeight > 0) rmCost = (rmWeight * rmRate) - (0.8 * (scrapWeight * scrapRate));
                rmCostInput.value = isNaN(rmCost) ? "" : rmCost.toFixed(2);
            } else if (rmType === 'Plate') {
                rmWeight = size1 * size2 * size3 * density;
                scrapWeight = rmWeight - finishWeight;
                if (rmWeight > 0) rmCost = (rmWeight * rmRate) - (0.8 * (scrapWeight * scrapRate));
                rmCostInput.value = isNaN(rmCost) ? "" : rmCost.toFixed(2);
            } else if (rmType === 'Pipe') {
                rmWeight = (3.142 * Math.pow(size1 / 2, 2) * size3 - 3.142 * Math.pow(size2 / 2, 2) * size3) * density;
                scrapWeight = rmWeight - finishWeight;
                if (rmWeight > 0) rmCost = (rmWeight * rmRate) - (0.8 * (scrapWeight * scrapRate));
                rmCostInput.value = isNaN(rmCost) ? "" : rmCost.toFixed(2);
            } else {
                rmCostInput.value = '';
            }
            // After updating RM cost, trigger value recalculation for this row
            $(row).find('.rm-cost').trigger('input');
        }

        // --- RFQ select auto-populate
        $('#rfqNo').on('change', function() {
            let rfqNo = $(this).val();
            if (!rfqNo) {
                $('#customerName, #address, #gst, #email, #phone').val('');
                return;
            }
            $.get("{{ url('admin/rfq-details') }}/" + rfqNo, function(resp) {
                if (resp.success) {
                    let rfq = resp.rfq;
                    $('#project-materialNo').val(rfq.project_material_no || '');
                    $('#drawingNo').val(rfq.drawing_no || '');
                    $('#drawingRev').val(rfq.drawing_rev || '');
                    $('#partNo').val(rfq.part_no || '');
                    $('#quantity').val(rfq.quantity || '');
                    $('#quantityUOM').val(rfq.uom || '');
                    $('#description').val(rfq.note || '');
                    $('#productType').val(rfq.product_type || '');
                    $('#rfqDate').val(rfq.rfq_date || '');
                    $('#customerName').val(resp.customer.company);
                    $('#address').val(resp.customer.address);
                    $('#gst').val(resp.customer.gstno);
                    $('#email').val(resp.customer.email);
                    $('#phone').val(resp.customer.mobile);
                    $('#customerId').val(resp.customer.id);


                } else {
                    $('#customerName, #address, #gst, #email, #phone').val('');
                }
                if (resp.raw_materials && resp.raw_materials.length > 0) {
                    populateRawMaterialTable(resp.raw_materials, window.allRawMaterials);
                }
            });
        });

        // --- Populate Raw Material Table for RFQ select
        function populateRawMaterialTable(rawMaterials, allRawMaterials) {
            const tbody = $('#rm-tbody');
            tbody.empty();
            rawMaterials.forEach(function(mat, idx) {
                let options = `<option value="">Select Raw Material</option>`;
                allRawMaterials.forEach(function(item) {
                    // This is the correct scope for 'item'
                    let selected = (parseInt(item.id) === parseInt(mat.material_id || mat.id)) ? 'selected' : '';
                    options += `<option value="${item.id}" data-density="${item.density || ''}" ${selected}>${item.name}</option>`;
                });
                tbody.append(`
            <tr>
                <td>${idx + 1}</td>
                <td>
                    <select name="raw_material[${idx}][material_id]" class="rm-material form-control">
                        ${options}
                    </select>
                    <input type="hidden" name="raw_material[${idx}][density]" value="${mat.density || ''}">
                </td>
                <td><input type="number" name="raw_material[${idx}][rate]" class="rm-rate" placeholder="Rate" step="0.01" value="${mat.rate || ''}"></td>
                <td><input type="number" name="raw_material[${idx}][scrap_rate]" class="rm-scrap-rate" placeholder="Scrap Rate" step="0.01" value="${mat.scrap_rate || ''}"></td>
                <td><input type="number" name="raw_material[${idx}][finish_weight]" class="rm-finish-weight" placeholder="Finish Weight" step="0.01" value="${mat.finish_weight || ''}"></td>
                <td>
                    <select name="raw_material[${idx}][type]" class="rm-type">
                        <option value="" disabled ${!mat.type ? 'selected' : ''}>Type</option>
                        <option value="Rod" ${mat.type === 'Rod' ? 'selected' : ''}>Rod</option>
                        <option value="Plate" ${mat.type === 'Plate' ? 'selected' : ''}>Plate</option>
                        <option value="Pipe" ${mat.type === 'Pipe' ? 'selected' : ''}>Pipe</option>
                        <option value="Other" ${mat.type === 'Other' ? 'selected' : ''}>Other</option>
                    </select>
                </td>
                <td><input type="number" name="raw_material[${idx}][quantity]" class="rm-quantity" placeholder="Quantity" min="1" value="${mat.quantity || ''}"></td>
                <td><input type="number" name="raw_material[${idx}][size1]" placeholder="Size 1" value="${mat.size1 || ''}"></td>
                <td><input type="number" name="raw_material[${idx}][size2]" placeholder="Size 2" value="${mat.size2 || ''}"></td>
                <td><input type="number" name="raw_material[${idx}][size3]" placeholder="Size 3" value="${mat.size3 || ''}"></td>
                <td><input type="number" name="raw_material[${idx}][rm_cost]" class="rm-cost" placeholder="RM Cost" step="0.01" value="${mat.rm_cost || ''}" readonly></td>
                <td><input type="text" name="raw_material[${idx}][value]" class="rm-value" placeholder="Value" value="${mat.value || ''}" readonly></td>
                <td><button type="button" class="btn btn-danger" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
            </tr>
        `);
            });
        }


        // --- Row HTML creators for Add buttons (copy from add page for consistency)
        function rawMaterialRow(idx) {
            return `
        <tr>
            <td>${idx + 1}</td>
            <td><input type="text" name="raw_material[${idx}][material]" placeholder="Raw Material"><input type="hidden" name="raw_material[${idx}][density]"></td>
            <td><input type="number" name="raw_material[${idx}][rate]" class="rm-rate" placeholder="Rate" step="0.01"></td>
            <td><input type="number" name="raw_material[${idx}][scrap_rate]" class="rm-scrap-rate" placeholder="Scrap Rate" step="0.01"></td>
            <td><input type="number" name="raw_material[${idx}][finish_weight]" class="rm-finish-weight" placeholder="Finish Weight" step="0.01"></td>
            <td>
                <select name="raw_material[${idx}][type]" class="rm-type">
                    <option value="" disabled selected>Type</option>
                    <option value="Rod">Rod</option>
                    <option value="Plate">Plate</option>
                    <option value="Pipe">Pipe</option>
                    <option value="Other">Other</option>
                </select>
            </td>
            <td><input type="number" name="raw_material[${idx}][quantity]" class="rm-quantity" placeholder="Quantity" min="1"></td>
            <td><input type="number" name="raw_material[${idx}][size1]" placeholder="Size 1"></td>
            <td><input type="number" name="raw_material[${idx}][size2]" placeholder="Size 2"></td>
            <td><input type="number" name="raw_material[${idx}][size3]" placeholder="Size 3"></td>
            <td><input type="number" name="raw_material[${idx}][rm_cost]" class="rm-cost" placeholder="RM Cost" step="0.01" readonly></td>
            <td><input type="text" name="raw_material[${idx}][value]" class="rm-value" placeholder="Value" readonly></td>
            <td><button type="button" class="btn btn-danger" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
        </tr>`;
        }

        function conversionCostRow(idx) {
            return `
        <tr>
            <td>${idx + 1}</td>
            <td>
                <input list="conversionCost-options" name="conversion_cost[${idx}][desc]" placeholder="Select an option">
            </td>
            <td><input type="number" name="conversion_cost[${idx}][quantity]" class="cc-quantity" placeholder="Quantity" min="1"></td>
            <td><input type="text" name="conversion_cost[${idx}][unit]" placeholder="Unit"></td>
            <td><input type="number" name="conversion_cost[${idx}][rate]" class="cc-rate" placeholder="Rate" min="0" step="0.01"></td>
            <td><input type="text" name="conversion_cost[${idx}][value]" class="cc-value" placeholder="Value" readonly></td>
            <td><button type="button" class="btn btn-danger" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
        </tr>`;
        }

        function packingChargeRow(idx) {
            return `
        <tr>
            <td>${idx + 1}</td>
            <td><input type="text" name="packing[${idx}][desc]" placeholder="Description"></td>
            <td><input type="number" name="packing[${idx}][quantity]" class="pc-quantity" placeholder="Quantity" min="1"></td>
            <td><input type="text" name="packing[${idx}][unit]" placeholder="Unit"></td>
            <td><input type="number" name="packing[${idx}][rate]" class="pc-rate" placeholder="Rate" min="0" step="0.01"></td>
            <td><input type="text" name="packing[${idx}][value]" class="pc-value" placeholder="Value" readonly></td>
            <td><button type="button" class="btn btn-danger" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
        </tr>`;
        }

        // --- Autofill phone
        $('#phone').on('input', function() {
            this.value = this.value.replace(/[^0-9]/g, '').slice(0, 10);
        });

        // --- Initial placeholders and RM cost calculation for loaded data
        $('#rm-tbody tr').each(function() {
            updateSizePlaceholders($(this).find('select[name$="[type]"]')[0]);
            calculateRMCost(this);
        });

    });
    $(document).on('change', '.rm-material', function() {
        let density = $(this).find(':selected').data('density');
        $(this).closest('tr').find('input[name$="[density]"]').val(density);
        calculateRMCost($(this).closest('tr')[0]);
    });
</script>
<style>
    .hidden {
        display: none;
    }
</style>
@endpush