@extends('layouts.app')

@section('title', 'Create Booking')
@section('page-title', 'Create New Booking')

@section('content')
<style>
    @import url('https://fonts.googleapis.com/css2?family=Noto+Nastaliq+Urdu:wght@400;700&display=swap');
    .urdu-font {
        font-family: 'Noto Nastaliq Urdu', serif;
        direction: rtl;
    }
</style>

<div class="max-w-7xl mx-auto px-2 sm:px-4 lg:px-6">
    <!-- Compact Header -->
    <div class="mb-3 sm:mb-4 md:mb-6">
        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 sm:gap-0">
            <div>
                <h2 class="text-lg sm:text-xl md:text-2xl font-bold text-gray-800">Create New Booking</h2>
                <p class="text-gray-500 text-xs sm:text-sm mt-0.5">Fill in the details below</p>
            </div>
            <!-- Booking Type Badge -->
            @if(request('type') == 'international')
                <span class="inline-flex items-center px-2 sm:px-3 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800 whitespace-nowrap">
                    <i class="fas fa-plane mr-1 sm:mr-1.5"></i> International {{ request('country') ? '- ' . request('country') : '' }}
                </span>
            @else
                <span class="inline-flex items-center px-2 sm:px-3 py-1 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800 whitespace-nowrap">
                    <i class="fas fa-truck mr-1 sm:mr-1.5"></i> Domestic
                </span>
            @endif
        </div>
    </div>

    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
        <div class="bg-gradient-to-r from-purple-600 to-indigo-600 px-3 sm:px-4 py-2.5 sm:py-3">
            <h3 class="text-xs sm:text-sm font-semibold text-white flex items-center">
                <i class="fas fa-box-open mr-2"></i> Booking Information
            </h3>
        </div>

        <form action="{{ route('bookings.store') }}" method="POST" class="p-3 sm:p-4 md:p-5 lg:p-6">
            @csrf
            
            <!-- Display Validation Errors -->
            @if ($errors->any())
                <div class="mb-6 bg-red-50 border-l-4 border-red-500 p-4 rounded">
                    <div class="flex items-start">
                        <div class="flex-shrink-0">
                            <i class="fas fa-exclamation-circle text-red-500 text-lg"></i>
                        </div>
                        <div class="ml-3 flex-1">
                            <h3 class="text-sm font-semibold text-red-800 mb-2">Please fix the following errors:</h3>
                            <ul class="list-disc list-inside text-sm text-red-700 space-y-1">
                                @foreach ($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    </div>
                </div>
            @endif
            
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 md:gap-5">
                <!-- CNTR No -->
                <div class="col-span-1">
                    <label class="block text-xs sm:text-sm font-semibold text-gray-700 mb-1 sm:mb-1.5">
                        CNTR NO <span class="urdu-font float-right text-gray-500 text-xs">کنٹینر نمبر</span>
                    </label>
                    <div class="relative rounded-md shadow-sm">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <i class="fas fa-hashtag text-gray-400 text-xs"></i>
                        </div>
                        <input type="text" name="cntr_no" value="{{ old('cntr_no') }}" required
                            class="pl-9 w-full px-3 py-2 sm:py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-purple-600 focus:border-purple-600 transition duration-150 ease-in-out"
                            placeholder="Enter Container No">
                    </div>
                </div>

                <!-- Customer Selection -->
                <div class="col-span-1 sm:col-span-2 lg:col-span-3">
                    <label class="block text-xs sm:text-sm font-semibold text-gray-700 mb-1 sm:mb-1.5">
                        Customer <span class="urdu-font float-right text-gray-500 text-xs">کسٹمر</span>
                    </label>
                    <div class="flex flex-col sm:flex-row gap-2">
                        <div class="relative flex-1 rounded-md shadow-sm">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fas fa-user text-gray-400 text-xs"></i>
                            </div>
                            <select name="customer_id" id="customer_id" required onchange="fetchCustomerRate()"
                                class="pl-9 w-full px-3 py-2 sm:py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-purple-600 focus:border-purple-600 transition duration-150 ease-in-out">
                                <option value="">Select Customer</option>
                                @foreach($customers as $customer)
                                    <option value="{{ $customer->id }}" {{ session('new_customer_id') == $customer->id ? 'selected' : '' }}>
                                        {{ $customer->name }} {{ $customer->cnic ? ' - ' . $customer->cnic : '' }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        <button type="button" onclick="openCustomerModal()" 
                            class="px-3 py-1.5 bg-green-600 text-white text-sm rounded hover:bg-green-700 flex items-center shadow-sm transition duration-150 ease-in-out">
                            <i class="fas fa-plus mr-1"></i>New
                        </button>
                    </div>
                </div>

                @if(session('success'))
                <div class="col-span-1 lg:col-span-4 mb-4">
                    <div class="bg-green-50 border border-green-200 text-green-800 px-4 py-3 rounded-lg flex items-center">
                        <i class="fas fa-check-circle mr-2"></i>
                        <span class="text-sm font-medium">{{ session('success') }}</span>
                    </div>
                </div>
                @endif

                <!-- Receiver Details Section -->
                <div class="col-span-1 lg:col-span-4 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4 border-t border-b border-gray-100 py-4 my-2">
                    <div class="col-span-1 sm:col-span-2 md:col-span-4 mb-1">
                         <h4 class="text-sm font-bold text-gray-700 flex justify-between items-center">
                            <span><i class="fas fa-user-check text-indigo-600 mr-2"></i>Receiver Details (Optional)</span>
                            <span class="urdu-font text-gray-500 text-xs">وصول کنندہ کی تفصیلات</span>
                        </h4>
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 mb-1.5">
                            Receiver Name <span class="urdu-font float-right text-gray-500 text-xs">نام</span>
                        </label>
                        <input type="text" name="receiver_name" value="{{ old('receiver_name') }}"
                            class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"
                            placeholder="Receiver Name">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 mb-1.5">
                            Receiver Phone <span class="urdu-font float-right text-gray-500 text-xs">فون نمبر</span>
                        </label>
                        <input type="text" name="receiver_phone" value="{{ old('receiver_phone') }}"
                            class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"
                            placeholder="Mobile No">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 mb-1.5">
                            Receiver CNIC <span class="urdu-font float-right text-gray-500 text-xs">شناختی کارڈ</span>
                        </label>
                        <input type="text" name="receiver_cnic" value="{{ old('receiver_cnic') }}"
                            class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"
                            placeholder="XXXXX-XXXXXXX-X">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 mb-1.5">
                            Receiver City <span class="urdu-font float-right text-gray-500 text-xs">شہر</span>
                        </label>
                        <input type="text" name="receiver_city" value="{{ old('receiver_city') }}"
                            class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"
                            placeholder="City">
                    </div>
                </div>

                <!-- Dates Section -->
                <div class="col-span-1 lg:col-span-4 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4 border-t border-b border-gray-100 py-4 my-2">
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 mb-1.5">
                            Booking Date <span class="urdu-font float-right text-gray-500 text-xs">بکنگ کی تاریخ</span>
                        </label>
                        <input type="date" name="booking_date" value="{{ old('booking_date', date('Y-m-d')) }}" required
                            class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 mb-1.5">
                            Loading Date <span class="urdu-font float-right text-gray-500 text-xs">لوڈنگ کی تاریخ</span>
                        </label>
                        <input type="date" name="loading_date" value="{{ old('loading_date') }}"
                            class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 mb-1.5">
                            Shipping Date <span class="urdu-font float-right text-gray-500 text-xs">شپنگ کی تاریخ</span>
                        </label>
                        <input type="date" name="shipping_date" value="{{ old('shipping_date') }}"
                            class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition">
                    </div>
                </div>

                <!-- Locations -->
                <div class="col-span-1 lg:col-span-4 grid grid-cols-1 sm:grid-cols-2 gap-4 mb-3">
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 mb-1.5">
                            Origin City <span class="urdu-font float-right text-gray-500 text-xs">روانگی کا شہر</span>
                        </label>
                        <input type="text" name="origin_city" value="{{ old('origin_city') }}"
                            class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"
                            placeholder="e.g. Karachi">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 mb-1.5">
                            Destination City <span class="urdu-font float-right text-gray-500 text-xs">منزل کا شہر</span>
                        </label>
                        <input type="text" name="destination_city" value="{{ old('destination_city') }}"
                            class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"
                            placeholder="e.g. Lahore">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 mb-1.5">
                            Pickup Location <span class="urdu-font float-right text-gray-500 text-xs">پک اپ کی جگہ</span>
                        </label>
                        <div class="relative rounded-lg shadow-sm">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fas fa-map-marker-alt text-gray-400 text-xs"></i>
                            </div>
                            <input type="text" name="pickup_location" value="{{ old('pickup_location') }}" required
                                class="pl-9 w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"
                                placeholder="Full Address">
                        </div>
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 mb-1.5">
                            Delivery Location <span class="urdu-font float-right text-gray-500 text-xs">ڈلیوری کی جگہ</span>
                        </label>
                        <div class="relative rounded-lg shadow-sm">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fas fa-map-marker-alt text-gray-400 text-xs"></i>
                            </div>
                            <input type="text" name="delivery_location" value="{{ old('delivery_location') }}" required
                                class="pl-9 w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"
                                placeholder="Full Address">
                        </div>
                    </div>
                </div>

                <!-- Cargo Items Section - Simplified -->
                <div class="col-span-1 md:col-span-2 lg:col-span-4 mt-5">
                    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 border-b-2 border-indigo-200 pb-3 mb-4">
                        <h4 class="text-sm sm:text-base font-bold text-gray-800 flex items-center">
                            <i class="fas fa-boxes text-indigo-600 mr-2"></i>
                            <span class="hidden sm:inline">Cargo Items</span>
                            <span class="sm:hidden">Items</span>
                            <span class="urdu-font text-gray-500 text-xs sm:text-sm ml-2 sm:ml-3">سامان کی تفصیلات</span>
                        </h4>
                        <button type="button" onclick="addSimpleItem()" class="w-full sm:w-auto px-3 sm:px-4 py-2 bg-indigo-600 text-white text-xs sm:text-sm font-medium rounded-lg hover:bg-indigo-700 shadow-md transition duration-150 ease-in-out flex items-center justify-center">
                            <i class="fas fa-plus mr-2"></i> Add Product
                        </button>
                    </div>
                    
                    <!-- Desktop Table View -->
                    <div class="hidden md:block overflow-x-auto border-2 border-gray-200 rounded-xl shadow-sm">
                        <table class="min-w-full divide-y divide-gray-200" id="simple_items_table">
                            <thead class="bg-gradient-to-r from-indigo-50 to-purple-50">
                                <tr>
                                    <th scope="col" class="px-3 py-3 text-left text-xs font-bold text-gray-700 uppercase">
                                        Description<br><span class="urdu-font text-[10px] font-normal text-gray-500">تفصیل</span>
                                    </th>
                                    <th scope="col" class="px-3 py-3 text-center text-xs font-bold text-gray-700 uppercase w-24">
                                        Quantity<br><span class="urdu-font text-[10px] font-normal text-gray-500">تعداد</span>
                                    </th>
                                    <th scope="col" class="px-3 py-3 text-center text-xs font-bold text-gray-700 uppercase w-28">
                                        Unit<br><span class="urdu-font text-[10px] font-normal text-gray-500">یونٹ</span>
                                    </th>
                                    <th scope="col" class="px-3 py-3 text-center text-xs font-bold text-gray-700 uppercase w-40">
                                        Additional Info<br><span class="urdu-font text-[10px] font-normal text-gray-500">اضافی معلومات</span>
                                    </th>
                                    <th scope="col" class="px-3 py-3 text-center text-xs font-bold text-gray-700 uppercase w-32">
                                        Rate/Unit<br><span class="urdu-font text-[10px] font-normal text-gray-500">فی یونٹ ریٹ</span>
                                    </th>
                                    <th scope="col" class="px-3 py-3 text-right text-xs font-bold text-gray-700 uppercase w-32">
                                        Amount<br><span class="urdu-font text-[10px] font-normal text-gray-500">رقم</span>
                                    </th>
                                    <th scope="col" class="px-3 py-3 text-center text-xs font-bold text-gray-700 uppercase w-16">
                                        Action
                                    </th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200" id="simple_items_body">
                                <!-- Rows will be added via JS -->
                            </tbody>
                            <tfoot class="bg-gradient-to-r from-gray-50 to-gray-100 font-bold border-t-2 border-indigo-200">
                                <tr>
                                    <td colspan="5" class="px-3 py-3 text-right text-sm uppercase text-gray-700">
                                        <span class="urdu-font ml-2">کل رقم:</span> TOTAL:
                                    </td>
                                    <td class="px-3 py-3 text-right text-base text-indigo-700 font-bold">
                                        Rs. <span id="simple_total_amount">0.00</span>
                                    </td>
                                    <td></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>

                    <!-- Mobile Card View -->
                    <div class="md:hidden space-y-3" id="simple_items_mobile">
                        <!-- Cards will be added via JS -->
                    </div>
                    
                    <!-- Mobile Total -->
                    <div class="md:hidden mt-4 bg-gradient-to-r from-indigo-50 to-purple-50 rounded-lg p-4 border-2 border-indigo-200">
                        <div class="flex justify-between items-center">
                            <span class="text-sm font-bold text-gray-700 uppercase">
                                <span class="urdu-font">کل رقم:</span> TOTAL:
                            </span>
                            <span class="text-lg font-bold text-indigo-700">
                                Rs. <span id="simple_total_amount_mobile">0.00</span>
                            </span>
                        </div>
                    </div>
                                    <td></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>

                <!-- Payment Details Section -->
                <div class="col-span-1 md:col-span-2 lg:col-span-4 mt-2">
                    <div class="bg-white border border-gray-200 rounded-lg shadow-sm p-4">
                        <h4 class="text-sm font-bold text-gray-800 border-b pb-2 mb-4 flex justify-between items-center">
                            <span class="flex items-center">
                                <i class="fas fa-money-bill-wave text-green-600 mr-2"></i>
                                Payment Details
                            </span>
                            <span class="urdu-font text-green-600 text-xs">ادائیگی کی تفصیلات</span>
                        </h4>
                    
                    <!-- Rate Display (Hidden Inputs) -->
                    <input type="hidden" id="customer_rate_kg" value="0">
                    <input type="hidden" id="customer_rate_cbm" value="0">
                    <input type="hidden" id="rate_kg" value="0">
                    <input type="hidden" id="rate_cbm" value="0">
                    <input type="hidden" id="rate_carton" value="0">
                    
                    <!-- Calculated Charges to be saved -->
                    <input type="hidden" name="weight_kg" id="input_total_weight" value="0">
                    <input type="hidden" name="volume_cbm" id="input_total_vol" value="0">
                    <input type="hidden" name="carton_count" id="input_total_ctn" value="0">
                    
                    <input type="hidden" name="weight_charge" id="weight_charge" value="0">
                    <input type="hidden" name="volume_charge" id="volume_charge" value="0">
                    <input type="hidden" name="carton_charge" id="carton_charge" value="0">

                    <!-- Payment Summary -->
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                        <div>
                            <label class="block text-xs font-semibold text-gray-700 mb-1.5">
                                Total Amount * <span class="urdu-font float-right text-gray-500 text-xs">کل رقم</span>
                            </label>
                            <div class="relative rounded-md shadow-sm">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <span class="text-gray-500 text-xs font-bold">Rs.</span>
                                </div>
                                <input type="number" step="0.01" name="total_amount" id="total_amount" value="{{ old('total_amount', 0) }}" required
                                    oninput="calculateDue()"
                                    class="pl-9 w-full px-3 py-2 text-sm font-bold border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-green-500 bg-white transition duration-150">
                            </div>
                        </div>
                        <div>
                            <label class="block text-xs font-semibold text-gray-700 mb-1.5">
                                Discount <span class="urdu-font float-right text-gray-500 text-xs">رعایت</span>
                            </label>
                            <div class="relative rounded-md shadow-sm">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <span class="text-gray-500 text-xs">Rs.</span>
                                </div>
                                <input type="number" step="0.01" name="discount" id="discount" value="{{ old('discount', 0) }}"
                                    oninput="calculateDue()"
                                    class="pl-9 w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-green-500 transition duration-150">
                            </div>
                        </div>
                        <div>
                            <label class="block text-xs font-semibold text-gray-700 mb-1.5">
                                Advance <span class="urdu-font float-right text-gray-500 text-xs">ایڈوانس</span>
                            </label>
                            <div class="relative rounded-md shadow-sm">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <span class="text-gray-500 text-xs">Rs.</span>
                                </div>
                                <input type="number" step="0.01" name="advance_payment" id="advance_payment" value="{{ old('advance_payment', 0) }}"
                                    oninput="calculateDue()"
                                    class="pl-9 w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-green-500 focus:border-green-500 transition duration-150">
                            </div>
                        </div>
                        <div>
                            <label class="block text-xs font-semibold text-gray-700 mb-1.5">
                                Due Payment <span class="urdu-font float-right text-gray-500 text-xs">بقایا</span>
                            </label>
                            <div class="relative rounded-md shadow-sm">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <span class="text-gray-500 text-xs">Rs.</span>
                                </div>
                                <input type="number" step="0.01" id="due_payment" readonly
                                    class="pl-9 w-full px-3 py-2 text-sm font-bold border border-gray-300 rounded-md bg-red-50 text-red-600 cursor-not-allowed">
                            </div>
                        </div>
                    </div>
                    </div>
                </div>

                <!-- Descriptions -->
                <div class="col-span-1 md:col-span-2 lg:col-span-4 mt-2">
                    <label class="block text-xs font-semibold text-gray-700 mb-1">
                        Cargo Description <span class="urdu-font float-right text-gray-500 text-xs">سامان کی تفصیل</span>
                    </label>
                    <textarea name="cargo_description" rows="2" required
                        class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-purple-600 focus:border-purple-600 transition duration-150 ease-in-out"
                        placeholder="Details about the cargo...">{{ old('cargo_description') }}</textarea>
                </div>

                <div class="col-span-1 md:col-span-2 lg:col-span-4">
                    <label class="block text-xs font-semibold text-gray-700 mb-1">
                        Notes <span class="urdu-font float-right text-gray-500 text-xs">نوٹس</span>
                    </label>
                    <textarea name="notes" rows="1"
                        class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-purple-600 focus:border-purple-600 transition duration-150 ease-in-out"
                        placeholder="Additional notes...">{{ old('notes') }}</textarea>
                </div>
            </div>

            <div class="mt-6 sm:mt-8 flex flex-col sm:flex-row justify-end gap-3 border-t pt-5">
                <a href="{{ route('bookings.index') }}" class="w-full sm:w-auto px-6 py-2.5 border-2 border-gray-300 rounded-lg text-sm text-gray-700 hover:bg-gray-50 transition duration-150 ease-in-out font-medium flex items-center justify-center">
                    <i class="fas fa-times mr-2"></i> Cancel
                </a>
                <button type="submit" class="w-full sm:w-auto px-8 py-2.5 bg-gradient-to-r from-purple-600 to-indigo-600 text-white rounded-lg hover:shadow-xl hover:from-purple-700 hover:to-indigo-700 transition duration-150 ease-in-out font-semibold text-sm flex items-center justify-center">
                    <i class="fas fa-save mr-2"></i> Create Booking
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Customer Creation Modal -->
<div id="customerModal" class="fixed inset-0 z-50 hidden overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
    <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <!-- Background overlay -->
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true" onclick="closeCustomerModal()"></div>

        <!-- Modal panel -->
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-3xl sm:w-full">
            <div class="bg-gradient-to-r from-green-600 to-teal-600 px-4 py-3">
                <div class="flex justify-between items-center">
                    <h3 class="text-base font-semibold text-white" id="modal-title">
                        Add New Customer <span class="urdu-font ml-2 text-green-100 text-xs">نیا کسٹمر شامل کریں</span>
                    </h3>
                    <button type="button" onclick="closeCustomerModal()" class="text-green-100 hover:text-white focus:outline-none">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            
            <form id="customerForm" onsubmit="submitCustomerForm(event)">
                @csrf
                <div class="bg-white px-6 py-4">
                    <div id="formErrors" class="hidden mb-3 bg-red-100 border border-red-400 text-red-700 px-3 py-2 rounded relative text-sm"></div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-3">
                        <!-- Name -->
                        <div class="col-span-1">
                            <label class="block text-xs font-semibold text-gray-700 mb-1">Name *</label>
                            <input type="text" name="name" required class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-green-500">
                        </div>

                        <!-- CNIC -->
                        <div class="col-span-1">
                            <label class="block text-xs font-semibold text-gray-700 mb-1">CNIC</label>
                            <input type="text" name="cnic" class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-green-500">
                        </div>
                        
                        <!-- Email -->
                        <div class="col-span-1">
                            <label class="block text-xs font-semibold text-gray-700 mb-1">Email *</label>
                            <input type="email" name="email" required class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-green-500">
                        </div>
                        
                        <!-- Phone -->
                        <div class="col-span-1">
                            <label class="block text-xs font-semibold text-gray-700 mb-1">Phone *</label>
                            <input type="text" name="phone" required class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-green-500">
                        </div>
                        
                        <!-- Company -->
                        <div class="col-span-1">
                            <label class="block text-xs font-semibold text-gray-700 mb-1">Company Name</label>
                            <input type="text" name="company_name" class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-green-500">
                        </div>
                        
                        <!-- Address -->
                        <div class="col-span-2">
                            <label class="block text-xs font-semibold text-gray-700 mb-1">Address *</label>
                            <input type="text" name="address" required class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-green-500">
                        </div>
                        
                        <!-- City -->
                        <div class="col-span-1">
                            <label class="block text-xs font-semibold text-gray-700 mb-1">City *</label>
                            <input type="text" name="city" required class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-green-500">
                        </div>
                        
                        <!-- State -->
                        <div class="col-span-1">
                            <label class="block text-xs font-semibold text-gray-700 mb-1">State *</label>
                            <input type="text" name="state" required class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-green-500">
                        </div>
                        
                        <!-- Postal Code -->
                        <div class="col-span-1">
                            <label class="block text-xs font-semibold text-gray-700 mb-1">Postal Code *</label>
                            <input type="text" name="postal_code" required class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-green-500">
                        </div>
                        
                        <!-- Country -->
                        <div class="col-span-1">
                            <label class="block text-xs font-semibold text-gray-700 mb-1">Country *</label>
                            <input type="text" name="country" required value="Pakistan" class="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-green-500">
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-4 py-3 flex justify-end gap-3">
                    <button type="button" onclick="closeCustomerModal()" class="px-4 py-2 border border-gray-300 rounded text-sm text-gray-700 hover:bg-gray-100 font-medium">
                        Cancel
                    </button>
                    <button type="submit" class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 text-sm font-semibold shadow-sm">
                        Save Customer
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Customer Modal Functions
function openCustomerModal() {
    document.getElementById('customerModal').classList.remove('hidden');
}

function closeCustomerModal() {
    document.getElementById('customerModal').classList.add('hidden');
    document.getElementById('customerForm').reset();
    document.getElementById('formErrors').classList.add('hidden');
}

async function submitCustomerForm(event) {
    event.preventDefault();
    
    const form = document.getElementById('customerForm');
    const formData = new FormData(form);
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalBtnText = submitBtn.innerHTML;
    
    // Disable button and show loading state
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Saving...';
    
    // Clear previous errors
    const errorDiv = document.getElementById('formErrors');
    errorDiv.classList.add('hidden');
    errorDiv.innerHTML = '';

    try {
        const response = await fetch('{{ route("customers.store") }}', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            body: formData
        });

        const text = await response.text();
        let data;
        try {
            data = JSON.parse(text);
        } catch (e) {
            console.error('JSON Parse Error:', e);
            console.log('Server Response:', text);
            throw new Error('Server returned invalid JSON. See console for details.');
        }

        if (response.ok) {
            // Success
            // Add new customer to dropdown
            const select = document.getElementById('customer_id');
            const option = new Option(data.name, data.id);
            select.add(option, undefined); // Add to end
            select.value = data.id; // Select the new customer
            
            // Trigger change event to fetch rates if applicable (though new customer likely has no rates yet)
            fetchCustomerRate();
            
            // Add to customersData array for rate lookup (initially empty rates)
            customersData.push({
                id: data.id,
                name: data.name,
                rates: []
            });
            
            closeCustomerModal();
        } else {
            // Validation errors
            errorDiv.classList.remove('hidden');
            if (data.errors) {
                let errorHtml = '<ul class="list-disc pl-5">';
                for (const [key, messages] of Object.entries(data.errors)) {
                    messages.forEach(msg => {
                        errorHtml += `<li>${msg}</li>`;
                    });
                }
                errorHtml += '</ul>';
                errorDiv.innerHTML = errorHtml;
            } else {
                errorDiv.innerHTML = data.message || 'An error occurred while saving the customer.';
            }
        }
    } catch (error) {
        console.error('Error:', error);
        errorDiv.classList.remove('hidden');
        errorDiv.innerHTML = 'An unexpected error occurred. ' + error.message;
    } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalBtnText;
    }
}

// Parse customers data with rates from the controller
const customersData = @json($customers);
const globalRates = @json($globalRates ?? []);

// Get active rate (manual rates are always enabled)
function getActiveRate(type) {
    // Use optional chaining to prevent null errors
    if (type === 'kg') {
        return parseFloat(document.getElementById('rate_kg')?.value) || 0;
    }
    if (type === 'cbm') {
        return parseFloat(document.getElementById('rate_cbm')?.value) || 0;
    }
    if (type === 'carton') {
        return parseFloat(document.getElementById('rate_carton')?.value) || 0;
    }
    
    return 0;
}

function fetchCustomerRate() {
    const customerSelect = document.getElementById('customer_id');
    const customerId = parseInt(customerSelect?.value);
    
    // Reset rates with null safety
    const rateKgEl = document.getElementById('rate_kg');
    const rateCbmEl = document.getElementById('rate_cbm');
    const rateCartonEl = document.getElementById('rate_carton');
    
    if (rateKgEl) rateKgEl.value = 0;
    if (rateCbmEl) rateCbmEl.value = 0;
    if (rateCartonEl) rateCartonEl.value = 0;
    
    if(customerId) {
        const customer = customersData.find(c => c.id === customerId);
        const customerRates = customer ? (customer.rates || []) : [];

        // Helper to find rate
        const findRate = (type) => {
            // First check customer specific rates
            let rate = customerRates.find(r => r.rate_type && r.rate_type.toLowerCase() === type.toLowerCase() && r.is_active);
            if (rate) return rate;
            
            // Then check global rates
            rate = globalRates.find(r => r.rate_type && r.rate_type.toLowerCase() === type.toLowerCase() && r.is_active);
            if (rate) return rate;
            
            return null;
        };

        // Find and set rates
        const kgRate = findRate('kg');
        if (kgRate && rateKgEl) {
            const rateValue = parseFloat(kgRate.base_rate);
            rateKgEl.value = rateValue;
        }

        const cbmRate = findRate('cbm');
        if (cbmRate && rateCbmEl) {
            const rateValue = parseFloat(cbmRate.base_rate);
            rateCbmEl.value = rateValue;
        }

        let cartonRate = findRate('carton');
        if (!cartonRate) cartonRate = findRate('per carton');
        if (cartonRate && rateCartonEl) {
            const rateValue = parseFloat(cartonRate.base_rate);
            rateCartonEl.value = rateValue;
        }
    } else {
        // No customer selected, try global rates only
        const findGlobalRate = (type) => {
            return globalRates.find(r => r.rate_type && r.rate_type.toLowerCase() === type.toLowerCase() && r.is_active);
        };
        
        const kgRate = findGlobalRate('kg');
        if (kgRate && rateKgEl) {
            const rateValue = parseFloat(kgRate.base_rate);
            rateKgEl.value = rateValue;
        }
        
        const cbmRate = findGlobalRate('cbm');
        if (cbmRate && rateCbmEl) {
            const rateValue = parseFloat(cbmRate.base_rate);
            rateCbmEl.value = rateValue;
        }
        
        let cartonRate = findGlobalRate('carton');
        if (!cartonRate) cartonRate = findGlobalRate('per carton');
        if (cartonRate && rateCartonEl) {
            const rateValue = parseFloat(cartonRate.base_rate);
            rateCartonEl.value = rateValue;
        }
    }
    
    // Recalculate totals for all rows with new rates
    recalculateAllRows();
}

// Booking Items Logic
let itemRowIndex = 0;

// Apply rates from Rate Configuration to all items
function applyRatesToAll() {
    const kgRate = parseFloat(document.getElementById('rate_kg')?.value) || 0;
    const cbmRate = parseFloat(document.getElementById('rate_cbm')?.value) || 0;
    const cartonRate = parseFloat(document.getElementById('rate_carton')?.value) || 0;
    
    const rows = document.querySelectorAll('#booking_items_body tr');
    rows.forEach(row => {
        row.querySelector('input[name*="[rate_kg]"]').value = kgRate;
        row.querySelector('input[name*="[rate_cbm]"]').value = cbmRate;
        row.querySelector('input[name*="[rate_carton]"]').value = cartonRate;
        calculateRow(row.id);
    });
}

function addBookingItem(data = null) {
    const tableBody = document.getElementById('booking_items_body');
    const rowId = `item-row-${itemRowIndex}`;
    
    const tr = document.createElement('tr');
    tr.id = rowId;
    
    const description = data ? data.description : '';
    const quantity = data ? data.quantity : 0;
    const carton = data ? data.carton_count : 0;
    const weight = data ? data.weight_kg : 0;
    const volume = data ? data.volume_cbm : 0;
    
    // Get rates from Rate Configuration with null safety
    const rateKg = parseFloat(document.getElementById('rate_kg')?.value) || 0;
    const rateCbm = parseFloat(document.getElementById('rate_cbm')?.value) || 0;
    const rateCarton = parseFloat(document.getElementById('rate_carton')?.value) || 0;

    tr.innerHTML = `
        <td class="px-2 py-2">
            <input type="text" name="items[${itemRowIndex}][description]" value="${description}" required class="w-full text-xs border-gray-300 rounded focus:ring-purple-500 focus:border-purple-500">
        </td>
        <td class="px-2 py-2">
            <input type="number" name="items[${itemRowIndex}][quantity]" value="${quantity}" min="0" oninput="calculateRow('${rowId}')" class="w-16 text-xs border-gray-300 rounded focus:ring-purple-500 focus:border-purple-500">
        </td>
        <td class="px-2 py-2">
            <input type="number" name="items[${itemRowIndex}][carton_count]" value="${carton}" min="0" oninput="calculateRow('${rowId}')" class="w-16 text-xs border-gray-300 rounded focus:ring-purple-500 focus:border-purple-500">
        </td>
        <td class="px-2 py-2">
            <input type="number" step="0.01" name="items[${itemRowIndex}][weight_kg]" value="${weight}" min="0" oninput="calculateRow('${rowId}')" class="w-20 text-xs border-gray-300 rounded focus:ring-purple-500 focus:border-purple-500">
        </td>
        <td class="px-2 py-2">
            <input type="number" step="0.01" name="items[${itemRowIndex}][volume_cbm]" value="${volume}" min="0" oninput="calculateRow('${rowId}')" class="w-20 text-xs border-gray-300 rounded focus:ring-purple-500 focus:border-purple-500">
        </td>
        <td class="px-2 py-2">
            <input type="number" step="0.01" name="items[${itemRowIndex}][rate_kg]" value="${rateKg}" min="0" oninput="calculateRow('${rowId}')" class="w-20 text-xs border-gray-300 rounded focus:ring-purple-500 focus:border-purple-500 bg-blue-50">
        </td>
        <td class="px-2 py-2">
            <input type="number" step="0.01" name="items[${itemRowIndex}][rate_cbm]" value="${rateCbm}" min="0" oninput="calculateRow('${rowId}')" class="w-20 text-xs border-gray-300 rounded focus:ring-purple-500 focus:border-purple-500 bg-green-50">
        </td>
        <td class="px-2 py-2">
            <input type="number" step="0.01" name="items[${itemRowIndex}][rate_carton]" value="${rateCarton}" min="0" oninput="calculateRow('${rowId}')" class="w-20 text-xs border-gray-300 rounded focus:ring-purple-500 focus:border-purple-500 bg-yellow-50">
        </td>
        <td class="px-2 py-2">
            <input type="number" step="0.01" name="items[${itemRowIndex}][amount]" value="0" readonly class="w-24 text-xs bg-gray-50 font-bold border-gray-300 rounded focus:ring-purple-500 focus:border-purple-500">
        </td>
        <td class="px-2 py-2 text-center">
            <button type="button" onclick="removeBookingItem('${rowId}')" class="text-red-600 hover:text-red-800">
                <i class="fas fa-trash"></i>
            </button>
        </td>
    `;
    
    tableBody.appendChild(tr);
    itemRowIndex++;
}

function removeBookingItem(rowId) {
    const row = document.getElementById(rowId);
    if (row) {
        row.remove();
        calculateTotals();
    }
}

function calculateRow(rowId) {
    const row = document.getElementById(rowId);
    if (!row) return;
    
    const weight = parseFloat(row.querySelector('input[name*="[weight_kg]"]').value) || 0;
    const vol = parseFloat(row.querySelector('input[name*="[volume_cbm]"]').value) || 0;
    const ctn = parseFloat(row.querySelector('input[name*="[carton_count]"]').value) || 0;
    
    const rateKg = parseFloat(row.querySelector('input[name*="[rate_kg]"]').value) || 0;
    const rateCbm = parseFloat(row.querySelector('input[name*="[rate_cbm]"]').value) || 0;
    const rateCarton = parseFloat(row.querySelector('input[name*="[rate_carton]"]').value) || 0;
    
    const amountInput = row.querySelector('input[name*="[amount]"]');
    
    // Calculate amount based on: (Weight × KG Rate) + (Volume × CBM Rate) + (Carton × Carton Rate)
    let amount = 0;
    amount += weight * rateKg;
    amount += vol * rateCbm;
    amount += ctn * rateCarton;
    
    amountInput.value = amount.toFixed(2);
    
    calculateTotals();
}

function recalculateAllRows() {
    const rows = document.querySelectorAll('#booking_items_body tr');
    rows.forEach(row => {
        calculateRow(row.id);
    });
}

function calculateTotals() {
    let totalQty = 0;
    let totalCtn = 0;
    let totalWeight = 0;
    let totalVol = 0;
    let totalAmount = 0;
    
    const rows = document.querySelectorAll('#booking_items_body tr');
    rows.forEach(row => {
        totalQty += parseFloat(row.querySelector('input[name*="[quantity]"]')?.value) || 0;
        totalCtn += parseFloat(row.querySelector('input[name*="[carton_count]"]')?.value) || 0;
        totalWeight += parseFloat(row.querySelector('input[name*="[weight_kg]"]')?.value) || 0;
        totalVol += parseFloat(row.querySelector('input[name*="[volume_cbm]"]')?.value) || 0;
        totalAmount += parseFloat(row.querySelector('input[name*="[amount]"]')?.value) || 0;
    });
    
    // Update Footer with null safety
    const totalQtyEl = document.getElementById('total_qty');
    const totalCtnEl = document.getElementById('total_ctn');
    const totalWeightEl = document.getElementById('total_weight');
    const totalVolEl = document.getElementById('total_vol');
    const totalItemsAmountEl = document.getElementById('total_items_amount');
    
    if (totalQtyEl) totalQtyEl.textContent = totalQty;
    if (totalCtnEl) totalCtnEl.textContent = totalCtn;
    if (totalWeightEl) totalWeightEl.textContent = totalWeight.toFixed(2);
    if (totalVolEl) totalVolEl.textContent = totalVol.toFixed(2);
    if (totalItemsAmountEl) totalItemsAmountEl.textContent = totalAmount.toFixed(2);
    
    // Update Hidden Inputs for Server Validation
    const inputTotalWeightEl = document.getElementById('input_total_weight');
    const inputTotalVolEl = document.getElementById('input_total_vol');
    const inputTotalCtnEl = document.getElementById('input_total_ctn');
    
    if (inputTotalWeightEl) inputTotalWeightEl.value = totalWeight.toFixed(2);
    if (inputTotalVolEl) inputTotalVolEl.value = totalVol.toFixed(2);
    if (inputTotalCtnEl) inputTotalCtnEl.value = totalCtn;

    // Update Main Payment Fields - always update, user can manually override if needed
    const totalAmountEl = document.getElementById('total_amount');
    if (totalAmountEl) totalAmountEl.value = totalAmount.toFixed(2);
    
    calculateDue();
}

function calculateDue() {
    const totalAmountEl = document.getElementById('total_amount');
    const discountEl = document.getElementById('discount');
    const advanceEl = document.getElementById('advance_payment');
    const dueEl = document.getElementById('due_payment');
    
    const total = parseFloat(totalAmountEl?.value) || 0;
    const discount = parseFloat(discountEl?.value) || 0;
    const advance = parseFloat(advanceEl?.value) || 0;
    
    const due = total - discount - advance;
    if (dueEl) dueEl.value = due.toFixed(2);
}

// Initialize if old values exist
document.addEventListener('DOMContentLoaded', function() {
    const customerIdEl = document.getElementById('customer_id');
    if(customerIdEl?.value) {
        fetchCustomerRate();
    }
});

// ============================================
// SIMPLIFIED CARGO ITEMS FUNCTIONS
// ============================================
let simpleItemIndex = 0;

function addSimpleItem() {
    const tbody = document.getElementById('simple_items_body');
    const mobileContainer = document.getElementById('simple_items_mobile');
    const rowId = `simple_item_${simpleItemIndex}`;
    
    // Desktop Table Row
    const tr = document.createElement('tr');
    tr.id = rowId;
    tr.className = 'hover:bg-gray-50 transition-colors';
    
    tr.innerHTML = `
        <td class="px-3 py-2">
            <input type="text" 
                   name="simple_items[${simpleItemIndex}][description]" 
                   required 
                   placeholder="Product name..."
                   class="w-full px-2 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
        </td>
        <td class="px-3 py-2">
            <input type="number" 
                   name="simple_items[${simpleItemIndex}][quantity]" 
                   value="1" 
                   min="0.01"
                   step="0.01"
                   required 
                   oninput="calculateSimpleItemAmount('${rowId}')"
                   class="w-full px-2 py-1.5 text-sm text-center border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
        </td>
        <td class="px-3 py-2">
            <select name="simple_items[${simpleItemIndex}][unit]" 
                    required
                    class="w-full px-2 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 bg-white">
                <option value="KG">KG</option>
                <option value="PCS">PCS</option>
                <option value="CTN">CTN</option>
                <option value="CBM">CBM</option>
            </select>
        </td>
        <td class="px-3 py-2">
            <div id="${rowId}_additional_info">
                <button type="button" onclick="showAdditionalOptions('${rowId}', ${simpleItemIndex})" 
                    class="w-full px-3 py-1.5 bg-blue-500 text-white text-xs rounded-lg hover:bg-blue-600 transition">
                    <i class="fas fa-plus mr-1"></i> Choose
                </button>
            </div>
        </td>
        <td class="px-3 py-2">
            <div class="relative">
                <span class="absolute left-2 top-1/2 -translate-y-1/2 text-gray-500 text-xs">Rs.</span>
                <input type="number" 
                       name="simple_items[${simpleItemIndex}][rate]" 
                       value="0" 
                       min="0"
                       step="0.01"
                       required 
                       oninput="calculateSimpleItemAmount('${rowId}')"
                       class="w-full pl-8 pr-2 py-1.5 text-sm text-center border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
            </div>
        </td>
        <td class="px-3 py-2 text-right">
            <span class="text-sm font-semibold text-gray-800">Rs. <span id="${rowId}_amount">0.00</span></span>
            <input type="hidden" name="simple_items[${simpleItemIndex}][amount]" id="${rowId}_amount_input" value="0">
        </td>
        <td class="px-3 py-2 text-center">
            <button type="button" 
                    onclick="removeSimpleItem('${rowId}')" 
                    class="text-red-600 hover:text-red-800 hover:bg-red-50 p-1.5 rounded transition-colors">
                <i class="fas fa-trash text-sm"></i>
            </button>
        </td>
    `;
    
    tbody.appendChild(tr);
    
    // Mobile Card
    const card = document.createElement('div');
    card.id = `${rowId}_card`;
    card.className = 'bg-white border-2 border-gray-200 rounded-xl p-4 shadow-sm';
    
    card.innerHTML = `
        <div class="flex justify-between items-start mb-3">
            <span class="text-xs font-semibold text-indigo-600 bg-indigo-50 px-2 py-1 rounded">Item #${simpleItemIndex + 1}</span>
            <button type="button" 
                    onclick="removeSimpleItem('${rowId}')" 
                    class="text-red-600 hover:text-red-800 p-1">
                <i class="fas fa-trash text-sm"></i>
            </button>
        </div>
        
        <div class="space-y-3">
            <div>
                <label class="block text-xs font-semibold text-gray-700 mb-1">Description</label>
                <input type="text" 
                       form="bookingForm"
                       name="simple_items_mobile[${simpleItemIndex}][description]" 
                       required 
                       placeholder="Product name..."
                       class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
            </div>
            
            <div class="grid grid-cols-2 gap-3">
                <div>
                    <label class="block text-xs font-semibold text-gray-700 mb-1">Quantity</label>
                    <input type="number" 
                           form="bookingForm"
                           name="simple_items_mobile[${simpleItemIndex}][quantity]" 
                           value="1" 
                           min="0.01"
                           step="0.01"
                           required 
                           oninput="calculateSimpleItemAmountMobile('${rowId}')"
                           class="w-full px-3 py-2 text-sm text-center border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-gray-700 mb-1">Unit</label>
                    <select form="bookingForm"
                            name="simple_items_mobile[${simpleItemIndex}][unit]" 
                            required
                            class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 bg-white">
                        <option value="KG">KG</option>
                        <option value="PCS">PCS</option>
                        <option value="CTN">CTN</option>
                        <option value="CBM">CBM</option>
                    </select>
                </div>
            </div>
            
            <div id="${rowId}_additional_info_mobile">
                <button type="button" onclick="showAdditionalOptionsMobile('${rowId}', ${simpleItemIndex})" 
                    class="w-full px-3 py-2 bg-blue-500 text-white text-sm rounded-lg hover:bg-blue-600 transition flex items-center justify-center">
                    <i class="fas fa-plus mr-2"></i> Additional Info
                </button>
            </div>
            
            <div>
                <label class="block text-xs font-semibold text-gray-700 mb-1">Rate/Unit (Rs.)</label>
                <input type="number" 
                       form="bookingForm"
                       name="simple_items_mobile[${simpleItemIndex}][rate]" 
                       value="0" 
                       min="0"
                       step="0.01"
                       required 
                       oninput="calculateSimpleItemAmountMobile('${rowId}')"
                       class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
            </div>
            
            <div class="bg-indigo-50 rounded-lg p-3 border border-indigo-200">
                <div class="flex justify-between items-center">
                    <span class="text-xs font-semibold text-gray-700">Amount:</span>
                    <span class="text-lg font-bold text-indigo-700">Rs. <span id="${rowId}_amount_mobile">0.00</span></span>
                </div>
                <input type="hidden" form="bookingForm" name="simple_items_mobile[${simpleItemIndex}][amount]" id="${rowId}_amount_input_mobile" value="0">
            </div>
        </div>
    `;
    
    mobileContainer.appendChild(card);
    simpleItemIndex++;
}

function calculateSimpleItemAmountMobile(rowId) {
    const card = document.getElementById(`${rowId}_card`);
    if (!card) return;
    
    const quantity = parseFloat(card.querySelector('input[name*="[quantity]"]').value) || 0;
    const rate = parseFloat(card.querySelector('input[name*="[rate]"]').value) || 0;
    
    const amount = quantity * rate;
    
    card.querySelector(`#${rowId}_amount_mobile`).textContent = amount.toFixed(2);
    card.querySelector(`#${rowId}_amount_input_mobile`).value = amount.toFixed(2);
    
    calculateSimpleTotal();
}

function showAdditionalOptionsMobile(rowId, index) {
    const container = document.getElementById(`${rowId}_additional_info_mobile`);
    container.innerHTML = `
        <div class="space-y-2">
            <select onchange="handleAdditionalInfoChangeMobile('${rowId}', ${index}, this.value)" 
                class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 bg-white">
                <option value="">Select Type</option>
                <option value="cartons">Cartons (کارٹن)</option>
                <option value="baggage">Baggage (بیگیج)</option>
                <option value="custom">Custom (کسٹم)</option>
            </select>
            <div id="${rowId}_additional_input_mobile"></div>
        </div>
    `;
}

function handleAdditionalInfoChangeMobile(rowId, index, type) {
    const inputContainer = document.getElementById(`${rowId}_additional_input_mobile`);
    
    if (type === 'cartons') {
        inputContainer.innerHTML = `
            <div class="flex items-center gap-2">
                <span class="text-xs text-gray-600 whitespace-nowrap">Cartons:</span>
                <input type="number" 
                       form="bookingForm"
                       name="simple_items_mobile[${index}][cartons]" 
                       value="0" 
                       min="0"
                       placeholder="0"
                       class="flex-1 px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
            </div>
        `;
    } else if (type === 'baggage') {
        inputContainer.innerHTML = `
            <div class="flex items-center gap-2">
                <span class="text-xs text-gray-600 whitespace-nowrap">Baggage:</span>
                <input type="number" 
                       form="bookingForm"
                       name="simple_items_mobile[${index}][baggage]" 
                       value="0" 
                       min="0"
                       placeholder="0"
                       class="flex-1 px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
            </div>
        `;
    } else if (type === 'custom') {
        inputContainer.innerHTML = `
            <div class="space-y-2">
                <input type="text" 
                       form="bookingForm"
                       name="simple_items_mobile[${index}][custom_label]" 
                       placeholder="Label (e.g., Boxes)"
                       class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
                <input type="number" 
                       form="bookingForm"
                       name="simple_items_mobile[${index}][custom_value]" 
                       value="0" 
                       min="0"
                       placeholder="Quantity"
                       class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500">
            </div>
        `;
    } else {
        inputContainer.innerHTML = '';
    }
}

function showAdditionalOptions(rowId, index) {
    const container = document.getElementById(`${rowId}_additional_info`);
    container.innerHTML = `
        <div class="space-y-2">
            <select onchange="handleAdditionalInfoChange('${rowId}', ${index}, this.value)" 
                class="w-full px-2 py-1.5 text-xs border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 bg-white">
                <option value="">Select Type</option>
                <option value="cartons">Cartons (کارٹن)</option>
                <option value="baggage">Baggage (بیگیج)</option>
                <option value="custom">Custom (کسٹم)</option>
            </select>
            <div id="${rowId}_additional_input"></div>
        </div>
    `;
}

function handleAdditionalInfoChange(rowId, index, type) {
    const inputContainer = document.getElementById(`${rowId}_additional_input`);
    
    if (type === 'cartons') {
        inputContainer.innerHTML = `
            <div class="flex items-center gap-1">
                <span class="text-xs text-gray-600">Cartons:</span>
                <input type="number" 
                       name="simple_items[${index}][cartons]" 
                       value="0" 
                       min="0"
                       placeholder="0"
                       class="flex-1 px-2 py-1 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-indigo-500">
            </div>
        `;
    } else if (type === 'baggage') {
        inputContainer.innerHTML = `
            <div class="flex items-center gap-1">
                <span class="text-xs text-gray-600">Baggage:</span>
                <input type="number" 
                       name="simple_items[${index}][baggage]" 
                       value="0" 
                       min="0"
                       placeholder="0"
                       class="flex-1 px-2 py-1 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-indigo-500">
            </div>
        `;
    } else if (type === 'custom') {
        inputContainer.innerHTML = `
            <div class="space-y-1">
                <input type="text" 
                       name="simple_items[${index}][custom_label]" 
                       placeholder="Label (e.g., Boxes)"
                       class="w-full px-2 py-1 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-indigo-500">
                <input type="number" 
                       name="simple_items[${index}][custom_value]" 
                       value="0" 
                       min="0"
                       placeholder="Quantity"
                       class="w-full px-2 py-1 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-indigo-500">
            </div>
        `;
    } else {
        inputContainer.innerHTML = '';
    }
}

function calculateSimpleItemAmount(rowId) {
    const row = document.getElementById(rowId);
    if (!row) return;
    
    const quantity = parseFloat(row.querySelector('input[name*="[quantity]"]').value) || 0;
    const rate = parseFloat(row.querySelector('input[name*="[rate]"]').value) || 0;
    
    const amount = quantity * rate;
    
    row.querySelector(`#${rowId}_amount`).textContent = amount.toFixed(2);
    row.querySelector(`#${rowId}_amount_input`).value = amount.toFixed(2);
    
    calculateSimpleTotal();
}

function calculateSimpleTotal() {
    let total = 0;
    
    // Desktop table
    document.querySelectorAll('#simple_items_body tr').forEach(row => {
        const amountInput = row.querySelector('input[name*="[amount]"]');
        if (amountInput) {
            total += parseFloat(amountInput.value) || 0;
        }
    });
    
    // Mobile cards
    document.querySelectorAll('#simple_items_mobile > div').forEach(card => {
        const amountInput = card.querySelector('input[name*="[amount]"]');
        if (amountInput) {
            total += parseFloat(amountInput.value) || 0;
        }
    });
    
    // Update both totals
    const desktopTotal = document.getElementById('simple_total_amount');
    const mobileTotal = document.getElementById('simple_total_amount_mobile');
    
    if (desktopTotal) desktopTotal.textContent = total.toFixed(2);
    if (mobileTotal) mobileTotal.textContent = total.toFixed(2);
    
    // Update total amount field
    const totalAmountField = document.getElementById('total_amount');
    if (totalAmountField) totalAmountField.value = total.toFixed(2);
    calculateDue();
}

function removeSimpleItem(rowId) {
    const row = document.getElementById(rowId);
    const card = document.getElementById(`${rowId}_card`);
    
    if (row) row.remove();
    if (card) card.remove();
    
    calculateSimpleTotal();
}

// Add initial row on page load
document.addEventListener('DOMContentLoaded', function() {
    if (document.querySelectorAll('#simple_items_body tr').length === 0) {
        addSimpleItem();
    }
    
    // Form validation before submit
    const form = document.querySelector('form[action*="bookings"]');
    if (form) {
        form.addEventListener('submit', function(e) {
            const itemsCount = document.querySelectorAll('#simple_items_body tr').length;
            
            if (itemsCount === 0) {
                e.preventDefault();
                alert('Please add at least one cargo item before submitting!');
                return false;
            }
            
            // Check if all items have required fields filled
            let hasEmptyFields = false;
            document.querySelectorAll('#simple_items_body tr').forEach(row => {
                const description = row.querySelector('input[name*="[description]"]').value.trim();
                const quantity = row.querySelector('input[name*="[quantity]"]').value;
                const rate = row.querySelector('input[name*="[rate]"]').value;
                
                if (!description || !quantity || !rate) {
                    hasEmptyFields = true;
                }
            });
            
            if (hasEmptyFields) {
                e.preventDefault();
                alert('Please fill all fields in cargo items (Description, Quantity, and Rate)!');
                return false;
            }
            
            console.log('Form submitting with', itemsCount, 'items');
        });
    }
});
</script>
@endsection
