<x-app-layout>
    <x-slot name="header">
        <div class="flex justify-between items-center">
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">
                {{ __('Edit Pembelian Bahan Bakar') }}
            </h2>
            <a href="{{ route('fuel-purchases.index') }}" class="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded">
                <i class="fas fa-arrow-left mr-2"></i>Kembali
            </a>
        </div>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900">
                    <form method="POST" action="{{ route('fuel-purchases.update', $fuelPurchase) }}" enctype="multipart/form-data">
                        @csrf
                        @method('PUT')

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <!-- Truk -->
                            <div>
                                <x-input-label for="truck_id" :value="__('Truk')" />
                                <select id="truck_id" name="truck_id" class="border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm block mt-1 w-full" required>
                                    <option value="">Pilih Truk</option>
                                    @foreach ($trucks as $truck)
                                        <option value="{{ $truck->id }}" {{ old('truck_id', $fuelPurchase->truck_id) == $truck->id ? 'selected' : '' }}>
                                            {{ $truck->plate_number }} - {{ $truck->brand }} {{ $truck->model }}
                                        </option>
                                    @endforeach
                                </select>
                                <x-input-error :messages="$errors->get('truck_id')" class="mt-2" />
                            </div>

                            <!-- Tanggal Pembelian -->
                            <div>
                                <x-input-label for="purchase_date" :value="__('Tanggal Pembelian')" />
                                <x-text-input id="purchase_date" class="block mt-1 w-full" type="date" name="purchase_date" :value="old('purchase_date', $fuelPurchase->purchase_date->format('Y-m-d'))" required />
                                <x-input-error :messages="$errors->get('purchase_date')" class="mt-2" />
                            </div>

                            <!-- Jenis Bahan Bakar -->
                            <div>
                                <x-input-label for="fuel_type" :value="__('Jenis Bahan Bakar')" />
                                <select id="fuel_type" name="fuel_type" class="border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm block mt-1 w-full" required>
                                    <option value="">Pilih Jenis Bahan Bakar</option>
                                    <option value="Solar" {{ old('fuel_type', $fuelPurchase->fuel_type) == 'Solar' ? 'selected' : '' }}>Solar</option>
                                    <option value="Bensin" {{ old('fuel_type', $fuelPurchase->fuel_type) == 'Bensin' ? 'selected' : '' }}>Bensin</option>
                                    <option value="Pertamax" {{ old('fuel_type', $fuelPurchase->fuel_type) == 'Pertamax' ? 'selected' : '' }}>Pertamax</option>
                                    <option value="Dexlite" {{ old('fuel_type', $fuelPurchase->fuel_type) == 'Dexlite' ? 'selected' : '' }}>Dexlite</option>
                                    <option value="Pertamina Dex" {{ old('fuel_type', $fuelPurchase->fuel_type) == 'Pertamina Dex' ? 'selected' : '' }}>Pertamina Dex</option>
                                </select>
                                <x-input-error :messages="$errors->get('fuel_type')" class="mt-2" />
                            </div>

                            <!-- Jumlah Liter -->
                            <div>
                                <x-input-label for="quantity" :value="__('Jumlah (Liter)')" />
                                <x-text-input id="quantity" class="block mt-1 w-full" type="number" name="quantity" :value="old('quantity', $fuelPurchase->quantity)" step="0.01" required />
                                <x-input-error :messages="$errors->get('quantity')" class="mt-2" />
                            </div>

                            <!-- Harga per Liter -->
                            <div>
                                <x-input-label for="price_per_liter" :value="__('Harga per Liter (Rp)')" />
                                <x-text-input id="price_per_liter" class="block mt-1 w-full" type="number" name="price_per_liter" :value="old('price_per_liter', $fuelPurchase->price_per_liter)" step="0.01" required />
                                <x-input-error :messages="$errors->get('price_per_liter')" class="mt-2" />
                            </div>

                            <!-- Total Biaya -->
                            <div>
                                <x-input-label for="total_cost" :value="__('Total Biaya (Rp)')" />
                                <x-text-input id="total_cost" class="block mt-1 w-full" type="number" name="total_cost" :value="old('total_cost', $fuelPurchase->total_cost)" step="0.01" required />
                                <x-input-error :messages="$errors->get('total_cost')" class="mt-2" />
                            </div>

                            <!-- Nama SPBU -->
                            <div>
                                <x-input-label for="station_name" :value="__('Nama SPBU')" />
                                <x-text-input id="station_name" class="block mt-1 w-full" type="text" name="station_name" :value="old('station_name', $fuelPurchase->station_name)" />
                                <x-input-error :messages="$errors->get('station_name')" class="mt-2" />
                            </div>

                            <!-- Nomor Struk -->
                            <div>
                                <x-input-label for="receipt_number" :value="__('Nomor Struk')" />
                                <x-text-input id="receipt_number" class="block mt-1 w-full" type="text" name="receipt_number" :value="old('receipt_number', $fuelPurchase->receipt_number)" />
                                <x-input-error :messages="$errors->get('receipt_number')" class="mt-2" />
                            </div>

                            <!-- Nama Driver -->
                            <div>
                                <x-input-label for="driver_name" :value="__('Nama Driver')" />
                                <select id="driver_name" name="driver_name" class="driver-select border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm block mt-1 w-full">
                                    <option value="">Pilih Driver</option>
                                    @foreach ($drivers as $driver)
                                        <option value="{{ $driver->name }}" {{ old('driver_name', $fuelPurchase->driver_name) == $driver->name ? 'selected' : '' }}>
                                            {{ $driver->name }} {{ $driver->truck_id ? '- ' . $driver->truck->plate_number : '' }}
                                        </option>
                                    @endforeach
                                </select>
                                <x-input-error :messages="$errors->get('driver_name')" class="mt-2" />
                            </div>
                        </div>

                        <!-- Struk BBM -->
                        @include('fuel-purchases.form')

                        <!-- Catatan -->
                        <div class="mt-4">
                            <x-input-label for="notes" :value="__('Catatan')" />
                            <textarea id="notes" name="notes" rows="4" class="border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm block mt-1 w-full">{{ old('notes', $fuelPurchase->notes) }}</textarea>
                            <x-input-error :messages="$errors->get('notes')" class="mt-2" />
                        </div>

                        <div class="flex items-center justify-end mt-4">
                            <x-primary-button>
                                {{ __('Simpan Perubahan') }}
                            </x-primary-button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Tambahkan ini di bagian atas script, setelah $(document).ready
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        document.addEventListener('DOMContentLoaded', function() {
            const quantityInput = document.getElementById('quantity');
            const pricePerLiterInput = document.getElementById('price_per_liter');
            const totalCostInput = document.getElementById('total_cost');

            function calculateTotal() {
                const quantity = parseFloat(quantityInput.value) || 0;
                const pricePerLiter = parseFloat(pricePerLiterInput.value) || 0;
                const total = quantity * pricePerLiter;
                totalCostInput.value = total.toFixed(2);
            }

            quantityInput.addEventListener('input', calculateTotal);
            pricePerLiterInput.addEventListener('input', calculateTotal);
            
            // Inisialisasi Select2 untuk dropdown driver
            $(document).ready(function() {
                $('.driver-select').select2({
                    placeholder: 'Pilih Driver',
                    allowClear: true
                });
                
                // Logika untuk mengisi driver berdasarkan truck yang dipilih
                $('#truck_id').change(function() {
                    const truckId = $(this).val();
                    console.log('Truck ID selected:', truckId);
                    
                    if (truckId) {
                        // Reset driver dropdown
                        $('.driver-select').val('').trigger('change');
                        
                        // Cari driver berdasarkan truck_id dari database
                        $.ajax({
                            url: window.location.origin + '/obm/public/api/drivers-by-truck/' + truckId,
                            type: 'GET',
                            dataType: 'json',
                            beforeSend: function() {
                                console.log('Sending request to: ' + this.url);
                            },
                            success: function(data) {
                                console.log('Data received from API:', data);
                                if (data && data.length > 0) {
                                    console.log('First driver:', data[0]);
                                    // Set driver dropdown ke driver pertama yang ditemukan
                                    $('.driver-select').val(data[0].name).trigger('change');
                                } else {
                                    console.log('No drivers found for this truck');
                                }
                            },
                            error: function(xhr, status, error) {
                                console.error('AJAX Error:', status, error);
                                console.log('Response:', xhr.responseText);
                                console.log('Request URL:', this.url);
                            }
                        });
                    }
                });
            });
        });
    </script>
</x-app-layout>