@extends('layouts.dashboard.superadminapp')

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

@section('styles')
<link rel="stylesheet" href="{{ asset('css/modern-form-pattern.css') }}">
<style>
    /* Toast Notification */
    .toast-notification {
        position: fixed;
        top: 20px;
        right: 20px;
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: white;
        padding: 1rem 1.5rem;
        border-radius: 12px;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
        display: none;
        align-items: center;
        gap: 0.75rem;
        z-index: 10000;
        min-width: 300px;
        animation: slideIn 0.3s ease-out;
    }

    .toast-notification.show {
        display: flex;
    }

    .toast-icon {
        font-size: 1.5rem;
    }

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

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

    <!-- Toast Notification -->
    <div id="toast-notification" class="toast-notification">
        <i class="fas fa-check-circle toast-icon"></i>
        <span id="toast-message"></span>
    </div>

    <!-- Modern Page Header -->
    <div class="modern-page-header">
        <div class="header-left">
            <div class="icon-wrapper">
                <i class="fas fa-edit"></i>
            </div>
            <div class="header-title">
                <h1>Edit Purchase Quotation</h1>
                <div class="header-subtitle">{{ $quotation->quotation_no }}</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>

    <form class="quotation-form-container" id="quotationForm" method="POST"
        action="{{ route('superadmin.purchasebom.quotation.update', $quotation->id) }}">
        @csrf
        @method('POST')

        <!-- Customer Information Card -->
        <div class="section-card">
            <div class="section-header">
                <i class="fas fa-user-tie"></i>
                <h2>Customer Information</h2>
            </div>
            <div class="section-body">
                @php
                $customerObj = $vendors
                    ->where('id', $quotation->vendor_id ?? $quotation->customer_id)
                    ->first();
                @endphp

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="customerName">
                            Customer Details
                            <span class="required-star">*</span>
                        </label>
                        <input type="text" id="customerName" name="customer_id"
                               value="{{ $customerObj->company ?? '' }}"
                               class="form-control" readonly>
                        <input type="hidden" id="customerId" name="customer_name"
                               value="{{ $quotation->customer_name }}">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="rfqNo">RFQ No</label>
                        <select id="rfqNo" name="rfq_no" class="form-control">
                            <option value="">Select RFQ No</option>
                            @foreach ($unassignedRfqs as $rfq)
                                <option value="{{ $rfq->id }}"
                                    @if ($quotation->rfq_no == $rfq->id) selected @endif>
                                    {{ $rfq->rfq_no }}
                                </option>
                            @endforeach
                            @if ($quotation->rfq_no && !$unassignedRfqs->contains('id', $quotation->rfq_no))
                                <option value="{{ $quotation->rfq_no }}" selected>
                                    {{ $quotation->rfq_no }}
                                </option>
                            @endif
                        </select>
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="address">Address</label>
                        <textarea id="address" name="address" rows="3"
                                  class="form-control" placeholder="Enter customer address">{{ $quotation->address }}</textarea>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="gst">GST Number</label>
                        <input type="text" id="gst" name="gst"
                               value="{{ $quotation->gst }}"
                               class="form-control" placeholder="Enter GST Number">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="phone">Contact Number</label>
                        <input type="tel" id="phone" name="phone"
                               value="{{ $quotation->phone }}"
                               class="form-control" placeholder="Enter 10-digit number" maxlength="10">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="email">Email Address</label>
                        <input type="email" id="email" name="email"
                               value="{{ $quotation->email }}"
                               class="form-control" placeholder="Enter email address">
                    </div>
                </div>
            </div>
        </div>

        <!-- Quotation Details Card -->
        <div class="section-card">
            <div class="section-header info">
                <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-6 mb-3">
                        <label class="form-label" for="quotationNo">
                            Quotation ID
                            <span class="required-star">*</span>
                        </label>
                        <input type="text" id="quotationNo" name="quotation_no"
                               value="{{ $quotation->quotation_no }}"
                               class="form-control" readonly>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="quotationDate">
                            Quotation Date
                            <span class="required-star">*</span>
                        </label>
                        <input type="date" id="quotationDate" name="quotation_date"
                               value="{{ $quotation->quotation_date ? \Carbon\Carbon::parse($quotation->quotation_date)->format('Y-m-d') : '' }}"
                               class="form-control" required>
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="rfqDate">RFQ Date</label>
                        <input type="date" id="rfqDate" name="rfq_date"
                               value="{{ $quotation->rfq_date ? \Carbon\Carbon::parse($quotation->rfq_date)->format('Y-m-d') : '' }}"
                               class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="custRefNo">Customer Reference No</label>
                        <input type="text" id="custRefNo" name="cust_ref_no"
                               value="{{ $quotation->cust_ref_no }}"
                               class="form-control" placeholder="Enter reference number">
                    </div>
                </div>
            </div>
        </div>

        <!-- Product Information Card -->
        <div class="section-card">
            <div class="section-header warning">
                <i class="fas fa-box"></i>
                <h2>Product Information</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="partNo">Part Number</label>
                        <input type="text" id="partNo" name="part_no"
                               value="{{ $quotation->part_no }}"
                               class="form-control" placeholder="Enter part number">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="project-materialNo">Project Material No</label>
                        <input type="text" id="project-materialNo" name="project_material_no"
                               value="{{ $quotation->project_material_no }}"
                               class="form-control" placeholder="Enter project material number">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="drawingNo">Drawing Number</label>
                        <input type="text" id="drawingNo" name="drawing_no"
                               value="{{ $quotation->drawing_no }}"
                               class="form-control" placeholder="Enter drawing number">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="drawingRev">Drawing Revision</label>
                        <input type="text" id="drawingRev" name="drawing_rev"
                               value="{{ $quotation->drawing_rev }}"
                               class="form-control" placeholder="Enter revision">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="quantity">Quantity</label>
                        <input type="number" id="quantity" name="quantity"
                               value="{{ $quotation->quantity }}"
                               class="form-control" placeholder="Enter quantity" min="1">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="quantityUOM">Unit of Measurement</label>
                        <input type="text" id="quantityUOM" name="quantity_uom"
                               value="{{ $quotation->quantity_uom }}"
                               class="form-control" placeholder="e.g., PCS, KG">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="productType">
                            Product Type
                            <span class="required-star">*</span>
                        </label>
                        <input type="text" id="productType" name="product_type"
                               value="{{ $quotation->product_type }}"
                               class="form-control" placeholder="Enter product type" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="description">Description</label>
                        <textarea id="description" name="description" rows="3"
                                  class="form-control" placeholder="Enter product description">{{ $quotation->description }}</textarea>
                    </div>
                </div>
            </div>
        </div>

        <!-- Cost Breakdown Card -->
        <div class="section-card">
            <div class="section-header success">
                <i class="fas fa-calculator"></i>
                <h2>Cost Breakdown</h2>
            </div>
            <div class="section-body">

                <!-- Raw Material Charges -->
                <div class="toggle-checkbox mb-3">
                    <input type="checkbox" id="checkbox1" onclick="toggleTable(1)" checked>
                    <label for="checkbox1">
                        <i class="fas fa-cubes"></i>
                        Raw Material Charges
                    </label>
                </div>
                <div class="table-responsive" id="table1">
                    <table class="product-table">
                        <thead>
                            <tr>
                                <th>Sl.No</th>
                                <th>Raw Material</th>
                                <th>Rate (₹/kg)</th>
                                <th>Scrap Rate (₹/kg)</th>
                                <th>Finish Weight (kg)</th>
                                <th>RM Type</th>
                                <th>Quantity</th>
                                <th>Size 1 (mm)</th>
                                <th>Size 2 (mm)</th>
                                <th>Size 3 (mm)</th>
                                <th>RM Cost (₹)</th>
                                <th>Value (₹)</th>
                                <th>RM Weight</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="rm-tbody">
                            @php
                            $rawMaterials = $quotation->raw_materials
                                ? json_decode($quotation->raw_materials, true)
                                : [];
                            @endphp

                            @foreach ($rawMaterials as $i => $rm)
                            <tr>
                                <td>{{ $i + 1 }}</td>
                                <td>
                                    <select name="raw_material[{{ $i }}][material_id]" class="rm-material form-control">
                                        <option value="">Select Raw Material</option>
                                        @foreach ($allRawMaterials as $rawMaterial)
                                        <option value="{{ $rawMaterial->id }}"
                                            {{ ((isset($rm['material_id']) && $rm['material_id'] == $rawMaterial->id) ||
                                                (isset($rm['material']) && $rm['material'] == $rawMaterial->id)) ? 'selected' : '' }}
                                            data-density="{{ $rawMaterial->density ?? '' }}">
                                            {{ $rawMaterial->name }}
                                        </option>
                                        @endforeach
                                    </select>
                                    <input type="hidden" name="raw_material[{{ $i }}][density]" value="{{ $rm['density'] ?? '' }}">
                                </td>
                                <td>
                                    <input type="number" name="raw_material[{{ $i }}][rate]"
                                           class="rm-rate form-control" placeholder="0.00"
                                           step="0.01" value="{{ $rm['rate'] ?? '' }}">
                                </td>
                                <td>
                                    <input type="number" name="raw_material[{{ $i }}][scrap_rate]"
                                           class="rm-scrap-rate form-control" placeholder="0.00"
                                           step="0.01" value="{{ $rm['scrap_rate'] ?? '' }}">
                                </td>
                                <td>
                                    <input type="number" name="raw_material[{{ $i }}][finish_weight]"
                                           class="rm-finish-weight form-control" placeholder="0.00"
                                           step="0.01" value="{{ $rm['finish_weight'] ?? '' }}">
                                </td>
                                <td>
                                    <select name="raw_material[{{ $i }}][type]" class="form-control">
                                        <option value="" disabled>Select Type</option>
                                        <option value="Rod" {{ ($rm['type'] ?? '') == 'Rod' ? 'selected' : '' }}>Rod</option>
                                        <option value="Plate" {{ ($rm['type'] ?? '') == 'Plate' ? 'selected' : '' }}>Plate</option>
                                        <option value="Pipe" {{ ($rm['type'] ?? '') == 'Pipe' ? 'selected' : '' }}>Pipe</option>
                                        <option value="Other" {{ ($rm['type'] ?? '') == 'Other' ? 'selected' : '' }}>Other</option>
                                    </select>
                                </td>
                                <td>
                                    <input type="number" name="raw_material[{{ $i }}][quantity]"
                                           class="rm-quantity form-control" placeholder="1"
                                           min="1" value="{{ $rm['quantity'] ?? '' }}">
                                </td>
                                <td>
                                    <input type="number" name="raw_material[{{ $i }}][size1]"
                                           class="form-control" placeholder="Size 1"
                                           value="{{ $rm['size1'] ?? '' }}">
                                </td>
                                <td>
                                    <input type="number" name="raw_material[{{ $i }}][size2]"
                                           class="form-control" placeholder="Size 2"
                                           value="{{ $rm['size2'] ?? '' }}">
                                </td>
                                <td>
                                    <input type="number" name="raw_material[{{ $i }}][size3]"
                                           class="form-control" placeholder="Size 3"
                                           value="{{ $rm['size3'] ?? '' }}">
                                </td>
                                <td>
                                    <input type="number" name="raw_material[{{ $i }}][rm_cost]"
                                           class="rm-cost form-control" placeholder="0.00"
                                           step="0.01" value="{{ $rm['rm_cost'] ?? '' }}" readonly>
                                </td>
                                <td>
                                    <input type="text" name="raw_material[{{ $i }}][value]"
                                           class="rm-value form-control" placeholder="0.00"
                                           readonly value="{{ $rm['value'] ?? '' }}">
                                </td>
                                <td>
                                    <input type="number" name="raw_material[{{ $i }}][rm_weight]"
                                           class="rm-weight form-control" placeholder="0.00"
                                           step="0.01" value="{{ $rm['rm_weight'] ?? '' }}">
                                </td>
                                <td>
                                    <button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
                <div class="mt-3">
                    <button type="button" id="addRowRM" class="btn btn-primary btn-sm">
                        <i class="fas fa-plus mr-1"></i> Add Raw Material Row
                    </button>
                </div>

                <hr class="my-4">

                <!-- Conversion Cost -->
                <div class="toggle-checkbox mb-3">
                    <input type="checkbox" id="checkbox2" onclick="toggleTable(2)" checked>
                    <label for="checkbox2">
                        <i class="fas fa-cogs"></i>
                        Conversion Cost
                    </label>
                </div>
                <div class="table-responsive" id="table2">
                    <table class="product-table">
                        <thead>
                            <tr>
                                <th>Sl.No</th>
                                <th>Description</th>
                                <th>Quantity</th>
                                <th>Unit</th>
                                <th>Rate (INR)</th>
                                <th>Value</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="cc-tbody">
                            @php
                            $conversionCosts = $quotation->conversion_costs
                                ? json_decode($quotation->conversion_costs, true)
                                : [];
                            @endphp
                            @foreach ($conversionCosts as $i => $cc)
                            <tr>
                                <td>{{ $i + 1 }}</td>
                                <td>
                                    <input list="conversionCost-options"
                                           name="conversion_cost[{{ $i }}][desc]"
                                           class="form-control" placeholder="Select an option"
                                           value="{{ $cc['desc'] ?? '' }}">
                                    <datalist id="conversionCost-options">
                                        @foreach ($conversionprocesses as $cost)
                                        <option value="{{ $cost }}"></option>
                                        @endforeach
                                    </datalist>
                                </td>
                                <td>
                                    <input type="number" name="conversion_cost[{{ $i }}][quantity]"
                                           class="cc-quantity form-control" placeholder="1"
                                           min="1" value="{{ $cc['quantity'] ?? '' }}">
                                </td>
                                <td>
                                    <input type="text" name="conversion_cost[{{ $i }}][unit]"
                                           class="form-control" placeholder="Unit"
                                           value="{{ $cc['unit'] ?? '' }}">
                                </td>
                                <td>
                                    <input type="number" name="conversion_cost[{{ $i }}][rate]"
                                           class="cc-rate form-control" placeholder="0.00"
                                           min="0" step="0.01" value="{{ $cc['rate'] ?? '' }}">
                                </td>
                                <td>
                                    <input type="text" name="conversion_cost[{{ $i }}][value]"
                                           class="cc-value form-control" placeholder="0.00"
                                           readonly value="{{ $cc['value'] ?? '' }}">
                                </td>
                                <td>
                                    <button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
                <div class="mt-3">
                    <button type="button" id="addRowCC" class="btn btn-primary btn-sm">
                        <i class="fas fa-plus mr-1"></i> Add Conversion Cost Row
                    </button>
                </div>

                <hr class="my-4">

                <!-- Packing Charges -->
                <div class="toggle-checkbox mb-3">
                    <input type="checkbox" id="checkbox3" onclick="toggleTable(3)" checked>
                    <label for="checkbox3">
                        <i class="fas fa-box-open"></i>
                        Packing Charges
                    </label>
                </div>
                <div class="table-responsive" id="table3">
                    <table class="product-table">
                        <thead>
                            <tr>
                                <th>Sl.No</th>
                                <th>Description</th>
                                <th>Quantity</th>
                                <th>Unit</th>
                                <th>Rate (INR)</th>
                                <th>Value</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="pc-tbody">
                            @php
                            $packingCharges = $quotation->packing_charges
                                ? json_decode($quotation->packing_charges, true)
                                : [];
                            @endphp
                            @foreach ($packingCharges as $i => $pc)
                            <tr>
                                <td>{{ $i + 1 }}</td>
                                <td>
                                    <input type="text" name="packing[{{ $i }}][desc]"
                                           class="form-control" placeholder="Description"
                                           value="{{ $pc['desc'] ?? '' }}">
                                </td>
                                <td>
                                    <input type="number" name="packing[{{ $i }}][quantity]"
                                           class="pc-quantity form-control" placeholder="1"
                                           min="1" value="{{ $pc['quantity'] ?? '' }}">
                                </td>
                                <td>
                                    <input type="text" name="packing[{{ $i }}][unit]"
                                           class="form-control" placeholder="Unit"
                                           value="{{ $pc['unit'] ?? '' }}">
                                </td>
                                <td>
                                    <input type="number" name="packing[{{ $i }}][rate]"
                                           class="pc-rate form-control" placeholder="0.00"
                                           min="0" step="0.01" value="{{ $pc['rate'] ?? '' }}">
                                </td>
                                <td>
                                    <input type="text" name="packing[{{ $i }}][value]"
                                           class="pc-value form-control" placeholder="0.00"
                                           readonly value="{{ $pc['value'] ?? '' }}">
                                </td>
                                <td>
                                    <button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
                <div class="mt-3">
                    <button type="button" id="addRowPC" class="btn btn-primary btn-sm">
                        <i class="fas fa-plus mr-1"></i> Add Packing Charge Row
                    </button>
                </div>

                <hr class="my-4">

                <!-- Note Section -->
                <div class="row form-row">
                    <div class="col-md-12 mb-3">
                        <label class="form-label" for="quoteNote">Additional Notes</label>
                        <textarea name="note" id="quoteNote" rows="4"
                                  class="form-control" placeholder="Enter any additional notes or terms">{{ $quotation->note }}</textarea>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quotation Summary Card -->
        <div class="section-card">
            <div class="section-header">
                <i class="fas fa-receipt"></i>
                <h2>Quotation Summary</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="GT-in-letters">Amount in Words (INR)</label>
                        <input type="text" id="GT-in-letters" class="form-control" readonly
                               style="font-weight: 600; color: #0e7490;">
                    </div>
                    <div class="col-md-6">
                        <div class="summary-table">
                            <div class="row mb-2">
                                <div class="col-md-4">
                                    <label class="form-label" for="totalAmount">SUB TOTAL</label>
                                </div>
                                <div class="col-md-8">
                                    <input type="text" name="sub_total" id="totalAmount"
                                           class="form-control text-right" readonly value="{{ $quotation->sub_total }}">
                                </div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-4">
                                    <label class="form-label" for="qt-discount">Discount (%)</label>
                                </div>
                                <div class="col-md-8">
                                    <input type="number" id="qt-discount" name="discount"
                                           class="form-control text-right" oninput="calculateTotals()"
                                           value="{{ $quotation->discount }}" min="0" max="100" step="0.01">
                                </div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-4">
                                    <label class="form-label" for="roundUp">RoundUp Amount</label>
                                </div>
                                <div class="col-md-8">
                                    <input type="text" id="roundUp" name="round_up"
                                           class="form-control text-right" readonly value="{{ $quotation->round_up }}">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-4">
                                    <label class="form-label" for="grandTotal">Grand Total</label>
                                </div>
                                <div class="col-md-8">
                                    <input type="text" id="grandTotal" name="grand_total"
                                           class="form-control text-right" readonly value="{{ $quotation->grand_total }}">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Footer Actions -->
        <div class="footer-actions">
            <a href="{{ route('superadmin.purchasebom.quotation.quotationdetails') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to List
            </a>
            <div>
                <button class="btn btn-success" type="submit">
                    <i class="fas fa-save"></i> Update Quotation
                </button>
            </div>
        </div>

    </form>

</div>
@endsection

@push('scripts')
<script>
    window.allRawMaterials = @json($allRawMaterials);

    $(function() {
        // 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
        function showToast(message, type = 'success') {
            const toast = document.getElementById('toast-notification');
            const toastMessage = document.getElementById('toast-message');
            const toastIcon = toast.querySelector('.toast-icon');

            toastMessage.textContent = message;

            if (type === 'error') {
                toast.style.background = 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)';
                toastIcon.className = 'fas fa-exclamation-circle toast-icon';
            } else {
                toast.style.background = 'linear-gradient(135deg, #10b981 0%, #059669 100%)';
                toastIcon.className = 'fas fa-check-circle toast-icon';
            }

            toast.classList.add('show');

            setTimeout(() => {
                toast.classList.remove('show');
            }, 4000);
        }

        // Show session messages
        @if(session('success'))
            showToast("{{ session('success') }}", 'success');
        @endif
        @if(session('error'))
            showToast("{{ session('error') }}", 'error');
        @endif
        @if($errors->any())
            showToast("{{ $errors->first() }}", 'error');
        @endif

        // Autofill today's date if blank
        let today = new Date();
        let yyyy = today.getFullYear();
        let mm = String(today.getMonth() + 1).padStart(2, '0');
        let dd = String(today.getDate()).padStart(2, '0');
        let todayStr = `${yyyy}-${mm}-${dd}`;
        if (!$('#quotationDate').val()) $('#quotationDate').val(todayStr);

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

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

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

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

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

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

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

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

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

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

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

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

        $(document).on('input', '.rm-value, .cc-value, .pc-value, #qt-discount', calculateTotals);
        calculateTotals(); // Trigger once on load

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

        // RM Type Placeholders
        function updateSizePlaceholders(selectElement) {
            const row = $(selectElement).closest('tr');
            const size1Input = row.find('input[name$="[size1]"]')[0];
            const size2Input = row.find('input[name$="[size2]"]')[0];
            const size3Input = row.find('input[name$="[size3]"]')[0];
            const rmCostInput = row.find('input[name$="[rm_cost]"]')[0];
            const selectedType = $(selectElement).val();

            if (selectedType === 'Rod') {
                size1Input.placeholder = 'Rod Diameter';
                size2Input.placeholder = 'Rod Length';
                size3Input.placeholder = '';
                size1Input.readOnly = false;
                size2Input.readOnly = false;
                size3Input.readOnly = true;
                rmCostInput.readOnly = true;
            } else if (selectedType === 'Plate') {
                size1Input.placeholder = 'Plate Thickness';
                size2Input.placeholder = 'Plate Length';
                size3Input.placeholder = 'Plate Width';
                size1Input.readOnly = false;
                size2Input.readOnly = false;
                size3Input.readOnly = false;
                rmCostInput.readOnly = true;
            } else if (selectedType === 'Pipe') {
                size1Input.placeholder = 'Outer Diameter';
                size2Input.placeholder = 'Inner Diameter';
                size3Input.placeholder = 'Pipe Length';
                size1Input.readOnly = false;
                size2Input.readOnly = false;
                size3Input.readOnly = false;
                rmCostInput.readOnly = true;
            } else {
                size1Input.placeholder = 'Size 1';
                size2Input.placeholder = 'Size 2';
                size3Input.placeholder = 'Size 3';
                size1Input.readOnly = true;
                size2Input.readOnly = true;
                size3Input.readOnly = true;
                rmCostInput.readOnly = false;
            }
        }

        // RM Cost Calculation (based on type)
        function calculateRMCost(row) {
            row = $(row);
            const rawMaterial = row.find('input[name$="[material]"]').val() || '';
            const materialName = rawMaterial.split('-')[0].trim();
            const rmRate = parseFloat(row.find('input[name$="[rate]"]').val()) || 0;
            const scrapRate = parseFloat(row.find('input[name$="[scrap_rate]"]').val()) || 0;
            const finishWeight = parseFloat(row.find('input[name$="[finish_weight]"]').val()) || 0;
            const size1 = (parseFloat(row.find('input[name$="[size1]"]').val()) || 0);
            const size2 = (parseFloat(row.find('input[name$="[size2]"]').val()) || 0);
            const size3 = (parseFloat(row.find('input[name$="[size3]"]').val()) || 0);
            const rmType = row.find('select[name$="[type]"]').val();
            const rmCostInput = row.find('input[name$="[rm_cost]"]')[0];
            const density = parseFloat(row.find('input[name$="[density]"]').val()) || 0;

            let rmWeight = 0,
                scrapWeight = 0,
                rmCost = 0;

            if (rmType === 'Rod') {
                rmWeight = 3.142 * Math.pow(size1 / 2, 2) * size2 * density;
                scrapWeight = rmWeight - finishWeight;
                if (rmWeight > 0) rmCost = (rmWeight * rmRate) - (0.8 * (scrapWeight * scrapRate));
                rmCostInput.value = isNaN(rmCost) ? "" : rmCost.toFixed(2);
            } else if (rmType === 'Plate') {
                rmWeight = size1 * size2 * size3 * density;
                scrapWeight = rmWeight - finishWeight;
                if (rmWeight > 0) rmCost = (rmWeight * rmRate) - (0.8 * (scrapWeight * scrapRate));
                rmCostInput.value = isNaN(rmCost) ? "" : rmCost.toFixed(2);
            } else if (rmType === 'Pipe') {
                rmWeight = (3.142 * Math.pow(size1 / 2, 2) * size3 - 3.142 * Math.pow(size2 / 2, 2) * size3) * density;
                scrapWeight = rmWeight - finishWeight;
                if (rmWeight > 0) rmCost = (rmWeight * rmRate) - (0.8 * (scrapWeight * scrapRate));
                rmCostInput.value = isNaN(rmCost) ? "" : rmCost.toFixed(2);
            } else {
                rmCostInput.value = '';
            }

            $(row).find('.rm-cost').trigger('input');
        }

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

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

        // Row HTML creators for Add buttons
        function rawMaterialRow(idx) {
            let options = '<option value="">Select Raw Material</option>';
            window.allRawMaterials.forEach(function(item) {
                options += `<option value="${item.id}" data-density="${item.density || ''}">${item.name}</option>`;
            });

            return `
                <tr>
                    <td>${idx + 1}</td>
                    <td>
                        <select name="raw_material[${idx}][material_id]" class="rm-material form-control">
                            ${options}
                        </select>
                        <input type="hidden" name="raw_material[${idx}][density]">
                    </td>
                    <td><input type="number" name="raw_material[${idx}][rate]" class="rm-rate form-control" placeholder="Rate" step="0.01"></td>
                    <td><input type="number" name="raw_material[${idx}][scrap_rate]" class="rm-scrap-rate form-control" placeholder="Scrap Rate" step="0.01"></td>
                    <td><input type="number" name="raw_material[${idx}][finish_weight]" class="rm-finish-weight form-control" placeholder="Finish Weight" step="0.01"></td>
                    <td>
                        <select name="raw_material[${idx}][type]" class="rm-type form-control">
                            <option value="" disabled selected>Type</option>
                            <option value="Rod">Rod</option>
                            <option value="Plate">Plate</option>
                            <option value="Pipe">Pipe</option>
                            <option value="Other">Other</option>
                        </select>
                    </td>
                    <td><input type="number" name="raw_material[${idx}][quantity]" class="rm-quantity form-control" placeholder="Quantity" min="1"></td>
                    <td><input type="number" name="raw_material[${idx}][size1]" class="form-control" placeholder="Size 1"></td>
                    <td><input type="number" name="raw_material[${idx}][size2]" class="form-control" placeholder="Size 2"></td>
                    <td><input type="number" name="raw_material[${idx}][size3]" class="form-control" placeholder="Size 3"></td>
                    <td><input type="number" name="raw_material[${idx}][rm_cost]" class="rm-cost form-control" placeholder="RM Cost" step="0.01" readonly></td>
                    <td><input type="text" name="raw_material[${idx}][value]" class="rm-value form-control" placeholder="Value" readonly></td>
                    <td><input type="number" name="raw_material[${idx}][rm_weight]" class="rm-weight form-control" placeholder="RM Weight" step="0.01"></td>
                    <td><button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
                </tr>`;
        }

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

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

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

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

        // Handle RM Material dropdown change (update 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]);
        });
    });
</script>
@endpush
