<?= $this->extend('admin/layout/main') ?>
<?= $this->section('title') ?>Customer Shipment Entry<?= $this->endSection() ?>

<?= $this->section('content') ?>
<?= $this->section('styles') ?>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
<style>
.select2-container--bootstrap-5 .select2-selection {
    font-size: 0.8rem !important;
    min-height: 28px !important;
    padding: 2px 8px !important;
}
.select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered {
    line-height: normal;
    padding-top: 2px;
}
</style>
<?= $this->endSection() ?>
<!-- Custom styles to match the provided screenshot UI -->
<style>
/* ===== Booking Form UI Styles ===== */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');

.ship-entry-form .row { display: flex; flex-wrap: wrap; margin-right: -8px; margin-left: -8px; }
.ship-entry-form .col-4 { flex: 0 0 auto; width: 33.33333333%; padding-right: 8px; padding-left: 8px; }
.ship-entry-form .col-12 { flex: 0 0 auto; width: 100%; padding-right: 8px; padding-left: 8px; }
.ship-entry-form .col-6 { flex: 0 0 auto; width: 50%; padding-right: 8px; padding-left: 8px; }
.ship-entry-form .col-5 { flex: 0 0 auto; width: 41.66666667%; padding-right: 8px; padding-left: 8px; }
.ship-entry-form .col-7 { flex: 0 0 auto; width: 58.33333333%; padding-right: 8px; padding-left: 8px; }
.ship-entry-form .col-md-2 { flex: 0 0 auto; width: 16.66666667%; padding-right: 8px; padding-left: 8px; }
.ship-entry-form .col-md-5 { flex: 0 0 auto; width: 41.66666667%; padding-right: 8px; padding-left: 8px; }
.ship-entry-form .d-flex, .d-flex { display: flex !important; }
.ship-entry-form .align-items-center, .align-items-center { align-items: center !important; }
.ship-entry-form .flex-grow-1 { flex-grow: 1 !important; }
.ship-entry-form .gap-1, .gap-1 { gap: 0.25rem !important; }
.ship-entry-form .gap-2, .gap-2 { gap: 0.5rem !important; }
.ship-entry-form .gap-3, .gap-3 { gap: 1rem !important; }
.ship-entry-form .w-100 { width: 100% !important; }
.ship-entry-form .form-control, .ship-entry-form .form-select { width: 100%; display: block; box-sizing: border-box; }
.ship-entry-form * { box-sizing: border-box; }
.ship-entry-form {
    font-family: 'Inter', sans-serif;
}
.ship-entry-form label {
    font-size: 0.72rem !important;
    font-weight: 700 !important;
    color: #6c757d !important;
    margin-bottom: 3px;
    text-transform: uppercase;
    letter-spacing: 0.4px;
}
.ship-entry-form .form-control,
.ship-entry-form .form-select {
    font-size: 0.8rem !important;
    padding: 6px 10px !important;
    border-radius: 6px !important;
    border: 1px solid #d1d5db !important;
    background: #fdfdfd !important;
    color: #1e293b !important;
    min-height: 34px;
    box-shadow: none !important;
}
.ship-entry-form .form-control:focus,
.ship-entry-form .form-select:focus {
    border-color: #3b82f6 !important;
    background: #fff !important;
}

/* Section Title Badges */
.section-title {
    color: white;
    border-radius: 20px;
    padding: 4px 14px;
    font-size: 0.75rem;
    position: absolute;
    top: -12px;
    left: 14px;
    font-weight: 700;
    z-index: 10;
    border: 2px solid #fff;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}
.section-title.account   { background-color: #701a75; }
.section-title.shipper   { background-color: #1e293b; }
.section-title.consignee { background-color: #1d4ed8; }
.section-title.services  { background-color: #15803d; }

/* Fieldset Cards */
.fieldset-box {
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    padding: 24px 14px 14px 14px;
    position: relative;
    margin-bottom: 16px;
    background: #fff;
    margin-top: 20px;
}

/* Form Action Buttons */
.btn-search-field {
    background-color: #1e293b;
    color: white;
    border: none;
    border-radius: 6px;
    width: 34px;
    height: 34px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}
.btn-search-field:hover { background-color: #0f172a; }

.btn-rate-compare {
    background-color: #1e293b;
    color: #fff;
    border: none;
    border-radius: 20px;
    padding: 5px 16px;
    font-size: 0.8rem;
    font-weight: 700;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}
.btn-rate-compare:hover { background-color: #0f172a; }

/* Input group appends */
.input-group-text-custom {
    background: #f8f9fa;
    border: 1px solid #d1d5db;
    border-left: none;
    border-radius: 0 6px 6px 0;
    font-size: 0.75rem;
    color: #6b7280;
    padding: 0 10px;
    display: flex;
    align-items: center;
    font-weight: 600;
}
.input-append-left input {
    border-right: none !important;
    border-radius: 6px 0 0 6px !important;
}

/* Booking Header Toolbar */
.booking-toolbar {
    background-color: #1958b9;
    border-radius: 8px;
    padding: 10px 16px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.booking-tab-btn {
    padding: 5px 16px;
    border-radius: 6px;
    border: none;
    font-size: 0.8rem;
    font-weight: 700;
    cursor: pointer;
    color: white;
    background: transparent;
}
.booking-tab-btn.active {
    background: #fff;
    color: #1958b9;
}
.booking-tab-btn:hover:not(.active) {
    background: rgba(255,255,255,0.1);
}
.btn-toolbar-icon {
    background: rgba(255,255,255,0.2);
    border: none;
    color: #fff;
    border-radius: 6px;
    width: 32px;
    height: 32px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 0.8rem;
    margin-right: 6px;
    cursor: pointer;
}
.btn-toolbar-icon:hover {
    background: rgba(255,255,255,0.3);
}
.awb-search-group {
    display: inline-flex;
    align-items: center;
    background: rgba(255,255,255,0.2);
    border-radius: 6px;
    overflow: hidden;
    height: 32px;
}
.awb-search-group input {
    background: transparent;
    border: none;
    outline: none;
    color: #fff;
    font-size: 0.8rem;
    padding: 0 10px;
    width: 200px;
}
.awb-search-group input::placeholder { color: rgba(255,255,255,0.7); }
.awb-search-group button {
    background: transparent;
    border: none;
    color: #fff;
    padding: 0 10px;
    cursor: pointer;
}
</style>

<!-- Booking Toolbar -->
<div class="booking-toolbar">
    <div class="d-flex align-items-center gap-3">
        <div class="d-flex gap-1">
            <button type="button" class="booking-tab-btn active" id="btn-awb" onclick="switchBookingTab('awb')">
                <i class="fa-solid fa-file-contract me-1"></i> AWB
            </button>
            <button type="button" class="booking-tab-btn" id="btn-kyc" onclick="switchBookingTab('kyc')">
                <i class="fa-solid fa-id-card me-1"></i> KYC
            </button>
        </div>
        <div style="color:rgba(255,255,255,0.7);font-size:0.75rem;">
            New Shipment Booking
        </div>
    </div>
    <div class="d-flex align-items-center">
        <button type="button" class="btn-toolbar-icon" title="Filter" onclick="alert('Filter coming soon!')">
            <i class="fa-solid fa-filter"></i>
        </button>
        <button type="button" class="btn-toolbar-icon" title="Column Layout" onclick="alert('Column layout coming soon!')">
            <i class="fa-solid fa-table-columns"></i>
        </button>
        <div class="awb-search-group">
            <input type="text" placeholder="Search By AWB No." id="awb-search-input">
            <button type="button" onclick="alert('AWB Search coming soon!')">
                <i class="fa-solid fa-magnifying-glass"></i>
            </button>
        </div>
    </div>
</div>

<?php if (session()->has('error')): ?>
    <div class="alert alert-danger py-2 px-3 mb-3 small">
        <?= session('error') ?>
    </div>
<?php endif ?>

<form action="<?= isset($submit_url) ? $submit_url : base_url('admin/shipments/store') ?>" method="POST" id="bookingForm" class="ship-entry-form">
    <input type="hidden" name="branch_id" value="<?= session()->get('branch_id') ?? 1 ?>">
    
    <!-- Account Details -->
    <div class="fieldset-box mt-3">
        <span class="section-title account">
            <i class="fa-solid fa-user-tie"></i> Account Details
        </span>
        <div class="row g-2 align-items-center">
            <div class="col-md-2">
                <label>Book Date *</label>
                <div class="d-flex gap-1">
                    <div class="d-flex position-relative flex-grow-1">
                        <input type="date" name="book_date" class="form-control w-100" value="<?= date('Y-m-d') ?>" required>
                    </div>
                    <div class="d-flex position-relative" style="width: 90px;">
                        <input type="time" name="book_time" class="form-control w-100" value="<?= date('H:i') ?>">
                    </div>
                </div>
            </div>
            <div class="col-md-5">
                <label>Client Name *</label>
                <div class="d-flex gap-2">
                    <select name="customer_id" id="customer_id" class="form-select flex-grow-1" required onchange="onClientChange()">
                        <option value="">Select Client Account</option>
                        <?php foreach($customers as $c): ?>
                            <option value="<?= $c['id'] ?>" 
                                    data-name="<?= esc($c['first_name'] . ' ' . ($c['last_name'] ?? '')) ?>" 
                                    data-phone="<?= esc($c['phone'] ?? '') ?>" 
                                    data-address="<?= esc($c['address'] ?? '') ?>" 
                                    data-pincode="<?= esc($c['pincode'] ?? '400001') ?>">
                                <?= esc($c['first_name'] . ' ' . $c['last_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="d-flex align-items-center gap-2" style="width: 220px;">
                        <input type="text" name="client_code" id="client_code" class="form-control bg-light" readonly placeholder="Client Code">
                        <i class="fa-solid fa-pen text-secondary" style="cursor:pointer;" onclick="var cc = document.getElementById('client_code'); cc.readOnly = !cc.readOnly; if(!cc.readOnly) cc.focus();" title="Edit Client Code"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-3">
        <!-- Shipper Details -->
        <div class="col-4">
            <div class="fieldset-box h-100">
                <span class="section-title shipper">
                    <i class="fa-solid fa-box-open"></i> Shipper Details
                </span>
                <div class="row g-2">
                    <div class="col-12">
                        <label>Origin *</label>
                        <div class="d-flex gap-1">
                            <input type="text" name="sender_city" id="sender_city" class="form-control" required value="HYDERABAD">
                            <input type="text" class="form-control bg-light" value="HYD" readonly style="width: 70px;">
                            <button type="button" class="btn-search-field"><i class="fa-solid fa-magnifying-glass"></i></button>
                        </div>
                    </div>

                    <div class="col-12">
                        <label>Company Name *</label>
                        <div class="d-flex gap-1">
                            <input type="text" name="sender_company" id="sender_company" class="form-control" required>
                            <button type="button" class="btn-search-field"><i class="fa-solid fa-magnifying-glass"></i></button>
                        </div>
                    </div>

                    <div class="col-5">
                        <label>Contact Name</label>
                        <input type="text" name="sender_name" id="sender_name" class="form-control">
                    </div>
                    <div class="col-7">
                        <label>Address 1</label>
                        <input type="text" name="sender_address" id="sender_address" class="form-control">
                    </div>

                    <div class="col-12">
                        <label>Address 2</label>
                        <input type="text" name="sender_address_2" id="sender_address_2" class="form-control">
                    </div>

                    <div class="col-5">
                        <label>Pincode</label>
                        <input type="text" name="sender_pincode" id="sender_pincode" class="form-control" required value="400001">
                    </div>
                    <div class="col-7">
                        <label>City</label>
                        <input type="text" id="sender_city_display" class="form-control">
                    </div>

                    <div class="col-5">
                        <label>State</label>
                        <input type="text" name="sender_state" id="sender_state" class="form-control">
                    </div>
                    <div class="col-7">
                        <label>Telephone</label>
                        <input type="text" name="sender_phone" id="sender_phone" class="form-control">
                    </div>

                    <div class="col-5">
                        <label>Mobile No *</label>
                        <input type="text" name="sender_mobile" id="sender_mobile" class="form-control" required>
                    </div>
                    <div class="col-7">
                        <label>E-Mail</label>
                        <input type="email" name="sender_email" id="sender_email" class="form-control">
                    </div>

                    <div class="col-5">
                        <label>Country</label>
                        <input type="text" name="sender_country" value="INDIA" class="form-control bg-light" readonly>
                    </div>
                    <div class="col-7">
                        <label>IEC No.</label>
                        <input type="text" name="sender_iec_no" class="form-control">
                    </div>

                    <div class="col-5">
                        <label>Document Type</label>
                        <select name="sender_document_type" class="form-select">
                            <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-7">
                        <label>Document No.</label>
                        <input type="text" name="sender_document_no" class="form-control">
                    </div>
                </div>
            </div>
        </div>

        <!-- Consignee Details -->
        <div class="col-4">
            <div class="fieldset-box h-100">
                <span class="section-title consignee">
                    <i class="fa-solid fa-location-dot"></i> Consignee Details
                </span>
                <div class="row g-2">
                    <div class="col-12">
                        <label>Destination *</label>
                        <div class="d-flex gap-1">
                            <input type="text" name="receiver_city" id="receiver_city" class="form-control" required onchange="calculatePrice()">
                            <input type="text" class="form-control bg-light" readonly style="width: 70px;">
                            <button type="button" class="btn-search-field"><i class="fa-solid fa-magnifying-glass"></i></button>
                        </div>
                    </div>

                    <div class="col-12">
                        <label>Company Name *</label>
                        <div class="d-flex gap-1">
                            <input type="text" name="receiver_company" class="form-control" required>
                            <button type="button" class="btn-search-field"><i class="fa-solid fa-magnifying-glass"></i></button>
                        </div>
                    </div>

                    <div class="col-5">
                        <label>Contact Name</label>
                        <input type="text" name="receiver_name" class="form-control">
                    </div>
                    <div class="col-7">
                        <label>Address 1 *</label>
                        <input type="text" name="receiver_address" id="receiver_address" class="form-control" required>
                    </div>

                    <div class="col-12">
                        <label>Address 2</label>
                        <input type="text" name="receiver_address_2" class="form-control">
                    </div>

                    <div class="col-5">
                        <label>Pincode *</label>
                        <input type="text" name="receiver_pincode" id="receiver_pincode" class="form-control" required onchange="lookupPincode()">
                    </div>
                    <div class="col-7">
                        <label>City *</label>
                        <input type="text" id="receiver_city_display" class="form-control" oninput="document.getElementById('receiver_city').value = this.value">
                    </div>

                    <div class="col-5">
                        <label>State *</label>
                        <input type="text" name="receiver_state" id="receiver_state" class="form-control">
                    </div>
                    <div class="col-7">
                        <label>Telephone *</label>
                        <input type="text" name="receiver_phone" class="form-control" required>
                    </div>

                    <div class="col-5">
                        <label>Mobile No.</label>
                        <input type="text" name="receiver_mobile" class="form-control">
                    </div>
                    <div class="col-7">
                        <label>E-Mail</label>
                        <input type="email" name="receiver_email" class="form-control">
                    </div>

                    <div class="col-5">
                        <label>Country</label>
                        <input type="text" name="receiver_country" value="INDIA" class="form-control bg-light" readonly>
                    </div>
                    <div class="col-7">
                        <label>IEC No.</label>
                        <input type="text" name="receiver_iec_no" class="form-control">
                    </div>

                    <div class="col-5">
                        <label>Document Type</label>
                        <select name="receiver_document_type" class="form-select">
                            <option value="Select">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-7">
                        <label>Document No.</label>
                        <input type="text" name="receiver_document_no" class="form-control">
                    </div>
                </div>
            </div>
        </div>

        <!-- Services Details -->
        <div class="col-4">
            <div class="fieldset-box h-100 d-flex flex-column">
                <span class="section-title services">
                    <i class="fa-solid fa-truck-fast"></i> Services Details
                </span>
                <div class="row g-2 flex-grow-1">
                    <div class="col-12">
                        <label>Product *</label>
                        <div class="d-flex gap-1">
                            <select name="product" class="form-select flex-grow-1" required>
                                <option value="DOMESTIC">DOMESTIC</option>
                                <option value="INTERNATIONAL">INTERNATIONAL</option>
                            </select>
                            <button type="button" class="btn-search-field"><i class="fa-solid fa-magnifying-glass"></i></button>
                        </div>
                    </div>

                    <div class="col-12">
                        <label>Vendor *</label>
                        <div class="d-flex gap-1">
                            <input type="text" name="vendor" class="form-control" value="UNITED XPRESS SERVICE" required>
                            <input type="text" class="form-control bg-light" value="UEX" readonly style="width: 70px;">
                            <button type="button" class="btn-search-field"><i class="fa-solid fa-magnifying-glass"></i></button>
                        </div>
                    </div>

                    <div class="col-12">
                        <label>Service *</label>
                        <div class="d-flex gap-1">
                            <select name="service_type_id" id="service_type_id" class="form-select flex-grow-1" required onchange="calculatePrice()">
                                <option value="">Select Service</option>
                                <?php foreach($services as $s): ?>
                                    <option value="<?= $s['id'] ?>"><?= esc($s['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <button type="button" class="btn-search-field"><i class="fa-solid fa-magnifying-glass"></i></button>
                        </div>
                    </div>

                    <div class="col-12 mt-2"></div>

                    <div class="col-6">
                        <label>Shipment Value</label>
                        <div class="d-flex input-append-left">
                            <input type="number" name="declared_value" id="declared_value" class="form-control w-100" value="0" onchange="calculatePrice()">
                            <span class="input-group-text-custom">INR</span>
                        </div>
                    </div>
                    <div class="col-6">
                        <label>Pieces *</label>
                        <div class="d-flex input-append-left">
                            <input type="number" name="pieces" id="total_pieces" class="form-control w-100" value="0" required>
                            <span class="input-group-text-custom">DOX</span>
                        </div>
                    </div>

                    <div class="col-12">
                        <label>Actual Weight *</label>
                        <div class="d-flex input-append-left">
                            <input type="number" step="0.01" name="actual_weight" id="total_weight" class="form-control w-100" value="0" required onchange="calculatePrice()">
                            <span class="input-group-text-custom" style="width: 50px; justify-content:center;">Kgs</span>
                        </div>
                    </div>

                    <div class="col-6">
                        <label>Volumetric Weight</label>
                        <input type="number" step="0.01" name="volumetric_weight" id="volumetric_weight" class="form-control" value="0" readonly>
                    </div>
                    <div class="col-6">
                        <label>Charge Weight *</label>
                        <input type="number" step="0.01" name="charge_weight" id="charge_weight" class="form-control bg-light" value="0" required readonly>
                    </div>

                    <div class="col-6 mt-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="is_commercial" value="1" id="is_commercial">
                            <label class="form-check-label text-dark fw-medium text-capitalize" style="font-size: 0.72rem !important; letter-spacing:0;" for="is_commercial">Commercial</label>
                        </div>
                        <div class="form-check mt-2">
                            <input class="form-check-input" type="checkbox" name="medical_charges" value="1" id="medical_charges">
                            <label class="form-check-label text-dark fw-medium text-capitalize" style="font-size: 0.72rem !important; letter-spacing:0;" for="medical_charges">Medical Charges</label>
                        </div>
                    </div>
                    <div class="col-6 mt-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="is_oda" value="1" id="is_oda" onchange="calculatePrice()">
                            <label class="form-check-label text-dark fw-medium text-capitalize" style="font-size: 0.72rem !important; letter-spacing:0;" for="is_oda">ODA</label>
                        </div>
                    </div>

                    <div class="col-12 text-end mt-auto pt-2">
                        <button type="button" class="btn-rate-compare" onclick="window.open('<?= base_url('admin/rate-compare') ?>', '_blank')">
                            <i class="fa-solid fa-scale-balanced"></i> Rate Compare
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Hidden pricing fields required by backend -->
    <input type="hidden" name="payment_mode" id="payment_mode" value="prepaid">
    <input type="hidden" name="freight_charge" id="h_freight" value="0">
    <input type="hidden" name="fuel_surcharge" id="h_fuel" value="0">
    <input type="hidden" name="handling_charge" id="h_handling" value="0">
    <input type="hidden" name="packing_charge" id="h_packing" value="0">
    <input type="hidden" name="pickup_charge" id="h_pickup" value="0">
    <input type="hidden" name="delivery_charge" id="h_delivery" value="0">
    <input type="hidden" name="remote_area_charge" id="h_remote" value="0">
    <input type="hidden" name="cod_charge" id="h_cod" value="0">
    <input type="hidden" name="insurance_charge" id="h_insurance" value="0">
    <input type="hidden" name="discount_amount" id="h_discount" value="0">
    <input type="hidden" name="sub_total" id="h_subtotal" value="0">
    <input type="hidden" name="taxable_amount" id="h_taxable" value="0">
    <input type="hidden" name="cgst" id="h_cgst" value="0">
    <input type="hidden" name="sgst" id="h_sgst" value="0">
    <input type="hidden" name="igst" id="h_igst" value="0">
    <input type="hidden" name="total_tax" id="h_totaltax" value="0">
    <input type="hidden" name="grand_total" id="h_grand" value="0">
    <!-- 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"><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>

    <!-- 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">
                                    <option>CSB 4</option>
                                    <option>CSB 5</option>
                                    <option>CSB 3</option>
                                    <option>COMMERCIAL</option>
                                    <option>ECM DOX</option>
                                    <option>ECM SPX</option>
                                    <option>CBE XII</option>
                                    <option>CBE XIII</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label>Term Of Invoice</label>
                                <select class="form-select form-select-sm">
                                    <option>Select</option>
                                    <option>Cost and Freight(CFR)</option>
                                    <option>Cost, Insurance and Freight(CIF)</option>
                                    <option>Carriage and Insurance Paid(CIP)</option>
                                    <option>Carriage Paid To(CPT)</option>
                                    <option>Delivered At Frontier(DAF)</option>
                                    <option>Delivered at Place(DAP)</option>
                                    <option>Delivered at Terminal(DAT)</option>
                                    <option>Delivery Duty Paid(DDP)</option>
                                    <option>Delivery Duty Unpaid(DDU)</option>
                                    <option>Delivered Ex Quay(DEQ)</option>
                                    <option>Delivered Ex Ship(DES)</option>
                                    <option>Ex Works(EXW)</option>
                                    <option>Free Along Side(FAS)</option>
                                    <option>Free Carrier(FCA)</option>
                                    <option>Free On Board(FOB)</option>
                                    <option>Unknown(UNK)</option>
                                </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">
                            </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">
                            </div>
                            <div class="col-md-4">
                                <label>Department No</label>
                                <input type="text" class="form-control form-control-sm">
                            </div>
                            <div class="col-md-3">
                                <label>Export Reason</label>
                                <select name="export_reason" class="form-select form-select-sm">
                                    <option>Bonafide Gift</option>
                                    <option>BUYER (IF OTHER THAN CONSIGNEE)</option>
                                    <option>Commercial</option>
                                    <option>FREE SAMPLE OF NO COMMERICAL VALUE</option>
                                    <option>Personal not for resale</option>
                                    <option>PERSONAL USE/GIFT PURPOSE ONLY</option>
                                    <option>Return after repair</option>
                                    <option>Return for repair</option>
                                    <option>Samples not for sale</option>
                                    <option>UNSOLICITED GIFT - NOT FOR SALE</option>
                                </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" value="0.00" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 100px;">
                            <label>Surcharge</label>
                            <input type="text" value="0.00" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 100px;">
                            <label>IGST</label>
                            <input type="text" value="0.00" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 100px;">
                            <label>CGST</label>
                            <input type="text" value="0.00" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 100px;">
                            <label>SGST</label>
                            <input type="text" value="0.00" readonly>
                        </div>
                        <div class="piece-input-group" style="min-width: 130px;">
                            <label>Total Amount</label>
                            <input type="text" 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>
                </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: 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: 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 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-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_address').value = option.getAttribute('data-address') || '';
        document.getElementById('sender_pincode').value = option.getAttribute('data-pincode') || '400001';
    }
    calculatePrice();
}

function calcPieceVol() {
    const l = parseFloat(document.getElementById('p_len').value) || 0;
    const w = parseFloat(document.getElementById('p_wid').value) || 0;
    const h = parseFloat(document.getElementById('p_hei').value) || 0;
    const div = parseFloat(document.getElementById('p_div').value) || 5000;
    const actWt = parseFloat(document.getElementById('p_act_wt').value) || 0;
    
    let volWt = 0;
    if (div > 0) {
        volWt = (l * w * h) / div;
    }
    
    document.getElementById('p_vol_wt').value = volWt.toFixed(2);
    document.getElementById('p_chrg_wt').value = Math.max(actWt, volWt).toFixed(2);
}

document.getElementById('p_act_wt').addEventListener('input', calcPieceVol);

function addPieceRow() {
    const actWt = parseFloat(document.getElementById('p_act_wt').value) || 0;
    const pcs = parseInt(document.getElementById('p_pcs').value) || 1;
    const len = parseFloat(document.getElementById('p_len').value) || 0;
    const wid = parseFloat(document.getElementById('p_wid').value) || 0;
    const hei = parseFloat(document.getElementById('p_hei').value) || 0;
    const volWt = parseFloat(document.getElementById('p_vol_wt').value) || 0;
    const chrgWt = parseFloat(document.getElementById('p_chrg_wt').value) || 0;
    
    if (actWt <= 0 && volWt <= 0) {
        alert("Please enter dimensions or actual weight.");
        return;
    }
    
    const tbody = document.getElementById('itemsBody');
    const tr = document.createElement('tr');
    tr.innerHTML = `
        <td>
            <input type="hidden" name="items[${itemCount}][description]" value="Piece ${itemCount+1}">
            Piece ${itemCount+1}
        </td>
        <td><input type="hidden" name="items[${itemCount}][weight]" class="weight-input" value="${actWt}">${actWt}</td>
        <td><input type="hidden" name="items[${itemCount}][quantity]" class="qty-input" value="${pcs}">${pcs}</td>
        <td><input type="hidden" name="items[${itemCount}][length]" value="${len}">${len}</td>
        <td><input type="hidden" name="items[${itemCount}][width]" value="${wid}">${wid}</td>
        <td><input type="hidden" name="items[${itemCount}][height]" value="${hei}">${hei}</td>
        <td><input type="hidden" name="items[${itemCount}][volumetric_weight]" class="vol-input" value="${volWt}">${volWt}</td>
        <td>${chrgWt}</td>
        <td><button type="button" class="btn btn-sm btn-danger py-0 px-2" onclick="this.closest('tr').remove(); updateTotals();"><i class="fa-solid fa-trash"></i></button></td>
    `;
    tbody.appendChild(tr);
    itemCount++;
    
    // Reset inputs
    document.getElementById('p_act_wt').value = 0;
    document.getElementById('p_pcs').value = 1;
    document.getElementById('p_len').value = 0;
    document.getElementById('p_wid').value = 0;
    document.getElementById('p_hei').value = 0;
    document.getElementById('p_vol_wt').value = 0;
    document.getElementById('p_chrg_wt').value = 0;
    
    updateTotals();
}

function updateTotals() {
    let totalWeight = 0;
    let totalVol = 0;
    let totalPieces = 0;
    const rows = document.getElementById('itemsBody').querySelectorAll('tr');
    
    rows.forEach(tr => {
        const qty = parseInt(tr.querySelector('.qty-input').value) || 0;
        const actualWt = parseFloat(tr.querySelector('.weight-input').value) || 0;
        const volWt = parseFloat(tr.querySelector('.vol-input').value) || 0;
        
        totalPieces += qty;
        totalWeight += actualWt;
        totalVol += volWt;
    });
    
    const chargeWeight = Math.max(totalWeight, totalVol);
    
    document.getElementById('total_pieces').value = totalPieces;
    document.getElementById('total_weight').value = totalWeight.toFixed(2);
    document.getElementById('volumetric_weight').value = totalVol.toFixed(2);
    document.getElementById('charge_weight').value = chargeWeight.toFixed(2);
    
    calculatePrice();
}

async function lookupPincode() {
    const input = document.getElementById('receiver_pincode');
    const state = document.getElementById('receiver_state');
    const val = input.value.trim();
    
    if (val.length < 3) return;
    
    try {
        const res = await fetch('<?= base_url("branch/shipments/lookupPincode") ?>?pincode=' + encodeURIComponent(val));
        const d = await res.json();
        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 (state) {
                state.value = d.data.state;
            }
            calculatePrice();
        }
    } 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;
    const totalWeight = parseFloat(document.getElementById('charge_weight').value) || 0;
    const declaredValue = parseFloat(document.getElementById('declared_value').value) || 0;
    
    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) {
        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);
    
    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') {
            errBox.classList.add('d-none');
            
            document.getElementById('d_subtotal').innerText = 'â‚¹' + parseFloat(d.sub_total).toFixed(2);
            document.getElementById('d_totaltax').innerText = 'â‚¹' + parseFloat(d.total_tax).toFixed(2);
            document.getElementById('d_grand_total').innerText = 'â‚¹' + parseFloat(d.grand_total).toFixed(2);

            document.getElementById('h_freight').value = d.freight_charge;
            document.getElementById('h_fuel').value = d.fuel_surcharge;
            document.getElementById('h_handling').value = d.handling_charge;
            document.getElementById('h_packing').value = d.packing_charge;
            document.getElementById('h_pickup').value = d.pickup_charge;
            document.getElementById('h_delivery').value = d.delivery_charge;
            document.getElementById('h_remote').value = d.remote_area_charge;
            document.getElementById('h_cod').value = d.cod_charge;
            document.getElementById('h_insurance').value = d.insurance_charge;
            document.getElementById('h_discount').value = d.discount_amount;
            document.getElementById('h_subtotal').value = d.sub_total;
            document.getElementById('h_taxable').value = d.taxable_amount;
            document.getElementById('h_cgst').value = d.cgst;
            document.getElementById('h_sgst').value = d.sgst;
            document.getElementById('h_igst').value = d.igst;
            document.getElementById('h_totaltax').value = d.total_tax;
            document.getElementById('h_grand').value = d.grand_total;
            
        } else {
            errBox.classList.remove('d-none');
            errMsg.innerText = d.message;
        }
    } catch (e) {
        console.error(e);
    }
}

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 prev1 = btn.parentElement.previousElementSibling;
            if (prev1) {
                label = prev1.querySelector('label');
                if (label && label.innerHTML.includes('&nbsp;')) {
                    let prev2 = prev1.previousElementSibling;
                    if (prev2) {
                        label = prev2.querySelector('label');
                    }
                }
            }
            let context = label ? label.innerText.replace('*', '').trim() : 'Lookup';
            document.getElementById('searchModalTitle').innerText = 'Search ' + context;
            
            // Show modal
            if (typeof bootstrap !== 'undefined') {
                var searchModal = new bootstrap.Modal(document.getElementById('genericSearchModal'));
                searchModal.show();
            } else {
                alert('Search ' + context + ' functionality coming soon!');
            }
        });
    });
});

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"]');
    const partySelect = document.querySelector('select[name="kyc_party"]');
    const docNoInput = document.querySelector('input[name="kyc_document_no"]');
    
    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 ? typeSelect.value : '');
    formData.append('kyc_party', partySelect ? partySelect.value : 'sender');
    formData.append('kyc_document_no', docNoInput ? docNoInput.value : '');
    
    try {
        const res = await fetch('<?= base_url('admin/bookings/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>
                    <input type="hidden" name="kyc_docs[${d.data.id}][file_name]" value="${d.data.file_name}">
                    <input type="hidden" name="kyc_docs[${d.data.id}][file_path]" value="${d.data.file_path}">
                    <input type="hidden" name="kyc_docs[${d.data.id}][document_type]" value="${d.data.entry_type}">
                    <input type="hidden" name="kyc_docs[${d.data.id}][party_type]" value="${d.data.party_type}">
                    <input type="hidden" name="kyc_docs[${d.data.id}][document_no]" value="${d.data.document_no}">
                </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>

<?= $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(); // Trigger the logic when a client is selected
        });
    });
</script>

<?php if (!empty($google_maps_api_key)): ?>
<script src="https://maps.googleapis.com/maps/api/js?key=<?= esc($google_maps_api_key) ?>&libraries=places&callback=initGoogleMapsPlaces" async defer></script>
<script>
function initGoogleMapsPlaces() {
    const senderInput = document.getElementById('sender_address');
    const receiverInput = document.getElementById('receiver_address');

    if (senderInput) {
        const senderAutocomplete = new google.maps.places.Autocomplete(senderInput);
        senderAutocomplete.addListener('place_changed', function() {
            const place = senderAutocomplete.getPlace();
            fillAddressComponents(place, 'sender');
        });
    }

    if (receiverInput) {
        const receiverAutocomplete = new google.maps.places.Autocomplete(receiverInput);
        receiverAutocomplete.addListener('place_changed', function() {
            const place = receiverAutocomplete.getPlace();
            fillAddressComponents(place, 'receiver');
        });
    }
}

function fillAddressComponents(place, prefix) {
    if (!place.address_components) return;

    let city = '';
    let state = '';
    let country = '';
    let pincode = '';

    place.address_components.forEach(component => {
        const types = component.types;
        if (types.includes('locality')) {
            city = component.long_name;
        }
        if (types.includes('administrative_area_level_1')) {
            state = component.long_name;
        }
        if (types.includes('country')) {
            country = component.long_name;
        }
        if (types.includes('postal_code')) {
            pincode = component.long_name;
        }
    });

    if (document.getElementById(prefix + '_city') && city) document.getElementById(prefix + '_city').value = city;
    if (document.getElementById(prefix + '_state') && state) document.getElementById(prefix + '_state').value = state;
    if (document.getElementById(prefix + '_country') && country) document.getElementById(prefix + '_country').value = country;
    if (document.getElementById(prefix + '_pincode') && pincode) {
        const pinInput = document.getElementById(prefix + '_pincode');
        pinInput.value = pincode;
        if (typeof calculatePrice === 'function') {
            calculatePrice();
        }
    }
}
</script>
<?php endif; ?>

<?= $this->endSection() ?>

