@extends('layouts.dashboard.adminapp')

@section('title', '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
<div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h5 mb-0 text-gray-800">UEPL | Quotation Form</h1>
    <div class="display-date">
        <span id="day">day</span>,
        <span id="daynum">00</span>
        <span id="month">month</span>
        <span id="year">0000</span>
    </div>
    <div class="display-time"></div>
</div>

<form class="row quotation-page-content" id="quotationContent" method="POST"
    action="{{ route('admin.quotations.store') }}">
    @csrf
    <div class="col-lg-12">
        <div class="quotation-form mb-5">
            <h1 class="pt-5 pb-5">Quotation</h1>
            <br>
            <!-- Company and Client Information -->
            <div class="company-info">
                <!-- Row 1: Customer Name & RFQ No -->
                <div class="row">
                    <div class="col-md-6">
                        <label for="customerName">Customer Name </label>
                        <input type="text" id="customerName" name="customer_name" placeholder="Customer Name" readonly>
                        <input type="hidden" id="customerId" name="customer_id">
                    </div>
                    <div class="col-md-6">
                        <label for="rfqNo">RFQ No <span class="required" title="required">*</span></label>
                        <select id="rfqNo" name="rfq_no" required>
                            <option value="">Select RFQ No</option>
                            @foreach ($unassignedRfqs as $rfq)
                                <option value="{{ $rfq->id }}">{{ $rfq->rfq_no }}</option>
                            @endforeach
                        </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"></textarea>
                    </div>
                    <div class="col-md-6">
                        <label for="rfqDate">RFQ Date</label>
                        <input type="date" id="rfqDate" name="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" >
                    </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>
                    </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">
                    </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>
                    </div>
                </div><br>
                
                <!-- Row 5: Email only (full width if needed) -->
                <div class="row">
                    <div class="col-md-6">
                        <label for="email">Email</label>
                        <input type="text" id="email" name="email" placeholder="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">
                    </div>
                </div><br>


                <div class="row">
                    <div class="col-md-6">
                        <label for="partNo">Part No</label>
                        <input type="text" id="partNo" name="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">
                    </div>
                </div><br>
                <div class="row">
                    <div class="col-md-6">
                        <label for="drawingNo">Drawing No</label>
                        <input type="text" id="drawingNo" name="drawing_no">
                    </div>
                    <div class="col-md-6">
                        <label for="drawingRev">Drawing Revision</label>
                        <input type="text" id="drawingRev" name="drawing_rev">
                    </div>
                </div><br>
                <div class="row">
                    <div class="col-md-6">
                        <label for="quantity">Quantity</label>
                        <input type="number" id="quantity" name="quantity">
                    </div>
                    <div class="col-md-6">
                        <label for="uom">Unit of Measurement</label>
                        <input type="text" id="quantityUOM" name="quantity_uom">
                    </div>
                </div><br>
                <div class="row">
                    <div class="product-selection col-md-6">
                        <label for="productType">Product Type <span class="required" title="required">*</span></label>
                        <!--<input type="text" id="productType" name="product_type" placeholder="Product Type" required>-->
                        <select id="productType" name="product_type" required>
                                <option value="">Select Product</option>
                            @foreach($productTypes as $type)
                                <option value="{{ $type->name }}">{{ $type->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label for="description">Description</label>
                        <textarea id="description" name="description" rows="2" placeholder="Project Description"></textarea>
                    </div>
                </div>

                <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)"> Raw Material Charges</label>
                        </div>
                    </div>
                    <div class="rawmaterial-table">
                        <table id="table1" class="product-table RMtable hidden">
                            <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">
                                <tr>
                                    <td>1</td>
                                    <td><select name="raw_material[0][material_id]" class="rm-material form-control">
                                            <option value="">Select Raw Material</option>
                                            @foreach ($allRawMaterials as $rawMaterial)
                                            <option value="{{ $rawMaterial->id }}" data-density="{{ $rawMaterial->density }}">{{ $rawMaterial->name }}</option>
                                            @endforeach
                                        </select>
                                        <input type="hidden" name="raw_material[0][density]">
                                    </td>
                                    <td><input type="number" name="raw_material[0][rate]" class="rm-rate"
                                            placeholder="Rate" step="0.01"></td>
                                    <td><input type="number" name="raw_material[0][scrap_rate]"
                                            class="rm-scrap-rate" placeholder="Scrap Rate" step="0.01"></td>
                                    <td><input type="number" name="raw_material[0][finish_weight]"
                                            class="rm-finish-weight" placeholder="Finish Weight" step="0.01"></td>
                                    <td>
                                        <select name="raw_material[0][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[0][quantity]" class="rm-quantity"
                                            placeholder="Quantity" min="1"></td>
                                    <td><input type="number" name="raw_material[0][size1]" placeholder="Size 1">
                                    </td>
                                    <td><input type="number" name="raw_material[0][size2]" placeholder="Size 2">
                                    </td>
                                    <td><input type="number" name="raw_material[0][size3]" placeholder="Size 3">
                                    </td>
                                    <td><input type="number" name="raw_material[0][rm_cost]" class="rm-cost"
                                            placeholder="RM Cost" step="0.01"></td>
                                    <td><input type="text" name="raw_material[0][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>
                            </tbody>
                        </table>
                    </div><br>
                    <div class="row col-md-2" id="add-row-1" style="display: none;">
                        <button type="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)"> Conversion
                                Cost</label>
                        </div>
                    </div>
                    <table id="table2" class="product-table hidden">
                        <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">
                            <tr>
                                <td>1</td>
                                <td>
                                    <input list="conversionCost-options" name="conversion_cost[0][desc]"
                                        placeholder="Select an option">
                                    <datalist id="conversionCost-options">
                                        @foreach ($conversionCosts as $cost)
                                        <option value="{{ $cost }}"></option>
                                        @endforeach
                                    </datalist>
                                </td>
                                <td><input type="number" name="conversion_cost[0][quantity]" class="cc-quantity"
                                        placeholder="Quantity" min="1"></td>
                                <td><input type="text" name="conversion_cost[0][unit]" placeholder="Unit"></td>
                                <td><input type="number" name="conversion_cost[0][rate]" class="cc-rate"
                                        placeholder="Rate" min="0" step="0.01"></td>
                                <td><input type="text" name="conversion_cost[0][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>
                        </tbody>
                    </table><br>
                    <div class="row col-md-2" id="add-row-2" style="display: none;">
                        <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)"> Packing
                                Charges</label>
                        </div>
                    </div>
                    <table id="table3" class="product-table hidden">
                        <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">
                            <tr>
                                <td>1</td>
                                <td><input type="text" name="packing[0][desc]" placeholder="Description"
                                        value="Packing cost"></td>
                                <td><input type="number" name="packing[0][quantity]" class="pc-quantity"
                                        placeholder="Quantity" min="1"></td>
                                <td><input type="text" name="packing[0][unit]" placeholder="Unit"></td>
                                <td><input type="number" name="packing[0][rate]" class="pc-rate" placeholder="Rate"
                                        min="0" step="0.01"></td>
                                <td><input type="text" name="packing[0][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>
                        </tbody>
                    </table><br>
                    <div class="row col-md-2" id="add-row-3" style="display: none;">
                        <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"></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>
                    </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>
                                </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()">
                                </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>
                                </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>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <hr>
                <div class="row p-5">
                    <!-- Submit Button -->
                    <div class="btn pt-5 pb-5">
                        <button class="btn btn-success" type="submit">Save</button>
                    </div>

                    <div class="btn pt-5 pb-5">
                        <button class="btn btn-danger" type="reset" onclick="resetForm()">Clear</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

@endsection

@push('scripts')
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(function() {
        // Autofill Quotation Date with today's date
        let today = new Date();
        let yyyy = today.getFullYear();
        let mm = String(today.getMonth() + 1).padStart(2, '0'); // Months are zero-based
        let dd = String(today.getDate()).padStart(2, '0');
        let todayStr = `${yyyy}-${mm}-${dd}`;
        $('#quotationDate').val(todayStr);
        // 1. Auto-fill Quotation No
        $.get("{{ url('admin/max-quotation-id') }}", function(data) {
            $('#quotationNo').val(data.newQuotationNo);
        });

        // 2. Autofill customer info
        $('#companyNameSelect').on('change', function() {
            let customerId = $(this).val();
            if (!customerId) {
                $('#address').val('');
                $('#gst').val('');
                $('#email').val('');
                $('#phone').val('');
                return;
            }
            $.get("{{ url('admin/customer-vendor') }}/" + customerId, function(data) {
                $('#address').val(data.billing_address || '');
                $('#gst').val(data.gstno || '');
                $('#email').val(data.email || '');
                $('#phone').val(data.mobile || '');
            });
        });

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

        // 3. Toggle Dynamic Tables
        window.toggleTable = function(num) {
            $("#table" + num).toggleClass('hidden');
            $("#add-row-" + num).toggle();
        };

        // 4. Add/Remove Row and Calculation for RM Table
        let rmRow = 1,
            ccRow = 1,
            pcRow = 1;
        $('#addRowRM').click(function() {
            let idx = rmRow++;
            let options = `<option value="">Select Raw Material</option>`;
            @foreach($allRawMaterials as $rawMaterial)
            options += `<option value="{{ $rawMaterial->id }}" data-density="{{ $rawMaterial->density }}">{{ $rawMaterial->name }}</option>`;
            @endforeach
            $('#rm-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]"></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]">
                    <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"></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>`);
        });

        $('#addRowCC').click(function() {
            let idx = ccRow++;
            $('#cc-tbody').append(`
        <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>`);
        });

        $('#addRowPC').click(function() {
            let idx = pcRow++;
            $('#pc-tbody').append(`
        <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>`);
        });

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

        // 6. Auto-value calculation for 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();
        });

        // 7. Totals calculation (including discount)
        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');
        };

        // Number to words (simple, for INR)
        function convertNumberToWords(amount) {
            var words = new Array();
            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();
        }

        // Re-calc totals on any relevant input change
        $(document).on('input', '.rm-value, .cc-value, .pc-value, #qt-discount', calculateTotals);

    });
    $('#rfqNo').on('change', function() {
        let rfqNo = $(this).val();
        if (!rfqNo) {
            // Clear all fields
            $('#customerName, #address, #gst, #email, #phone').val('');
            return;
        }
        $.get("{{ url('admin/rfq-details') }}/" + rfqNo, function(resp) {
            console.log('RFQ AJAX response:', resp);
            if (resp.success) {
                let rfq = resp.rfq;
                // Adjust below keys according to your RFQ table/columns
                let customer = resp.customer || {};
                $('#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.billing_address);
                $('#gst').val(resp.customer.gstno);
                $('#email').val(resp.customer.email);
                $('#phone').val(resp.customer.mobile);
                $('#customerId').val(resp.customer.id);
                $('#custRefNo').val(rfq.cus_ref_no);
                // You can autofill more fields as needed
                if (resp.raw_materials && resp.raw_materials.length > 0) {
                    console.log('Populating RM Table with:', resp.raw_materials);
                    populateRawMaterialTable(resp.raw_materials);
                } else {
                    console.log('No raw_materials to populate!');
                }
            } else {
                console.log('AJAX call failed or returned no success.');
                $('#customerName, #address, #gst, #email, #phone').val('');
            }
        }).fail(function(xhr, status, error) {
            console.log('AJAX ERROR:', error, xhr.responseText);
        });
    });

    function populateRawMaterialTable(rawMaterials) {
        console.log('populateRawMaterialTable called with:', rawMaterials);
        const tbody = $('#rm-tbody');
        tbody.empty();
        // Get options HTML as a JS string
        let options = `<option value="">Select Raw Material</option>`;
        @foreach($allRawMaterials as $rawMaterial)
        options += `<option value="{{ $rawMaterial->id }}" data-density="{{ $rawMaterial->density }}">{{ $rawMaterial->name }}</option>`;
        @endforeach
        // If no raw materials, just return (and optionally hide the table/checkbox)
        if (!rawMaterials.length) {
            // Optionally hide the table and uncheck the box if you want
            $('#checkbox1').prop('checked', false);
            $('#table1').addClass('hidden');
            $('#add-row-1').hide();
            return;
        }

        // Always check the checkbox and show the table when populating
        $('#checkbox1').prop('checked', true);
        $('#table1').removeClass('hidden');
        $('#add-row-1').show();

        rawMaterials.forEach(function(mat, idx) {
            console.log('Adding RM row:', mat);
            // Create the dropdown with the correct selected value
            let dropdown = `<select name="raw_material[${idx}][material_id]" class="rm-material form-control">`;
            dropdown += options.replace(
                `value="${mat.material_id || mat.id || ''}"`,
                `value="${mat.material_id || mat.id || ''}" selected`
            );
            dropdown += `</select>`;
            tbody.append(`
        <tr>
            <td>${idx + 1}</td>
            <td>
                ${dropdown}
                <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"></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>
        `);
        });
        console.log('RM Table rows after populate:', $('#rm-tbody').children().length);
        tbody.find('select.rm-type').each(function() {
            updateSizePlaceholders(this);
        });
        // Optionally scroll to the table for better UX:
        // document.getElementById('table1').scrollIntoView({ behavior: 'smooth', block: 'center' });
    }


    // 1. Densities object
    const rawMaterialsDensity = {
        'MS': 7.85,
        'SS': 7.9,
        'AL': 2.7,
        // Add more if needed
    };

    // 2. Placeholder Update
    function updateSizePlaceholders(selectElement) {
        // Get the row
        const row = $(selectElement).closest('tr');
        // Find inputs by attribute ends-with selector
        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;
        }
    }

    // 3. Calculate RM Cost
    function calculateRMCost(row) {
        // Use jQuery for compatibility
        row = $(row);
        // Get values
        const rawMaterial = row.find('input[name$="[material]"]').val() || '';
        // You may want to split name if your materials are named like 'MS-XXX'
        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 = '';
        }
    }

    // 4. Bind Events
    // Placeholder update
    $(document).on('change', 'select[name^="raw_material"][name$="[type]"]', function() {
        updateSizePlaceholders(this);
    });

    // Calculate cost on relevant input
    $(document).on('input', `
    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]);
    });
    $(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