    <div class="modal fade" id="locationSearchModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header bg-dark text-white py-2">
            <h5 class="modal-title fs-6" id="locationSearchTitle">Search Location</h5>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body p-0">
            <div class="d-flex justify-content-end p-2 bg-light border-bottom">
               <div class="input-group input-group-sm" style="width: 250px;">
                  <span class="input-group-text bg-white">Search</span>
                  <input type="text" class="form-control" id="locSearchInput" onkeyup="if(event.key === 'Enter') performLocationSearch()">
                  <button class="btn btn-dark" type="button" onclick="performLocationSearch()"><i class="fa-solid fa-search"></i></button>
               </div>
            </div>
            <div class="table-responsive" style="max-height:400px; overflow-y:auto;">
              <table class="table table-hover table-bordered mb-0 text-sm" style="font-size: 13px;">
                <thead class="table-dark sticky-top">
                  <tr>
                    <th>Name <i class="fa-solid fa-sort ms-1"></i></th>
                    <th>Code <i class="fa-solid fa-sort ms-1"></i></th>
                    <th style="width:100px;">Action <i class="fa-solid fa-sort ms-1"></i></th>
                  </tr>
                </thead>
                <tbody id="locationSearchResults">
                  <tr>
                    <td colspan="3" class="text-center text-muted py-4">Type to search and press Enter...</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- Generic Search Modal -->
    <div class="modal fade" id="genericSearchModal" tabindex="-1" aria-labelledby="searchModalTitle" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header bg-dark text-white py-2">
            <h5 class="modal-title fs-6" id="searchModalTitle">Search Lookup</h5>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body p-3">
            <div class="input-group mb-3">
              <input type="text" class="form-control" placeholder="Search keyword..." id="searchInput">
              <button class="btn btn-dark" type="button" id="modalSearchBtn" onclick="performModalSearch()"><i class="fa-solid fa-search"></i></button>
            </div>
            <div class="list-group" id="searchResults" style="max-height:200px; overflow-y:auto;">
              <button type="button" class="list-group-item list-group-item-action text-center text-muted" disabled>
                Type to search and results will appear here...
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>


    <!-- Edit Shipper Modal -->
    <div class="modal fade" id="editShipperModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header bg-dark text-white py-2">
            <h5 class="modal-title fs-6"><i class="fa-solid fa-user-pen me-2"></i>Edit Shipper Details</h5>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body p-3">
            <div class="row g-2">
              <div class="col-md-8">
                <label class="form-label small fw-bold">Company Name *</label>
                <input type="text" class="form-control form-control-sm" id="es_company">
              </div>
              <div class="col-md-4">
                <label class="form-label small fw-bold">Origin</label>
                <input type="text" class="form-control form-control-sm" id="es_origin">
              </div>
              <div class="col-md-6">
                <label class="form-label small fw-bold">Contact Name</label>
                <input type="text" class="form-control form-control-sm" id="es_name">
              </div>
              <div class="col-md-6">
                <label class="form-label small fw-bold">Mobile No. *</label>
                <input type="text" class="form-control form-control-sm" id="es_mobile">
              </div>
              <div class="col-md-6">
                <label class="form-label small fw-bold">Telephone</label>
                <input type="text" class="form-control form-control-sm" id="es_phone">
              </div>
              <div class="col-md-6">
                <label class="form-label small fw-bold">E-Mail</label>
                <input type="email" class="form-control form-control-sm" id="es_email">
              </div>
              <div class="col-md-12">
                <label class="form-label small fw-bold">Address Line 1</label>
                <input type="text" class="form-control form-control-sm" id="es_address">
              </div>
              <div class="col-md-12">
                <label class="form-label small fw-bold">Address Line 2</label>
                <input type="text" class="form-control form-control-sm" id="es_address2">
              </div>
              <div class="col-md-4">
                <label class="form-label small fw-bold">Pincode</label>
                <input type="text" class="form-control form-control-sm" id="es_pincode">
              </div>
              <div class="col-md-4">
                <label class="form-label small fw-bold">City</label>
                <input type="text" class="form-control form-control-sm" id="es_city_display">
              </div>
              <div class="col-md-4">
                <label class="form-label small fw-bold">State</label>
                <input type="text" class="form-control form-control-sm" id="es_state">
              </div>
              <div class="col-md-4">
                <label class="form-label small fw-bold">Country</label>
                <input type="text" class="form-control form-control-sm" id="es_country" value="INDIA">
              </div>
              <div class="col-md-4">
                <label class="form-label small fw-bold">IEC No.</label>
                <input type="text" class="form-control form-control-sm" id="es_iec">
              </div>
              <div class="col-md-4">
                <label class="form-label small fw-bold">Document Type</label>
                <select class="form-select form-select-sm" id="es_doc_type">
                  <option value="">Select</option>
                  <option value="Aadhaar Number">Aadhaar Number</option>
                  <option value="GSTIN (Normal)">GSTIN (Normal)</option>
                  <option value="PAN Number">PAN Number</option>
                  <option value="Passport Number">Passport Number</option>
                  <option value="TAN Number">TAN Number</option>
                  <option value="TAX ID">TAX ID</option>
                  <option value="VAT Number">VAT Number</option>
                  <option value="Voter Id">Voter Id</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label small fw-bold">Document No.</label>
                <input type="text" class="form-control form-control-sm" id="es_doc_no">
              </div>
            </div>
          </div>
          <div class="modal-footer py-2">
            <button type="button" class="btn btn-secondary btn-sm px-3" data-bs-dismiss="modal">Cancel</button>
            <button type="button" class="btn btn-success btn-sm px-4" onclick="applyShipperEdit()">
              <i class="fa-solid fa-check me-1"></i>Save Changes
            </button>
          </div>
        </div>
      </div>
    </div>
    
    
    </div>
    
    
    <!-- Accordions -->
    <div class="accordion accordion-flush mt-3 border" id="shipmentAccordion">
        <div class="accordion-item">
            <h2 class="accordion-header" id="headingOne">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne">
                    Click here to enter Pieces details
                </button>
            </h2>
            <div id="collapseOne" class="accordion-collapse collapse" aria-labelledby="headingOne" data-bs-parent="#shipmentAccordion">
                <div class="accordion-body p-2 bg-white">
                    <style>
                        .piece-input-group {
                            position: relative;
                            border: 1px solid #ced4da;
                            border-radius: 4px;
                            padding: 6px;
                            background: white;
                            flex: 1;
                            min-width: 90px;
                            margin-top: 10px;
                        }
                        .piece-input-group label {
                            position: absolute;
                            top: -9px;
                            left: 8px;
                            background: white;
                            padding: 0 4px;
                            font-size: 0.65rem !important;
                            color: #495057 !important;
                            font-weight: 600 !important;
                            white-space: nowrap;
                            z-index: 2;
                        }
                        .piece-input-group input, .piece-input-group select {
                            border: none !important;
                            outline: none !important;
                            box-shadow: none !important;
                            width: 100%;
                            padding: 0 !important;
                            font-size: 0.85rem !important;
                            text-align: right;
                            background: transparent;
                        }
                        .piece-input-group select {
                            text-align: left;
                        }
                        .pieces-add-btn {
                            background-color: #1a233a;
                            color: white;
                            border-radius: 4px;
                            border: none;
                            padding: 8px 20px;
                            font-weight: 600;
                            height: 100%;
                            white-space: nowrap;
                            margin-top: 10px;
                        }
                        .pieces-table th {
                            background-color: #1a233a !important;
                            color: white !important;
                            font-weight: 500 !important;
                            font-size: 0.75rem !important;
                            padding: 8px !important;
                            text-align: center;
                            border: 1px solid #333d5a !important;
                        }
                        .pieces-table td {
                            text-align: center;
                            vertical-align: middle;
                        }
                    </style>

                    <div class="d-flex align-items-stretch gap-2 mb-3 mt-2 px-1" style="overflow-x: auto;">
                        <div class="piece-input-group" style="min-width: 130px;">
                            <label>Measurement Unit</label>
                            <select id="p_unit">
                                <option value="Centimeter">Centimeter</option>
                                <option value="Inch">Inch</option>
                            </select>
                        </div>
                        <div class="piece-input-group" style="min-width: 120px;">
                            <label>Actl Weight/PCS</label>
                            <input type="number" id="p_act_wt" value="0" step="0.01">
                        </div>
                        <div class="piece-input-group" style="min-width: 100px;">
                            <label>No. Of Pieces</label>
                            <input type="number" id="p_pcs" value="1" min="1">
                        </div>
                        <div class="piece-input-group">
                            <label>Length</label>
                            <input type="number" id="p_len" value="0" step="0.1" onchange="calcPieceVol()">
                        </div>
                        <div class="piece-input-group">
                            <label>Width</label>
                            <input type="number" id="p_wid" value="0" step="0.1" onchange="calcPieceVol()">
                        </div>
                        <div class="piece-input-group">
                            <label>Height</label>
                            <input type="number" id="p_hei" value="0" step="0.1" onchange="calcPieceVol()">
                        </div>
                        <div class="piece-input-group" style="min-width: 90px;">
                            <label>Division</label>
                            <input type="number" id="p_div" value="5000" onchange="calcPieceVol()">
                        </div>
                        <div class="piece-input-group" style="min-width: 170px;">
                            <label>Vol Weight (Discount - 0 %)</label>
                            <input type="number" id="p_vol_wt" value="0" step="0.01" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 110px;">
                            <label>Chrg Weight</label>
                            <input type="number" id="p_chrg_wt" value="0" step="0.01" readonly>
                        </div>
                        <div>
                            <button type="button" class="pieces-add-btn" onclick="addPieceRow()"><i class="fa-solid fa-plus me-1"></i> Add</button>
                        </div>
                    </div>

                    <table class="table table-sm table-bordered mb-0 pieces-table" id="itemsTable">
                        <thead>
                            <tr>
                                <th>Child AWB</th>
                                <th>Actl Weight/PCS</th>
                                <th>Pieces</th>
                                <th>Length</th>
                                <th>Breadth</th>
                                <th>Height</th>
                                <th>Volumetric Weight</th>
                                <th>Charge Weight</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="itemsBody">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <div class="accordion-item">
            <h2 class="accordion-header" id="headingTwo">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
                    Click here to enter performa details
                </button>
            </h2>
            <div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#shipmentAccordion">
                <div class="accordion-body p-2 bg-white">
                    <!-- Manifest GST Detail box -->
                    <div class="fieldset-box mt-3 mx-2">
                        <span class="section-title">Manifest GST Detail</span>
                        <div class="row g-2 align-items-center">
                            <div class="col-md-3">
                                <label>CSB_Type</label>
                                <select class="form-select form-select-sm" name="csb_type">
                                    <?php if(!empty($csb_types)): ?>
                                        <?php foreach($csb_types as $ct): ?>
                                            <option value="<?= esc($ct['name']) ?>"><?= esc($ct['name']) ?></option>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <option>CSB 4</option>
                                        <option>CSB 5</option>
                                    <?php endif; ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label>Term Of Invoice</label>
                                <select class="form-select form-select-sm" name="term_of_invoice">
                                    <option value="">Select</option>
                                    <?php if(!empty($invoice_terms)): ?>
                                        <?php foreach($invoice_terms as $it): ?>
                                            <option value="<?= esc($it['name']) ?>"><?= esc($it['name']) ?></option>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <option>Cost and Freight(CFR)</option>
                                    <?php endif; ?>
                                </select>
                            </div>
                            <div class="col-md-2 text-center mt-3">
                                <label class="d-block text-muted small mb-1" style="font-size:0.65rem;text-align:left;margin-bottom:0 !important;position:relative;top:5px;left:5px;z-index:2;background:white;width:max-content;padding:0 4px;">GST Invoice</label>
                                <div class="btn-group btn-group-sm w-100 border" style="border-radius:4px;">
                                    <input type="hidden" name="gst_invoice" id="gst_invoice_val" value="0">
                                    <button type="button" id="btn_gst_yes" class="btn btn-light bg-white border-end" onclick="toggleGst(1)">Yes</button>
                                    <button type="button" id="btn_gst_no" class="btn btn-success" style="background-color:#2a7e4b;border-color:#2a7e4b;" onclick="toggleGst(0)">No</button>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <label>Invoice No</label>
                                <input type="text" class="form-control form-control-sm" name="invoice_no">
                            </div>
                        </div>
                        <div class="row g-2 align-items-center mt-1">
                            <div class="col-md-3">
                                <label>Invoice Date</label>
                                <input type="text" class="form-control form-control-sm" name="invoice_date">
                            </div>
                            <div class="col-md-4">
                                <label>Department No</label>
                                <input type="text" class="form-control form-control-sm" name="dept_no">
                            </div>
                            <div class="col-md-3">
                                <label>Export Reason</label>
                                <select name="export_reason" class="form-select form-select-sm">
                                    <?php if(!empty($export_reasons)): ?>
                                        <?php foreach($export_reasons as $er): ?>
                                            <option value="<?= esc($er['name']) ?>"><?= esc($er['name']) ?></option>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <option>Bonafide Gift</option>
                                    <?php endif; ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label>Format</label>
                                <select name="format" class="form-select form-select-sm">
                                    <option>Select</option>
                                    <option>B2B</option>
                                    <option>C2C</option>
                                    <option>COM</option>
                                    <option>CSB 5</option>
                                    <option>performainv1</option>
                                    <option>performainv2</option>
                                    <option>performainvcom</option>
                                    <option>performainvGSTBill</option>
                                    <option>PERSONAL</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- Items Add Row -->
                    <div class="d-flex align-items-stretch gap-2 mt-4 px-2" style="overflow-x: auto;">
                        <div class="piece-input-group" style="min-width: 90px;">
                            <label>Box No</label>
                            <select id="perf_box"><option></option></select>
                        </div>
                        <div class="piece-input-group">
                            <label>Packages</label>
                            <input type="text" id="perf_pkg">
                        </div>
                        <div class="piece-input-group" style="flex: 2; min-width: 150px;">
                            <label>Description</label>
                            <input type="text" id="perf_desc">
                        </div>
                        <div class="piece-input-group">
                            <label>HSN Code</label>
                            <input type="text" id="perf_hsn">
                        </div>
                        <div class="piece-input-group">
                            <label>Quantity</label>
                            <input type="number" id="perf_qty" value="">
                        </div>
                        <div class="piece-input-group">
                            <label>Weight</label>
                            <input type="number" id="perf_wt" value="">
                        </div>
                        <div class="piece-input-group" style="min-width: 90px;">
                            <label>Unit</label>
                            <select id="perf_unit">
                                <option value="KGS">KGS</option>
                                <option value="PCS" selected>PCS</option>
                            </select>
                        </div>
                        <div class="piece-input-group">
                            <label>Rate</label>
                            <input type="number" id="perf_rate" value="">
                        </div>
                        <div class="piece-input-group" style="background:#f8f9fa;">
                            <label>Amount</label>
                            <input type="number" id="perf_amt" value="" readonly>
                        </div>
                        <div>
                            <button type="button" class="pieces-add-btn" onclick="addPerformaRow()"><i class="fa-solid fa-plus me-1"></i> Add</button>
                        </div>
                    </div>

                    <!-- Summary -->
                    <div class="d-flex justify-content-between align-items-center mt-3 px-2 mx-1 small fw-bold" style="color: #4a75cc; font-size: 0.75rem;">
                        <div>Total Record: <span id="perf_total_rec">0</span></div>
                        <div>Quantity: <span id="perf_total_qty">0</span></div>
                        <div>Weight: <span id="perf_total_wt">0</span></div>
                        <div>Amount: <span id="perf_total_amt">0</span></div>
                    </div>

                    <!-- Table -->
                    <div class="table-responsive mt-1 px-1">
                        <table class="table table-bordered table-sm pieces-table mb-0">
                            <thead>
                                <tr>
                                    <th>Box No</th>
                                    <th>Package</th>
                                    <th>Description</th>
                                    <th>HS Code</th>
                                    <th>Quantity</th>
                                    <th>Weight</th>
                                    <th>Unit</th>
                                    <th>Rate</th>
                                    <th>Amount</th>
                                    <th>IGST %</th>
                                    <th>IGST Amount</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody id="performaBody">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="accordion-item border-bottom-0">
            <h2 class="accordion-header" id="headingThree">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
                    Click here to enter Charge details
                </button>
            </h2>
            <div id="collapseThree" class="accordion-collapse collapse" aria-labelledby="headingThree" data-bs-parent="#shipmentAccordion">
                <div class="accordion-body p-2 bg-white">
                    <!-- Row 1: readonly fields -->
                    <div class="d-flex align-items-center gap-2 mt-2 px-2" style="overflow-x: auto;">
                        <div class="piece-input-group" style="min-width: 130px;">
                            <label>Contract Charges</label>
                            <input type="text" value="0.00" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 130px;">
                            <label>Other Charges</label>
                            <input type="text" value="0.00" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 100px;">
                            <label>Total</label><input type="text" id="d_subtotal" value="0.00" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 100px;">
                            <label>Surcharge</label><input type="text" id="d_surcharge" value="0.00" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 100px;">
                            <label>IGST</label><input type="text" id="d_igst" value="0.00" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 100px;">
                            <label>CGST</label><input type="text" id="d_cgst" value="0.00" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 100px;">
                            <label>SGST</label><input type="text" id="d_sgst" value="0.00" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 130px;">
                            <label>Total Amount</label><input type="text" id="d_grand_total" value="0.00" readonly>
                        </div>
                    </div>

                    <!-- Row 2: Add fields -->
                    <div class="d-flex align-items-center gap-2 mt-4 px-2" style="overflow-x: auto;">
                        <div class="piece-input-group" style="min-width: 150px;">
                            <label style="color:#d32f2f;">Description *</label>
                            <select><option>Select</option></select>
                        </div>
                        <div class="piece-input-group" style="min-width: 120px;">
                            <label style="color:#d32f2f;">Item Amount *</label>
                            <input type="text" value="">
                        </div>
                        <div class="piece-input-group" style="min-width: 120px;">
                            <label>Item Fuel(0)</label>
                            <select><option>No</option></select>
                        </div>
                        <div class="piece-input-group bg-light" style="min-width: 80px;">
                            <input type="text" value="0.00" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 120px;">
                            <label>Tax On Fuel</label>
                            <select><option>No</option></select>
                        </div>
                        <div class="piece-input-group bg-light" style="min-width: 80px;">
                            <input type="text" value="0.00" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 100px;">
                            <label>Tax</label>
                            <select><option>No</option></select>
                        </div>
                        <div class="piece-input-group bg-light" style="min-width: 80px;">
                            <input type="text" value="0.00" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 130px;">
                            <label>Item Total</label>
                            <input type="text" value="">
                        </div>
                    </div>

                    <!-- Table -->
                    <div class="table-responsive mt-4 px-1">
                        <table class="table table-bordered table-sm pieces-table mb-0">
                            <thead>
                                <tr>
                                    <th>Description</th>
                                    <th>Rate</th>
                                    <th>Amount</th>
                                    <th>Fuel Apply</th>
                                    <th>Fuel Amt</th>
                                    <th>TaxApply</th>
                                    <th>Tax On Fuel</th>
                                    <th>IGST</th>
                                    <th>SGST</th>
                                    <th>CGST</th>
                                    <th>Total</th>
                                    <th>Charges Type</th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Shipment Details Box -->
    <div class="fieldset-box mt-4 mx-1">
        <span class="section-title">Shipment Details</span>
        <div class="row g-2 align-items-center">
            <div class="col-md-3" style="position:relative;">
                <label style="color:#d32f2f;font-size:0.65rem;font-weight:600;position:absolute;top:-8px;left:20px;background:white;padding:0 4px;z-index:5;">Payment Type *</label>
                <select name="payment_type" class="form-select form-select-sm">
                    <option value="Credit">Credit</option>
                    <option value="Cash">Cash</option>
                    <option value="COD">COD</option>
                    <option value="Bank">Bank</option>
                    <option value="UPI">UPI</option>
                </select>
            </div>
            <div class="col-md-3" style="position:relative;">
                <label style="font-size:0.65rem;font-weight:600;position:absolute;top:-8px;left:20px;background:white;padding:0 4px;z-index:5;color:#495057;">Reference No.</label>
                <input type="text" name="reference_number" class="form-control form-control-sm">
            </div>
            <div class="col-md-3" style="position:relative;">
                <label style="font-size:0.65rem;font-weight:600;position:absolute;top:-8px;left:20px;background:white;padding:0 4px;z-index:5;color:#495057;">Content</label>
                <input type="text" name="content_desc" class="form-control form-control-sm">
            </div>
            <div class="col-md-3" style="position:relative;">
                <label style="font-size:0.65rem;font-weight:600;position:absolute;top:-8px;left:20px;background:white;padding:0 4px;z-index:5;color:#495057;">Instruction</label>
                <input type="text" name="instruction" class="form-control form-control-sm">
            </div>
        </div>
    </div>

    <!-- Footer Information Bar -->
    <div class="border rounded px-3 py-2 mx-1 mt-4 mb-2 bg-white d-flex justify-content-between small text-muted" style="border-color:#e0e0e0 !important;">
        <div>AWB UserID: <?= esc(session()->get('name') ?? 'FLYSTAR') ?></div>
        <div>POD UserID: </div>
        <div>Manifest No: 0</div>
        <div>Invoice No: </div>
    </div>

    <!-- Save/Cancel Buttons -->
    <div class="text-end mt-3 mb-5 mx-1">
        <button type="submit" class="btn px-4 fw-bold me-2" style="background-color: #a5d6a7; border-color: #a5d6a7; color: white;" id="bookBtn">Save</button>
        <a href="<?= base_url('branch/shipments') ?>" class="btn btn-danger px-4 fw-bold" style="background-color: #e53935; border-color: #e53935;">Cancel</a>
    </div>
</form>

    <!-- KYC Section -->
    <div id="kycSection" style="display: none;">
        <div class="card border border-light-subtle shadow-sm mt-3" style="border-radius: 4px;">
            <div class="card-body p-3">
                <div class="row">
                    <div class="col-md-3 pe-4">
                        <label class="form-label small fw-bold text-muted mb-1" style="font-size: 0.75rem;">Type</label>
                        <select name="kyc_document_type" class="form-select form-select-sm mb-3">
                            <option>Aadhaar Number</option>
                            <option>GSTIN (Normal)</option>
                            <option>PAN Number</option>
                            <option>Passport Number</option>
                            <option>TAN Number</option>
                            <option>TAX ID</option>
                            <option>VAT Number</option>
                            <option>Voter Id</option>
                            <option>Performa Invoice</option>
                            <option>Document</option>
                        </select>
                        <div class="position-relative">
                            <input type="file" id="kyc_file_upload" class="position-absolute w-100 h-100 opacity-0" style="cursor: pointer; z-index: 2; top: 0; left: 0;" onchange="handleFileUpload(this)">
                            <div class="p-5 border border-success border-2 text-center text-success bg-white d-flex align-items-center justify-content-center" style="border-style: dashed !important; min-height: 160px; position: relative; z-index: 1;">
                                <span class="small fw-semibold" id="upload_text" style="color: #4CAF50;">DRAG AND DROP A FILE OR SELECT ADD<br>IMAGE</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-9 border-start ps-4">
                        <div class="table-responsive">
                            <table class="table table-bordered border-light m-0">
                                <thead style="background-color: #1a233a; color: white;">
                                    <tr>
                                        <th class="py-2 px-3 fw-normal border-0" style="font-size: 0.8rem; background-color: #1a233a; color: white;">Id</th>
                                        <th class="py-2 px-3 fw-normal border-0" style="font-size: 0.8rem; background-color: #1a233a; color: white;">File Name</th>
                                        <th class="py-2 px-3 fw-normal border-0" style="font-size: 0.8rem; background-color: #1a233a; color: white;">Entry Type</th>
                                        <th class="py-2 px-3 fw-normal border-0" style="font-size: 0.8rem; background-color: #1a233a; color: white;">Entry Date</th>
                                        <th class="py-2 px-3 fw-normal border-0" style="font-size: 0.8rem; background-color: #1a233a; color: white;">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr><td colspan="5" style="height: 180px;"></td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="border mt-3 py-2 px-3 d-flex justify-content-between align-items-center rounded bg-white text-muted" style="font-size: 0.75rem; border-color: #e0e0e0 !important;">
            <div>AWB UserID: <?= esc(session()->get('name') ?? 'FLYSTAR') ?></div>
            <div>POD UserID: </div>
            <div>Manifest No: 0</div>
            <div>Invoice No: </div>
        </div>
        
        <div class="d-flex justify-content-end mt-3 gap-2">
            <button type="button" class="btn btn-success px-4" style="border-radius: 20px; background-color: #a5d6a7; border: none; color: white; font-weight: 500;" onclick="uploadKycDoc()">Save</button>
            <button type="button" class="btn btn-danger px-4" style="border-radius: 20px; background-color: #d32f2f; border: none; color: white; font-weight: 500;" onclick="cancelKycDoc()">Cancel</button>
        </div>
    </div><script>
let itemCount = 1;

function onVendorChange() {
    const select = document.getElementById('vendor_select');
    if (!select) return;
    const option = select.options[select.selectedIndex];
    const code = option ? option.getAttribute('data-code') : 'UEX';
    document.getElementById('vendor_code_display').value = code;
    calculatePrice();
}

function onClientChange() {
    const select = document.getElementById('customer_id');
    const option = select.options[select.selectedIndex];
    
    if (select.value) {
        document.getElementById('client_code').value = 'FLX-' + select.value.padStart(4, '0');
        document.getElementById('sender_company').value = option.getAttribute('data-company') || option.getAttribute('data-name') || '';
        document.getElementById('sender_name').value = option.getAttribute('data-name') || '';
        document.getElementById('sender_mobile').value = option.getAttribute('data-phone') || '';
        document.getElementById('sender_phone').value = option.getAttribute('data-phone') || '';
        document.getElementById('sender_email').value = option.getAttribute('data-email') || '';
        document.getElementById('sender_address').value = option.getAttribute('data-address') || '';
        document.getElementById('sender_pincode').value = option.getAttribute('data-pincode') || '400001';
        if (document.getElementById('sender_city_display')) {
            document.getElementById('sender_city_display').value = option.getAttribute('data-city') || '';
        }
        if (document.getElementById('sender_state')) {
            document.getElementById('sender_state').value = option.getAttribute('data-state') || '';
        }
    } else {
        document.getElementById('client_code').value = '';
        document.getElementById('sender_company').value = '';
        document.getElementById('sender_name').value = '';
        document.getElementById('sender_mobile').value = '';
        document.getElementById('sender_phone').value = '';
        document.getElementById('sender_email').value = '';
        document.getElementById('sender_address').value = '';
        document.getElementById('sender_pincode').value = '400001';
        if (document.getElementById('sender_city_display')) {
            document.getElementById('sender_city_display').value = '';
        }
        if (document.getElementById('sender_state')) {
            document.getElementById('sender_state').value = '';
        }
    }
    calculatePrice();
}

let senderLookupTimer;
function triggerSenderPincodeLookup() {
    clearTimeout(senderLookupTimer);
    senderLookupTimer = setTimeout(() => {
        const val = document.getElementById('sender_pincode').value.trim();
        if (val.length < 3) return;
        
        let url = (typeof baseUrl !== 'undefined' ? baseUrl : (window.location.origin + '/flystarcourier/public')) + '/admin/shipments/lookupPincode?pincode=' + encodeURIComponent(val);
        if (window.location.href.indexOf('/branch/') !== -1) { url = url.replace('/admin/shipments/', '/branch/shipments/'); }
        
        fetch(url)
        .then(res => res.json())
        .then(d => {
            if (d.status === 'success') {
                if (document.getElementById('sender_city')) document.getElementById('sender_city').value = d.data.city;
                if (document.getElementById('sender_city_display')) document.getElementById('sender_city_display').value = d.data.city;
                if (document.getElementById('sender_state')) document.getElementById('sender_state').value = d.data.state;
                if (document.getElementById('sender_country')) document.getElementById('sender_country').value = d.data.country || 'INDIA';
                if (document.getElementById('sender_lat')) document.getElementById('sender_lat').value = d.data.latitude || '';
                if (document.getElementById('sender_lon')) document.getElementById('sender_lon').value = d.data.longitude || '';
                
                checkVendorServiceability();
            }
        }).catch(e => console.error(e));
    }, 800);
}

let receiverLookupTimer;
function triggerReceiverPincodeLookup() {
    clearTimeout(receiverLookupTimer);
    receiverLookupTimer = setTimeout(() => {
        const val = document.getElementById('receiver_pincode').value.trim();
        if (val.length < 3) return;
        
        let url = (typeof baseUrl !== 'undefined' ? baseUrl : (window.location.origin + '/flystarcourier/public')) + '/admin/shipments/lookupPincode?pincode=' + encodeURIComponent(val);
        if (window.location.href.indexOf('/branch/') !== -1) { url = url.replace('/admin/shipments/', '/branch/shipments/'); }
        
        fetch(url)
        .then(res => res.json())
        .then(d => {
            if (d.status === 'success') {
                if (document.getElementById('receiver_city')) document.getElementById('receiver_city').value = d.data.city;
                if (document.getElementById('receiver_city_display')) document.getElementById('receiver_city_display').value = d.data.city;
                if (document.getElementById('receiver_state')) document.getElementById('receiver_state').value = d.data.state;
                if (document.getElementById('receiver_country')) document.getElementById('receiver_country').value = d.data.country || 'INDIA';
                if (document.getElementById('receiver_lat')) document.getElementById('receiver_lat').value = d.data.latitude || '';
                if (document.getElementById('receiver_lon')) document.getElementById('receiver_lon').value = d.data.longitude || '';
                
                checkVendorServiceability();
            }
        }).catch(e => console.error(e));
    }, 800);
}

function checkVendorServiceability() {
    const sPin = document.getElementById('sender_pincode') ? document.getElementById('sender_pincode').value.trim() : '';
    const rPin = document.getElementById('receiver_pincode') ? document.getElementById('receiver_pincode').value.trim() : '';
    if (sPin.length < 3 || rPin.length < 3) return;
    
    let url = (typeof baseUrl !== 'undefined' ? baseUrl : (window.location.origin + '/flystarcourier/public')) + '/admin/shipments/checkServiceability';
    if (window.location.href.indexOf('/branch/') !== -1) { url = url.replace('/admin/shipments/', '/branch/shipments/'); }
    
    const formData = new FormData();
    formData.append('sender_pincode', sPin);
    formData.append('receiver_pincode', rPin);
    
    fetch(url, { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
    .then(r => r.json())
    .then(d => {
        const vendorSelect = document.getElementById('vendor_select');
        if(!vendorSelect) return;
        
        let oldVal = vendorSelect.value;
        vendorSelect.innerHTML = '';
        
        if (d.status === 'success' && d.data.length > 0) {
            let matched = false;
            d.data.forEach(v => {
                let opt = document.createElement('option');
                opt.value = v.name;
                opt.textContent = v.name;
                opt.setAttribute('data-code', v.code);
                if (v.name === oldVal) { opt.selected = true; matched = true; }
                vendorSelect.appendChild(opt);
            });
            onVendorChange();
            calculatePrice();
        } else {
            alert(d.message || 'Pincode is invalid or courier service is unavailable for this location.');
            document.getElementById('vendor_code_display').value = '';
        }
    }).catch(e => console.error(e));
}

async function calculatePrice() {
    const senderPincode = document.getElementById('sender_pincode').value;
    const receiverPincode = document.getElementById('receiver_pincode').value;
    const serviceTypeId = document.getElementById('service_type_id').value;
    
    // Auto-calculate charge weight based on actual vs volumetric
    const actualWt = parseFloat(document.getElementById('total_weight').value) || 0;
    const volWt = parseFloat(document.getElementById('volumetric_weight').value) || 0;
    const totalWeight = Math.max(actualWt, volWt);
    
    const cwInput = document.getElementById('charge_weight');
    if (cwInput) cwInput.value = totalWeight.toFixed(2);
    
    const declaredValue = parseFloat(document.getElementById('declared_value').value) || 0;
    
    let vendorName = '';
    const vendorSelect = document.getElementById('vendor_select');
    if (vendorSelect) {
        vendorName = vendorSelect.value;
    }
    
    const errBox = document.getElementById('pricingError');
    const errMsg = document.getElementById('pricingErrorMsg');
    const bookBtn = document.getElementById('bookBtn');
    
    if (senderPincode.length < 3 || receiverPincode.length < 3 || !serviceTypeId || totalWeight <= 0) {
        if(errBox) errBox.classList.add('d-none');
        return;
    }
    
    const formData = new FormData();
    formData.append('sender_pincode', senderPincode);
    formData.append('receiver_pincode', receiverPincode);
    formData.append('service_type_id', serviceTypeId);
    formData.append('total_weight', totalWeight);
    formData.append('declared_value', declaredValue);
    formData.append('vendor', vendorName);
    
    try {
        const res = await fetch('<?= base_url('branch/shipments/calculatePrice') ?>', {
            method: 'POST',
            body: formData,
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });
        
        const d = await res.json();
        
        if (d.status === 'success') {
            if(errBox) errBox.classList.add('d-none');
            
            let dSub = document.getElementById('d_subtotal');
            if (dSub) { dSub.value = parseFloat(d.sub_total).toFixed(2); }
            let dIgst = document.getElementById('d_igst');
            if (dIgst) { dIgst.value = parseFloat(d.igst).toFixed(2); }
            let dCgst = document.getElementById('d_cgst');
            if (dCgst) { dCgst.value = parseFloat(d.cgst).toFixed(2); }
            let dSgst = document.getElementById('d_sgst');
            if (dSgst) { dSgst.value = parseFloat(d.sgst).toFixed(2); }
            let dGrand = document.getElementById('d_grand_total');
            if (dGrand) { dGrand.value = parseFloat(d.grand_total).toFixed(2); }

            let hFreight = document.getElementById('h_freight'); if (hFreight) hFreight.value = d.freight_charge;
            let hFuel = document.getElementById('h_fuel'); if (hFuel) hFuel.value = d.fuel_surcharge;
            let hHandling = document.getElementById('h_handling'); if (hHandling) hHandling.value = d.handling_charge;
            let hPacking = document.getElementById('h_packing'); if (hPacking) hPacking.value = d.packing_charge;
            let hPickup = document.getElementById('h_pickup'); if (hPickup) hPickup.value = d.pickup_charge;
            let hDelivery = document.getElementById('h_delivery'); if (hDelivery) hDelivery.value = d.delivery_charge;
            let hRemote = document.getElementById('h_remote'); if (hRemote) hRemote.value = d.remote_area_charge;
            let hCod = document.getElementById('h_cod'); if (hCod) hCod.value = d.cod_charge;
            let hInsurance = document.getElementById('h_insurance'); if (hInsurance) hInsurance.value = d.insurance_charge;
            let hDiscount = document.getElementById('h_discount'); if (hDiscount) hDiscount.value = d.discount_amount;
            let hSubtotal = document.getElementById('h_subtotal'); if (hSubtotal) hSubtotal.value = d.sub_total;
            let hTaxable = document.getElementById('h_taxable'); if (hTaxable) hTaxable.value = d.taxable_amount;
            let hCgst = document.getElementById('h_cgst'); if (hCgst) hCgst.value = d.cgst;
            let hSgst = document.getElementById('h_sgst'); if (hSgst) hSgst.value = d.sgst;
            let hIgst = document.getElementById('h_igst'); if (hIgst) hIgst.value = d.igst;
            let hTotalTax = document.getElementById('h_totaltax'); if (hTotalTax) hTotalTax.value = d.total_tax;
            let hGrand = document.getElementById('h_grand'); if (hGrand) hGrand.value = d.grand_total;
            
            // --- Auto Rate Compare ---
            try {
                const rcFormData = new FormData();
                rcFormData.append('weight', totalWeight);
                const vWt = parseFloat(document.getElementById('volumetric_weight').value) || 0;
                rcFormData.append('vol_weight', vWt);
                rcFormData.append('service_type_id', serviceTypeId);
                rcFormData.append('to_pincode', receiverPincode);

                const rcRes = await fetch('<?= base_url('admin/ratecompare/calculate') ?>', {
                    method: 'POST',
                    body: rcFormData,
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                });
                const rcData = await rcRes.json();
                const rcBox = document.getElementById('auto_rate_compare');
                if (rcBox) {
                    if (rcData.status === 'success' && rcData.results && rcData.results.length > 0) {
                        rcBox.style.display = 'block';
                        let html = '';
                        rcData.results.forEach(r => {
                            let badge = (r.partner === vendorName) ? '<span class="badge bg-success ms-1">Selected</span>' : '';
                            html += `<tr>
                                <td>${r.partner} ${badge}</td>
                                <td>₹${r.base_price}</td>
                                <td class="fw-bold text-success">₹${r.total}</td>
                                <td><button type="button" class="btn btn-xs btn-outline-primary py-0" onclick="selectVendor('${r.partner}')">Select</button></td>
                            </tr>`;
                        });
                        document.getElementById('auto_rate_body').innerHTML = html;
                    } else {
                        rcBox.style.display = 'none';
                    }
                }
            } catch(e) { console.error('Rate Compare Error: ', e); }
            // -------------------------
        } else {
            if(errBox) errBox.classList.remove('d-none');
            if(errMsg) errMsg.innerText = d.message;
        }
    } catch (e) {
        console.error(e);
    }
}

function selectVendor(name) {
    let sel = document.getElementById('vendor_select');
    if(!sel) return;
    for(let i=0; i<sel.options.length; i++) {
        if(sel.options[i].value == name || sel.options[i].text == name) {
            sel.selectedIndex = i;
            if(typeof onVendorChange === 'function') onVendorChange();
            break;
        }
    }
}
function toggleGst(val)
{
    document.getElementById('gst_invoice_val').value = val;
    let btnYes = document.getElementById('btn_gst_yes');
    let btnNo = document.getElementById('btn_gst_no');
    
    if(val === 1) {
        btnYes.className = 'btn btn-success border-end';
        btnYes.style.backgroundColor = '#2a7e4b';
        btnYes.style.borderColor = '#2a7e4b';
        btnYes.style.color = 'white';
        
        btnNo.className = 'btn btn-light bg-white';
        btnNo.style.backgroundColor = '';
        btnNo.style.borderColor = '';
        btnNo.style.color = '';
    } else {
        btnNo.className = 'btn btn-success';
        btnNo.style.backgroundColor = '#2a7e4b';
        btnNo.style.borderColor = '#2a7e4b';
        btnNo.style.color = 'white';
        
        btnYes.className = 'btn btn-light bg-white border-end';
        btnYes.style.backgroundColor = '';
        btnYes.style.borderColor = '';
        btnYes.style.color = '';
    }
}

document.addEventListener("DOMContentLoaded", function() {
    var btnAwb = document.getElementById('btn-awb');
    var btnKyc = document.getElementById('btn-kyc');
    
    if(btnAwb) {
        btnAwb.addEventListener('click', function() {
            document.getElementById('btn-awb').classList.add('active');
            document.getElementById('btn-kyc').classList.remove('active');
            document.getElementById('bookingForm').style.display = 'block';
            document.getElementById('kycSection').style.display = 'none';
        });
    }
    
    if(btnKyc) {
        btnKyc.addEventListener('click', function() {
            document.getElementById('btn-kyc').classList.add('active');
            document.getElementById('btn-awb').classList.remove('active');
            document.getElementById('bookingForm').style.display = 'none';
            document.getElementById('kycSection').style.display = 'block';
        });
    }
});
document.addEventListener('DOMContentLoaded', function() {
        let searchBtns = document.querySelectorAll('.search-btn');
    searchBtns.forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            let label = null;
            let targetInput = null;
            let prev1 = btn.parentElement.previousElementSibling;
            if (prev1) {
                targetInput = prev1.querySelector('input');
                label = prev1.querySelector('label');
                if (label && label.innerHTML.includes('&nbsp;')) {
                    let prev2 = prev1.previousElementSibling;
                    if (prev2) {
                        label = prev2.querySelector('label');
                        if (!targetInput) targetInput = prev2.querySelector('input');
                    }
                }
            }
            let context = label ? label.innerText.replace('*', '').trim() : 'Lookup';
            document.getElementById('searchModalTitle').innerText = 'Search ' + context;
            
            // Set global tracking variables
            currentSearchContext = context;
            currentSearchInputTarget = targetInput;
            document.getElementById('searchInput').value = '';
            
            // Show modal
            if (typeof bootstrap !== 'undefined') {
                var searchModal = new bootstrap.Modal(document.getElementById('genericSearchModal'));
                searchModal.show();
                // Auto load all options immediately
                performModalSearch();
            } else {
                alert('Search ' + context + ' functionality coming soon!');
            }
        });
    });
});

let currentSearchContext = '';
let currentSearchInputTarget = null;

function performModalSearch() {
    let keyword = document.getElementById('searchInput').value;
    let resultsDiv = document.getElementById('searchResults');
    resultsDiv.innerHTML = '<div class="text-center py-3"><i class="fa-solid fa-spinner fa-spin text-muted"></i></div>';
    
    // Determine URL based on whether we are in admin or branch
    let baseUrl = window.location.pathname.includes('/branch/') ? 
        window.location.origin + '/flystarcourier/public/branch/shipments/searchLookup' : 
        window.location.origin + '/flystarcourier/public/admin/bookings/searchLookup';
        
    fetch(baseUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: 'type=' + encodeURIComponent(currentSearchContext) + '&keyword=' + encodeURIComponent(keyword)
    })
    .then(res => res.json())
    .then(data => {
        resultsDiv.innerHTML = '';
        if (data.status === 'success' && data.data.length > 0) {
            data.data.forEach(item => {
                let btn = document.createElement('button');
                btn.type = 'button';
                btn.className = 'list-group-item list-group-item-action fw-bold text-primary';
                btn.innerHTML = `<i class="fa-solid fa-check me-2 text-muted"></i> ${item.name}`;
                btn.onclick = function() {
                    if (currentSearchInputTarget) {
                        currentSearchInputTarget.value = item.name;
                        currentSearchInputTarget.dispatchEvent(new Event('change'));
                        currentSearchInputTarget.dispatchEvent(new Event('keyup'));
                    }
                    
                    if (currentSearchContext === 'Company Name' || currentSearchContext === 'Company' || currentSearchContext === 'Company Name *') {
                        // Populate shipper details if present
                        if (item.contact_name) {
                            let el = document.getElementById('sender_name');
                            if (el) el.value = item.contact_name.trim();
                        }
                        if (item.address) {
                            let el = document.getElementById('sender_address');
                            if (el) el.value = item.address;
                        }
                        if (item.pincode) {
                            let el = document.getElementById('sender_pincode');
                            if (el) {
                                el.value = item.pincode;
                                el.dispatchEvent(new Event('change'));
                                el.dispatchEvent(new Event('keyup'));
                            }
                        }
                        if (item.city) {
                            let el = document.getElementById('sender_city_display');
                            if (el) el.value = item.city;
                        }
                        if (item.state) {
                            let el = document.getElementById('sender_state');
                            if (el) el.value = item.state;
                        }
                        if (item.mobile) {
                            let el = document.getElementById('sender_mobile');
                            if (el) el.value = item.mobile;
                        }
                        if (item.email) {
                            let el = document.getElementById('sender_email');
                            if (el) el.value = item.email;
                        }
                        if (item.gst_no) {
                            let docType = document.querySelector('[name="sender_document_type"]');
                            if (docType) docType.value = 'GSTIN (Normal)';
                            let docNo = document.querySelector('[name="sender_document_no"]');
                            if (docNo) docNo.value = item.gst_no;
                        }
                    }

                    var searchModal = bootstrap.Modal.getInstance(document.getElementById('genericSearchModal'));
                    if (searchModal) searchModal.hide();
                };
                resultsDiv.appendChild(btn);
            });
        } else {
            resultsDiv.innerHTML = '<button type="button" class="list-group-item list-group-item-action text-center text-muted" disabled>No results found.</button>';
        }
    })
    .catch(err => {
        resultsDiv.innerHTML = '<button type="button" class="list-group-item list-group-item-action text-center text-danger" disabled>Error fetching data.</button>';
    });
}
});

function handleFileUpload(input) {
    if (input.files && input.files[0]) {
        document.getElementById('upload_text').innerHTML = 'Selected:<br>' + input.files[0].name;
    } else {
        document.getElementById('upload_text').innerHTML = 'DRAG AND DROP A FILE OR SELECT ADD<br>IMAGE';
    }
}

function calcPerformaAmt() {
    const qty = parseFloat(document.getElementById('perf_qty').value) || 0;
    const rate = parseFloat(document.getElementById('perf_rate').value) || 0;
    document.getElementById('perf_amt').value = (qty * rate).toFixed(2);
}

document.getElementById('perf_qty').addEventListener('input', calcPerformaAmt);
document.getElementById('perf_rate').addEventListener('input', calcPerformaAmt);

let perfItemCount = 0;

function addPerformaRow() {
    const box = document.getElementById('perf_box').value || '';
    const pkg = document.getElementById('perf_pkg').value || '';
    const desc = document.getElementById('perf_desc').value || '';
    const hsn = document.getElementById('perf_hsn').value || '';
    const qty = parseFloat(document.getElementById('perf_qty').value) || 0;
    const wt = parseFloat(document.getElementById('perf_wt').value) || 0;
    const unit = document.getElementById('perf_unit').value || 'PCS';
    const rate = parseFloat(document.getElementById('perf_rate').value) || 0;
    const amt = parseFloat(document.getElementById('perf_amt').value) || 0;
    
    if (qty <= 0 || rate <= 0) {
        alert("Please enter valid quantity and rate.");
        return;
    }
    if (desc === '') {
        alert("Please enter a description.");
        return;
    }
    
    const tbody = document.getElementById('performaBody');
    const tr = document.createElement('tr');
    tr.innerHTML = `
        <td><input type="hidden" name="perf_items[${perfItemCount}][box_no]" value="${box}">${box}</td>
        <td><input type="hidden" name="perf_items[${perfItemCount}][package]" value="${pkg}">${pkg}</td>
        <td><input type="hidden" name="perf_items[${perfItemCount}][description]" value="${desc}">${desc}</td>
        <td><input type="hidden" name="perf_items[${perfItemCount}][hsn]" value="${hsn}">${hsn}</td>
        <td><input type="hidden" name="perf_items[${perfItemCount}][quantity]" class="p-qty" value="${qty}">${qty}</td>
        <td><input type="hidden" name="perf_items[${perfItemCount}][weight]" class="p-wt" value="${wt}">${wt}</td>
        <td><input type="hidden" name="perf_items[${perfItemCount}][unit]" value="${unit}">${unit}</td>
        <td><input type="hidden" name="perf_items[${perfItemCount}][rate]" value="${rate}">${rate}</td>
        <td><input type="hidden" name="perf_items[${perfItemCount}][amount]" class="p-amt" value="${amt}">${amt}</td>
        <td><input type="hidden" name="perf_items[${perfItemCount}][igst_pct]" value="0">0%</td>
        <td><input type="hidden" name="perf_items[${perfItemCount}][igst_amt]" value="0">0.00</td>
        <td><button type="button" class="btn btn-sm btn-danger py-0 px-2" onclick="this.closest('tr').remove(); updatePerformaTotals();"><i class="fa-solid fa-trash"></i></button></td>
    `;
    tbody.appendChild(tr);
    perfItemCount++;
    
    // Reset inputs
    document.getElementById('perf_desc').value = '';
    document.getElementById('perf_qty').value = '';
    document.getElementById('perf_wt').value = '';
    document.getElementById('perf_rate').value = '';
    document.getElementById('perf_amt').value = '';
    
    updatePerformaTotals();
}

function updatePerformaTotals() {
    let tRec = 0;
    let tQty = 0;
    let tWt = 0;
    let tAmt = 0;
    
    const rows = document.getElementById('performaBody').querySelectorAll('tr');
    rows.forEach(tr => {
        tRec++;
        tQty += parseFloat(tr.querySelector('.p-qty').value) || 0;
        tWt += parseFloat(tr.querySelector('.p-wt').value) || 0;
        tAmt += parseFloat(tr.querySelector('.p-amt').value) || 0;
    });
    
    document.getElementById('perf_total_rec').innerText = tRec;
    document.getElementById('perf_total_qty').innerText = tQty;
    document.getElementById('perf_total_wt').innerText = tWt.toFixed(2);
    document.getElementById('perf_total_amt').innerText = tAmt.toFixed(2);
}

async function uploadKycDoc() {
    const fileInput = document.getElementById('kyc_file_upload');
    const typeSelect = document.querySelector('select[name="kyc_document_type"]');
    
    if (!fileInput.files || fileInput.files.length === 0) {
        alert("Please select a file to upload.");
        return;
    }
    
    const formData = new FormData();
    formData.append('kyc_file', fileInput.files[0]);
    formData.append('kyc_type', typeSelect.value);
    
    try {
        const res = await fetch('<?= base_url('branch/shipments/uploadKyc') ?>', {
            method: 'POST',
            body: formData,
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });
        
        const d = await res.json();
        if (d.status === 'success') {
            const tbody = document.querySelector('#kycSection tbody');
            if (tbody.querySelector('td[colspan="5"]')) {
                tbody.innerHTML = '';
            }
            
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td class="py-2 px-3 align-middle" style="font-size: 0.85rem;">${d.data.id}</td>
                <td class="py-2 px-3 align-middle" style="font-size: 0.85rem;">${d.data.file_name}</td>
                <td class="py-2 px-3 align-middle" style="font-size: 0.85rem;">${d.data.entry_type}</td>
                <td class="py-2 px-3 align-middle" style="font-size: 0.85rem;">${d.data.entry_date}</td>
                <td class="py-2 px-3 align-middle text-center">
                    <button type="button" class="btn btn-sm btn-outline-danger py-0 px-2" onclick="this.closest('tr').remove()"><i class="fa-solid fa-trash"></i></button>
                </td>
            `;
            tbody.appendChild(tr);
            
            cancelKycDoc(false);
            alert("KYC Document uploaded successfully!");
        } else {
            alert("Error: " + d.message);
        }
    } catch(e) {
        console.error(e);
        alert("An error occurred during upload.");
    }
}

function cancelKycDoc(switchView = true) {
    document.getElementById('kyc_file_upload').value = '';
    document.getElementById('upload_text').innerHTML = 'DRAG AND DROP A FILE OR SELECT ADD<br>IMAGE';
    if(switchView && document.getElementById('btn-awb')) {
        document.getElementById('btn-awb').click();
    }
}
</script>


<script>
let currentLocTarget = 'origin';

function openLocationSearch(target) {
    currentLocTarget = target;
    document.getElementById('locationSearchTitle').textContent = target === 'origin' ? 'Origin' : 'Destination';
    document.getElementById('locSearchInput').value = '';
    document.getElementById('locationSearchResults').innerHTML = '<tr><td colspan="3" class="text-center text-muted py-4">Type to search and press Enter...</td></tr>';
    
    var modal = new bootstrap.Modal(document.getElementById("locationSearchModal"));
    modal.show();
    
    setTimeout(() => {
        document.getElementById('locSearchInput').focus();
        performLocationSearch(); // Auto fetch on open
    }, 200);
}

function performLocationSearch() {
    let kw = document.getElementById('locSearchInput').value;
    let tbody = document.getElementById('locationSearchResults');
    tbody.innerHTML = '<tr><td colspan="3" class="text-center py-4"><i class="fa-solid fa-spinner fa-spin me-2"></i>Searching...</td></tr>';
    
    let url = (typeof baseUrl !== 'undefined' ? baseUrl : (window.location.origin + '/flystarcourier/public')) + '/admin/searchLookup';
    // Use branch endpoint if in branch panel
    if (window.location.href.indexOf('/branch/') !== -1) {
        url = url.replace('/admin/', '/branch/');
    }
    
    // Using type=State because user requested states data
    fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' },
        body: 'type=State&keyword=' + encodeURIComponent(kw)
    })
    .then(r => r.json())
    .then(res => {
        if(res.status === 'success' && res.data && res.data.length > 0) {
            let html = '';
            res.data.forEach(item => {
                let code = item.code || item.name.substring(0,3).toUpperCase();
                html += `<tr>
                    <td>${item.name}</td>
                    <td><span class="badge bg-secondary">${code}</span></td>
                    <td><button type="button" class="btn btn-sm btn-light border py-0 px-2" onclick="selectLocation('${item.name.replace(/'/g, "\\'")}', '${code.replace(/'/g, "\\'")}', '${item.name.replace(/'/g, "\\'")}')"><i class="fa-solid fa-check me-1"></i>Select</button></td>
                </tr>`;
            });
            tbody.innerHTML = html;
        } else {
            tbody.innerHTML = '<tr><td colspan="3" class="text-center text-muted py-4">No locations found.</td></tr>';
        }
    })
    .catch(e => {
        tbody.innerHTML = '<tr><td colspan="3" class="text-center text-danger py-4">Error searching.</td></tr>';
    });
}

function selectLocation(name, code, stateName) {
    if (currentLocTarget === 'origin') {
        document.getElementById('sender_city').value = name;
        if(document.getElementById('sender_city_code')) document.getElementById('sender_city_code').value = code;
        if(document.getElementById('sender_state') && stateName) document.getElementById('sender_state').value = stateName;
        // Trigger any dependent events
        let ev = new Event('change');
        document.getElementById('sender_city').dispatchEvent(ev);
    } else {
        document.getElementById('receiver_city').value = name;
        if(document.getElementById('receiver_city_code')) document.getElementById('receiver_city_code').value = code;
        if(document.getElementById('receiver_state') && stateName) document.getElementById('receiver_state').value = stateName;
        // Trigger any dependent events
        let ev = new Event('change');
        document.getElementById('receiver_city').dispatchEvent(ev);
        if(typeof calculatePrice === 'function') calculatePrice();
    }
    
    var modalEl = document.getElementById("locationSearchModal");
    var modal = bootstrap.Modal.getInstance(modalEl);
    if (modal) modal.hide();
}
</script>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
    $(document).ready(function() {
        $('#customer_id').select2({
            theme: 'bootstrap-5',
            placeholder: 'Select Client Account',
            width: '100%'
        }).on('select2:select', function (e) {
            onClientChange();
    onVendorChange();
    filterServices();
        });
    });
</script>

<script>
document.addEventListener("DOMContentLoaded", function() {
    var esPincode = document.getElementById("es_pincode");
    if (esPincode) {
        esPincode.addEventListener("input", async function() {
            var pin = this.value.trim();
            if (pin.length === 6) {
                try {
                    var res = await fetch("<?= base_url("admin/bookings/lookupPincode") ?>?pincode=" + encodeURIComponent(pin));
                    var json = await res.json();
                    if (json.status === "success") {
                        document.getElementById("es_city_display").value = json.data.city  || "";
                        document.getElementById("es_state").value        = json.data.state || "";
                    }
                } catch(e) {}
            }
        });
    }
});

function openShipperEditModal() {
    function g(id) { return document.getElementById(id); }
    function qs(sel) { return document.querySelector(sel); }
    function val(id) { var el = g(id); return el ? el.value : ""; }
    function qval(sel) { var el = qs(sel); return el ? el.value : ""; }

    g("es_company").value      = val("sender_company");
    g("es_name").value          = val("sender_name");
    g("es_address").value       = val("sender_address");
    g("es_address2").value      = val("sender_address_2");
    g("es_pincode").value       = val("sender_pincode");
    g("es_city_display").value  = val("sender_city_display");
    g("es_state").value         = val("sender_state");
    g("es_mobile").value        = val("sender_mobile");
    g("es_phone").value         = val("sender_phone");
    g("es_email").value         = val("sender_email");
    g("es_origin").value        = val("sender_city");
    g("es_country").value       = qval('input[name="sender_country"]') || "INDIA";
    g("es_iec").value           = qval('input[name="sender_iec_no"]');

    var docType = qs('select[name="sender_document_type"]');
    var docNo   = qs('input[name="sender_document_no"]');
    if (docType) g("es_doc_type").value = docType.value;
    if (docNo)   g("es_doc_no").value   = docNo.value;

    var modal = new bootstrap.Modal(document.getElementById("editShipperModal"));
    modal.show();
}

function applyShipperEdit() {
    function g(id) { return document.getElementById(id); }
    function qs(sel) { return document.querySelector(sel); }
    function setV(id, val) { var el = g(id); if (el) el.value = val; }
    function setQ(sel, val) { var el = qs(sel); if (el) el.value = val; }

    setV("sender_company",      g("es_company").value);
    setV("sender_name",         g("es_name").value);
    setV("sender_address",      g("es_address").value);
    setV("sender_address_2",    g("es_address2").value);
    setV("sender_pincode",      g("es_pincode").value);
    setV("sender_city_display", g("es_city_display").value);
    setV("sender_state",        g("es_state").value);
    setV("sender_mobile",       g("es_mobile").value);
    setV("sender_phone",        g("es_phone").value);
    setV("sender_email",        g("es_email").value);
    setV("sender_city",         g("es_origin").value);
    setQ('input[name="sender_country"]',     g("es_country").value);
    setQ('input[name="sender_iec_no"]',      g("es_iec").value);
    setQ('input[name="sender_document_no"]', g("es_doc_no").value);

    var docType = qs('select[name="sender_document_type"]');
    if (docType) docType.value = g("es_doc_type").value;

    // Close the modal
    var modalEl = document.getElementById("editShipperModal");
    var modal = bootstrap.Modal.getInstance(modalEl);
    if (modal) modal.hide();

    // Show success toast
    var toast = document.createElement("div");
    toast.style.cssText = "position:fixed;bottom:24px;right:24px;background:#28a745;color:#fff;padding:12px 22px;border-radius:8px;font-size:13px;font-weight:600;z-index:99999;box-shadow:0 4px 16px rgba(0,0,0,.15);";
    toast.innerHTML = '<i class="fa-solid fa-check me-2"></i>Shipper details updated!';
    document.body.appendChild(toast);
    setTimeout(function() { toast.remove(); }, 3000);

    // Trigger price recalculation
    if (typeof calculatePrice === "function") calculatePrice();
}
</script>



<script>
let currentLocTarget = 'origin';

function openLocationSearch(target) {
    currentLocTarget = target;
    document.getElementById('locationSearchTitle').textContent = target === 'origin' ? 'Origin' : 'Destination';
    document.getElementById('locSearchInput').value = '';
    document.getElementById('locationSearchResults').innerHTML = '<tr><td colspan="3" class="text-center text-muted py-4">Type to search and press Enter...</td></tr>';
    
    var modal = new bootstrap.Modal(document.getElementById("locationSearchModal"));
    modal.show();
    
    setTimeout(() => {
        document.getElementById('locSearchInput').focus();
        performLocationSearch(); // Auto fetch on open
    }, 200);
}

function performLocationSearch() {
    let kw = document.getElementById('locSearchInput').value;
    let tbody = document.getElementById('locationSearchResults');
    tbody.innerHTML = '<tr><td colspan="3" class="text-center py-4"><i class="fa-solid fa-spinner fa-spin me-2"></i>Searching...</td></tr>';
    
    let url = (typeof baseUrl !== 'undefined' ? baseUrl : (window.location.origin + '/flystarcourier/public')) + '/admin/searchLookup';
    // Use branch endpoint if in branch panel
    if (window.location.href.indexOf('/branch/') !== -1) {
        url = url.replace('/admin/', '/branch/');
    }
    
    // Using type=State because user requested states data
    fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' },
        body: 'type=State&keyword=' + encodeURIComponent(kw)
    })
    .then(r => r.json())
    .then(res => {
        if(res.status === 'success' && res.data && res.data.length > 0) {
            let html = '';
            res.data.forEach(item => {
                let code = item.code || item.name.substring(0,3).toUpperCase();
                html += `<tr>
                    <td>${item.name}</td>
                    <td><span class="badge bg-secondary">${code}</span></td>
                    <td><button type="button" class="btn btn-sm btn-light border py-0 px-2" onclick="selectLocation('${item.name.replace(/'/g, "\\'")}', '${code.replace(/'/g, "\\'")}', '${item.name.replace(/'/g, "\\'")}')"><i class="fa-solid fa-check me-1"></i>Select</button></td>
                </tr>`;
            });
            tbody.innerHTML = html;
        } else {
            tbody.innerHTML = '<tr><td colspan="3" class="text-center text-muted py-4">No locations found.</td></tr>';
        }
    })
    .catch(e => {
        tbody.innerHTML = '<tr><td colspan="3" class="text-center text-danger py-4">Error searching.</td></tr>';
    });
}

function selectLocation(name, code, stateName) {
    if (currentLocTarget === 'origin') {
        document.getElementById('sender_city').value = name;
        if(document.getElementById('sender_city_code')) document.getElementById('sender_city_code').value = code;
        if(document.getElementById('sender_state') && stateName) document.getElementById('sender_state').value = stateName;
        // Trigger any dependent events
        let ev = new Event('change');
        document.getElementById('sender_city').dispatchEvent(ev);
    } else {
        document.getElementById('receiver_city').value = name;
        if(document.getElementById('receiver_city_code')) document.getElementById('receiver_city_code').value = code;
        if(document.getElementById('receiver_state') && stateName) document.getElementById('receiver_state').value = stateName;
        // Trigger any dependent events
        let ev = new Event('change');
        document.getElementById('receiver_city').dispatchEvent(ev);
        if(typeof calculatePrice === 'function') calculatePrice();
    }
    
    var modalEl = document.getElementById("locationSearchModal");
    var modal = bootstrap.Modal.getInstance(modalEl);
    if (modal) modal.hide();
}
</script>
<?= $this->endSection() ?>



