@extends('layouts.dashboard.superadminapp')

@section('title', 'Create Sales Quotation')

@section('styles')
<link rel="stylesheet" href="{{ asset('css/modern-form-pattern.css') }}">
<style>
    /* Fix Issue 1: Dropdown overlap - ensure selectpicker dropdowns render above other content */
    .section-card {
        position: relative;
        z-index: 1;
        overflow: visible !important;
    }
    .section-card .section-body {
        position: relative;
        overflow: visible !important;
    }
    .section-card .section-body .form-row {
        position: relative;
    }
    /* Bootstrap Select dropdown rendered via data-container="body" - ensure high z-index */
    .bootstrap-select .dropdown-menu,
    body > .bootstrap-select .dropdown-menu,
    body > .dropdown-menu {
        z-index: 1060 !important;
    }
    /* Ensure bootstrap-select button container does not clip */
    .bootstrap-select {
        position: relative;
        z-index: 2;
    }
    .bootstrap-select.open,
    .bootstrap-select.show {
        z-index: 1050 !important;
    }

    /* Fix Issue 2: Table column width - increase minimum widths for readability */
    .product-table {
        min-width: 1100px;
    }
    .product-table input.form-control-sm,
    .product-table select.form-control-sm {
        min-width: 80px;
    }
    .product-table tbody td {
        padding: 0.5rem 0.4rem;
    }

    /* Fix Issue 3: Visual indicator for auto-calculated vs manual fields */
    .product-table input.rm-cost[readonly] {
        background: #e8f5e9 !important;
        border-color: #a5d6a7 !important;
        color: #2e7d32 !important;
        font-weight: 600;
    }
    .product-table input.rm-weight[readonly] {
        background: #e8f5e9 !important;
        border-color: #a5d6a7 !important;
        color: #2e7d32 !important;
        font-weight: 600;
    }
    .product-table input.rm-cost:not([readonly]) {
        background: #fff3e0 !important;
        border-color: #ffcc80 !important;
    }
</style>
@endsection

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

    {{-- PAGE HEADER --}}
    <div class="modern-page-header">
        <div class="header-left">
            <div class="icon-wrapper">
                <i class="fas fa-file-invoice"></i>
            </div>
            <div class="header-title">
                <h1>Create Quotation</h1>
                <div class="header-subtitle">Quotation Registration Form</div>
            </div>
        </div>
        <div class="datetime-display">
            <div class="date-box">
                <i class="far fa-calendar-alt"></i>
                <span id="day">{{ now()->format('l') }}</span>,
                <span id="daynum">{{ now()->format('d') }}</span>
                <span id="month">{{ now()->format('F') }}</span>
                <span id="year">{{ now()->format('Y') }}</span>
            </div>
            <div class="time-box">
                <i class="far fa-clock"></i>
                <span class="display-time"></span>
            </div>
        </div>
    </div>

    {{-- TOAST NOTIFICATION CONTAINER --}}
    <div class="toast-container"></div>

    {{-- ALERTS --}}
    @if (session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif
    @if (session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif
    @if ($errors->any())
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle mr-2"></i><strong>Validation Errors:</strong>
            <ul class="mb-0 mt-2">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif

    {{-- QUOTATION FORM --}}
    <form id="quotationForm" method="POST" action="{{ route('superadmin.salesbom.quotations.store') }}">
        @csrf

        {{-- QUOTATION DETAILS SECTION --}}
        <div class="section-card">
            <div class="section-header">
                <i class="fas fa-file-alt"></i>
                <h2>Quotation Details</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-3">
                        <label class="form-label">Quotation No <span class="required-star">*</span></label>
                        <input type="text" class="form-control" id="quotationNo" name="quotation_no" readonly required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Quotation Date <span class="required-star">*</span></label>
                        <input type="date" class="form-control" id="quotationDate" name="quotation_date" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">RFQ No</label>
                        <select class="form-control selectpicker" data-container="body" id="rfqNo" name="rfq_no" data-live-search="true">
                            <option value="">Select RFQ No</option>
                            @foreach ($unassignedRfqs as $rfq)
                                <option value="{{ $rfq->id }}">{{ $rfq->rfq_no }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">RFQ Date</label>
                        <input type="date" class="form-control" id="rfqDate" name="rfq_date">
                    </div>
                </div>
            </div>
        </div>

        {{-- CUSTOMER INFORMATION SECTION --}}
        <div class="section-card">
            <div class="section-header info">
                <i class="fas fa-user"></i>
                <h2>Customer Information</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6">
                        <label class="form-label">Customer Name <span class="required-star">*</span></label>
                        <select class="form-control selectpicker" data-container="body" id="customerName" name="customer_id" data-live-search="true" required>
                            <option value="">Select Customer</option>
                            @foreach ($customers as $customer)
                                <option value="{{ $customer->id }}"
                                    data-address="{{ $customer->billing_address ?? $customer->address }}"
                                    data-gst="{{ $customer->gstno }}"
                                    data-email="{{ $customer->email }}"
                                    data-phone="{{ $customer->mobile }}">
                                    {{ $customer->company }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Customer Reference No</label>
                        <input type="text" class="form-control" id="custRefNo" name="cust_ref_no" placeholder="Reference No">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-6">
                        <label class="form-label">Address</label>
                        <textarea class="form-control" id="address" name="address" rows="2" placeholder="Customer Address"></textarea>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">GST No</label>
                        <input type="text" class="form-control" id="gst" name="gst" placeholder="GST Number">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Contact Number</label>
                        <input type="tel" class="form-control" id="phone" name="phone" placeholder="10-digit number" maxlength="10">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-6">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" id="email" name="email" placeholder="Email Address">
                    </div>
                </div>
            </div>
        </div>

        {{-- PRODUCT INFORMATION SECTION --}}
        <div class="section-card">
            <div class="section-header success">
                <i class="fas fa-box"></i>
                <h2>Product Information</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-3">
                        <label class="form-label">Product Type <span class="required-star">*</span></label>
                        <select class="form-control selectpicker" data-container="body" id="productType" name="product_type" data-live-search="true" required>
                            <option value="">Select Product</option>
                            @foreach($productTypes as $type)
                                <option value="{{ $type->name }}">{{ $type->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Part No</label>
                        <input type="text" class="form-control" id="partNo" name="part_no" placeholder="Part No">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Project/Material No</label>
                        <input type="text" class="form-control" id="project-materialNo" name="project_material_no" placeholder="Project Material No">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Drawing No</label>
                        <input type="text" class="form-control" id="drawingNo" name="drawing_no" placeholder="Drawing No">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-3">
                        <label class="form-label">Drawing Revision</label>
                        <input type="text" class="form-control" id="drawingRev" name="drawing_rev" placeholder="Revision">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Quantity</label>
                        <input type="number" class="form-control" id="quantity" name="quantity" placeholder="Quantity">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Unit of Measurement</label>
                        <input type="text" class="form-control" id="quantityUOM" name="quantity_uom" placeholder="UOM">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-12">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" id="description" name="description" rows="2" placeholder="Product Description"></textarea>
                    </div>
                </div>
            </div>
        </div>

        {{-- COST BREAKDOWN SECTION --}}
        <div class="section-card">
            <div class="section-header warning">
                <i class="fas fa-calculator"></i>
                <h2>Cost Breakdown</h2>
            </div>
            <div class="section-body">

                {{-- RAW MATERIAL CHARGES --}}
                <div class="checkbox-section">
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="checkbox1" onclick="toggleTable(1)">
                        <label class="custom-control-label" for="checkbox1">
                            <i class="fas fa-cubes mr-1"></i> Raw Material Charges
                        </label>
                    </div>
                </div>
                <div class="table-responsive mb-3">
                    <table id="table1" class="table table-sm product-table hidden">
                        <thead>
                            <tr>
                                <th style="min-width:35px; width:3%">#</th>
                                <th style="min-width:150px; width:14%">Raw Material</th>
                                <th style="min-width:100px; width:8%">Rate(&#8377;/kg)</th>
                                <th style="min-width:100px; width:8%">Scrap Rate</th>
                                <th style="min-width:100px; width:7%">Finish Wt</th>
                                <th style="min-width:100px; width:8%">RM Type</th>
                                <th style="min-width:70px; width:5%">Qty</th>
                                <th style="min-width:90px; width:7%">Size 1</th>
                                <th style="min-width:90px; width:7%">Size 2</th>
                                <th style="min-width:90px; width:7%">Size 3</th>
                                <th style="min-width:100px; width:8%">RM Weight</th>
                                <th style="min-width:110px; width:8%">RM Cost(&#8377;)</th>
                                <th style="min-width:110px; width:8%">Value(&#8377;)</th>
                                <th style="min-width:40px; width:3%"></th>
                            </tr>
                        </thead>
                        <tbody id="rm-tbody">
                            <tr>
                                <td class="text-center">1</td>
                                <td>
                                    <select name="raw_material[0][material_id]" class="form-control form-control-sm rm-material">
                                        <option value="">Select</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="form-control form-control-sm rm-rate" step="0.01"></td>
                                <td><input type="number" name="raw_material[0][scrap_rate]" class="form-control form-control-sm rm-scrap-rate" step="0.01"></td>
                                <td><input type="number" name="raw_material[0][finish_weight]" class="form-control form-control-sm rm-finish-weight" step="0.01"></td>
                                <td>
                                    <select name="raw_material[0][type]" class="form-control form-control-sm rm-type">
                                        <option value="">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="form-control form-control-sm rm-quantity" min="1"></td>
                                <td><input type="number" name="raw_material[0][size1]" class="form-control form-control-sm rm-size1"></td>
                                <td><input type="number" name="raw_material[0][size2]" class="form-control form-control-sm rm-size2"></td>
                                <td><input type="number" name="raw_material[0][size3]" class="form-control form-control-sm rm-size3"></td>
                                <td><input type="text" name="raw_material[0][rm_weight]" class="form-control form-control-sm rm-weight" readonly></td>
                                <td><input type="number" name="raw_material[0][rm_cost]" class="form-control form-control-sm rm-cost" step="0.01"></td>
                                <td><input type="text" name="raw_material[0][value]" class="form-control form-control-sm rm-value" readonly></td>
                                <td class="text-center"><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 id="add-row-1" class="add-row-container" style="display: none;">
                    <button type="button" class="btn btn-primary btn-sm" id="addRowRM">
                        <i class="fas fa-plus mr-1"></i> Add Raw Material Row
                    </button>
                </div>

                {{-- CONVERSION COST --}}
                <div class="checkbox-section">
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="checkbox2" onclick="toggleTable(2)">
                        <label class="custom-control-label" for="checkbox2">
                            <i class="fas fa-cogs mr-1"></i> Conversion Cost
                        </label>
                    </div>
                </div>
                <div class="table-responsive mb-3">
                    <table id="table2" class="table table-sm product-table hidden">
                        <thead>
                            <tr>
                                <th style="width:5%">#</th>
                                <th style="width:30%">Description</th>
                                <th style="width:15%">Quantity</th>
                                <th style="width:15%">Unit</th>
                                <th style="width:15%">Rate(INR)</th>
                                <th style="width:15%">Value</th>
                                <th style="width:5%"></th>
                            </tr>
                        </thead>
                        <tbody id="cc-tbody">
                            <tr>
                                <td class="text-center">1</td>
                                <td>
                                    <input list="conversionCost-options" name="conversion_cost[0][desc]" class="form-control form-control-sm" placeholder="Select process">
                                    <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="form-control form-control-sm cc-quantity" min="1"></td>
                                <td><input type="text" name="conversion_cost[0][unit]" class="form-control form-control-sm" placeholder="Unit"></td>
                                <td><input type="number" name="conversion_cost[0][rate]" class="form-control form-control-sm cc-rate" min="0" step="0.01"></td>
                                <td><input type="text" name="conversion_cost[0][value]" class="form-control form-control-sm cc-value" readonly></td>
                                <td class="text-center"><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 id="add-row-2" class="add-row-container" style="display: none;">
                    <button type="button" class="btn btn-primary btn-sm" id="addRowCC">
                        <i class="fas fa-plus mr-1"></i> Add Conversion Cost Row
                    </button>
                </div>

                {{-- PACKING CHARGES --}}
                <div class="checkbox-section">
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="checkbox3" onclick="toggleTable(3)">
                        <label class="custom-control-label" for="checkbox3">
                            <i class="fas fa-box-open mr-1"></i> Packing Charges
                        </label>
                    </div>
                </div>
                <div class="table-responsive mb-3">
                    <table id="table3" class="table table-sm product-table hidden">
                        <thead>
                            <tr>
                                <th style="width:5%">#</th>
                                <th style="width:30%">Description</th>
                                <th style="width:15%">Quantity</th>
                                <th style="width:15%">Unit</th>
                                <th style="width:15%">Rate(INR)</th>
                                <th style="width:15%">Value</th>
                                <th style="width:5%"></th>
                            </tr>
                        </thead>
                        <tbody id="pc-tbody">
                            <tr>
                                <td class="text-center">1</td>
                                <td><input type="text" name="packing[0][desc]" class="form-control form-control-sm" value="Packing cost"></td>
                                <td><input type="number" name="packing[0][quantity]" class="form-control form-control-sm pc-quantity" min="1"></td>
                                <td><input type="text" name="packing[0][unit]" class="form-control form-control-sm" placeholder="Unit"></td>
                                <td><input type="number" name="packing[0][rate]" class="form-control form-control-sm pc-rate" min="0" step="0.01"></td>
                                <td><input type="text" name="packing[0][value]" class="form-control form-control-sm pc-value" readonly></td>
                                <td class="text-center"><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 id="add-row-3" class="add-row-container" style="display: none;">
                    <button type="button" class="btn btn-primary btn-sm" id="addRowPC">
                        <i class="fas fa-plus mr-1"></i> Add Packing Charge Row
                    </button>
                </div>
            </div>
        </div>

        {{-- SUMMARY & TOTALS SECTION --}}
        <div class="section-card">
            <div class="section-header">
                <i class="fas fa-rupee-sign"></i>
                <h2>Summary & Totals</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6">
                        <label class="form-label">Note / Remarks</label>
                        <textarea name="note" id="quoteNote" class="form-control" rows="3" placeholder="Additional notes or remarks"></textarea>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Grand Total in Words (INR)</label>
                        <input type="text" class="form-control" id="GT-in-letters" readonly style="background: var(--purple-pale); font-weight: 600; color: var(--purple-dark);">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-6"></div>
                    <div class="col-md-6">
                        <div class="summary-table">
                            <table class="table table-sm table-borderless mb-0">
                                <tr>
                                    <td class="text-right font-weight-bold" style="color: var(--text-medium);">Sub Total:</td>
                                    <td width="150"><input type="text" class="form-control form-control-sm text-right" name="sub_total" id="totalAmount" readonly></td>
                                </tr>
                                <tr>
                                    <td class="text-right" style="color: var(--text-light);">Discount (%):</td>
                                    <td><input type="number" class="form-control form-control-sm text-right" id="qt-discount" name="discount" step="0.01" oninput="calculateTotals()"></td>
                                </tr>
                                <tr>
                                    <td class="text-right" style="color: var(--text-light);">Round Up:</td>
                                    <td><input type="text" class="form-control form-control-sm text-right" id="roundUp" name="round_up" readonly></td>
                                </tr>
                                <tr>
                                    <td class="text-right font-weight-bold total-row" style="color: var(--purple-dark);">Grand Total:</td>
                                    <td class="total-row"><input type="text" class="form-control form-control-sm text-right font-weight-bold" id="grandTotal" name="grand_total" readonly></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        {{-- FORM ACTIONS --}}
        <div class="footer-actions">
            <a href="{{ route('superadmin.salesbom.quotation.quotationdetails') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to List
            </a>
            <div>
                <button class="btn btn-danger" type="reset" onclick="resetForm()">
                    <i class="fas fa-undo"></i> Clear Form
                </button>
                <button class="btn btn-success" type="submit" id="submitBtn">
                    <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                    <i class="fas fa-save" id="submitIcon"></i>
                    <span id="submitText">Save Quotation</span>
                </button>
            </div>
        </div>
    </form>
</div>
@endsection

@section('scripts')
<script>
// ===== Dynamic Date/Time Update =====
function updateDateTime() {
    const now = new Date();
    const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

    document.getElementById('day').textContent = days[now.getDay()];
    document.getElementById('daynum').textContent = now.getDate();
    document.getElementById('month').textContent = months[now.getMonth()];
    document.getElementById('year').textContent = now.getFullYear();

    const timeStr = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
    document.querySelector('.display-time').textContent = timeStr;
}
updateDateTime();
setInterval(updateDateTime, 1000);

// ===== Toast Notification =====
function showToast(message, type = 'success') {
    const toast = $(`
        <div class="toast ${type}">
            <div class="toast-header">
                <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} mr-2"></i>
                <strong class="mr-auto">${type === 'success' ? 'Success' : 'Error'}</strong>
                <button type="button" class="ml-2 mb-1 close" data-dismiss="toast">&times;</button>
            </div>
            <div class="toast-body">${message}</div>
        </div>
    `);

    $('.toast-container').append(toast);
    setTimeout(() => toast.fadeOut(() => toast.remove()), 5000);
}

// Row counters (global scope so populateRawMaterialTable can update them)
var rmRow = 1, ccRow = 1, pcRow = 1;
var isRfqPopulating = false;

$(document).ready(function() {
    // Initialize selectpicker
    $('.selectpicker').selectpicker();

    // Set today's date for quotation date
    let today = new Date();
    let todayStr = today.toISOString().split('T')[0];
    $('#quotationDate').val(todayStr);

    // Fetch next quotation number
    $.get("{{ url('superadmin/sales/max-quotation-id') }}", function(data) {
        $('#quotationNo').val(data.newQuotationNo);
    });

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

    // Customer dropdown change - populate related fields
    $('#customerName').on('changed.bs.select change', function() {
        if (isRfqPopulating) return;
        let selected = $(this).find('option:selected');
        if (selected.val()) {
            $('#address').val(selected.data('address') || '');
            $('#gst').val(selected.data('gst') || '');
            $('#email').val(selected.data('email') || '');
            $('#phone').val(selected.data('phone') || '');
        } else {
            $('#address, #gst, #email, #phone').val('');
        }
    });

    // Form submit with loading spinner
    $('#quotationForm').on('submit', function(e) {
        var $btn = $('#submitBtn');
        var $spinner = $btn.find('.spinner-border');

        $btn.prop('disabled', true);
        $spinner.removeClass('d-none');

        // Disable inputs inside hidden tables so they don't submit empty data
        $('.product-table.hidden').find('input, select').prop('disabled', true);
    });

    // Add Row - Raw Material
    $('#addRowRM').click(function() {
        let idx = rmRow++;
        let options = '<option value="">Select</option>';
        @foreach($allRawMaterials as $rawMaterial)
        options += '<option value="{{ $rawMaterial->id }}" data-density="{{ $rawMaterial->density }}">{{ $rawMaterial->rm_grade }}</option>';
        @endforeach

        $('#rm-tbody').append(`
            <tr>
                <td class="text-center">${idx+1}</td>
                <td>
                    <select name="raw_material[${idx}][material_id]" class="form-control form-control-sm rm-material">
                        ${options}
                    </select>
                    <input type="hidden" name="raw_material[${idx}][density]">
                </td>
                <td><input type="number" name="raw_material[${idx}][rate]" class="form-control form-control-sm rm-rate" step="0.01"></td>
                <td><input type="number" name="raw_material[${idx}][scrap_rate]" class="form-control form-control-sm rm-scrap-rate" step="0.01"></td>
                <td><input type="number" name="raw_material[${idx}][finish_weight]" class="form-control form-control-sm rm-finish-weight" step="0.01"></td>
                <td>
                    <select name="raw_material[${idx}][type]" class="form-control form-control-sm rm-type">
                        <option value="">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="form-control form-control-sm rm-quantity" min="1"></td>
                <td><input type="number" name="raw_material[${idx}][size1]" class="form-control form-control-sm rm-size1"></td>
                <td><input type="number" name="raw_material[${idx}][size2]" class="form-control form-control-sm rm-size2"></td>
                <td><input type="number" name="raw_material[${idx}][size3]" class="form-control form-control-sm rm-size3"></td>
                <td><input type="text" name="raw_material[${idx}][rm_weight]" class="form-control form-control-sm rm-weight" readonly></td>
                <td><input type="number" name="raw_material[${idx}][rm_cost]" class="form-control form-control-sm rm-cost" step="0.01"></td>
                <td><input type="text" name="raw_material[${idx}][value]" class="form-control form-control-sm rm-value" readonly></td>
                <td class="text-center"><button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
            </tr>
        `);
    });

    // Add Row - Conversion Cost
    $('#addRowCC').click(function() {
        let idx = ccRow++;
        $('#cc-tbody').append(`
            <tr>
                <td class="text-center">${idx+1}</td>
                <td><input list="conversionCost-options" name="conversion_cost[${idx}][desc]" class="form-control form-control-sm" placeholder="Select process"></td>
                <td><input type="number" name="conversion_cost[${idx}][quantity]" class="form-control form-control-sm cc-quantity" min="1"></td>
                <td><input type="text" name="conversion_cost[${idx}][unit]" class="form-control form-control-sm" placeholder="Unit"></td>
                <td><input type="number" name="conversion_cost[${idx}][rate]" class="form-control form-control-sm cc-rate" min="0" step="0.01"></td>
                <td><input type="text" name="conversion_cost[${idx}][value]" class="form-control form-control-sm cc-value" readonly></td>
                <td class="text-center"><button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
            </tr>
        `);
    });

    // Add Row - Packing Charges
    $('#addRowPC').click(function() {
        let idx = pcRow++;
        $('#pc-tbody').append(`
            <tr>
                <td class="text-center">${idx+1}</td>
                <td><input type="text" name="packing[${idx}][desc]" class="form-control form-control-sm" placeholder="Description"></td>
                <td><input type="number" name="packing[${idx}][quantity]" class="form-control form-control-sm pc-quantity" min="1"></td>
                <td><input type="text" name="packing[${idx}][unit]" class="form-control form-control-sm" placeholder="Unit"></td>
                <td><input type="number" name="packing[${idx}][rate]" class="form-control form-control-sm pc-rate" min="0" step="0.01"></td>
                <td><input type="text" name="packing[${idx}][value]" class="form-control form-control-sm pc-value" readonly></td>
                <td class="text-center"><button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
            </tr>
        `);
    });

    // Value calculations for tables (RM handled by calculateRMCost below)
    $(document).on('input', '.cc-rate, .cc-quantity', function() {
        let row = $(this).closest('tr');
        let rate = parseFloat(row.find('.cc-rate').val()) || 0;
        let quantity = parseFloat(row.find('.cc-quantity').val()) || 0;
        row.find('.cc-value').val((rate * quantity).toFixed(2));
        calculateTotals();
    });

    $(document).on('input', '.pc-rate, .pc-quantity', function() {
        let row = $(this).closest('tr');
        let rate = parseFloat(row.find('.pc-rate').val()) || 0;
        let quantity = parseFloat(row.find('.pc-quantity').val()) || 0;
        row.find('.pc-value').val((rate * quantity).toFixed(2));
        calculateTotals();
    });

    // Raw Material type change - update placeholders and recalculate
    $(document).on('change', '.rm-type', function() {
        updateSizePlaceholders(this);
        calculateRMCost($(this).closest('tr')[0]);
    });

    // Raw Material selection - get density
    $(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]);
    });

    // Calculate RM cost on relevant input changes
    $(document).on('input', '.rm-rate, .rm-scrap-rate, .rm-finish-weight, .rm-quantity, .rm-size1, .rm-size2, .rm-size3, .rm-cost', function() {
        calculateRMCost($(this).closest('tr')[0]);
    });

    // RFQ selection - populate fields
    $('#rfqNo').on('change', function() {
        let rfqNo = $(this).val();
        if (!rfqNo) {
            clearCustomerFields();
            return;
        }

        isRfqPopulating = true;
        $.get("{{ url('superadmin/sales/rfq-details') }}/" + rfqNo, function(resp) {
            if (resp.success) {
                let rfq = resp.rfq;
                let customer = resp.customer || {};

                // Select customer in dropdown and populate fields
                if (customer.id) {
                    $('#customerName').val(customer.id).selectpicker('refresh');
                }
                $('#address').val(customer.billing_address || customer.address || '');
                $('#gst').val(customer.gstno || '');
                $('#email').val(customer.email || '');
                $('#phone').val(customer.mobile || '');

                // Populate RFQ fields
                $('#rfqDate').val(rfq.rfq_date ? rfq.rfq_date.substring(0, 10) : '');
                $('#custRefNo').val(rfq.cus_ref_no || '');
                $('#partNo').val(rfq.part_no || '');
                $('#project-materialNo').val(rfq.project_material_no || '');
                $('#drawingNo').val(rfq.drawing_no || '');
                $('#drawingRev').val(rfq.drawing_rev || '');
                $('#quantity').val(rfq.quantity || '');
                $('#quantityUOM').val(rfq.uom || '');
                $('#description').val(rfq.description || '');
                $('#quoteNote').val(rfq.note || '');
                $('#productType').val(rfq.product_type || '').selectpicker('refresh');

                // Populate raw materials if available
                if (resp.raw_materials && resp.raw_materials.length > 0) {
                    populateRawMaterialTable(resp.raw_materials);
                }

                showToast('RFQ data loaded successfully', 'success');
            } else {
                clearCustomerFields();
                showToast('Failed to load RFQ data', 'error');
            }
        }).fail(function() {
            clearCustomerFields();
            showToast('Error loading RFQ data', 'error');
        }).always(function() {
            isRfqPopulating = false;
        });
    });
});

// Toggle table visibility
function toggleTable(num) {
    $("#table" + num).toggleClass('hidden');
    $("#add-row-" + num).toggle();
    calculateTotals();
}

// Delete row
function deleteRow(btn) {
    $(btn).closest('tr').remove();
    calculateTotals();
}

// Clear customer fields
function clearCustomerFields() {
    $('#customerName').val('').selectpicker('refresh');
    $('#address, #gst, #email, #phone').val('');
    $('#rfqDate, #custRefNo, #partNo, #project-materialNo, #drawingNo, #drawingRev, #quantity, #quantityUOM, #description, #quoteNote').val('');
}

// Calculate totals
function calculateTotals() {
    let subtotal = 0;
    // Only sum values from visible (not hidden) tables
    $('.product-table:not(.hidden)').find('.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(numberToWords(Math.round(grandTotal)) + ' Rupees Only');
}

// Update size placeholders based on RM type
function updateSizePlaceholders(selectElement) {
    let row = $(selectElement).closest('tr');
    let size1 = row.find('.rm-size1')[0];
    let size2 = row.find('.rm-size2')[0];
    let size3 = row.find('.rm-size3')[0];
    let rmCost = row.find('.rm-cost')[0];
    let rmWeight = row.find('.rm-weight')[0];
    let type = $(selectElement).val();

    if (type === 'Rod') {
        size1.placeholder = 'Diameter';
        size2.placeholder = 'Length';
        size3.placeholder = '';
        size1.readOnly = false;
        size2.readOnly = false;
        size3.readOnly = true;
        size3.value = '';
        rmCost.readOnly = true;
        rmWeight.readOnly = true;
    } else if (type === 'Plate') {
        size1.placeholder = 'Thickness';
        size2.placeholder = 'Length';
        size3.placeholder = 'Width';
        size1.readOnly = false;
        size2.readOnly = false;
        size3.readOnly = false;
        rmCost.readOnly = true;
        rmWeight.readOnly = true;
    } else if (type === 'Pipe') {
        size1.placeholder = 'Outer Dia';
        size2.placeholder = 'Inner Dia';
        size3.placeholder = 'Length';
        size1.readOnly = false;
        size2.readOnly = false;
        size3.readOnly = false;
        rmCost.readOnly = true;
        rmWeight.readOnly = true;
    } else {
        // "Other" type - manual cost entry, sizes not applicable
        size1.placeholder = 'N/A';
        size2.placeholder = 'N/A';
        size3.placeholder = 'N/A';
        size1.value = '';
        size2.value = '';
        size3.value = '';
        size1.readOnly = true;
        size2.readOnly = true;
        size3.readOnly = true;
        rmCost.readOnly = false;
        rmCost.placeholder = 'Enter cost';
        rmWeight.readOnly = true;
        rmWeight.value = '';
    }
}

// Calculate RM Cost
function calculateRMCost(rowElement) {
    let row = $(rowElement);
    let rmType = row.find('.rm-type').val();
    let quantity = parseFloat(row.find('.rm-quantity').val()) || 0;

    // For "Other" or no type selected, rm-cost is manually entered - don't auto-calculate weight/cost
    if (!rmType || rmType === 'Other') {
        let cost = parseFloat(row.find('.rm-cost').val()) || 0;
        // Weight stays empty for "Other" type
        row.find('.rm-weight').val('');
        row.find('.rm-value').val((quantity * cost).toFixed(2));
        calculateTotals();
        return;
    }

    // For Rod, Pipe, Plate - auto-calculate weight and cost from dimensions
    let rmRate = parseFloat(row.find('.rm-rate').val()) || 0;
    let scrapRate = parseFloat(row.find('.rm-scrap-rate').val()) || 0;
    let finishWeight = parseFloat(row.find('.rm-finish-weight').val()) || 0;
    let size1 = parseFloat(row.find('.rm-size1').val()) || 0;
    let size2 = parseFloat(row.find('.rm-size2').val()) || 0;
    let size3 = parseFloat(row.find('.rm-size3').val()) || 0;
    let density = parseFloat(row.find('input[name$="[density]"]').val()) || 0;

    let rmWeight = 0, rmCost = 0;

    if (rmType === 'Rod') {
        rmWeight = 3.142 * Math.pow(size1 / 2, 2) * size2 * density;
    } else if (rmType === 'Plate') {
        rmWeight = size1 * size2 * size3 * density;
    } else if (rmType === 'Pipe') {
        rmWeight = (3.142 * Math.pow(size1 / 2, 2) * size3 - 3.142 * Math.pow(size2 / 2, 2) * size3) * density;
    }

    if (rmWeight > 0) {
        let scrapWeight = rmWeight - finishWeight;
        rmCost = (rmWeight * rmRate) - (0.8 * (scrapWeight * scrapRate));
    }

    row.find('.rm-weight').val(rmWeight > 0 ? rmWeight.toFixed(4) : '');
    row.find('.rm-cost').val(rmWeight > 0 ? rmCost.toFixed(2) : '');

    // Calculate value = quantity * rmCost
    row.find('.rm-value').val(rmWeight > 0 ? (quantity * rmCost).toFixed(2) : '');
    calculateTotals();
}

// Populate Raw Material Table from RFQ
function populateRawMaterialTable(rawMaterials) {
    let tbody = $('#rm-tbody');
    tbody.empty();

    let options = '<option value="">Select</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;
    }

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

    rawMaterials.forEach(function(mat, idx) {
        let selectedOption = options.replace(
            'value="' + (mat.material_id || mat.id || '') + '"',
            'value="' + (mat.material_id || mat.id || '') + '" selected'
        );

        tbody.append(`
            <tr>
                <td class="text-center">${idx + 1}</td>
                <td>
                    <select name="raw_material[${idx}][material_id]" class="form-control form-control-sm rm-material">
                        ${selectedOption}
                    </select>
                    <input type="hidden" name="raw_material[${idx}][density]" value="${mat.density || ''}">
                </td>
                <td><input type="number" name="raw_material[${idx}][rate]" class="form-control form-control-sm rm-rate" step="0.01"></td>
                <td><input type="number" name="raw_material[${idx}][scrap_rate]" class="form-control form-control-sm rm-scrap-rate" step="0.01"></td>
                <td><input type="number" name="raw_material[${idx}][finish_weight]" class="form-control form-control-sm rm-finish-weight" step="0.01"></td>
                <td>
                    <select name="raw_material[${idx}][type]" class="form-control form-control-sm rm-type">
                        <option value="">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="form-control form-control-sm rm-quantity" min="1"></td>
                <td><input type="number" name="raw_material[${idx}][size1]" class="form-control form-control-sm rm-size1"></td>
                <td><input type="number" name="raw_material[${idx}][size2]" class="form-control form-control-sm rm-size2"></td>
                <td><input type="number" name="raw_material[${idx}][size3]" class="form-control form-control-sm rm-size3"></td>
                <td><input type="text" name="raw_material[${idx}][rm_weight]" class="form-control form-control-sm rm-weight" readonly></td>
                <td><input type="number" name="raw_material[${idx}][rm_cost]" class="form-control form-control-sm rm-cost" step="0.01"></td>
                <td><input type="text" name="raw_material[${idx}][value]" class="form-control form-control-sm rm-value" readonly></td>
                <td class="text-center"><button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
            </tr>
        `);
    });

    // Update row counter so "Add Row" doesn't create duplicate indices
    rmRow = rawMaterials.length;
}

// Reset form
function resetForm() {
    $('#quotationForm')[0].reset();
    setTimeout(function() {
        $.get("{{ url('superadmin/sales/max-quotation-id') }}", function(data) {
            $('#quotationNo').val(data.newQuotationNo);
        });
        let today = new Date().toISOString().split('T')[0];
        $('#quotationDate').val(today);
        $('#totalAmount, #roundUp, #grandTotal, #GT-in-letters').val('');
        $('.selectpicker').selectpicker('refresh');

        // Hide all cost tables and uncheck their checkboxes
        $('#table1, #table2, #table3').addClass('hidden');
        $('#add-row-1, #add-row-2, #add-row-3').hide();
        $('#checkbox1, #checkbox2, #checkbox3').prop('checked', false);

        // Re-enable any disabled inputs (from previous submit attempt)
        $('.product-table').find('input, select').prop('disabled', false);

        showToast('Form cleared successfully', 'success');
    }, 100);
}

// Number to Words (Indian Format)
function numberToWords(num) {
    if (num === 0) return 'Zero';

    const ones = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
                  'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen',
                  'Seventeen', 'Eighteen', 'Nineteen'];
    const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];

    function convertLessThanHundred(n) {
        if (n < 20) return ones[n];
        return tens[Math.floor(n / 10)] + (n % 10 ? ' ' + ones[n % 10] : '');
    }

    function convertLessThanThousand(n) {
        if (n < 100) return convertLessThanHundred(n);
        return ones[Math.floor(n / 100)] + ' Hundred' + (n % 100 ? ' ' + convertLessThanHundred(n % 100) : '');
    }

    if (num < 0) return 'Negative ' + numberToWords(-num);
    if (num < 1000) return convertLessThanThousand(num);
    if (num < 100000) {
        return convertLessThanHundred(Math.floor(num / 1000)) + ' Thousand' +
               (num % 1000 ? ' ' + convertLessThanThousand(num % 1000) : '');
    }
    if (num < 10000000) {
        return convertLessThanHundred(Math.floor(num / 100000)) + ' Lakh' +
               (num % 100000 ? ' ' + numberToWords(num % 100000) : '');
    }
    return convertLessThanHundred(Math.floor(num / 10000000)) + ' Crore' +
           (num % 10000000 ? ' ' + numberToWords(num % 10000000) : '');
}
</script>
@endsection
