@extends('layouts.dashboard.superadminapp')

@section('title', 'Quotation')

@section('styles')
{{-- New Modern UI Stylesheet --}}
<link rel="stylesheet" href="{{ asset('css/modern-ui.css') }}">
<style>
    /* Toast Notification */
    #toastContainer {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
    }

    .toast {
        background: white;
        border-radius: 8px;
        padding: 1rem 1.25rem;
        margin-bottom: 0.75rem;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        display: flex;
        align-items: center;
        gap: 0.75rem;
        min-width: 300px;
        animation: slideIn 0.3s ease;
    }

    .toast.success {
        border-left: 4px solid #10b981;
    }

    .toast.error {
        border-left: 4px solid #ef4444;
    }

    .toast i {
        font-size: 1.25rem;
    }

    .toast.success i {
        color: #10b981;
    }

    .toast.error i {
        color: #ef4444;
    }

    @keyframes slideIn {
        from {
            transform: translateX(400px);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
</style>
@endsection

@section('content')
<div class="container-fluid theme-teal">

    <!-- Toast Container -->
    <div id="toastContainer"></div>

    {{-- Modern Page Header Component --}}
    <x-modern-ui.page-header
        title="Create Purchase Quotation"
        subtitle="Purchase Quotation Registration Form"
        icon="file-invoice"
        theme="teal"
    />

    <form class="quotation-page-content" id="quotationContent" method="POST"
        action="{{ route('superadmin.purchasebom.quotations.store') }}">
        @csrf

        {{-- Section 1: Customer Information --}}
        <x-modern-ui.section-card
            title="Customer Information"
            icon="user-tie"
            theme="teal"
        >
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="customerName">Customer Name</label>
                        <input type="text" id="customerName" name="customer_name" placeholder="Customer Name" class="form-control">
                        <input type="hidden" id="customerId" name="customer_id">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="rfqNo">RFQ No <span class="required-star">*</span></label>
                        <select id="rfqNo" name="rfq_no" required class="form-control">
                            <option value="">Select RFQ No</option>
                            @foreach ($unassignedRfqs as $rfq)
                                <option value="{{ $rfq->id }}">{{ $rfq->rfq_no }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="address">Address</label>
                        <textarea id="address" name="address" rows="2" placeholder="Address" class="form-control"></textarea>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="rfqDate">RFQ Date</label>
                        <input type="date" id="rfqDate" name="rfq_date" class="form-control">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="gst">GST</label>
                        <input type="text" id="gst" name="gst" placeholder="Enter valid GST number" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="quotationNo">Quotation ID <span class="required-star">*</span></label>
                        <input type="text" id="quotationNo" name="quotation_no" readonly required class="form-control">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="phone">Contact Number</label>
                        <input type="tel" id="phone" name="phone" placeholder="Enter 10-digit number" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="quotationDate">Quotation Date <span class="required-star">*</span></label>
                        <input type="date" id="quotationDate" name="quotation_date" required class="form-control">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="email">Email</label>
                        <input type="email" id="email" name="email" placeholder="Email" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="custRefNo">Customer Reference No</label>
                        <input type="text" id="custRefNo" name="cust_ref_no" placeholder="Reference No" class="form-control">
                    </div>
                </div>
        </x-modern-ui.section-card>

        {{-- Section 2: Product Details --}}
        <x-modern-ui.section-card
            title="Product Details"
            icon="cube"
            theme="info"
        >
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="partNo">Part No</label>
                        <input type="text" id="partNo" name="part_no" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="project-materialNo">Project Material No</label>
                        <input type="text" id="project-materialNo" name="project_material_no" placeholder="Project Material No" class="form-control">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="drawingNo">Drawing No</label>
                        <input type="text" id="drawingNo" name="drawing_no" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="drawingRev">Drawing Revision</label>
                        <input type="text" id="drawingRev" name="drawing_rev" class="form-control">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="quantity">Quantity</label>
                        <input type="number" id="quantity" name="quantity" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="quantityUOM">Unit of Measurement</label>
                        <input type="text" id="quantityUOM" name="quantity_uom" class="form-control">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="productType">Product Type <span class="required-star">*</span></label>
                        <select id="productType" name="product_type" required class="form-control">
                            <option value="">Select Product</option>
                            @foreach($productTypes as $type)
                                <option value="{{ $type->name }}">{{ $type->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="description">Description</label>
                        <textarea id="description" name="description" rows="2" placeholder="Project Description" class="form-control"></textarea>
                    </div>
                </div>
        </x-modern-ui.section-card>

        {{-- Section 3: Cost Breakdown --}}
        <x-modern-ui.section-card
            title="Cost Breakdown"
            icon="calculator"
            theme="success"
        >
                <!-- RAW MATERIAL CHARGES -->
                <div class="toggle-checkbox mb-3">
                    <input type="checkbox" id="checkbox1" onclick="toggleTable(1)">
                    <label for="checkbox1">Raw Material Charges</label>
                </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 Weight</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->rm_grade }}</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="text" name="raw_material[0][rm_weight]" class="rm-weight" placeholder="RM Weight" readonly></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 btn-sm" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="mt-3" id="add-row-1" style="display: none;">
                    <button type="button" class="btn btn-primary btn-sm" id="addRowRM"><i class="fa fa-plus mr-1"></i> Add Row</button>
                </div>

                <hr class="my-4">

                <!-- CONVERSION COST -->
                <div class="toggle-checkbox mb-3">
                    <input type="checkbox" id="checkbox2" onclick="toggleTable(2)">
                    <label for="checkbox2">Conversion Cost</label>
                </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 btn-sm" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
                        </tr>
                    </tbody>
                </table>
                <div class="mt-3" id="add-row-2" style="display: none;">
                    <button type="button" class="btn btn-primary btn-sm" id="addRowCC"><i class="fa fa-plus mr-1"></i> Add Row</button>
                </div>

                <hr class="my-4">

                <!-- PACKING CHARGES -->
                <div class="toggle-checkbox mb-3">
                    <input type="checkbox" id="checkbox3" onclick="toggleTable(3)">
                    <label for="checkbox3">Packing Charges</label>
                </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 btn-sm" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
                        </tr>
                    </tbody>
                </table>
                <div class="mt-3" id="add-row-3" style="display: none;">
                    <button type="button" class="btn btn-primary btn-sm" id="addRowPC"><i class="fa fa-plus mr-1"></i> Add Row</button>
                </div>

                <hr class="my-4">

                <div class="row form-row">
                    <div class="col-md-12 mb-3">
                        <label class="form-label" for="quoteNote">Note</label>
                        <textarea name="note" id="quoteNote" placeholder="Note" class="form-control" rows="3"></textarea>
                    </div>
                </div>
        </x-modern-ui.section-card>

        {{-- Section 4: Quotation Summary --}}
        <x-modern-ui.section-card
            title="Quotation Summary"
            icon="chart-line"
            theme="warning"
        >
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="GT-in-letters">Grand Total in Words (INR)</label>
                        <input type="text" id="GT-in-letters" readonly class="form-control" style="font-weight: 600; color: #0e7490;">
                    </div>
                    <div class="col-md-6">
                        <div class="summary-table">
                            <div class="row mb-2">
                                <div class="col-md-4">
                                    <label class="form-label" for="totalAmount">SUB TOTAL</label>
                                </div>
                                <div class="col-md-8">
                                    <input type="text" name="sub_total" id="totalAmount" readonly class="form-control text-right">
                                </div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-4">
                                    <label class="form-label" for="qt-discount">Discount (%)</label>
                                </div>
                                <div class="col-md-8">
                                    <input type="number" id="qt-discount" name="discount" oninput="calculateTotals()" class="form-control text-right">
                                </div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-4">
                                    <label class="form-label" for="roundUp">RoundUp Amount</label>
                                </div>
                                <div class="col-md-8">
                                    <input type="text" id="roundUp" name="round_up" readonly class="form-control text-right">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-4">
                                    <label class="form-label" for="grandTotal">Grand Total</label>
                                </div>
                                <div class="col-md-8">
                                    <input type="text" id="grandTotal" name="grand_total" readonly class="form-control text-right">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
        </x-modern-ui.section-card>

        {{-- Footer Actions Component --}}
        <x-modern-ui.footer-actions
            backUrl="{{ route('superadmin.purchasebom.quotation.quotationdetails') }}"
            backText="Back to List"
            submitText="Save Quotation"
            submitIcon="save"
            :showClear="true"
            clearText="Clear Form"
            clearId="resetFormBtn"
        />

    </form>

</div>
@endsection

@push('scripts')
<script>
    // Toast Notification Function
    function showToast(message, type = 'success') {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = `toast ${type}`;

        const icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
        toast.innerHTML = `
            <i class="fas ${icon}"></i>
            <span>${message}</span>
        `;

        container.appendChild(toast);

        setTimeout(() => {
            toast.style.animation = 'slideOut 0.3s ease';
            setTimeout(() => toast.remove(), 300);
        }, 5000);
    }

    // Show session messages as toasts
    @if (session('success'))
        showToast("{{ session('success') }}", 'success');
    @endif

    @if (session('error'))
        showToast("{{ session('error') }}", 'error');
    @endif

    @if ($errors->any())
        @foreach ($errors->all() as $error)
            showToast("{{ $error }}", 'error');
        @endforeach
    @endif

    $(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');
        let dd = String(today.getDate()).padStart(2, '0');
        let todayStr = `${yyyy}-${mm}-${dd}`;
        $('#quotationDate').val(todayStr);

        // 1. Auto-fill Quotation No
        $.get("{{ url('superadmin/purchase/max-quotation-id') }}", function(data) {
            $('#quotationNo').val(data.newQuotationNo);
        });

        // 2. Phone validation
        $('#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->rm_grade }}</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="text" name="raw_material[${idx}][rm_weight]" class="rm-weight" placeholder="RM Weight" readonly></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 btn-sm" 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 btn-sm" 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 btn-sm" 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-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 (Indian system)
        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);
    });

    // RFQ selection auto-fill
    $('#rfqNo').on('change', function() {
        let rfqNo = $(this).val();
        if (!rfqNo) {
            $('#customerName, #address, #gst, #email, #phone').val('');
            return;
        }
        $.get("{{ url('superadmin/purchase/rfq-details') }}/" + rfqNo, function(resp) {
            console.log('RFQ AJAX response:', resp);
            if (resp.success) {
                let rfq = resp.rfq;
                let vendor = resp.vendor || {};
                $('#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(vendor.company || '');
                $('#address').val(vendor.billing_address || '');
                $('#gst').val(vendor.gstno || '');
                $('#email').val(vendor.email || '');
                $('#phone').val(vendor.mobile || '');
                $('#customerId').val(vendor.id || '');
                $('#custRefNo').val(rfq.vendor_reference_no || '');

                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!');
                    $('#customerName, #address, #gst, #email, #phone').val('');
                }
            } 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();
        let options = `<option value="">Select Raw Material</option>`;
        @foreach($allRawMaterials as $rawMaterial)
        options += `<option value="{{ $rawMaterial->id }}" data-density="{{ $rawMaterial->density }}">{{ $rawMaterial->rm_grade }}</option>`;
        @endforeach

        if (!rawMaterials.length) {
            $('#checkbox1').prop('checked', false);
            $('#table1').addClass('hidden');
            $('#add-row-1').hide();
            return;
        }

        $('#checkbox1').prop('checked', true);
        $('#table1').removeClass('hidden');
        $('#add-row-1').show();

        rawMaterials.forEach(function(mat, idx) {
            console.log('Adding RM row:', mat);
            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="text" name="raw_material[${idx}][rm_weight]" class="rm-weight" placeholder="RM Weight" readonly></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 btn-sm" 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);
        });
    }

    // Placeholder Update for RM Type
    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;
        }
    }

    // Calculate RM Cost based on geometry
    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);
        const size2 = (parseFloat(row.find('input[name$="[size2]"]').val()) || 0);
        const size3 = (parseFloat(row.find('input[name$="[size3]"]').val()) || 0);
        const rmType = row.find('select[name$="[type]"]').val();
        const rmCostInput = row.find('input[name$="[rm_cost]"]')[0];
        const rmWeightInput = row.find('input[name$="[rm_weight]"]')[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;
            console.log(density,size2,size1,rmWeight);
            scrapWeight = rmWeight - finishWeight;
            if (rmWeight > 0) {
                rmCost = (rmWeight * rmRate) - (0.8 * (scrapWeight * scrapRate));
            }
            rmCostInput.value = isNaN(rmCost) ? "" : rmCost.toFixed(2);
            rmWeightInput.value = Number(rmWeight).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);
            rmWeightInput.value = Number(rmWeight).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);
            rmWeightInput.value = Number(rmWeight).toFixed(2);
        } else {
            rmCostInput.value = '';
            rmWeightInput.value = "";
        }
    }

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

    $(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');
        console.log(density);
        $(this).closest('tr').find('input[name$="[density]"]').val(density);
        calculateRMCost($(this).closest('tr')[0]);
    });
</script>
@endpush
