@extends('layouts.dashboard.superadminapp')

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

@section('styles')
<style>
    :root {
        --purple-primary: #8b5cf6;
        --purple-dark: #7c3aed;
        --purple-light: #a78bfa;
        --purple-lighter: #c4b5fd;
        --purple-pale: #f3f0ff;
    }

    /* ===== Modern Purple Page Header ===== */
    .modern-page-header {
        background: linear-gradient(135deg, var(--purple-pale) 0%, #ffffff 100%);
        border-radius: 0.75rem;
        padding: 1rem 1.5rem;
        margin-bottom: 1.5rem;
        box-shadow: 0 2px 8px rgba(139, 92, 246, 0.12);
        border-left: 4px solid var(--purple-primary);
    }
    .modern-page-header h1 {
        font-size: 1.25rem;
        font-weight: 600;
        color: var(--purple-dark);
        margin: 0;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    .modern-page-header h1 i {
        color: var(--purple-primary);
        font-size: 1.25rem;
    }
    .header-datetime {
        display: flex;
        gap: 1.5rem;
        font-size: 0.875rem;
        color: #64748b;
    }
    .header-datetime > div {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        background: #ffffff;
        padding: 0.375rem 0.875rem;
        border-radius: 0.5rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.08);
    }
    .header-datetime i {
        font-size: 0.95rem;
    }

    /* ===== Purple Section Cards ===== */
    .section-card {
        background: linear-gradient(135deg, #ffffff 0%, var(--purple-pale) 100%);
        border-radius: 0.75rem;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
        box-shadow: 0 2px 8px rgba(139, 92, 246, 0.1);
        border-left: 4px solid var(--purple-primary);
    }

    .section-title {
        font-size: 1.125rem;
        font-weight: 600;
        color: var(--purple-dark);
        margin-bottom: 1.25rem;
        display: flex;
        align-items: center;
        gap: 0.625rem;
        padding-bottom: 0.75rem;
        border-bottom: 2px solid var(--purple-light);
    }
    .section-title i {
        color: var(--purple-primary);
        font-size: 1.125rem;
    }

    /* ===== Purple Form Controls ===== */
    .form-control, .form-control-sm {
        border: 2px solid #e2e8f0;
        border-radius: 0.5rem;
        transition: all 0.2s;
        background: #ffffff;
    }
    .form-control:hover, .form-control-sm:hover {
        border-color: #cbd5e1;
    }
    .form-control:focus, .form-control-sm:focus {
        border-color: var(--purple-primary);
        box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.1);
        background: #ffffff;
    }
    label {
        font-weight: 500;
        color: #475569;
        margin-bottom: 0.5rem;
        font-size: 0.875rem;
    }
    .text-danger { color: #ef4444 !important; }

    /* ===== Purple Product Tables ===== */
    .product-table {
        font-size: 0.813rem;
        border-collapse: separate;
        border-spacing: 0;
        width: 100%;
        overflow: hidden;
        border-radius: 0.5rem;
    }
    .product-table thead th {
        background: linear-gradient(135deg, var(--purple-pale) 0%, #faf5ff 100%);
        color: var(--purple-dark);
        font-weight: 600;
        padding: 0.75rem 0.625rem;
        border-bottom: 2px solid var(--purple-primary);
        font-size: 0.75rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        white-space: nowrap;
    }
    .product-table tbody tr {
        transition: all 0.15s;
    }
    .product-table tbody tr:hover {
        background: var(--purple-pale);
    }
    .product-table tbody td {
        padding: 0.5rem;
        border-bottom: 1px solid #e2e8f0;
        vertical-align: middle;
    }
    .product-table input, .product-table select {
        font-size: 0.875rem;
        padding: 0.438rem 0.625rem;
        border-radius: 0.375rem;
        color: #1e293b;
        background: #fff;
        border: 1.5px solid #cbd5e1;
        transition: border-color 0.2s, box-shadow 0.2s;
    }
    .product-table input:focus, .product-table select:focus {
        border-color: #8b5cf6;
        box-shadow: 0 0 0 2px rgba(139, 92, 246, 0.12);
        background: #fff;
        outline: none;
        color: #1e293b;
    }
    .product-table input[readonly] {
        background: #f1f5f9;
        color: #334155;
        font-weight: 600;
    }
    .product-table input::placeholder {
        color: #cbd5e1;
        font-weight: 400;
    }
    .product-table .btn-sm {
        padding: 0.25rem 0.5rem;
        font-size: 0.75rem;
    }
    .hidden { display: none; }

    /* ===== Purple Checkbox Sections ===== */
    .checkbox-section {
        background: linear-gradient(135deg, var(--purple-pale) 0%, #faf5ff 100%);
        padding: 1rem 1.5rem;
        border-radius: 0.5rem;
        margin-bottom: 1rem;
        border-left: 4px solid var(--purple-primary);
        box-shadow: 0 1px 3px rgba(139, 92, 246, 0.08);
    }
    .custom-control-label {
        font-weight: 600;
        color: var(--purple-dark);
        cursor: pointer;
        user-select: none;
    }
    .custom-control-label i {
        color: var(--purple-primary);
    }

    /* ===== Purple Gradient Buttons ===== */
    .btn-gradient-primary {
        background: linear-gradient(135deg, var(--purple-primary) 0%, var(--purple-dark) 100%);
        color: #ffffff;
        border: none;
        padding: 0.625rem 1.5rem;
        border-radius: 0.5rem;
        font-weight: 500;
        transition: all 0.2s;
        box-shadow: 0 2px 6px rgba(139, 92, 246, 0.3);
    }
    .btn-gradient-primary:hover {
        background: linear-gradient(135deg, var(--purple-dark) 0%, #6d28d9 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(139, 92, 246, 0.4);
        color: #ffffff;
    }
    .btn-gradient-success {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: #ffffff;
        border: none;
        padding: 0.625rem 1.5rem;
        border-radius: 0.5rem;
        font-weight: 500;
        transition: all 0.2s;
        box-shadow: 0 2px 6px rgba(16, 185, 129, 0.3);
    }
    .btn-gradient-success:hover {
        background: linear-gradient(135deg, #059669 0%, #047857 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
        color: #ffffff;
    }
    .btn-outline-secondary {
        border: 2px solid #e2e8f0;
        color: #64748b;
        background: #ffffff;
        padding: 0.625rem 1.5rem;
        border-radius: 0.5rem;
        font-weight: 500;
        transition: all 0.2s;
    }
    .btn-outline-secondary:hover {
        background: #f8fafc;
        border-color: #cbd5e1;
        color: #475569;
    }

    /* ===== Alerts ===== */
    .alert {
        border: none;
        border-radius: 0.75rem;
        padding: 1rem 1.25rem;
        margin-bottom: 1.25rem;
        display: flex;
        align-items: center;
        box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    }
    .alert-success {
        background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%);
        color: #047857;
        border-left: 4px solid #10b981;
    }
    .alert-danger {
        background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
        color: #dc2626;
        border-left: 4px solid #ef4444;
    }

    /* ===== Toast Notifications ===== */
    .toast-container {
        position: fixed;
        top: 80px;
        right: 20px;
        z-index: 9999;
    }
    .toast {
        min-width: 300px;
        background: #ffffff;
        border-radius: 0.75rem;
        box-shadow: 0 4px 16px rgba(0,0,0,0.15);
        margin-bottom: 1rem;
        overflow: hidden;
        animation: slideInRight 0.3s ease-out;
    }
    @keyframes slideInRight {
        from { transform: translateX(400px); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    .toast.success { border-left: 4px solid #10b981; }
    .toast.error { border-left: 4px solid #ef4444; }
    .toast-header {
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        padding: 0.875rem 1rem;
        font-weight: 600;
        font-size: 0.875rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    .toast-body {
        padding: 0.875rem 1rem;
        font-size: 0.875rem;
        color: #475569;
    }

    /* ===== Purple Summary Table ===== */
    .summary-table {
        background: linear-gradient(135deg, #ffffff 0%, var(--purple-pale) 100%);
        border-radius: 0.75rem;
        padding: 1.25rem;
        box-shadow: 0 2px 8px rgba(139, 92, 246, 0.1);
        border: 1px solid var(--purple-lighter);
    }
    .summary-table tr td {
        padding: 0.625rem 0;
        font-size: 0.938rem;
    }
    .summary-table .total-row {
        border-top: 2px solid var(--purple-primary);
        padding-top: 1rem !important;
    }
    .summary-table .total-row input {
        background: linear-gradient(135deg, var(--purple-pale) 0%, #faf5ff 100%) !important;
        border: 2px solid var(--purple-primary) !important;
        color: var(--purple-dark) !important;
        font-weight: 600 !important;
        font-size: 1.125rem !important;
    }

    /* ===== Responsive ===== */
    @media (max-width: 768px) {
        .modern-page-header {
            flex-direction: column;
            align-items: flex-start;
        }
        .header-datetime {
            flex-direction: column;
            gap: 0.5rem;
            width: 100%;
        }
        .section-card {
            padding: 1rem;
        }
    }

    /* ===== Spinner ===== */
    .spinner-border-sm {
        width: 1rem;
        height: 1rem;
        border-width: 0.15em;
    }
</style>
@endsection

@section('content')
    <!-- Modern Purple Page Header -->
    <div class="modern-page-header d-flex justify-content-between align-items-center flex-wrap">
        <h1>
            <i class="fas fa-edit"></i>
            Edit Quotation - {{ $quotation->quotation_no }}
        </h1>
        <div class="header-datetime">
            <div>
                <i class="far fa-calendar" style="color: var(--purple-primary);"></i>
                <span class="display-date"></span>
            </div>
            <div>
                <i class="far fa-clock" style="color: #06b6d4;"></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.quotation.update', $quotation->id) }}">
        @csrf

        <!-- Quotation Details Section -->
        <div class="section-card">
            <div class="section-title">
                <i class="fas fa-file-alt"></i>
                Quotation Details
            </div>
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label>Quotation No <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="quotationNo" name="quotation_no" value="{{ $quotation->quotation_no }}" readonly required>
                </div>
                <div class="col-md-3 mb-3">
                    <label>Quotation Date <span class="text-danger">*</span></label>
                    <input type="date" class="form-control" id="quotationDate" name="quotation_date" value="{{ $quotation->quotation_date?->format('Y-m-d') }}" required>
                </div>
                <div class="col-md-3 mb-3">
                    <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 }}" {{ $quotation->rfq_no == $rfq->id ? 'selected' : '' }}>{{ $rfq->rfq_no }}</option>
                        @endforeach
                        @if ($quotation->rfq_no && !$unassignedRfqs->contains('id', $quotation->rfq_no))
                            @php $currentRfq = \App\Models\Rfq::find($quotation->rfq_no); @endphp
                            @if($currentRfq)
                                <option value="{{ $currentRfq->id }}" selected>{{ $currentRfq->rfq_no }}</option>
                            @endif
                        @endif
                    </select>
                </div>
                <div class="col-md-3 mb-3">
                    <label>RFQ Date</label>
                    <input type="date" class="form-control" id="rfqDate" name="rfq_date" value="{{ $quotation->rfq_date?->format('Y-m-d') }}">
                </div>
            </div>
        </div>

        <!-- Customer Information Section -->
        <div class="section-card">
            <div class="section-title">
                <i class="fas fa-user"></i>
                Customer Information
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Customer Name <span style="color:#ef4444">*</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 $cust)
                            <option value="{{ $cust->id }}"
                                data-address="{{ $cust->billing_address ?? $cust->address }}"
                                data-gst="{{ $cust->gstno }}"
                                data-email="{{ $cust->email }}"
                                data-phone="{{ $cust->mobile }}"
                                {{ ($quotation->customer_name == $cust->id) ? 'selected' : '' }}>
                                {{ $cust->company }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label>Customer Reference No</label>
                    <input type="text" class="form-control" id="custRefNo" name="cust_ref_no" value="{{ $quotation->cust_ref_no }}" placeholder="Reference No">
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Address</label>
                    <textarea class="form-control" id="address" name="address" rows="2" placeholder="Customer Address">{{ $quotation->address }}</textarea>
                </div>
                <div class="col-md-3 mb-3">
                    <label>GST No</label>
                    <input type="text" class="form-control" id="gst" name="gst" value="{{ $quotation->gst }}" placeholder="GST Number">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Contact Number</label>
                    <input type="tel" class="form-control" id="phone" name="phone" value="{{ $quotation->phone }}" placeholder="10-digit number" maxlength="10">
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Email</label>
                    <input type="email" class="form-control" id="email" name="email" value="{{ $quotation->email }}" placeholder="Email Address">
                </div>
            </div>
        </div>

        <!-- Product Information Section -->
        <div class="section-card">
            <div class="section-title">
                <i class="fas fa-box"></i>
                Product Information
            </div>
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label>Product Type <span class="text-danger">*</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 }}" {{ $quotation->product_type == $type->name ? 'selected' : '' }}>{{ $type->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3 mb-3">
                    <label>Part No</label>
                    <input type="text" class="form-control" id="partNo" name="part_no" value="{{ $quotation->part_no }}" placeholder="Part No">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Project/Material No</label>
                    <input type="text" class="form-control" id="project-materialNo" name="project_material_no" value="{{ $quotation->project_material_no }}" placeholder="Project Material No">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Drawing No</label>
                    <input type="text" class="form-control" id="drawingNo" name="drawing_no" value="{{ $quotation->drawing_no }}" placeholder="Drawing No">
                </div>
            </div>
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label>Drawing Revision</label>
                    <input type="text" class="form-control" id="drawingRev" name="drawing_rev" value="{{ $quotation->drawing_rev }}" placeholder="Revision">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Quantity</label>
                    <input type="number" class="form-control" id="quantity" name="quantity" value="{{ $quotation->quantity }}" placeholder="Quantity">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Unit of Measurement</label>
                    <input type="text" class="form-control" id="quantityUOM" name="quantity_uom" value="{{ $quotation->quantity_uom }}" placeholder="UOM">
                </div>
            </div>
            <div class="row">
                <div class="col-md-12 mb-3">
                    <label>Description</label>
                    <textarea class="form-control" id="description" name="description" rows="2" placeholder="Product Description">{{ $quotation->description }}</textarea>
                </div>
            </div>
        </div>

        @php
            $rawMaterials = is_array($quotation->raw_materials) ? $quotation->raw_materials : json_decode($quotation->raw_materials, true) ?? [];
            $conversionCostsData = is_array($quotation->conversion_costs) ? $quotation->conversion_costs : json_decode($quotation->conversion_costs, true) ?? [];
            $packingCharges = is_array($quotation->packing_charges) ? $quotation->packing_charges : json_decode($quotation->packing_charges, true) ?? [];
        @endphp

        <!-- Cost Breakdown Section -->
        <div class="section-card">
            <div class="section-title">
                <i class="fas fa-calculator"></i>
                Cost Breakdown
            </div>

            <!-- 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)" {{ count($rawMaterials) > 0 ? 'checked' : '' }}>
                    <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-bordered table-sm product-table {{ count($rawMaterials) == 0 ? 'hidden' : '' }}">
                    <thead>
                        <tr>
                            <th style="width:3%">#</th>
                            <th style="width:12%">Raw Material</th>
                            <th style="width:7%">Rate(₹/kg)</th>
                            <th style="width:7%">Scrap Rate</th>
                            <th style="width:7%">Finish Wt</th>
                            <th style="width:7%">RM Type</th>
                            <th style="width:5%">Qty</th>
                            <th style="width:7%">Size 1</th>
                            <th style="width:7%">Size 2</th>
                            <th style="width:7%">Size 3</th>
                            <th style="width:7%">RM Weight</th>
                            <th style="width:8%">RM Cost(₹)</th>
                            <th style="width:8%">Value(₹)</th>
                            <th style="width:4%"></th>
                        </tr>
                    </thead>
                    <tbody id="rm-tbody">
                        @if(count($rawMaterials) > 0)
                            @foreach($rawMaterials as $index => $rm)
                            <tr>
                                <td class="text-center">{{ $index + 1 }}</td>
                                <td>
                                    <select name="raw_material[{{ $index }}][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 }}" {{ ($rm['material_id'] ?? '') == $rawMaterial->id ? 'selected' : '' }}>{{ $rawMaterial->rm_grade }}</option>
                                        @endforeach
                                    </select>
                                    <input type="hidden" name="raw_material[{{ $index }}][density]" value="{{ $rm['density'] ?? '' }}">
                                </td>
                                <td><input type="number" name="raw_material[{{ $index }}][rate]" class="form-control form-control-sm rm-rate" step="0.01" value="{{ $rm['rate'] ?? '' }}"></td>
                                <td><input type="number" name="raw_material[{{ $index }}][scrap_rate]" class="form-control form-control-sm rm-scrap-rate" step="0.01" value="{{ $rm['scrap_rate'] ?? '' }}"></td>
                                <td><input type="number" name="raw_material[{{ $index }}][finish_weight]" class="form-control form-control-sm rm-finish-weight" step="0.01" value="{{ $rm['finish_weight'] ?? '' }}"></td>
                                <td>
                                    <select name="raw_material[{{ $index }}][type]" class="form-control form-control-sm rm-type">
                                        <option value="">Type</option>
                                        <option value="Rod" {{ ($rm['type'] ?? '') == 'Rod' ? 'selected' : '' }}>Rod</option>
                                        <option value="Plate" {{ ($rm['type'] ?? '') == 'Plate' ? 'selected' : '' }}>Plate</option>
                                        <option value="Pipe" {{ ($rm['type'] ?? '') == 'Pipe' ? 'selected' : '' }}>Pipe</option>
                                        <option value="Other" {{ ($rm['type'] ?? '') == 'Other' ? 'selected' : '' }}>Other</option>
                                    </select>
                                </td>
                                <td><input type="number" name="raw_material[{{ $index }}][quantity]" class="form-control form-control-sm rm-quantity" min="1" value="{{ $rm['quantity'] ?? '' }}"></td>
                                <td><input type="number" name="raw_material[{{ $index }}][size1]" class="form-control form-control-sm rm-size1" value="{{ $rm['size1'] ?? '' }}"></td>
                                <td><input type="number" name="raw_material[{{ $index }}][size2]" class="form-control form-control-sm rm-size2" value="{{ $rm['size2'] ?? '' }}"></td>
                                <td><input type="number" name="raw_material[{{ $index }}][size3]" class="form-control form-control-sm rm-size3" value="{{ $rm['size3'] ?? '' }}"></td>
                                <td><input type="text" name="raw_material[{{ $index }}][rm_weight]" class="form-control form-control-sm rm-weight" readonly value="{{ $rm['rm_weight'] ?? '' }}"></td>
                                <td><input type="number" name="raw_material[{{ $index }}][rm_cost]" class="form-control form-control-sm rm-cost" step="0.01" value="{{ $rm['rm_cost'] ?? '' }}"></td>
                                <td><input type="text" name="raw_material[{{ $index }}][value]" class="form-control form-control-sm rm-value" readonly value="{{ $rm['value'] ?? '' }}"></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>
                            @endforeach
                        @else
                            <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>
                        @endif
                    </tbody>
                </table>
            </div>
            <div id="add-row-1" class="mb-3" style="display: {{ count($rawMaterials) > 0 ? 'block' : 'none' }};">
                <button type="button" class="btn btn-gradient-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)" {{ count($conversionCostsData) > 0 ? 'checked' : '' }}>
                    <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-bordered table-sm product-table {{ count($conversionCostsData) == 0 ? '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">
                        @if(count($conversionCostsData) > 0)
                            @foreach($conversionCostsData as $index => $cc)
                            <tr>
                                <td class="text-center">{{ $index + 1 }}</td>
                                <td>
                                    <input list="conversionCost-options" name="conversion_cost[{{ $index }}][desc]" class="form-control form-control-sm" placeholder="Select process" value="{{ $cc['desc'] ?? '' }}">
                                    <datalist id="conversionCost-options">
                                        @foreach ($conversionCosts as $cost)
                                            <option value="{{ $cost }}"></option>
                                        @endforeach
                                    </datalist>
                                </td>
                                <td><input type="number" name="conversion_cost[{{ $index }}][quantity]" class="form-control form-control-sm cc-quantity" min="1" value="{{ $cc['quantity'] ?? '' }}"></td>
                                <td><input type="text" name="conversion_cost[{{ $index }}][unit]" class="form-control form-control-sm" placeholder="Unit" value="{{ $cc['unit'] ?? '' }}"></td>
                                <td><input type="number" name="conversion_cost[{{ $index }}][rate]" class="form-control form-control-sm cc-rate" min="0" step="0.01" value="{{ $cc['rate'] ?? '' }}"></td>
                                <td><input type="text" name="conversion_cost[{{ $index }}][value]" class="form-control form-control-sm cc-value" readonly value="{{ $cc['value'] ?? '' }}"></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>
                            @endforeach
                        @else
                            <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>
                        @endif
                    </tbody>
                </table>
            </div>
            <div id="add-row-2" class="mb-3" style="display: {{ count($conversionCostsData) > 0 ? 'block' : 'none' }};">
                <button type="button" class="btn btn-gradient-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)" {{ count($packingCharges) > 0 ? 'checked' : '' }}>
                    <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-bordered table-sm product-table {{ count($packingCharges) == 0 ? '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">
                        @if(count($packingCharges) > 0)
                            @foreach($packingCharges as $index => $pc)
                            <tr>
                                <td class="text-center">{{ $index + 1 }}</td>
                                <td><input type="text" name="packing[{{ $index }}][desc]" class="form-control form-control-sm" value="{{ $pc['desc'] ?? 'Packing cost' }}"></td>
                                <td><input type="number" name="packing[{{ $index }}][quantity]" class="form-control form-control-sm pc-quantity" min="1" value="{{ $pc['quantity'] ?? '' }}"></td>
                                <td><input type="text" name="packing[{{ $index }}][unit]" class="form-control form-control-sm" placeholder="Unit" value="{{ $pc['unit'] ?? '' }}"></td>
                                <td><input type="number" name="packing[{{ $index }}][rate]" class="form-control form-control-sm pc-rate" min="0" step="0.01" value="{{ $pc['rate'] ?? '' }}"></td>
                                <td><input type="text" name="packing[{{ $index }}][value]" class="form-control form-control-sm pc-value" readonly value="{{ $pc['value'] ?? '' }}"></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>
                            @endforeach
                        @else
                            <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>
                        @endif
                    </tbody>
                </table>
            </div>
            <div id="add-row-3" class="mb-3" style="display: {{ count($packingCharges) > 0 ? 'block' : 'none' }};">
                <button type="button" class="btn btn-gradient-primary btn-sm" id="addRowPC">
                    <i class="fas fa-plus mr-1"></i> Add Packing Charge Row
                </button>
            </div>
        </div>

        <!-- Summary & Totals Section -->
        <div class="section-card">
            <div class="section-title">
                <i class="fas fa-rupee-sign"></i>
                Summary & Totals
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Note / Remarks</label>
                    <textarea name="note" id="quoteNote" class="form-control" rows="3" placeholder="Additional notes or remarks">{{ $quotation->note }}</textarea>
                </div>
                <div class="col-md-6 mb-3">
                    <label>Grand Total in Words (INR)</label>
                    <input type="text" class="form-control" id="GT-in-letters" readonly>
                </div>
            </div>
            <div class="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: #475569;">Sub Total:</td>
                                <td width="150"><input type="text" class="form-control form-control-sm text-right" name="sub_total" id="totalAmount" readonly value="{{ $quotation->sub_total }}"></td>
                            </tr>
                            <tr>
                                <td class="text-right" style="color: #64748b;">Discount (%):</td>
                                <td><input type="number" class="form-control form-control-sm text-right" id="qt-discount" name="discount" step="0.01" oninput="calculateTotals()" value="{{ $quotation->discount }}"></td>
                            </tr>
                            <tr>
                                <td class="text-right" style="color: #64748b;">Round Up:</td>
                                <td><input type="text" class="form-control form-control-sm text-right" id="roundUp" name="round_up" readonly value="{{ $quotation->round_up }}"></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 value="{{ $quotation->grand_total }}"></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Form Actions -->
        <div class="d-flex justify-content-end mb-4">
            <button type="submit" class="btn btn-gradient-success mr-2" id="submitBtn">
                <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                <i class="fas fa-save mr-1"></i> Update Quotation
            </button>
            <a href="{{ route('superadmin.salesbom.quotation.quotationdetails') }}" class="btn btn-outline-secondary">
                <i class="fa fa-arrow-left mr-1"></i> Back to List
            </a>
        </div>
    </form>
@endsection

@section('scripts')
<script>
// ===== DateTime Update =====
function updateDateTime() {
    const now = new Date();
    const dateOptions = { year: 'numeric', month: 'short', day: 'numeric' };
    const timeOptions = { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true };

    document.querySelector('.display-date').textContent = now.toLocaleDateString('en-US', dateOptions);
    document.querySelector('.display-time').textContent = now.toLocaleTimeString('en-US', timeOptions);
}
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);
}

var isRfqPopulating = false;

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

    // 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') || '');
        }
    });

    // 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);
    });

    // Initialize row counters
    let rmRow = {{ count($rawMaterials) }};
    let ccRow = {{ count($conversionCostsData) }};
    let pcRow = {{ count($packingCharges) }};

    // Calculate initial totals
    calculateTotals();

    // 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) {
            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');

                showToast('RFQ data loaded successfully', 'success');
            } else {
                showToast('Failed to load RFQ data', 'error');
            }
        }).fail(function() {
            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();
}

// 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 type = $(selectElement).val();

    if (type === 'Rod') {
        size1.placeholder = 'Diameter';
        size2.placeholder = 'Length';
        size3.placeholder = '';
        size1.readOnly = false;
        size2.readOnly = false;
        size3.readOnly = true;
        rmCost.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;
    } 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;
    } else {
        size1.placeholder = 'Size 1';
        size2.placeholder = 'Size 2';
        size3.placeholder = 'Size 3';
        size1.value = '';
        size2.value = '';
        size3.value = '';
        size1.readOnly = true;
        size2.readOnly = true;
        size3.readOnly = true;
        rmCost.readOnly = false;
    }
}

// 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
    if (!rmType || rmType === 'Other') {
        let cost = parseFloat(row.find('.rm-cost').val()) || 0;
        row.find('.rm-value').val((quantity * cost).toFixed(2));
        calculateTotals();
        return;
    }

    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();
}

// 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
