@extends('admin-layouts.master')

@section('title', $title)
<style>
    .pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
    padding: 10px 0;
}

.pagination {
    display: flex;
    list-style: none;
    padding: 0;
    margin: 0;
    gap: 5px;
}

.pagination .page-item {
    display: inline-block;
}

.pagination .page-link {
    display: inline-block;
    padding: 6px 12px;
    border: 1px solid #dee2e6;
    border-radius: 4px;
    color: #007bff;
    text-decoration: none;
    transition: background-color 0.2s;
}

.pagination .page-link:hover {
    background-color: #f8f9fa;
}

.pagination .active .page-link {
    background-color: #007bff;
    color: white;
    border-color: #007bff;
}

.result-info {
    font-size: 0.9rem;
    color: #6c757d;
}


    .hover-card {
        transition: all 0.3s ease;
    }
    .hover-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 25px rgba(0,0,0,0.15) !important;
    }

    .border-left-primary { border-left: 0.25rem solid #4e73df !important; }
    .border-left-success { border-left: 0.25rem solid #1cc88a !important; }
    .border-left-info { border-left: 0.25rem solid #36b9cc !important; }
    .border-left-warning { border-left: 0.25rem solid #f6c23e !important; }
    .border-left-danger { border-left: 0.25rem solid #e74a3b !important; }
    .border-left-secondary { border-left: 0.25rem solid #858796 !important; }

    .avatar-circle {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        font-size: 14px;
    }

    .search-suggestions {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        z-index: 1000;
        background: white;
        border: 1px solid #e3e6f0;
        border-top: none;
        border-radius: 0 0 0.35rem 0.35rem;
        max-height: 300px;
        overflow-y: auto;
        display: none;
    }

    .search-suggestion-item {
        padding: 8px 12px;
        cursor: pointer;
        border-bottom: 1px solid #f8f9fc;
        transition: background-color 0.2s;
    }

    .search-suggestion-item:hover {
        background-color: #f8f9fc;
    }

    .search-suggestion-item:last-child {
        border-bottom: none;
    }

    .badge-sm {
        font-size: 0.7rem;
        padding: 0.25em 0.5em;
    }

    .result-info {
        font-size: 0.9rem;
    }

    .view-toggle .btn {
        border-color: #d1d3e2;
    }

    .view-toggle .btn.active {
        background-color: #4e73df;
        border-color: #4e73df;
        color: white;
    }

    @media (max-width: 768px) {
        .hover-card:hover {
            transform: none;
        }

        .d-flex.gap-2 {
            flex-direction: column;
            gap: 0.5rem;
        }

        .btn-group {
            flex-direction: column;
        }
    }
</style>
@section('content')
<div class="container-fluid">
    <!-- Page Header -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <div>
            <h1 class="h3 mb-2 text-gray-800">
                <i class="fas fa-users text-primary me-2"></i>{{ $title }}
            </h1>
            <p class="mb-0 text-gray-600">{{ $subtitle }}</p>
        </div>
        <div class="d-flex gap-2">
            <a href="{{ route('guests.create') }}" class="btn btn-primary shadow-sm mr-2">
                <i class="fas fa-user-plus fa-sm me-1"></i> Tambah Tamu
            </a>
            <div class="dropdown">
                <button class="btn btn-success dropdown-toggle shadow-sm mr-2" type="button" data-toggle="dropdown">
                    <i class="fas fa-download fa-sm me-1"></i> Export
                </button>
                <div class="dropdown-menu">
                    <a class="dropdown-item" href="#" onclick="exportData('excel')">
                        <i class="fas fa-file-excel text-success me-1"></i> Export Excel
                    </a>
                    <a class="dropdown-item" href="#" onclick="exportData('pdf')">
                        <i class="fas fa-file-pdf text-danger me-1"></i> Export PDF
                    </a>
                </div>
            </div>
            <button class="btn btn-info shadow-sm" onclick="refreshData()">
                <i class="fas fa-sync-alt fa-sm me-1"></i> Refresh
            </button>
        </div>
    </div>

    <!-- Breadcrumb -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            @foreach($breadcrumb as $item)
                @if($loop->last)
                    <li class="breadcrumb-item active">{{ $item['name'] }}</li>
                @else
                    <li class="breadcrumb-item">
                        <a href="{{ $item['url'] }}">{{ $item['name'] }}</a>
                    </li>
                @endif
            @endforeach
        </ol>
    </nav>

    <!-- Enhanced Statistics Cards -->
    <div class="row mb-4">
        <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2 hover-card">
                <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 Tamu</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($statistics['totalGuests']) }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-users fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
            <div class="card border-left-success shadow h-100 py-2 hover-card">
                <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">Baru Bulan Ini</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $statistics['newThisMonth'] }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-user-plus fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
            <div class="card border-left-info shadow h-100 py-2 hover-card">
                <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">{{ $statistics['currentlyStaying'] }}</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-2 col-md-4 col-sm-6 mb-4">
            <div class="card border-left-warning shadow h-100 py-2 hover-card">
                <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">Check-in 7 Hari</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $statistics['upcomingGuests'] }}</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-2 col-md-4 col-sm-6 mb-4">
            <div class="card border-left-danger shadow h-100 py-2 hover-card">
                <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-danger text-uppercase mb-1">Tamu VIP</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $statistics['vipGuests'] }}</div>
                            <div class="text-xs text-muted">5+ booking</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-crown fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-2 col-md-4 col-sm-6 mb-4">
            <div class="card border-left-secondary shadow h-100 py-2 hover-card">
                <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-secondary text-uppercase mb-1">Returning Rate</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $statistics['returningRate'] }}%</div>
                            <div class="text-xs text-muted">{{ $statistics['returningGuests'] }} tamu</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-redo-alt fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions & Recent Activity Row -->
    <div class="row mb-4">
        <!-- Recent Activities -->
        <div class="col-lg-8">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-clock me-1"></i>Aktivitas Terbaru
                    </h6>
                    <div class="dropdown no-arrow">
                        <a class="dropdown-toggle" href="#" role="button" data-toggle="dropdown">
                            <i class="fas fa-ellipsis-v fa-sm fa-fw text-gray-400"></i>
                        </a>
                        <div class="dropdown-menu dropdown-menu-right shadow animated--fade-in">
                            <a class="dropdown-item" href="#">Lihat Semua</a>
                            <a class="dropdown-item" href="#">Refresh</a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="row">
                        <!-- New Registrations -->
                        <div class="col-md-6">
                            <h6 class="font-weight-bold text-success mb-3">
                                <i class="fas fa-user-plus me-1"></i>Tamu Baru (7 hari terakhir)
                            </h6>
                            @forelse($recentActivities['new_registrations'] as $guest)
                                <div class="d-flex align-items-center mb-3">
                                    <div class="avatar-circle bg-success text-white me-3">
                                        {{ substr($guest->name, 0, 1) }}
                                    </div>
                                    <div class="flex-grow-1">
                                        <div class="font-weight-bold">{{ $guest->name }}</div>
                                        <small class="text-muted">
                                            {{ $guest->created_at->diffForHumans() }}
                                            @if($guest->bookings->count() > 0)
                                                <span class="badge badge-info badge-sm ml-1">{{ $guest->bookings->count() }} booking</span>
                                            @endif
                                        </small>
                                    </div>
                                    <div>
                                        <a href="{{ route('guests.show', $guest->id) }}" class="btn btn-sm btn-outline-primary">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                    </div>
                                </div>
                            @empty
                                <div class="text-center text-muted py-3">
                                    <i class="fas fa-user-times fa-2x mb-2"></i>
                                    <p class="mb-0">Tidak ada tamu baru</p>
                                </div>
                            @endforelse
                        </div>

                        <!-- Recent Bookings -->
                        <div class="col-md-6">
                            <h6 class="font-weight-bold text-info mb-3">
                                <i class="fas fa-calendar-plus me-1"></i>Booking Baru (7 hari terakhir)
                            </h6>
                            @forelse($recentActivities['recent_bookings'] as $booking)
                                <div class="d-flex align-items-center mb-3">
                                    <div class="avatar-circle bg-info text-white me-3">
                                        {{ substr($booking->guest->name ?? 'U', 0, 1) }}
                                    </div>
                                    <div class="flex-grow-1">
                                        <div class="font-weight-bold">{{ $booking->guest->name ?? 'Unknown' }}</div>
                                        <small class="text-muted">
                                            {{ $booking->created_at->diffForHumans() }}
                                            <br>
                                            @if($booking->bookingDetails->count() > 0)
                                                {{ $booking->bookingDetails->pluck('room.room_number')->join(', ') }}
                                            @endif
                                        </small>
                                    </div>
                                    <div class="text-right">
                                        @php
                                            $statusConfig = [
                                                'booked' => ['class' => 'info', 'text' => 'Booked'],
                                                'checked_in' => ['class' => 'warning', 'text' => 'Check-in'],
                                                'checked_out' => ['class' => 'success', 'text' => 'Check-out'],
                                                'cancelled' => ['class' => 'danger', 'text' => 'Cancelled']
                                            ];
                                            $config = $statusConfig[$booking->status] ?? ['class' => 'secondary', 'text' => $booking->status];
                                        @endphp
                                        <span class="badge badge-{{ $config['class'] }} badge-sm">{{ $config['text'] }}</span>
                                    </div>
                                </div>
                            @empty
                                <div class="text-center text-muted py-3">
                                    <i class="fas fa-calendar-times fa-2x mb-2"></i>
                                    <p class="mb-0">Tidak ada booking baru</p>
                                </div>
                            @endforelse
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Top Guests -->
        <div class="col-lg-4">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-trophy me-1"></i> Top 5 Tamu Setia
                    </h6>
                </div>
                <div class="card-body">
                    @forelse($topGuests->take(5) as $guest)
                        <div class="d-flex align-items-center mb-3">
                            <div class="avatar-circle bg-warning text-white me-3">
                                @if($loop->first)
                                    <i class="fas fa-crown"></i>
                                @else
                                    {{ $loop->iteration }}
                                @endif
                            </div>
                            <div class="flex-grow-1">
                                <div class="font-weight-bold">{{ $guest->name }}</div>
                                <small class="text-muted">
                                    {{ $guest->bookings_count }} booking
                                    @if($guest->total_spent_formatted)
                                        • {{ $guest->total_spent_formatted }}
                                    @endif
                                </small>
                            </div>
                            <div>
                                <a href="{{ route('guests.show', $guest->id) }}" class="btn btn-sm btn-outline-warning">
                                    <i class="fas fa-eye"></i>
                                </a>
                            </div>
                        </div>
                    @empty
                        <div class="text-center text-muted py-3">
                            <i class="fas fa-user-slash fa-2x mb-2"></i>
                            <p class="mb-0">Belum ada data</p>
                        </div>
                    @endforelse
                </div>
            </div>
        </div>
    </div>
     <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-primary">
                <i class="fas fa-search me-1"></i> Pencarian & Filter
            </h6>
            <button class="btn btn-sm btn-outline-secondary" type="button" data-toggle="collapse" data-target="#filterCollapse">
                <i class="fas fa-filter me-1"></i> Filter Lanjutan
            </button>
        </div>
        <div class="card-body">
            <form method="GET" action="{{ route('guests.index') }}" id="filterForm">
                <div class="row">
                    <!-- Main Search -->
                    <div class="col-lg-4 col-md-6 mb-3">
                        <label class="form-label small font-weight-bold">Cari Tamu</label>
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text">
                                    <i class="fas fa-search text-primary"></i>
                                </span>
                            </div>
                            <input type="text"
                                   class="form-control"
                                   name="search"
                                   value="{{ $search }}"
                                   placeholder="Nama, telepon, email, atau ID..."
                                   autocomplete="off"
                                   id="searchInput">
                            <div class="input-group-append">
                                <button class="btn btn-outline-secondary" type="button" onclick="clearSearch()">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                        <!-- Search Suggestions Dropdown -->
                        <div id="searchSuggestions" class="search-suggestions"></div>
                    </div>

                    <!-- Status Filter -->
                    <div class="col-lg-2 col-md-3 mb-3">
                        <label class="form-label small font-weight-bold">Status</label>
                        <select class="form-control" name="status" onchange="submitFilter()">
                            <option value="">Semua Status</option>
                            <option value="active" {{ $status == 'active' ? 'selected' : '' }}>
                                <i class="fas fa-user-check"></i> Aktif
                            </option>
                            <option value="recent" {{ $status == 'recent' ? 'selected' : '' }}>
                                <i class="fas fa-user-plus"></i> Baru (30 hari)
                            </option>
                            <option value="vip" {{ $status == 'vip' ? 'selected' : '' }}>
                                <i class="fas fa-crown"></i> VIP (5+ booking)
                            </option>
                            <option value="staying" {{ $status == 'staying' ? 'selected' : '' }}>
                                <i class="fas fa-bed"></i> Sedang Menginap
                            </option>
                            <option value="upcoming" {{ $status == 'upcoming' ? 'selected' : '' }}>
                                <i class="fas fa-calendar-check"></i> Ada Booking
                            </option>
                        </select>
                    </div>

                    <!-- Sort By -->
                    <div class="col-lg-2 col-md-3 mb-3">
                        <label class="form-label small font-weight-bold">Urutkan</label>
                        <select class="form-control" name="sort_by" onchange="submitFilter()">
                            <option value="created_at" {{ $sortBy == 'created_at' ? 'selected' : '' }}>Tanggal Daftar</option>
                            <option value="name" {{ $sortBy == 'name' ? 'selected' : '' }}>Nama</option>
                            <option value="total_bookings" {{ $sortBy == 'total_bookings' ? 'selected' : '' }}>Total Booking</option>
                            <option value="last_booking" {{ $sortBy == 'last_booking' ? 'selected' : '' }}>Booking Terakhir</option>
                        </select>
                        <input type="hidden" name="sort_order" value="{{ $sortOrder }}">
                    </div>

                    <!-- Per Page -->
                    <div class="col-lg-2 col-md-6 mb-3">
                        <label class="form-label small font-weight-bold">Tampilkan</label>
                        <select class="form-control" name="per_page" onchange="submitFilter()">
                            <option value="10" {{ $perPage == 10 ? 'selected' : '' }}>10 per halaman</option>
                            <option value="15" {{ $perPage == 15 ? 'selected' : '' }}>15 per halaman</option>
                            <option value="25" {{ $perPage == 25 ? 'selected' : '' }}>25 per halaman</option>
                            <option value="50" {{ $perPage == 50 ? 'selected' : '' }}>50 per halaman</option>
                        </select>
                    </div>

                    <!-- Action Buttons -->
                    <div class="col-lg-2 col-md-6 mb-3">
                        <label class="form-label small font-weight-bold">&nbsp;</label>
                        <div class="d-flex">
                            <button type="submit" class="btn btn-primary btn-sm me-1 mr-2">
                                <i class="fas fa-search"></i> Filter
                            </button>
                            <a href="{{ route('guests.index') }}" class="btn btn-secondary btn-sm">
                                <i class="fas fa-undo"></i> Reset
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Advanced Filters (Collapsible) -->
                <div class="collapse" id="filterCollapse">
                    <hr>
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label small font-weight-bold">Terdaftar Dari</label>
                            <input type="date" class="form-control form-control-sm" name="date_from" value="{{ request('date_from') }}">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label small font-weight-bold">Sampai</label>
                            <input type="date" class="form-control form-control-sm" name="date_to" value="{{ request('date_to') }}">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label small font-weight-bold">Minimal Booking</label>
                            <select class="form-control form-control-sm" name="min_bookings">
                                <option value="">Semua</option>
                                <option value="1" {{ request('min_bookings') == '1' ? 'selected' : '' }}>1+ booking</option>
                                <option value="3" {{ request('min_bookings') == '3' ? 'selected' : '' }}>3+ booking</option>
                                <option value="5" {{ request('min_bookings') == '5' ? 'selected' : '' }}>5+ booking (VIP)</option>
                                <option value="10" {{ request('min_bookings') == '10' ? 'selected' : '' }}>10+ booking</option>
                            </select>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label small font-weight-bold">Aksi</label>
                            <div class="d-flex">
                                <button type="submit" class="btn btn-info btn-sm me-1">
                                    <i class="fas fa-filter"></i> Terapkan
                                </button>
                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearAdvancedFilters()">
                                    <i class="fas fa-eraser"></i> Clear
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Quick Actions Bar -->
    {{-- <div class="row mb-4">
        <div class="col-12">
            <div class="card border-left-info shadow-sm">
                <div class="card-body py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-bolt text-info me-2"></i>
                            <span class="font-weight-bold text-gray-800">Aksi Cepat:</span>
                        </div>
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-sm btn-outline-primary" onclick="bulkAction('export')">
                                <i class="fas fa-download me-1"></i> Export Pilihan
                            </button>

                            <button type="button" class="btn btn-sm btn-outline-info" onclick="openQuickBooking()">
                                <i class="fas fa-plus-circle me-1"></i> Quick Booking
                            </button>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div> --}}

    <!-- Results Info Bar -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div class="result-info">
            <span class="text-muted">
                Menampilkan {{ $guests->firstItem() ?? 0 }} - {{ $guests->lastItem() ?? 0 }}
                dari {{ $guests->total() }} tamu
                @if($search || $status)
                    <span class="badge badge-info ml-2">
                        <i class="fas fa-filter me-1"></i>Difilter
                    </span>
                @endif
            </span>
        </div>
        <div class="view-toggle">
            <div class="btn-group btn-group-sm" role="group">
                <button type="button" class="btn btn-outline-secondary active" id="cardViewBtn" onclick="toggleView('card')">
                    <i class="fas fa-th-large"></i> Card
                </button>
                <button type="button" class="btn btn-outline-secondary" id="tableViewBtn" onclick="toggleView('table')">
                    <i class="fas fa-table"></i> Table
                </button>
            </div>
        </div>
    </div>
<!-- Guests Display - Card View (Default) -->
    <div id="cardView" class="guests-display">
        @if($guests->count() > 0)
            <div class="row">
                @foreach($guests as $guest)
                    <div class="col-xl-4 col-lg-6 col-md-6 mb-4">
                        <div class="card guest-card shadow-sm h-100 border-left-primary">
                            <!-- Guest Card Header -->
                            <div class="card-header bg-gradient-primary text-white py-3">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-circle bg-white text-primary me-3">
                                            {{ substr($guest->name, 0, 1) }}
                                        </div>
                                        <div>
                                            <h6 class="mb-1 text-white font-weight-bold">{{ $guest->name }}</h6>
                                            @if($guest->bookings_count > 0)
                                                <small class="text-white-75">
                                                    {{ $guest->bookings_count }} booking
                                                    @if($guest->bookings_count >= 5)
                                                        <i class="fas fa-crown ml-1"></i>
                                                    @endif
                                                </small>
                                            @else
                                                <small class="text-white-75">Tamu baru</small>
                                            @endif
                                        </div>
                                    </div>
                                    {{-- <div class="dropdown">
                                        <button class="btn btn-sm btn-outline-light dropdown-toggle" type="button" data-toggle="dropdown">
                                            <i class="fas fa-cog"></i>
                                        </button>
                                        <div class="dropdown-menu dropdown-menu-right">
                                            <a class="dropdown-item" href="{{ route('guests.show', $guest->id) }}">
                                                <i class="fas fa-eye text-info"></i> Lihat Detail
                                            </a>
                                            <a class="dropdown-item" href="{{ route('guests.edit', $guest->id) }}">
                                                <i class="fas fa-edit text-warning"></i> Edit
                                            </a>
                                            <div class="dropdown-divider"></div>
                                            <a class="dropdown-item" href="#" onclick="createBooking({{ $guest->id }})">
                                                <i class="fas fa-plus-circle text-success"></i> Buat Booking
                                            </a>
                                            <a class="dropdown-item" href="#" onclick="sendMessage({{ $guest->id }})">
                                                <i class="fas fa-sms text-primary"></i> Kirim Pesan
                                            </a>
                                            <div class="dropdown-divider"></div>
                                            <a class="dropdown-item text-danger" href="#" onclick="deleteGuest({{ $guest->id }})">
                                                <i class="fas fa-trash"></i> Hapus
                                            </a>
                                        </div>
                                    </div> --}}
                                </div>
                            </div>

                            <!-- Guest Card Body -->
                            <div class="card-body">
                                <div class="guest-info">
                                    <!-- Contact Info -->
                                    <div class="row mb-3">
                                        <div class="col-12">
                                            @if($guest->phone)
                                                <div class="d-flex align-items-center mb-2">
                                                    <i class="fas fa-phone text-success me-2"></i>
                                                    <span class="text-sm"> {{ $guest->phone }}</span>
                                                    <a href="tel:{{ $guest->phone }}" class="btn btn-sm btn-outline-success ml-auto">
                                                        <i class="fas fa-phone-alt"></i>
                                                    </a>
                                                </div>
                                            @endif

                                            @if($guest->email)
                                                <div class="d-flex align-items-center mb-2">
                                                    <i class="fas fa-envelope text-info me-2"></i>
                                                    <span class="text-sm"> {{ Str::limit($guest->email, 25) }}</span>
                                                    <a href="mailto:{{ $guest->email }}" class="btn btn-sm btn-outline-info ml-auto">
                                                        <i class="fas fa-envelope"></i>
                                                    </a>
                                                </div>
                                            @endif

                                            @if($guest->identity_number)
                                                <div class="d-flex align-items-center mb-2">
                                                    <i class="fas fa-id-card text-warning me-2"></i>
                                                    <span class="text-sm"> {{ $guest->identity_number }}</span>
                                                </div>
                                            @endif
                                            @if($guest->gender)
                                                <div class="d-flex align-items-center mb-2">
                                                    <i class="fas fa-venus-mars text-secondary me-2"></i>
                                                    <span class="text-sm"> {{ $guest->gender }}</span>
                                                </div>
                                            @endif

                                            @if($guest->birth_date)
                                                <div class="d-flex align-items-center mb-2">
                                                    <i class="fas fa-id-card text-secondary me-2"></i>
                                                    <span class="text-sm"> {{ $guest->getUmur() }} Tahun</span>
                                                </div>
                                            @endif
                                        </div>
                                    </div>

                                    <!-- Address -->
                                    @if($guest->address)
                                        <div class="mb-3">
                                            <small class="text-muted d-flex align-items-center">
                                                <i class="fas fa-map-marker-alt me-1"></i>
                                                {{ Str::limit($guest->address, 60) }}
                                            </small>
                                        </div>
                                    @endif

                                    <!-- Recent Bookings Preview -->
                                    @if($guest->bookings->count() > 0)
                                        <div class="recent-bookings mb-3">
                                            <h6 class="font-weight-bold text-gray-800 mb-2">Booking Terakhir:</h6>
                                            @foreach($guest->bookings->take(2) as $booking)
                                                <div class="d-flex justify-content-between align-items-center mb-2">
                                                    <div>
                                                        <small class="font-weight-bold">{{ $booking->booking_code ?? 'B-' . $booking->id }}</small>
                                                        <br>
                                                        <small class="text-muted">{{ $booking->created_at->format('d/m/Y') }}</small>
                                                    </div>
                                                    <div>
                                                        @php
                                                            $statusConfig = [
                                                                'booked' => ['class' => 'info', 'text' => 'Booked'],
                                                                'checked_in' => ['class' => 'warning', 'text' => 'Check-in'],
                                                                'checked_out' => ['class' => 'success', 'text' => 'Check-out'],
                                                                'cancelled' => ['class' => 'danger', 'text' => 'Cancelled']
                                                            ];
                                                            $config = $statusConfig[$booking->status] ?? ['class' => 'secondary', 'text' => $booking->status];
                                                        @endphp
                                                        <span class="badge badge-{{ $config['class'] }} badge-sm">{{ $config['text'] }}</span>
                                                    </div>
                                                </div>
                                            @endforeach
                                        </div>
                                    @endif
                                </div>
                            </div>

                            <!-- Guest Card Footer -->
                            <div class="card-footer bg-light d-flex justify-content-between align-items-center">
                                <div class="guest-stats">
                                    <small class="text-muted">
                                        Terdaftar: {{ $guest->created_at->format('d/m/Y') }}
                                        @if($guest->bookings_count >= 5)
                                            <span class="badge badge-warning badge-sm ml-1">VIP</span>
                                        @endif
                                    </small>
                                </div>

                                <div class="guest-actions">
                                    <a href="{{ route('guests.show', $guest->id) }}" class="btn btn-sm btn-outline-primary" title="Lihat Detail">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="{{ route('guests.edit', $guest->id) }}" class="btn btn-sm btn-outline-warning" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                     <button onclick="deleteGuest({{$guest->id}})" class="btn btn-sm btn-outline-danger" title="Delete">
                                        <i class="fas fa-trash"></i>
                                     </button>
                                    {{-- <button class="btn btn-sm btn-outline-success" onclick="createBooking({{ $guest->id }})" title="Buat Booking">
                                        <i class="fas fa-plus-circle"></i>
                                    </button> --}}
                                </div>
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
        @else
            <!-- Empty State -->
            <div class="card shadow">
                <div class="card-body text-center py-5">
                    <i class="fas fa-users fa-4x text-muted mb-4"></i>
                    <h4 class="text-muted mb-3">Tidak ada tamu ditemukan</h4>
                    @if($search || $status)
                        <p class="text-muted mb-4">
                            Coba ubah kata kunci pencarian atau filter yang digunakan.
                        </p>
                        <a href="{{ route('guests.index') }}" class="btn btn-secondary me-2">
                            <i class="fas fa-undo me-1"></i> Reset Filter
                        </a>
                    @else
                        <p class="text-muted mb-4">
                            Belum ada tamu yang terdaftar. Mulai dengan menambahkan tamu pertama.
                        </p>
                    @endif
                    <a href="{{ route('guests.create') }}" class="btn btn-primary">
                        <i class="fas fa-user-plus me-1"></i> Tambah Tamu Pertama
                    </a>
                </div>
            </div>
        @endif
    </div>

    <!-- Guests Display - Table View (Hidden by default) -->
    <div id="tableView" class="guests-display" style="display: none;">
        <div class="card shadow">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-table me-1"></i>Data Tamu - Tampilan Tabel
                </h6>
            </div>
            <div class="card-body">
                @if($guests->count() > 0)
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover" id="guestsTable">
                            <thead class="thead-light">
                                <tr>
                                    <th width="5%">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input" id="selectAll">
                                            <label class="custom-control-label" for="selectAll"></label>
                                        </div>
                                    </th>
                                    <th width="20%">Nama & Kontak</th>
                                    <th width="15%">Identitas</th>
                                    <th>Jenis Kelamin</th>
                                    <th>Umur</th>
                                    <th width="20%">Alamat</th>
                                    <th width="15%">Booking</th>
                                    <th width="10%">Status</th>
                                    <th width="10%">Terdaftar</th>
                                    <th width="5%">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($guests as $guest)
                                <tr>
                                    <td>
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input guest-checkbox"
                                                   id="guest{{ $guest->id }}" value="{{ $guest->id }}">
                                            <label class="custom-control-label" for="guest{{ $guest->id }}"></label>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="avatar-circle bg-primary text-white me-2">
                                                {{ substr($guest->name, 0, 1) }}
                                            </div>
                                            <div>
                                                <div class="font-weight-bold">{{ $guest->name }}</div>
                                                <small class="text-muted">
                                                    @if($guest->phone)
                                                        <i class="fas fa-phone me-1"></i>{{ $guest->phone }}
                                                    @endif
                                                    @if($guest->email)
                                                        <br><i class="fas fa-envelope me-1"></i>{{ $guest->email }}
                                                    @endif
                                                </small>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        @if($guest->identity_number)
                                            <span class="font-weight-bold">{{ $guest->identity_number }}</span>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                     <td>
                                        @if($guest->gender)
                                            <span class="font-weight-bold">{{ $guest->gender }}</span>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                     <td>
                                        @if($guest->birth_date)
                                            <span class="font-weight-bold">{{ $guest->getUmur() }}</span>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                    <td>
                                        @if($guest->address)
                                            <small>{{ Str::limit($guest->address, 50) }}</small>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                    <td class="text-center">
                                        <span class="badge badge-primary badge-lg">{{ $guest->bookings_count }}</span>
                                        @if($guest->bookings_count >= 5)
                                            <br><span class="badge badge-warning badge-sm mt-1">VIP</span>
                                        @endif
                                    </td>
                                    <td>
                                        @php
                                            $hasActiveBooking = $guest->bookings->whereIn('status', ['booked', 'checked_in'])->count() > 0;
                                        @endphp
                                        @if($hasActiveBooking)
                                            <span class="badge badge-success">Aktif</span>
                                        @elseif($guest->created_at->diffInDays() <= 30)
                                            <span class="badge badge-info">Baru</span>
                                        @else
                                            <span class="badge badge-secondary">Regular</span>
                                        @endif
                                    </td>
                                    <td>
                                        <small>
                                            {{ $guest->created_at->format('d/m/Y') }}
                                            <br>
                                            <span class="text-muted">{{ $guest->created_at->diffForHumans() }}</span>
                                        </small>
                                    </td>
                                    <td>
                                        <div class="btn-group-vertical">
                                            <a href="{{ route('guests.show', $guest->id) }}"
                                               class="btn btn-sm btn-outline-info" title="Detail">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="{{ route('guests.edit', $guest->id) }}"
                                               class="btn btn-sm btn-outline-warning" title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <button class="btn btn-sm btn-outline-danger"
                                                    onclick="deleteGuest({{ $guest->id }})" title="Hapus">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                @else
                    <div class="text-center py-4">
                        <i class="fas fa-users fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">Tidak ada data tamu</h5>
                    </div>
                @endif
            </div>
        </div>
    </div>

@if ($guests->hasPages())
    <div class="pagination-container">
        <div class="result-info">
            Halaman {{ $guests->currentPage() }} dari {{ $guests->lastPage() }}
            ({{ $guests->total() }} total tamu)
        </div>
        <div>
            {{ $guests->appends(request()->query())->links('pagination::bootstrap-4') }}
        </div>
    </div>
@endif




</div>
<!-- Quick Booking Modal -->
<div class="modal fade" id="quickBookingModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">
                    <i class="fas fa-plus-circle me-2"></i>Quick Booking
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="quickBookingForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Tamu</label>
                                <select class="form-control" id="quickBookingGuest" required>
                                    <option value="">Pilih Tamu...</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Tipe Kamar</label>
                                <select class="form-control" id="quickBookingRoomType" required>
                                    <option value="">Pilih Tipe Kamar...</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Check-in</label>
                                <input type="date" class="form-control" id="quickBookingCheckin" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Check-out</label>
                                <input type="date" class="form-control" id="quickBookingCheckout" required>
                            </div>
                        </div>
                    </div>
                    <div class="alert alert-info" id="pricePreview" style="display: none;"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                <button type="button" class="btn btn-success" onclick="submitQuickBooking()">
                    <i class="fas fa-check me-1"></i> Buat Booking
                </button>
            </div>
        </div>
    </div>
</div>


<!-- Message Modal -->
<div class="modal fade" id="messageModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">
                    <i class="fas fa-sms me-2"></i>Kirim Pesan
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="messageForm">
                    <div class="form-group">
                        <label>Template Pesan</label>
                        <select class="form-control" id="messageTemplate">
                            <option value="">Pilih Template...</option>
                            <option value="welcome">Selamat Datang</option>
                            <option value="birthday">Ucapan Ulang Tahun</option>
                            <option value="promo">Penawaran Khusus</option>
                            <option value="feedback">Minta Feedback</option>
                            <option value="custom">Pesan Custom</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Pesan</label>
                        <textarea class="form-control" id="messageContent" rows="4" required></textarea>
                    </div>
                    <div class="form-group">
                        <div class="custom-control custom-checkbox">
                            <input type="checkbox" class="custom-control-input" id="sendSMS">
                            <label class="custom-control-label" for="sendSMS">Kirim via SMS</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="custom-control custom-checkbox">
                            <input type="checkbox" class="custom-control-input" id="sendEmail">
                            <label class="custom-control-label" for="sendEmail">Kirim via Email</label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                <button type="button" class="btn btn-primary" onclick="sendMessage()">
                    <i class="fas fa-paper-plane me-1"></i> Kirim Pesan
                </button>
            </div>
        </div>
    </div>
</div>
<!-- Form untuk Delete -->
<form action="" method="post" id="deleteForm">
    @csrf
    @method("DELETE")
    <input type="submit" value="Hapus" style="display:none">
</form>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>

<script>
$(document).ready(function() {
    // Initialize search suggestions
    initializeSearchSuggestions();

    // Set minimum dates for date inputs
    const today = new Date().toISOString().split('T')[0];
    $('#quickBookingCheckin').attr('min', today);

    // Auto-update checkout date
    $('#quickBookingCheckin').change(function() {
        const checkinDate = new Date($(this).val());
        checkinDate.setDate(checkinDate.getDate() + 1);
        $('#quickBookingCheckout').attr('min', checkinDate.toISOString().split('T')[0]);
        $('#quickBookingCheckout').val(checkinDate.toISOString().split('T')[0]);
    });

    // Load room types and guests for quick booking
    loadQuickBookingData();
});
// Delete guest function
function deleteGuest(id) {
    Swal.fire({
        title: 'Apakah Anda yakin?',
        text: "Data tamu yang sudah dihapus tidak dapat dikembalikan!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Ya, Hapus!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.value) {
            // Set form action and submit
            $('#deleteForm').attr('action', `{{ url('guests') }}/${id}`);
            $('#deleteForm').submit();
        }
    });
}
// Search suggestions functionality
function initializeSearchSuggestions() {
    let searchTimeout;

    $('#searchInput').on('input', function() {
        const query = $(this).val();

        clearTimeout(searchTimeout);

        if (query.length < 2) {
            $('#searchSuggestions').hide();
            return;
        }

        searchTimeout = setTimeout(() => {
            $.ajax({
                url: '{{ route("api.guests.search") }}',
                method: 'GET',
                data: { search: query, search_suggestions: true },
                success: function(response) {
                    if (response.suggestions && response.suggestions.length > 0) {
                        let html = '';
                        response.suggestions.forEach(function(suggestion) {
                            html += `
                                <div class="search-suggestion-item" data-id="${suggestion.id}" onclick="selectGuest(${suggestion.id}, '${suggestion.name}')">
                                    <div class="font-weight-bold">${suggestion.name}</div>
                                    <small class="text-muted">${suggestion.phone || ''} ${suggestion.email || ''}</small>
                                </div>
                            `;
                        });
                        $('#searchSuggestions').html(html).show();
                    } else {
                        $('#searchSuggestions').hide();
                    }
                }
            });
        }, 300);
    });

    // Hide suggestions when clicking outside
    $(document).on('click', function(e) {
        if (!$(e.target).closest('#searchInput, #searchSuggestions').length) {
            $('#searchSuggestions').hide();
        }
    });
}

function selectGuest(guestId, guestName) {
    $('#searchInput').val(guestName);
    $('#searchSuggestions').hide();
    $('#filterForm').submit();
}

// Filter functions
function submitFilter() {
    $('#filterForm').submit();
}

function clearSearch() {
    $('#searchInput').val('');
    submitFilter();
}

function clearAdvancedFilters() {
    $('input[name="date_from"]').val('');
    $('input[name="date_to"]').val('');
    $('select[name="min_bookings"]').val('');
}

// View toggle functions
function toggleView(viewType) {
    if (viewType === 'card') {
        $('#cardView').show();
        $('#tableView').hide();
        $('#cardViewBtn').addClass('active');
        $('#tableViewBtn').removeClass('active');
        localStorage.setItem('guestViewPreference', 'card');
    } else {
        $('#cardView').hide();
        $('#tableView').show();
        $('#cardViewBtn').removeClass('active');
        $('#tableViewBtn').addClass('active');
        localStorage.setItem('guestViewPreference', 'table');
    }
}

// Load saved view preference
function loadViewPreference() {
    const preference = localStorage.getItem('guestViewPreference') || 'card';
    toggleView(preference);
}

// Bulk actions
function bulkAction(action) {
    const selectedGuests = $('.guest-checkbox:checked').map(function() {
        return $(this).val();
    }).get();

    if (selectedGuests.length === 0) {
        Swal.fire('Info', 'Pilih tamu terlebih dahulu', 'info');
        return;
    }

    switch(action) {
        case 'export':
            exportSelectedGuests(selectedGuests);
            break;
        case 'message':
            showBulkMessageModal(selectedGuests);
            break;
        default:
            console.log('Bulk action:', action, selectedGuests);
    }
}

// Quick booking functions
function openQuickBooking(guestId = null) {
    $('#quickBookingModal').modal('show');
    if (guestId) {
        $('#quickBookingGuest').val(guestId);
    }
}

function createBooking(guestId) {
    openQuickBooking(guestId);
}

function loadQuickBookingData() {
    // Load guests
    $.ajax({
        url: '{{ route("guests.index") }}',
        method: 'GET',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        success: function(response) {
            if (response.success && response.data) {
                let options = '<option value="">Pilih Tamu...</option>';
                response.data.forEach(function(guest) {
                    options += `<option value="${guest.id}">${guest.name}</option>`;
                });
                $('#quickBookingGuest').html(options);
            }
        }
    });

    // Load room types (you might need to create this endpoint)
    // $('#quickBookingRoomType').html('<option value="">Loading...</option>');
}

function submitQuickBooking() {
    const formData = {
        guest_id: $('#quickBookingGuest').val(),
        room_type_id: $('#quickBookingRoomType').val(),
        check_in_date: $('#quickBookingCheckin').val(),
        check_out_date: $('#quickBookingCheckout').val(),
        _token: $('meta[name="csrf-token"]').attr('content')
    };

    if (!formData.guest_id || !formData.room_type_id || !formData.check_in_date || !formData.check_out_date) {
        Swal.fire('Error', 'Lengkapi semua field', 'error');
        return;
    }

    // Submit booking (implement your booking endpoint)
    Swal.fire({
        title: 'Berhasil!',
        text: 'Quick booking berhasil dibuat',
        icon: 'success',
        timer: 2000
    });
    $('#quickBookingModal').modal('hide');
}





// Message functions
function sendMessage(guestId = null) {
    $('#messageModal').modal('show');
    if (guestId) {
        // Pre-fill guest data
    }
}

// Delete function
function deleteGuest(guestId) {
    Swal.fire({
        title: 'Konfirmasi Hapus',
        text: 'Apakah Anda yakin ingin menghapus tamu ini?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Ya, Hapus!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            // Create and submit delete form
            const form = $('<form>', {
                method: 'POST',
                action: `{{ url('guests') }}/${guestId}`
            }).append(
                $('<input>', { type: 'hidden', name: '_token', value: $('meta[name="csrf-token"]').attr('content') }),
                $('<input>', { type: 'hidden', name: '_method', value: 'DELETE' })
            );

            $('body').append(form);
            form.submit();
        }
    });
}

// Export functions
function exportData(format) {
    const url = `{{ route('guests.index') }}/export/${format}?${new URLSearchParams(window.location.search)}`;
    window.open(url, '_blank');
}

function refreshData() {
    location.reload();
}

// Select all checkbox functionality
$('#selectAll').change(function() {
    $('.guest-checkbox').prop('checked', $(this).is(':checked'));
});

$('.guest-checkbox').change(function() {
    const totalCheckboxes = $('.guest-checkbox').length;
    const checkedCheckboxes = $('.guest-checkbox:checked').length;
    $('#selectAll').prop('checked', totalCheckboxes === checkedCheckboxes);
});

// Load view preference on page load
$(document).ready(function() {
    loadViewPreference();
});

// Handle success/error messages
@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
