@extends('admin-layouts.master')

@section('content')
<div class="container-fluid">

    <!-- Page Heading -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">{{$title}}</h1>
        <a href="{{ route('bookings.create') }}" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm">
            <i class="fas fa-plus fa-sm text-white-50"></i> Booking Baru
        </a>
    </div>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                Total Booking
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800" id="totalBookings">
                                {{ $bookings->total() }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-calendar-check fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                Check-in Hari Ini
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800" id="todayCheckins">
                               {{ \App\Models\CheckIn::whereDate('check_in_time', today())->count() }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-sign-in-alt fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                Sedang Menginap
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800" id="checkedIn">
                                {{ $bookings->where('status', 'checked_in')->count() }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-bed fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                Pendapatan Bulan Ini
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800" id="monthlyRevenue">
                                Rp {{ number_format($monthlyRevenue ?? 0, 0, ',', '.') }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filter Card -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Filter & Pencarian</h6>
        </div>
        <div class="card-body">
            <form method="GET" action="{{ route('bookings.index') }}" id="filterForm">
                <div class="row">
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>Status:</label>
                            <select class="form-control" name="status" id="statusFilter">
                                <option value="">Semua Status</option>
                                <option value="booked" {{ request('status') == 'booked' ? 'selected' : '' }}>Booked</option>
                                <option value="checked_in" {{ request('status') == 'checked_in' ? 'selected' : '' }}>Checked In</option>
                                <option value="checked_out" {{ request('status') == 'checked_out' ? 'selected' : '' }}>Checked Out</option>
                                <option value="cancelled" {{ request('status') == 'cancelled' ? 'selected' : '' }}>Cancelled</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>Tipe Booking:</label>
                            <select class="form-control" name="booking_type" id="bookingTypeFilter">
                                <option value="">Semua Tipe</option>
                                <option value="daily" {{ request('booking_type') == 'daily' ? 'selected' : '' }}>Harian</option>
                                <option value="hourly" {{ request('booking_type') == 'hourly' ? 'selected' : '' }}>Per Jam</option>
                                <option value="per_person" {{ request('booking_type') == 'per_person' ? 'selected' : '' }}>Per Orang</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Tanggal Check-in:</label>
                            <input type="date" class="form-control" name="check_in_date" value="{{ request('check_in_date') }}">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Cari Tamu:</label>
                            <input type="text" class="form-control" name="search" placeholder="Nama tamu..." value="{{ request('search') }}">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <div class="d-flex">
                                <button type="submit" class="btn btn-primary mr-2">
                                    <i class="fas fa-search"></i> Filter
                                </button>
                                <a href="{{ route('bookings.index') }}" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> Reset
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- DataTales Example -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Data Booking</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Tamu</th>
                            <th>Kamar</th>
                            <th>Tipe</th>
                            <th>Plan Check-in</th>
                            <th>Plan Check-out</th>
                            <th>Durasi</th>
                            <th>Total</th>
                            <th>Status</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    
                    <tbody>
                        @forelse ($bookings as $booking)
                        <tr>
                            <td>#{{ $booking->id }}</td>
                            <td>
                                <strong>{{ $booking->guest->name ?? '' }}</strong><br>
                                <small class="text-muted">
                                    {{ $booking->guest->phone ?? 'No phone' }}
                                </small>
                            </td>
                            <td>
                                @foreach($booking->bookingDetails as $detail)
                                    <span class="badge badge-info">
                                        {{ $detail->room->room_number ?? 'N/A' }}
                                    </span>
                                    <br>
                                    <small class="text-muted">
                                        {{ $detail->room->typeRoom->name ?? 'Unknown Type' }}
                                    </small>
                                @endforeach
                            </td>
                            <td>
                                @if($booking->booking_type == 'daily')
                                    <span class="badge badge-success">Harian</span>
                                @elseif($booking->booking_type == 'hourly')
                                    <span class="badge badge-warning">Per Jam</span>
                                @elseif($booking->booking_type == 'per_person')
                                    <span class="badge badge-info">Per Orang</span>
                                @else
                                    <span class="badge badge-secondary">Daily</span>
                                @endif
                            </td>
                            <td>{{ $booking->check_in_date_formatted }}</td>
                            <td>{{ $booking->check_out_date_formatted }}</td>
                            <td>
                                @if($booking->booking_type == 'daily' || !$booking->booking_type)
                                    <span class="badge badge-secondary">{{ $booking->nights }} malam</span>
                                @elseif($booking->booking_type == 'hourly')
                                    <span class="badge badge-warning">{{ $booking->duration_hours }} jam</span>
                                @elseif($booking->booking_type == 'per_person')
                                    <span class="badge badge-info">
                                        {{ $booking->guest_count }} orang
                                        @if($booking->nights > 0)
                                            <br><small>{{ $booking->nights }} malam</small>
                                        @endif
                                    </span>
                                @endif
                            </td>
                            <td>
                                <strong class="text-success">
                                    Rp {{ number_format($booking->total_amount, 0, ',', '.') }}
                                </strong>
                            </td>
                            <td>
                                @if($booking->status == 'booked')
                                    <span class="badge badge-primary">Booked</span>
                                @elseif($booking->status == 'checked_in')
                                    <span class="badge badge-success">Checked In</span>
                                @elseif($booking->status == 'checked_out')
                                    <span class="badge badge-info">Checked Out</span>
                                @else
                                    <span class="badge badge-danger">Cancelled</span>
                                @endif
                            </td>
                            <td>
                                <div class="btn-group" role="group">
                                     <a href="{{ route('bookings.show', $booking->id) }}" 
                                            class="btn btn-secondary btn-sm " title="Lihat Detail">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                     @if($booking->canCheckIn())
                                        <button class="btn btn-success btn-sm" onclick="checkInBooking({{ $booking->id }})" title="Check-in">
                                            <i class="fas fa-sign-in-alt"></i>
                                        </button>
                                        
                                    @endif
                                    
                                    @if($booking->canCheckOut())
                                        <button class="btn btn-danger btn-sm" onclick="checkOutBooking({{ $booking->id }})" title="Check-out">
                                            <i class="fas fa-sign-out-alt"></i>
                                        </button>
                                    @endif
                                    @if($booking->status == 'booked')
                                     
                                        <button class="btn btn-warning btn-sm" onclick="cancelBooking({{ $booking->id }})" title="Cancel">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    @endif
                                    
                                    @if($booking->status == 'checked_in')
                                        
                                        @if($booking->hasInvoice())
                                            <a href="{{ route('invoices.show', $booking->invoice->id) }}" 
                                            class="btn btn-success btn-sm" title="Lihat Invoice">
                                                <i class="fas fa-file-invoice-dollar"></i>
                                            </a>
                                        @else
                                            <a href="{{ route('booking-services.create', ['booking_id' => $booking->id]) }}" 
                                            class="btn btn-purple btn-sm" title="Tambah Layanan">
                                                <i class="fas fa-concierge-bell"></i>
                                            </a>
                                            <a href="{{ route('invoices.create', ['booking_id' => $booking->id]) }}" 
                                            class="btn btn-primary btn-sm" title="Generate Invoice">
                                                <i class="fas fa-file-invoice"></i>
                                            </a>
                                        @endif
                                    @endif

                                    @if($booking->status == 'checked_out')
                                        @if($booking->hasInvoice())
                                            <a href="{{ route('invoices.show', $booking->invoice->id) }}" 
                                            class="btn btn-success btn-sm" title="Lihat Invoice">
                                                <i class="fas fa-file-invoice-dollar"></i>
                                            </a>
                                        @else
                                            <a href="{{ route('invoices.create', ['booking_id' => $booking->id]) }}" 
                                            class="btn btn-primary btn-sm" title="Generate Invoice">
                                                <i class="fas fa-file-invoice"></i>
                                            </a>
                                        @endif
                                    @endif
                                    
                                </div>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="10" class="text-center py-4">
                                <i class="fas fa-inbox fa-3x text-gray-400 mb-3"></i>
                                <p class="text-gray-500">Tidak ada data booking ditemukan</p>
                                <a href="{{ route('bookings.create') }}" class="btn btn-primary">
                                    <i class="fas fa-plus"></i> Buat Booking Baru
                                </a>
                            </td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            
            <!-- Pagination -->
            @if($bookings->hasPages())
            <div class="d-flex justify-content-center mt-4">
                {{ $bookings->appends(request()->query())->links() }}
            </div>
            @endif
        </div>
    </div>

</div>

<!-- Modal untuk Detail Booking -->
<div class="modal fade" id="bookingDetailModal" tabindex="-1" role="dialog" aria-labelledby="bookingDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="bookingDetailModalLabel">Detail Booking</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="bookingDetailContent">
                <!-- Content will be loaded here -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>

<!-- Form untuk Cancel -->
<form action="" method="post" id="cancelForm" style="display: none;">
    @csrf
    @method("PATCH")
</form>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(document).ready(function() {
    // Auto refresh statistics every 30 seconds
    setInterval(updateStatistics, 30000);
    
    // Real-time search
    let searchTimeout;
    $('input[name="search"]').on('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            $('#filterForm').submit();
        }, 1000);
    });
});

// Update function checkInBooking
function checkInBooking(id) {
    Swal.fire({
        title: 'Konfirmasi Check-in',
        text: 'Apakah Anda yakin ingin melakukan check-in untuk booking ini?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Ya, Check-in!',
        cancelButtonText: 'Batal',
        showLoaderOnConfirm: true,
        allowOutsideClick: () => !Swal.isLoading(),
        preConfirm: () => {
            return $.ajax({
                url: `/bookings/${id}/quick-checkin`,
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    'Accept': 'application/json'
                }
            }).catch(error => {
                Swal.showValidationMessage(`Request failed: ${error.responseJSON?.message || error.statusText}`);
            });
        }
    }).then((result) => {
        if (result.isConfirmed && result.value) {
            const response = result.value;
            if (response.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil!',
                    text: response.message,
                    timer: 2000,
                    showConfirmButton: false
                }).then(() => {
                    location.reload();
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal!',
                    text: response.message || 'Gagal melakukan check-in'
                });
            }
        }
    });
}

// Function untuk check-out booking
function checkOutBooking(id) {
    Swal.fire({
        title: 'Konfirmasi Check-out',
        text: 'Apakah Anda yakin ingin melakukan check-out untuk booking ini?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#ffc107',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Ya, Check-out!',
        cancelButtonText: 'Batal',
        showLoaderOnConfirm: true,
        allowOutsideClick: () => !Swal.isLoading(),
        preConfirm: () => {
            return $.ajax({
                url: `/bookings/${id}/quick-checkout`,
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    'Accept': 'application/json'
                }
            }).catch(error => {
                Swal.showValidationMessage(`Request failed: ${error.responseJSON?.message || error.statusText}`);
            });
        }
    }).then((result) => {
        if (result.isConfirmed && result.value) {
            const response = result.value;
            if (response.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil!',
                    text: response.message,
                    timer: 2000,
                    showConfirmButton: false
                }).then(() => {
                    location.reload();
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal!',
                    text: response.message || 'Gagal melakukan check-out'
                });
            }
        }
    });
}

// View booking details
function viewBooking(id) {
    console.log('Loading booking details for ID:', id);
    
    $('#bookingDetailContent').html(`
        <div class="text-center py-4">
            <i class="fas fa-spinner fa-spin fa-2x text-primary"></i>
            <p class="mt-2">Memuat detail booking...</p>
        </div>
    `);
    $('#bookingDetailModal').modal('show');
    
    $.ajax({
        url: `{{ url('bookings') }}/${id}`,
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
            'Accept': 'application/json'
        },
        success: function(response) {
            console.log('Booking detail response:', response);
            
            if (response.success) {
                const booking = response.data;
                let roomsHtml = '';
                
                if (booking.booking_details && booking.booking_details.length > 0) {
                    booking.booking_details.forEach(detail => {
                        let durationText = detail.nights > 0 ? detail.nights + ' malam' : 
                                         (detail.duration_hours ? detail.duration_hours + ' jam' : '1 malam');
                        
                        roomsHtml += `
                            <tr>
                                <td>Kamar ${detail.room_number}</td>
                                <td>${detail.room_type}</td>
                                <td>${durationText}</td>
                                <td>Rp ${detail.room_price.toLocaleString('id-ID')}</td>
                                <td>Rp ${detail.total_price.toLocaleString('id-ID')}</td>
                            </tr>
                        `;
                    });
                } else {
                    roomsHtml = '<tr><td colspan="5" class="text-center">Data kamar tidak tersedia</td></tr>';
                }

                // Get booking type display
                let bookingTypeDisplay = '';
                switch(booking.booking_type) {
                    case 'daily':
                        bookingTypeDisplay = 'Harian';
                        break;
                    case 'hourly':
                        bookingTypeDisplay = 'Per Jam';
                        break;
                    case 'per_person':
                        bookingTypeDisplay = 'Per Orang';
                        break;
                    default:
                        bookingTypeDisplay = 'Harian';
                }
                
                const content = `
                    <div class="row">
                        <div class="col-md-6">
                            <h6>Informasi Tamu:</h6>
                            <table class="table table-borderless table-sm">
                                <tr><td><strong>Nama:</strong></td><td>${booking.guest.name || 'N/A'}</td></tr>
                                <tr><td><strong>Telepon:</strong></td><td>${booking.guest.phone || 'N/A'}</td></tr>
                                <tr><td><strong>Email:</strong></td><td>${booking.guest.email || 'N/A'}</td></tr>
                                <tr><td><strong>ID:</strong></td><td>${booking.guest.identity_number || 'N/A'}</td></tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6>Informasi Booking:</h6>
                            <table class="table table-borderless table-sm">
                                <tr><td><strong>ID Booking:</strong></td><td>#${booking.id}</td></tr>
                                <tr><td><strong>Tipe Booking:</strong></td><td>${bookingTypeDisplay}</td></tr>
                                <tr><td><strong>Check-in:</strong></td><td>${booking.check_in_date}</td></tr>
                                <tr><td><strong>Check-out:</strong></td><td>${booking.check_out_date}</td></tr>
                                <tr><td><strong>Status:</strong></td><td>
                                    <span class="badge badge-${booking.status === 'booked' ? 'primary' : booking.status === 'checked_in' ? 'success' : 'danger'}">
                                        ${booking.status}
                                    </span>
                                </td></tr>
                                <tr><td><strong>Dibuat:</strong></td><td>${booking.created_at}</td></tr>
                            </table>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <h6>Detail Kamar & Biaya:</h6>
                    <div class="table-responsive">
                        <table class="table table-bordered table-sm">
                            <thead class="thead-light">
                                <tr>
                                    <th>Kamar</th>
                                    <th>Tipe</th>
                                    <th>Durasi</th>
                                    <th>Harga</th>
                                    <th>Subtotal</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${roomsHtml}
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="row mt-3">
                        <div class="col-md-6 offset-md-6">
                            <table class="table table-borderless">
                                <tr>
                                    <td><strong>Subtotal:</strong></td>
                                    <td class="text-right">Rp ${booking.booking_details && booking.booking_details.length > 0 ? booking.booking_details[0].total_price.toLocaleString('id-ID') : '0'}</td>
                                </tr>
                                <tr>
                                    <td><strong>PPN:</strong></td>
                                    <td class="text-right">Rp ${booking.booking_details && booking.booking_details.length > 0 ? booking.booking_details[0].ppn_amount.toLocaleString('id-ID') : '0'}</td>
                                </tr>
                                <tr class="table-success">
                                    <td><strong>Total:</strong></td>
                                    <td class="text-right"><strong>Rp ${booking.total_amount.toLocaleString('id-ID')}</strong></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                `;
                
                $('#bookingDetailContent').html(content);
            } else {
                $('#bookingDetailContent').html(`
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle"></i>
                        Data booking tidak ditemukan
                    </div>
                `);
            }
        },
        error: function(xhr, status, error) {
            console.error('AJAX Error:', {
                status: xhr.status,
                statusText: xhr.statusText,
                responseText: xhr.responseText,
                error: error
            });
            
            let errorMessage = 'Gagal memuat detail booking';
            if (xhr.status === 404) {
                errorMessage = 'Booking tidak ditemukan';
            } else if (xhr.status === 500) {
                errorMessage = 'Server error. Periksa log server';
            }
            
            $('#bookingDetailContent').html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    ${errorMessage}
                    <br><small>Error ${xhr.status}: ${xhr.statusText}</small>
                </div>
            `);
        }
    });
}

// Cancel booking
function cancelBooking(id) {
    Swal.fire({
        title: 'Konfirmasi Pembatalan',
        text: 'Apakah Anda yakin ingin membatalkan booking ini?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Ya, Batalkan!',
        cancelButtonText: 'Tidak'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: `/bookings/${id}/cancel`,
                method: 'PATCH',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil!',
                            text: response.message,
                            timer: 2000,
                            showConfirmButton: false
                        }).then(() => {
                            location.reload();
                        });
                    }
                },
                error: function(xhr) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal!',
                        text: xhr.responseJSON?.message || 'Gagal membatalkan booking'
                    });
                }
            });
        }
    });
}

// Update statistics
function updateStatistics() {
    // Optional: Hanya refresh halaman untuk update statistik sederhana
    // location.reload();
}

// Handle success messages from server
@if(session('success'))
    Swal.fire({
        title: 'Berhasil!',
        text: '{{ session("success") }}',
        icon: 'success',
        timer: 3000,
        showConfirmButton: false
    });
@endif

@if(session('error'))
    Swal.fire({
        title: 'Error!',
        text: '{{ session("error") }}',
        icon: 'error'
    });
@endif
</script>

@endpush

@endsection