@extends('layouts.user.app')
{{-- @include('layouts.user.header') --}}

@section('content')
<div class="container mx-auto px-4">
    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <h1 class="text-2xl font-bold text-[#8B0000] mb-6">Pilih Meja</h1>

    @if(session('error'))
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
            <span class="block sm:inline">{{ session('error') }}</span>
        </div>
    @endif

    <!-- Category Filter -->
    <div class="flex justify-center space-x-4 mb-8 overflow-x-auto">
        <button class="filter-btn bg-[#8B0000] text-white px-6 py-2 rounded-full hover:bg-[#660000] transition whitespace-nowrap" data-category="all">
            Semua Meja
        </button>
        <button class="filter-btn bg-white text-[#8B0000] border border-[#8B0000] px-6 py-2 rounded-full hover:bg-[#ffebeb] transition whitespace-nowrap" data-category="outdoor">
            Outdoor
        </button>
        <button class="filter-btn bg-white text-[#8B0000] border border-[#8B0000] px-6 py-2 rounded-full hover:bg-[#ffebeb] transition whitespace-nowrap" data-category="vip-outdoor">
            VIP Outdoor
        </button>
        <button class="filter-btn bg-white text-[#8B0000] border border-[#8B0000] px-6 py-2 rounded-full hover:bg-[#ffebeb] transition whitespace-nowrap" data-category="vip-indoor">
            VIP Indoor
        </button>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" id="mejaContainer">
        @foreach($mejas as $meja)
        <div class="meja-item bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow" 
            data-category="{{ $meja->kategori }}"
            data-category-debug="{{ var_export($meja->kategori, true) }}">
            @if($meja->gambar)
                <img src="{{ asset('storage/' . $meja->gambar) }}" alt="Meja {{ $meja->nomor_meja }}" class="w-full h-48 object-cover">
            @else
                <div class="bg-gray-200 h-48 flex items-center justify-center">
                    <span class="text-gray-500">Tidak ada gambar</span>
                </div>
            @endif
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-xl font-bold">Meja {{ $meja->nomor_meja }}</h3>
                    <span class="px-3 py-1 bg-[#ffebeb] text-[#8B0000] rounded-full text-sm">
                        {{ $meja->kapasitas }} Orang
                    </span>
                </div>
                
                <div class="mb-4">
                    <p class="text-gray-600">Kategori: <span class="font-medium">{{ $meja->getFormattedCategory() }}</span></p>
                    @if($meja->deskripsi)
                        <p class="text-gray-600 mt-2">{{ $meja->deskripsi }}</p>
                    @endif
                </div>

                <div class="flex justify-between items-center">
                    <form action="{{ route('meja.select') }}" method="POST">
                        @csrf
                        <input type="hidden" name="meja_id" value="{{ $meja->id }}">
                        <button type="submit" 
                            class="select-table-btn bg-[#8B0000] text-white px-4 py-2 rounded-lg hover:bg-[#660000] transition">
                            Pilih Meja
                        </button>
                    </form>
                </div>
            </div>
        </div>
        @endforeach
    </div>
</div>

<!-- Modal Ketersediaan -->
<div id="availabilityModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-lg p-6 max-w-lg w-full mx-4">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-bold">Ketersediaan Meja <span id="selectedTableNumber"></span></h3>
            <button onclick="closeModal()" class="text-gray-500 hover:text-gray-700">
                <svg class="w-6 h-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"></path>
                </svg>
            </button>
        </div>
        <div class="mb-4">
            <p class="text-sm text-gray-600">Slot waktu tersedia untuk tanggal: <span id="selectedDate" class="font-medium"></span></p>
        </div>
        <div id="availabilityMessage" class="mb-4 text-center hidden">
            <!-- Message will be shown here -->
        </div>
        <div id="availableSlots" class="grid grid-cols-2 sm:grid-cols-3 gap-2 max-h-60 overflow-y-auto">
            <!-- Slot waktu akan ditampilkan di sini -->
        </div>
        <div class="mt-4 flex justify-end">
            <button onclick="closeModal()" class="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600">
                Tutup
            </button>
        </div>
    </div>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const filterDate = document.getElementById('filter_date');
    const selectedDateInputs = document.querySelectorAll('.selected-date');
    const mejaContainer = document.getElementById('mejaContainer');
    
    // Update selected date inputs when date changes
    filterDate.addEventListener('change', function() {
        selectedDateInputs.forEach(input => {
            input.value = this.value;
        });
    });

    // Set initial date values
    selectedDateInputs.forEach(input => {
        input.value = filterDate.value;
    });

    // Category filter functionality
    document.querySelectorAll('.filter-btn').forEach(button => {
        button.addEventListener('click', function() {
            const category = this.getAttribute('data-category');
            console.log('Selected category:', category);
            
            // Update button styles
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.classList.remove('bg-[#8B0000]', 'text-white');
                btn.classList.add('bg-white', 'text-[#8B0000]');
            });
            this.classList.remove('bg-white', 'text-[#8B0000]');
            this.classList.add('bg-[#8B0000]', 'text-white');
            
            // Filter meja items
            const mejaItems = document.querySelectorAll('.meja-item');
            mejaItems.forEach(item => {
                const itemCategory = item.getAttribute('data-category');
                console.log('Item category:', itemCategory, 'Looking for:', category);
                
                if (category === 'all' || itemCategory === category) {
                    item.style.display = '';
                } else {
                    item.style.display = 'none';
                }
            });
        });
    });

    // Handle form submission
    document.querySelectorAll('.meja-form').forEach(form => {
        form.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            try {
                const formData = new FormData(this);
                const response = await fetch(this.action, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    }
                });

                const data = await response.json();

                if (response.ok && data.status === 'success') {
                    // Langsung redirect ke halaman yang ditentukan
                    window.location.href = data.redirect;
                } else {
                    throw new Error(data.message || 'Terjadi kesalahan saat memilih meja');
                }
            } catch (error) {
                console.error('Error:', error);
                alert(error.message || 'Terjadi kesalahan saat memilih meja');
            }
        });
    });
});

function showAvailabilityModal(mejaId, nomorMeja) {
    const date = document.getElementById('filter_date').value;
    
    // Validasi tanggal harus diisi
    if (!date) {
        alert('Silakan pilih tanggal reservasi terlebih dahulu');
        return;
    }
    
    const modal = document.getElementById('availabilityModal');
    const slotsContainer = document.getElementById('availableSlots');
    const messageContainer = document.getElementById('availabilityMessage');
    const selectedDateSpan = document.getElementById('selectedDate');
    const selectedTableNumber = document.getElementById('selectedTableNumber');
    
    // Show loading state
    slotsContainer.innerHTML = '<div class="col-span-full text-center py-4">Memuat slot waktu...</div>';
    messageContainer.classList.add('hidden');
    modal.classList.remove('hidden');
    modal.classList.add('flex');
    
    // Set table number
    selectedTableNumber.textContent = nomorMeja;
    
    // Format date for display
    const displayDate = new Date(date).toLocaleDateString('id-ID', {
        weekday: 'long',
        year: 'numeric',
        month: 'long',
        day: 'numeric'
    });
    selectedDateSpan.textContent = displayDate;

    // Fetch available slots
    fetch(`/meja/${mejaId}/check-availability?date=${date}`, {
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            throw new Error(data.error);
        }

        if (data.available && data.slots && data.slots.length > 0) {
            slotsContainer.innerHTML = data.slots.map(slot => `
                <div class="bg-green-100 text-green-800 rounded p-2 text-center text-sm">
                    ${slot}
                </div>
            `).join('');
            messageContainer.classList.add('hidden');
        } else {
            slotsContainer.innerHTML = '';
            messageContainer.innerHTML = `
                <div class="text-red-600">
                    ${data.message || 'Tidak ada slot waktu tersedia untuk tanggal ini'}
                </div>
            `;
            messageContainer.classList.remove('hidden');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        slotsContainer.innerHTML = '';
        messageContainer.innerHTML = `
            <div class="text-red-600">
                ${error.message || 'Terjadi kesalahan saat memuat slot waktu'}
            </div>
        `;
        messageContainer.classList.remove('hidden');
    });
}

function closeModal() {
    const modal = document.getElementById('availabilityModal');
    modal.classList.add('hidden');
    modal.classList.remove('flex');
}

// Close modal when clicking outside
document.getElementById('availabilityModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeModal();
    }
});
</script>
@endpush
@endsection
