@extends('layouts.app')

@section('title', 'Riwayat Sewa - INUFA')

@section('header', 'Riwayat Sewa')

@section('content')
<div class="bg-white rounded-lg shadow-lg p-6">
    @if(count($sewas) > 0)
    <div class="overflow-x-auto">
        <table class="min-w-full bg-white">
            <thead>
                <tr class="bg-gray-100">
                    <th class="py-3 px-4 text-left">No</th>
                    <th class="py-3 px-4 text-left">Tanggal</th>
                    <th class="py-3 px-4 text-left">Paket</th>
                    <th class="py-3 px-4 text-left">Total Harga</th>
                    <th class="py-3 px-4 text-left">Nominal Pembayaran</th>
                    <th class="py-3 px-4 text-left">Sisa Pembayaran</th>
                    <th class="py-3 px-4 text-left">Status</th>
                    <th class="py-3 px-4 text-left">Aksi</th>
                </tr>
            </thead>
            <tbody>
                @foreach($sewas as $index => $sewa)
                <tr class="border-b hover:bg-gray-50">
                    <td class="py-3 px-4">{{ $index + 1 }}</td>
                    <td class="py-3 px-4">{{ $sewa->created_at->format('d/m/Y') }}</td>
                    <td class="py-3 px-4">{{ $sewa->paket->nama_paket }}</td>
                    <td class="py-3 px-4">Rp {{ number_format($sewa->total_harga, 0, ',', '.') }}</td>
                    <td class="py-3 px-4">
                        @if($sewa->nominal_pembayaran)
                            Rp {{ number_format($sewa->nominal_pembayaran, 0, ',', '.') }}
                        @else
                            <span class="text-gray-500">-</span>
                        @endif
                    </td>
                    <td class="py-3 px-4">
                        @php
                            $sisaPembayaran = $sewa->total_harga - ($sewa->nominal_pembayaran ?? 0);
                        @endphp
                        @if($sisaPembayaran > 0)
                            <span class="text-red-600 font-medium">
                                Rp {{ number_format($sisaPembayaran, 0, ',', '.') }}
                            </span>
                        @else
                            <span class="text-green-600 font-medium">Lunas</span>
                        @endif
                    </td>
                    <td class="py-3 px-4">
                        <span class="px-2 py-1 rounded-full text-xs font-semibold
                            @if($sewa->status == 'pending') bg-yellow-100 text-yellow-800
                            @elseif($sewa->status == 'confirmed') bg-blue-100 text-blue-800
                            @elseif($sewa->status == 'completed') bg-green-100 text-green-800
                            @elseif($sewa->status == 'dibatalkan') bg-red-100 text-red-800
                            @endif">
                            {{ ucfirst($sewa->status) }}
                        </span>
                    </td>
                    <td class="py-3 px-4">
                        <div class="space-y-2">
                            <!-- Tombol Detail dengan Modal -->
                            <button type="button" 
                                onclick="showDetail('{{ $sewa->id }}')"
                                class="w-full bg-blue-600 text-white px-3 py-1 rounded hover:bg-blue-700">
                                Detail
                            </button>

                            @if(!in_array($sewa->status, ['completed', 'dibatalkan', 'ongoing']))
                                <form action="{{ route('riwayat.batal', $sewa->id) }}" method="POST">
                                    @csrf
                                    @method('PUT')
                                    <button type="submit"
                                        onclick="return confirm('Apakah Anda yakin ingin membatalkan pesanan ini?' +
                                            (('{{ $sewa->status }}' === 'confirmed') ? ' Pembatalan setelah disetujui mungkin dikenakan biaya pembatalan.' : ''))"
                                        class="w-full bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600">
                                        Batalkan Pesanan
                                    </button>
                                </form>
                            @endif

                            @if(in_array($sewa->status, ['dibatalkan', 'completed']))
                                <form action="{{ route('riwayat.hapus', $sewa->id) }}" method="POST">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit"
                                        onclick="return confirm('Apakah Anda yakin ingin menghapus riwayat pesanan ini?')"
                                        class="w-full bg-gray-500 text-white px-3 py-1 rounded hover:bg-gray-600">
                                        Hapus Riwayat
                                    </button>
                                </form>
                            @endif
                        </div>
                    </td>
                </tr>
                @endforeach
            </tbody>
        </table>
    </div>

    <!-- Modal Detail -->
    <div id="detailModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
        <div class="bg-white rounded-lg shadow-xl max-w-4xl w-full mx-4 max-h-[90vh] overflow-y-auto">
            <div class="p-6">
                <div class="flex justify-between items-start mb-4">
                    <h3 class="text-xl font-bold text-gray-800">Detail Pesanan</h3>
                    <button onclick="closeDetail()" class="text-gray-400 hover:text-gray-600">
                        <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
                <div id="modalContent" class="space-y-4">
                    <!-- Konten modal akan diisi melalui JavaScript -->
                </div>
            </div>
        </div>
    </div>

    @else
    <div class="text-center py-8">
        <p class="text-gray-500">Belum ada riwayat pemesanan</p>
        @auth
            @if(auth()->user()->tipe_pengguna === 'customer')
                <a href="{{ route('customer.sewa') }}" class="mt-4 inline-block bg-blue-800 text-white py-2 px-4 rounded hover:bg-blue-900 transition duration-200">
                    Pesan Sekarang
                </a>
            @else
                <a href="{{ route('paket.index') }}" class="mt-4 inline-block bg-blue-800 text-white py-2 px-4 rounded hover:bg-blue-900 transition duration-200">
                    Lihat Paket
                </a>
            @endif
        @else
            <a href="{{ route('login') }}" class="mt-4 inline-block bg-blue-800 text-white py-2 px-4 rounded hover:bg-blue-900 transition duration-200">
                Login untuk Memesan
            </a>
        @endauth
    </div>
    @endif
</div>

@push('scripts')
<script>
async function showDetail(sewaId) {
    try {
        const response = await fetch(`/riwayat/${sewaId}`, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        
        const modalContent = document.getElementById('modalContent');
        modalContent.innerHTML = `
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Status Pembayaran -->
                <div class="space-y-2">
                    <h4 class="font-semibold">Status Pembayaran</h4>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <p class="text-sm">Tanggal Pembayaran: ${data.tanggal_pembayaran || '-'}</p>
                        <p class="text-sm">Status: ${data.status_pembayaran}</p>
                    </div>
                </div>

                <!-- Informasi Pengiriman -->
                <div class="space-y-2">
                    <h4 class="font-semibold">Informasi Pengiriman</h4>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <p class="text-sm">Lokasi: ${data.lokasi || '-'}</p>
                        <p class="text-sm">Kota: ${data.kota?.nama_kota || '-'}</p>
                        <p class="text-sm">Ongkir: ${data.ongkir ? `Rp ${parseInt(data.ongkir).toLocaleString('id-ID')}` : '-'}</p>
                    </div>
                </div>

                <!-- Bukti Pembayaran -->
                ${data.bukti_pembayaran ? `
                <div class="space-y-2">
                    <h4 class="font-semibold">Bukti Pembayaran</h4>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <a href="/storage/${data.bukti_pembayaran}" target="_blank" 
                           class="text-blue-600 hover:text-blue-800">Lihat Bukti Pembayaran</a>
                    </div>
                </div>
                ` : ''}

                <!-- Jaminan -->
                ${data.foto_jaminan ? `
                <div class="space-y-2">
                    <h4 class="font-semibold">Jaminan</h4>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <p class="text-sm">Jenis: ${data.jenis_jaminan || '-'}</p>
                        <a href="/storage/${data.foto_jaminan}" target="_blank"
                           class="text-blue-600 hover:text-blue-800">Lihat Jaminan</a>
                    </div>
                </div>
                ` : ''}
            </div>
        `;

        document.getElementById('detailModal').classList.remove('hidden');
        document.getElementById('detailModal').classList.add('flex');
        document.body.style.overflow = 'hidden';
    } catch (error) {
        console.error('Error:', error);
        alert('Terjadi kesalahan saat memuat detail. Silakan coba lagi.');
    }
}

function closeDetail() {
    document.getElementById('detailModal').classList.add('hidden');
    document.getElementById('detailModal').classList.remove('flex');
    document.body.style.overflow = 'auto';
}

// Menutup modal saat mengklik area di luar modal
document.getElementById('detailModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeDetail();
    }
});
</script>
@endpush
@endsection