@extends('layouts.dashboard.superadminapp')
@section('title', 'Edit Purchase Order')

@section('styles')
    <!-- DataTables Bootstrap 5 styling for buttons -->
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <!-- Bootstrap Select CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/css/bootstrap-select.min.css">
    <style>
        #productTable th, #productTable td{
            min-width: 100px;
        }
        #productTable th:nth-child(2),
        #productTable td:nth-child(2) {
            min-width: 250px;
        }
        #productTable th:nth-child(3),
        #productTable td:nth-child(3) {
            min-width: 150px;
        }
        #productTable th:nth-child(4),
        #productTable td:nth-child(4) {
            min-width: 150px !important;
        }
        #productTable th:nth-child(5),
        #productTable td:nth-child(5) {
            min-width: 150px !important;
        }
    </style>
@endsection

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

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

<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-edit mr-2"></i> Edit Purchase Order
        </h6>
        <a href="{{ route('superadmin.purchase.purchasedetails') }}" class="btn btn-light btn-sm">
            <i class="fa fa-arrow-left mr-1"></i> Back to List
        </a>
    </div>
    <div class="card-body">
        <!-- Hidden Order ID for JS -->
        <input type="hidden" id="editOrderId" value="{{ $po->id }}">

        <form id="soForm" method="POST" action="{{ route('superadmin.purchase.order.update', $po->id) }}" enctype="multipart/form-data">
            @csrf
            @method('PUT')

            <input type="hidden" id="tableProducts" name="tableProducts">

    <div class="row mt-3">
        <div class="col-md-6">
            <label>Purchase Order No.
                <input type="text" id="sOrderNo" name="soNo1" value="{{ $po->purchase_order_no }}" readonly class="form-control">
            </label>
        </div>
        <div class="col-md-6">
            <label>Quotation ID
                <input type="text" id="quotationSelect" name="quotationId" value="{{ $po->quotation_no }}" class="form-control">
            </label>
        </div>
    </div>

    <div class="row mt-3">
        <div class="col-md-6">
            <label>Purchase Date
                <input type="date" id="sOrderDate" name="soDate" value="{{ $po->purchase_order_date }}" class="form-control">
            </label>
        </div>
        <div class="col-md-6">
            <label>Quotation Date
                <input type="date" id="quotationDate" name="quotationDate" value="{{ $po->quotation_date }}" class="form-control">
            </label>
        </div>
    </div>

    <div class="row mt-3">
        <div class="col-md-6">
            <label>Vendor Company Name
                <input type="text" id="soCompanyName" name="soCompanyName" value="{{ optional($po->vendor)->company ?? $po->company_name }}" class="form-control">
                <input type="hidden" id="soCompanyId" name="soCompanyId" value="{{ optional($po->vendor)->id ?? $po->vendor_id }}">
            </label>
        </div>
        <div class="col-md-6">
            <label>Vendor Reference No.
                <input type="text" id="custRefNo" name="custRefNo" value="{{ $po->customer_ref_no }}" class="form-control">
            </label>
        </div>
    </div>

    <div class="row mt-3">
        <div class="col-md-6">
            <label>Address
                <input type="text" id="soCompanyAddress" name="soCompanyAddress" value="{{ $po->company_address }}" class="form-control">
            </label>
        </div>
        <div class="col-md-6">
            <label>GSTN
                <input type="text" id="soCompanyGSTN" name="soCompanyGSTN" value="{{ $po->company_gstn }}" class="form-control">
            </label>
        </div>
    </div>

    <div class="row mt-3">
        <div class="col-md-6">
            <label>Phone
                <input type="tel" id="soCompanyPhone" name="soCompanyPhone" value="{{ $po->company_phone }}" class="form-control">
            </label>
        </div>
        <div class="col-md-6">
            <label>Email
                <input type="email" id="soCompanyEmail" name="soCompanyEmail" value="{{ $po->company_email }}" class="form-control">
            </label>
        </div>
    </div>

    <div class="row mt-3">
        <div class="col-md-6">
            <label for="rfqNo">RFQ No</label>
            <input type="text" id="rfqNo" name="rfqNo" value="{{ $po->rfq_no }}" class="form-control">
        </div>
        <div class="col-md-6">
            <label for="rfqDate">RFQ Date</label>
            <input type="date" id="rfqDate" name="rfqDate" value="{{ $po->rfq_date }}" class="form-control">
        </div>
    </div>

    <div class="row mt-3">
        <div class="col-md-6">
            <label for="projectDescription">Note Ⅰ </label>
            <input type="text" id="projectDescription" name="projectDescription" value="{{ $po->description }}" class="form-control">
        </div>
        <div class="col-md-6">
            <label for="deliveryTerms">Delivery Terms</label>
            <input type="text" id="deliveryTerms" name="deliveryTerms" value="{{ $po->delivery_terms }}" class="form-control" placeholder="Delivery Terms">
        </div>
    </div>

    <div class="row mt-3">
        <div class="col-md-6">
            <label for="additionalCharges">Additional Charges</label>
            <input type="text" id="additionalCharges" name="additionalCharges" value="{{ $po->additional_charges }}" class="form-control">
        </div>
        <div class="col-md-6">
            <label for="note">Note ⅠⅠ</label>
            <textarea id="note" name="note" rows="2" class="form-control">{{ $po->note }}</textarea>
        </div>
    </div>

    <hr>

    <div class="row">
        <div class="col-md-6">
            <label>Bill To
                <textarea name="billAddress" id="billAddress" rows="3" class="form-control">{{ $po->bill_address }}</textarea>
            </label>
        </div>
        <div class="col-md-6">
            <label>Ship To
                <textarea name="shipAddress" id="shipAddress" rows="3" class="form-control">{{ $po->ship_address }}</textarea>
            </label>
        </div>
    </div>

    <hr>

    <div style="overflow-x: auto; width: 100%;">
        <table id="productTable" class="table table-bordered product-table">
          <thead>
            <tr>
              <th>Sl No.</th>
              <th>Item</th>
              <th>Description</th>
              <th>Req By Date</th>
              <th>Quantity</th>
              <th>UOM</th>
              <th>Unit Rate (INR)</th>
              <th>TDS (%)</th>
              <th>Discount (%)</th>
              <th>Value (INR)</th>
              <th>SGST (%)</th>
              <th>CGST (%)</th>
              <th>IGST (%)</th>
              <th>Amount (INR)</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            @foreach ($po->items as $index => $item)
            <tr>
              <td>{{ $loop->iteration }}</td>
              <td>
                <select class="form-select item-select w-100" name="item[]" required>
                  <option value="">Select Item</option>
                  @foreach ($stock_items as $stock)
                    <option value="{{ $stock->id }}" {{ $stock->id == $item->item ? 'selected' : '' }}>
                      {{ $stock->item_name }}
                    </option>
                  @endforeach
                </select>
              </td>
              <td>
                <input type="text" name="description[]" value="{{ $item->description }}" placeholder="Description" class="form-control" />
              </td>
              <td>
                <input type="date" name="req_by_date[]" value="{{ $item->req_by_date }}" placeholder="Select date" class="form-control" />
              </td>
              <td>
                <input type="number" name="quantity[]" value="{{ $item->quantity }}" step="1" min="0" placeholder="Qty" class="form-control" />
              </td>
              <td>
                <input type="text" name="uom[]" value="{{ $item->uom }}" placeholder="UOM" class="form-control" />
              </td>
              <td>
                <input type="number" name="unit_rate[]" value="{{ $item->unit_rate }}" step="0.01" placeholder="Rate" class="form-control" />
              </td>
              <td>
                <input type="number" name="tds[]" value="{{ $item->tds }}" step="0.01" placeholder="TDS %" class="form-control" />
              </td>
              <td>
                <input type="number" name="discount[]" value="{{ $item->discount }}" step="0.01" placeholder="Discount %" class="form-control" />
              </td>
              <td>
                <input type="number" name="value[]" value="{{ $item->value }}" step="0.01" placeholder="Value" class="form-control" readonly />
              </td>
              <td>
                <input type="number" name="sgst[]" value="{{ $item->sgst }}" step="0.01" placeholder="SGST %" class="form-control" />
              </td>
              <td>
                <input type="number" name="cgst[]" value="{{ $item->cgst }}" step="0.01" placeholder="CGST %" class="form-control" />
              </td>
              <td>
                <input type="number" name="igst[]" value="{{ $item->igst }}" step="0.01" placeholder="IGST %" class="form-control" />
              </td>
              <td>
                <input type="number" name="amount[]" value="{{ $item->amount }}" step="0.01" placeholder="Amount" class="form-control" readonly />
              </td>
                <td>
                    <button type="button" class="btn btn-danger" onclick="deleteRow(this)">
                        <i class="fa fa-trash"></i>
                    </button>
                </td>
            </tr>
            @endforeach
          </tbody>
        </table>

    </div>

    <button type="button" class="btn btn-primary" onclick="addRow()">Add Row</button>

    <hr>

    <div class="row mt-4">
        <div class="col-md-6">
            <label for="inr_in_words">Grand Total in Words in INR</label>
            <input type="text" id="inr_in_words" name="inr_in_words" value="{{ $po->inr_in_words }}" readonly class="form-control">
        </div>
        <div class="col-md-6 total-fields">
            <div class="row mb-2">
                <label class="col-md-4">SUB TOTAL</label>
                <div class="col-md-8"><input type="text" id="totalAmount" name="totalAmount" value="{{ $po->subtotal }}" readonly class="form-control" style="text-align: right;"></div>
            </div>
            <div class="row mb-2">
                <label class="col-md-4">SGST</label>
                <div class="col-md-8"><input type="text" id="sgstA" name="sgstA" value="{{ $po->sgst_amount }}" readonly class="form-control" style="text-align: right;"></div>
            </div>
            <div class="row mb-2">
                <label class="col-md-4">CGST</label>
                <div class="col-md-8"><input type="text" id="cgstA" name="cgstA" value="{{ $po->cgst_amount }}" readonly class="form-control" style="text-align: right;"></div>
            </div>
            <div class="row mb-2">
                <label class="col-md-4">IGST</label>
                <div class="col-md-8"><input type="text" id="IgstA" name="IgstA" value="{{ $po->igst_amount }}" readonly class="form-control" style="text-align: right;"></div>
            </div>
            <div class="row mb-2">
                <label class="col-md-4">Round Up</label>
                <div class="col-md-8"><input type="text" id="roundUp" name="roundUp" value="{{ $po->round_up }}" readonly class="form-control" style="text-align: right;"></div>
            </div>
            <div class="row mb-2">
                <label class="col-md-4">Grand Total</label>
                <div class="col-md-8"><input type="text" id="grandTotal" name="grandTotal" value="{{ $po->grand_total }}" readonly class="form-control" style="text-align: right;"></div>
            </div>
        </div>
    </div>

    <hr>
    <div class="d-flex justify-content-end mt-4">
        <button class="btn btn-success mr-2" type="submit">
            <i class="fa fa-save mr-1"></i> Update
        </button>
        <button class="btn btn-secondary mr-2" type="reset" onclick="resetForm()">
            <i class="fa fa-times mr-1"></i> Clear
        </button>
        <a href="{{ route('superadmin.purchase.purchasedetails') }}" class="btn btn-outline-secondary">
            <i class="fa fa-arrow-left mr-1"></i> Back
        </a>
    </div>
        </form>
    </div>
</div>

@endsection
@section('scripts')
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <!-- Load jQuery FIRST -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- Then Select2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <!-- Bootstrap JS (required by Bootstrap Select) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- Bootstrap Select JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/js/bootstrap-select.min.js"></script>
    <script>
    
        const stockItems = @json($stock_items);
        const poItems = @json($po->items);
        
        $(document).ready(function () {
            initializeSelect2();
            
            // Apply selected values explicitly from JSON (ensures correctness)
            poItems.forEach((item, index) => {
                const select = $(`select[name='item[]']`).eq(index);
                
                //console.log(select.length, poItems, item.item);
                if (select.length) {
                    select.val(String(item.item)).trigger('change.select2');
                }
            });
        });
        
        function initializeSelect2() {
            $('.item-select').each(function () {
                const $this = $(this);
                if ($this.hasClass("select2-hidden-accessible")) {
                    $this.select2('destroy');
                }
                $this.select2({
                    dropdownParent: $('#rfqform'),
                    width: 'resolve',
                    placeholder: "Select Item",
                    allowClear: true
                });
            });
        }
        
        function convertNumberToWords(num) {
            var a = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
                'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
            var b = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
        
            if ((num = num.toString()).length > 9) return 'Overflow';
            if (parseInt(num) === 0) return 'Zero';
        
            num = ('000000000' + num).substr(-9);
            var n = [
                parseInt(num.substr(0, 2), 10), // crore
                parseInt(num.substr(2, 2), 10), // lakh
                parseInt(num.substr(4, 2), 10), // thousand
                parseInt(num.substr(6, 1), 10), // hundred
                parseInt(num.substr(7, 2), 10)  // rest
            ];
        
            var str = '';
            if (n[0]) str += (n[0] < 20 ? a[n[0]] : b[Math.floor(n[0] / 10)] + ' ' + a[n[0] % 10]) + ' crore ';
            if (n[1]) str += (n[1] < 20 ? a[n[1]] : b[Math.floor(n[1] / 10)] + ' ' + a[n[1] % 10]) + ' lakh ';
            if (n[2]) str += (n[2] < 20 ? a[n[2]] : b[Math.floor(n[2] / 10)] + ' ' + a[n[2] % 10]) + ' thousand ';
            if (n[3]) str += a[n[3]] + ' hundred ';
            if (n[4]) str += (str !== '' ? 'and ' : '') + (n[4] < 20 ? a[n[4]] : b[Math.floor(n[4] / 10)] + ' ' + a[n[4] % 10]);
        
            return str.replace(/\s+/g, ' ').trim().replace(/^\w/, c => c.toUpperCase());
        }

        function calculateRowValue(row) {
            const quantity = parseFloat(row.querySelector('[name="quantity[]"]').value) || 0;
            const rate = parseFloat(row.querySelector('[name="unit_rate[]"]').value) || 0;
            const discount = parseFloat(row.querySelector('[name="discount[]"]').value) || 0;
            const sgst = parseFloat(row.querySelector('[name="sgst[]"]').value) || 0;
            const cgst = parseFloat(row.querySelector('[name="cgst[]"]').value) || 0;
            const igst = parseFloat(row.querySelector('[name="igst[]"]').value) || 0;
            const tds = parseFloat(row.querySelector('[name="tds[]"]').value) || 0;
        
            // Base after discount
            const base = quantity * rate * (1 - discount / 100);
            const gstTotal = base * (sgst + cgst + igst) / 100;
            const tdsAmount = base * (tds / 100);
        
            const total = base + gstTotal - tdsAmount;
        
            row.querySelector('[name="value[]"]').value = base.toFixed(2);
            row.querySelector('[name="amount[]"]').value = total.toFixed(2);
        
            calculateAllTotals();
        }

        function calculateAllTotals() {
            let subtotal = 0, sgstTotal = 0, cgstTotal = 0, igstTotal = 0, tdsTotal = 0;
        
            document.querySelectorAll("#productTable tbody tr").forEach(row => {
                const value = parseFloat(row.querySelector('[name="value[]"]').value) || 0;
                const sgst = parseFloat(row.querySelector('[name="sgst[]"]').value) || 0;
                const cgst = parseFloat(row.querySelector('[name="cgst[]"]').value) || 0;
                const igst = parseFloat(row.querySelector('[name="igst[]"]').value) || 0;
                const tds = parseFloat(row.querySelector('[name="tds[]"]').value) || 0;
        
                subtotal += value;
                sgstTotal += value * sgst / 100;
                cgstTotal += value * cgst / 100;
                igstTotal += value * igst / 100;
                tdsTotal += value * tds / 100;
            });
        
            const rawGrand = subtotal + sgstTotal + cgstTotal + igstTotal - tdsTotal;
            const round = Math.ceil(rawGrand) - rawGrand;
            const grand = rawGrand + round;
        
            document.getElementById("totalAmount").value = subtotal.toFixed(2);
            document.getElementById("sgstA").value = sgstTotal.toFixed(2);
            document.getElementById("cgstA").value = cgstTotal.toFixed(2);
            document.getElementById("IgstA").value = igstTotal.toFixed(2);
            document.getElementById("roundUp").value = round.toFixed(2);
            document.getElementById("grandTotal").value = grand.toFixed(2);
            document.getElementById("inr_in_words").value = convertNumberToWords(grand.toFixed(0));
        }

        function addRowEventListeners(row) {
            const fields = ['quantity[]', 'unit_rate[]', 'tds[]', 'discount[]', 'sgst[]', 'cgst[]', 'igst[]'];
        
            fields.forEach(name => {
                const input = row.querySelector(`[name="${name}"]`);
                if (input) {
                    input.addEventListener('input', () => {
                        calculateRowValue(row);
                    });
                }
            });
        }

        function getTableData() {
            const rows = document.querySelectorAll("#productTable tbody tr");
            const data = [];
            let slNo = 1;
        
            rows.forEach(row => {
                const itemSelect = row.querySelector('[name="item[]"]');
                const rowData = {
                    sl_no: slNo++,
                    item: itemSelect ? itemSelect.value : "",
                    description: row.querySelector('[name="description[]"]')?.value || "",
                    req_by_date: row.querySelector('[name="req_by_date[]"]')?.value || "",
                    quantity: row.querySelector('[name="quantity[]"]')?.value || "",
                    uom: row.querySelector('[name="uom[]"]')?.value || "",
                    unit_rate: row.querySelector('[name="unit_rate[]"]')?.value || "",
                    tds: row.querySelector('[name="tds[]"]')?.value || "",
                    discount: row.querySelector('[name="discount[]"]')?.value || "",
                    value: row.querySelector('[name="value[]"]')?.value || "",
                    sgst: row.querySelector('[name="sgst[]"]')?.value || "",
                    cgst: row.querySelector('[name="cgst[]"]')?.value || "",
                    igst: row.querySelector('[name="igst[]"]')?.value || "",
                    amount: row.querySelector('[name="amount[]"]')?.value || ""
                };
                data.push(rowData);
            });
        
            return data;
        }

        window.addRow = function () {
            const table = document.getElementById("productTable").querySelector("tbody");
            const idx = table.rows.length + 1;
            const row = document.createElement("tr");
        
            row.innerHTML = `
                <td>${idx}</td>
                <td>
                    <select class="form-select item-select w-100" name="item[]" required>
                        <option value="">Select Item</option>
                        @foreach ($stock_items as $item)
                            <option value="{{ $item->id }}">{{ $item->item_name }}</option>
                        @endforeach
                    </select>
                </td>
                <td><input type="text" name="description[]" class="form-control" placeholder="Description" /></td>
                <td><input type="date" name="req_by_date[]" class="form-control" placeholder="Select date" /></td>
                <td><input type="number" name="quantity[]" class="form-control" step="1" min="0" placeholder="Qty" /></td>
                <td><input type="text" name="uom[]" class="form-control" placeholder="UOM" /></td>
                <td><input type="number" name="unit_rate[]" class="form-control" step="0.01" placeholder="Rate" /></td>
                <td><input type="number" name="tds[]" class="form-control" step="0.01" placeholder="TDS %" /></td>
                <td><input type="number" name="discount[]" class="form-control" step="0.01" placeholder="Discount %" /></td>
                <td><input type="number" name="value[]" class="form-control" step="0.01" readonly placeholder="Value" /></td>
                <td><input type="number" name="sgst[]" class="form-control" step="0.01" placeholder="SGST %" /></td>
                <td><input type="number" name="cgst[]" class="form-control" step="0.01" placeholder="CGST %" /></td>
                <td><input type="number" name="igst[]" class="form-control" step="0.01" placeholder="IGST %" /></td>
                <td><input type="number" name="amount[]" class="form-control" step="0.01" readonly placeholder="Amount" /></td>
                <td>
                    <button type="button" class="btn btn-danger" onclick="deleteRow(this)">
                        <i class="fa fa-trash"></i>
                    </button>
                </td>
            `;
        
            table.appendChild(row);
        
            addRowEventListeners(row); // Optional: add your live calculation or field change handlers here
        
            const itemSelect = row.querySelector('.item-select');
            if (itemSelect) {
                initializeSelect2OnElement(itemSelect);
            }
        };

        function initializeSelect2OnElement(element) {
            if (!$(element).hasClass("select2-hidden-accessible")) {
                $(element).select2({
                    dropdownParent: $('#soForm'),
                    width: 'resolve',
                    placeholder: "Select Item",
                    allowClear: true
                });
            }
        }

        window.deleteRow = function (btn) {
            const row = btn.closest("tr");
            row.remove();
            calculateAllTotals();
        };

        document.addEventListener("DOMContentLoaded", function () {
            document.querySelectorAll("#productTable tbody tr").forEach(row => addRowEventListeners(row));
            calculateAllTotals();
        
            document.getElementById("soForm").addEventListener("submit", async function (e) {
                e.preventDefault();
                const form = this;
        
                document.getElementById("tableProducts").value = JSON.stringify(getTableData());
        
                const formData = new FormData(form);
                const payload = {};
                formData.forEach((value, key) => { payload[key] = value; });
                payload['tableProducts'] = getTableData();
                payload['_method'] = 'PUT';
        
                Swal.fire({
                    title: "Saving...",
                    text: "Updating Purchase Order, please wait.",
                    allowOutsideClick: false,
                    didOpen: () => Swal.showLoading()
                });
        
                try {
                    const response = await fetch(form.action, {
                        method: "POST",
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                        },
                        body: JSON.stringify(payload)
                    });
        
                    const result = await response.json();
                    Swal.close();
        
                    if (response.ok && result.message?.includes("updated")) {
                        Swal.fire("Success", result.message, "success").then(() => {
                            window.location.href = "{{ route('superadmin.purchase.purchasedetails') }}";
                        });
                    } else {
                        Swal.fire("Error", result.error || result.message || "An error occurred.", "error");
                    }
                } catch (error) {
                    Swal.close();
                    Swal.fire("Error", "Something went wrong during submission.", "error");
                }
            });
        });
        
</script>
@endsection
