@extends('admin-layouts.master')

@section('title', $title)
<style>
    /* Booking Type Styles */
    .booking-type-selector {
        background: white;
        border-radius: 15px;
        padding: 25px;
        margin-bottom: 30px;
        border: 2px solid #e9ecef;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
    }
    
    .booking-type-options {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        margin-top: 20px;
    }
    
    .booking-type-card {
        background: #f8f9fa;
        border: 2px solid #e9ecef;
        border-radius: 12px;
        padding: 20px;
        cursor: pointer;
        transition: all 0.3s ease;
        text-align: center;
        position: relative;
    }
    
    .booking-type-card:hover {
        border-color: #667eea;
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
    }
    
    .booking-type-card.selected {
        border-color: #667eea;
        background: linear-gradient(135deg, #f8f9ff, #e3f2fd);
        box-shadow: 0 8px 25px rgba(102, 126, 234, 0.2);
    }
    
    .booking-type-card .type-icon {
        font-size: 36px;
        color: #667eea;
        margin-bottom: 10px;
    }
    
    .booking-type-card .type-name {
        font-weight: bold;
        color: #2d3436;
        margin-bottom: 5px;
    }
    
    .booking-type-card .type-description {
        font-size: 12px;
        color: #636e72;
    }
    
    .booking-type-card .check-icon {
        position: absolute;
        top: 10px;
        right: 10px;
        color: #28a745;
        font-size: 18px;
        display: none;
    }
    
    .booking-type-card.selected .check-icon {
        display: block;
    }
    
    /* Dynamic form fields based on booking type */
    .booking-parameters {
        background: #f8f9fa;
        border-radius: 12px;
        padding: 20px;
        margin-top: 20px;
        display: none;
    }
    
    .booking-parameters.active {
        display: block;
    }
    
    .parameter-group {
        margin-bottom: 20px;
    }
    
    .parameter-group:last-child {
        margin-bottom: 0;
    }
    
    .parameter-label {
        font-weight: 600;
        color: #2d3436;
        margin-bottom: 8px;
        display: block;
    }
    
    .price-preview {
        background: linear-gradient(135deg, #e8f5e8, #f0f8ff);
        border: 2px solid #28a745;
        border-radius: 12px;
        padding: 20px;
        margin-top: 20px;
        display: none;
    }
    
    .price-preview.show {
        display: block;
    }
    
    .hourly-datetime {
        display: grid;
        grid-template-columns: 1fr auto 1fr;
        gap: 15px;
        align-items: end;
    }
    
    .hourly-datetime .duration-display {
        text-align: center;
        padding: 10px;
        background: white;
        border-radius: 8px;
        border: 2px solid #e9ecef;
        font-weight: bold;
        color: #667eea;
    }

    /* Base Layout Styles */
    .booking-wrapper {
        min-height: 100vh;
        padding: 20px 0;
    }
    
    .booking-container {
        background: white;
        border-radius: 20px;
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        max-width: 1000px;
        margin: 0 auto;
    }
    
    .booking-header {
        color: white;
        padding: 40px 30px;
        text-align: center;
        position: relative;
    }
    
    .booking-header::before {
        content: '';
        position: absolute;
        bottom: -10px;
        left: 50%;
        transform: translateX(-50%);
        width: 0;
        height: 0;
        border-left: 20px solid transparent;
        border-right: 20px solid transparent;
        border-top: 20px solid #764ba2;
    }
    
    .step-progress {
        padding: 40px 30px 20px;
        background: #f8f9ff;
    }
    
    .step-indicator {
        display: flex;
        justify-content: space-between;
        align-items: center;
        position: relative;
        margin-bottom: 30px;
    }
    
    .step-indicator::before {
        content: '';
        position: absolute;
        top: 20px;
        left: 0;
        right: 0;
        height: 4px;
        background: #e9ecef;
        z-index: 1;
    }
    
    .step-indicator::after {
        content: '';
        position: absolute;
        top: 20px;
        left: 0;
        height: 4px;
        background: linear-gradient(to right, #28a745, #20c997);
        z-index: 2;
        transition: width 0.3s ease;
        width: 0%;
    }
    
    .step-indicator.step-1::after { width: 0%; }
    .step-indicator.step-2::after { width: 25%; }
    .step-indicator.step-3::after { width: 50%; }
    .step-indicator.step-4::after { width: 75%; }
    .step-indicator.step-5::after { width: 100%; }
    
    .step-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        z-index: 3;
        position: relative;
        background: white;
        padding: 5px;
        border-radius: 50px;
    }
    
    .step-number {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: #e9ecef;
        color: #6c757d;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        font-size: 14px;
        transition: all 0.3s ease;
        margin-bottom: 8px;
    }
    
    .step-item.active .step-number {
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
        transform: scale(1.1);
        box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
    }
    
    .step-item.completed .step-number {
        background: linear-gradient(135deg, #28a745, #20c997);
        color: white;
    }
    
    .step-label {
        font-size: 12px;
        color: #6c757d;
        font-weight: 600;
        text-align: center;
        min-width: 60px;
    }
    
    .step-item.active .step-label {
        color: #667eea;
        font-weight: bold;
    }
    
    .step-item.completed .step-label {
        color: #28a745;
    }
    
    .form-content {
        padding: 40px;
    }
    
    .form-step {
        display: none;
        animation: slideIn 0.5s ease;
    }
    
    .form-step.active {
        display: block;
    }
    
    @keyframes slideIn {
        from { opacity: 0; transform: translateX(30px); }
        to { opacity: 1; transform: translateX(0); }
    }
    
    .step-title {
        font-size: 24px;
        font-weight: bold;
        color: #2d3436;
        margin-bottom: 8px;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .step-subtitle {
        color: #636e72;
        margin-bottom: 30px;
    }
    
    .guest-section {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 30px;
        margin-bottom: 40px;
    }
    
    @media (max-width: 768px) {
        .guest-section {
            grid-template-columns: 1fr;
            gap: 20px;
        }
    }
    
    .section-card {
        background: #f8f9fa;
        border-radius: 15px;
        padding: 25px;
        border: 2px solid #e9ecef;
        transition: all 0.3s ease;
    }
    
    .section-card:hover {
        border-color: #667eea;
        box-shadow: 0 5px 15px rgba(102, 126, 234, 0.1);
    }
    
    .section-title {
        font-size: 16px;
        font-weight: bold;
        color: #2d3436;
        margin-bottom: 20px;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .guest-card {
        background: white;
        border: 2px solid #e9ecef;
        border-radius: 12px;
        padding: 15px;
        margin-bottom: 15px;
        cursor: pointer;
        transition: all 0.3s ease;
        position: relative;
    }
    
    .guest-card:hover {
        border-color: #667eea;
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
    }
    
    .guest-card.selected {
        border-color: #667eea;
        background: linear-gradient(135deg, #f8f9ff, #e3f2fd);
        box-shadow: 0 8px 25px rgba(102, 126, 234, 0.2);
    }
    
    .guest-card .check-icon {
        position: absolute;
        top: 10px;
        right: 10px;
        color: #28a745;
        font-size: 18px;
        display: none;
    }
    
    .guest-card.selected .check-icon {
        display: block;
    }
    
    .guest-name {
        font-weight: bold;
        color: #2d3436;
        margin-bottom: 5px;
    }
    
    .guest-info {
        color: #636e72;
        font-size: 14px;
    }
    
    .form-group {
        margin-bottom: 20px;
    }
    
    .form-label {
        font-weight: 600;
        color: #2d3436;
        margin-bottom: 8px;
        display: block;
    }
    
    .form-control {
        border: 2px solid #e9ecef;
        border-radius: 10px;
        padding: 12px 15px;
        font-size: 14px;
        transition: all 0.3s ease;
    }
    
    .form-control:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
    }
    
    .date-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
        margin-bottom: 20px;
    }
    
    @media (max-width: 576px) {
        .date-row {
            grid-template-columns: 1fr;
        }
    }
    
    .night-info {
        background: linear-gradient(135deg, #e3f2fd, #f8f9ff);
        border: 2px solid #667eea;
        border-radius: 12px;
        padding: 15px;
        text-align: center;
        margin-bottom: 20px;
    }
    
    .night-count {
        font-size: 24px;
        font-weight: bold;
        color: #667eea;
    }
    
    .room-card {
        background: white;
        border: 2px solid #e9ecef;
        border-radius: 15px;
        padding: 20px;
        margin-bottom: 20px;
        cursor: pointer;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }
    
    .room-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 5px;
        height: 100%;
        background: #28a745;
        transform: scaleY(0);
        transition: transform 0.3s ease;
    }
    
    .room-card:hover {
        border-color: #28a745;
        transform: translateY(-3px);
        box-shadow: 0 10px 30px rgba(40, 167, 69, 0.15);
    }
    
    .room-card:hover::before {
        transform: scaleY(1);
    }
    
    .room-card.selected {
        border-color: #28a745;
        background: linear-gradient(135deg, #f8fff8, #e8f5e8);
        box-shadow: 0 10px 30px rgba(40, 167, 69, 0.2);
    }
    
    .room-card.selected::before {
        transform: scaleY(1);
    }
    
    .btn-step {
        padding: 12px 30px;
        border-radius: 25px;
        font-weight: bold;
        font-size: 14px;
        transition: all 0.3s ease;
        border: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }
    
    .btn-step:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
    }
    
    .btn-primary {
        color: white;
    }
    
    .btn-secondary {
        background: #6c757d;
        color: white;
    }
    
    .btn-success {
        background: linear-gradient(135deg, #28a745, #20c997);
        color: white;
    }
    
    .step-navigation {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 40px;
        padding-top: 20px;
        border-top: 2px solid #e9ecef;
    }
    
    .loading-spinner {
        text-align: center;
        padding: 60px 20px;
        display: none;
    }
    
    .loading-spinner.show {
        display: block;
    }
    
    .spinner {
        font-size: 40px;
        color: #667eea;
        margin-bottom: 20px;
        animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    .summary-card {
        background: white;
        border-radius: 15px;
        border: 2px solid #e9ecef;
        overflow: hidden;
    }
    
    .summary-header {
        background: linear-gradient(135deg, #f8f9fa, #e9ecef);
        padding: 20px;
        border-bottom: 2px solid #e9ecef;
    }
    
    .summary-title {
        font-weight: bold;
        color: #2d3436;
        margin: 0;
    }
    
    .summary-body {
        padding: 20px;
    }
    
    .summary-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #e9ecef;
    }
    
    .summary-item:last-child {
        border-bottom: none;
        font-weight: bold;
        font-size: 18px;
        color: #28a745;
        padding-top: 15px;
        margin-top: 10px;
        border-top: 2px solid #e9ecef;
    }
    
    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #636e72;
    }
    
    .empty-icon {
        font-size: 60px;
        color: #e9ecef;
        margin-bottom: 20px;
    }
</style>

@section('content')
<div class="booking mb-5">
    <div class="container">
        <div class="booking-container">
            <!-- Header -->
            <div class="booking-header bg-primary">
                <h1><i class="fas fa-calendar-check"></i> Booking Kamar Hotel</h1>
                <p class="mb-0">Pilih tipe booking dan ikuti langkah mudah untuk reservasi</p>
            </div>
            
            <!-- Step Progress -->
            <div class="step-progress">
                <div class="step-indicator step-1" id="stepIndicator">
                    <div class="step-item active" id="step-1">
                        <div class="step-number">1</div>
                        <div class="step-label">Tipe Booking</div>
                    </div>
                    <div class="step-item" id="step-2">
                        <div class="step-number">2</div>
                        <div class="step-label">Data Tamu</div>
                    </div>
                    <div class="step-item" id="step-3">
                        <div class="step-number">3</div>
                        <div class="step-label">Tanggal & Durasi</div>
                    </div>
                    <div class="step-item" id="step-4">
                        <div class="step-number">4</div>
                        <div class="step-label">Pilih Kamar</div>
                    </div>
                    <div class="step-item" id="step-5">
                        <div class="step-number">5</div>
                        <div class="step-label">Konfirmasi</div>
                    </div>
                </div>
            </div>
            
            <!-- Form Content -->
            <div class="form-content">
                <form id="bookingForm">
                    @csrf
                    
                    <!-- Step 1: Pilih Tipe Booking -->
                    <div class="form-step active" id="form-step-1">
                        <div class="step-title">
                            <i class="fas fa-list-alt"></i>
                            Pilih Tipe Booking
                        </div>
                        <div class="step-subtitle">Tentukan jenis pemesanan kamar sesuai kebutuhan Anda</div>
                        
                        <div class="booking-type-selector">
                            <div class="booking-type-options">
                                <div class="booking-type-card" data-type="daily">
                                    <i class="fas fa-check-circle check-icon"></i>
                                    <div class="type-icon">
                                        <i class="fas fa-bed"></i>
                                    </div>
                                    <div class="type-name">Harian</div>
                                    <div class="type-description">Booking per hari/malam</div>
                                </div>
                                
                                <div class="booking-type-card" data-type="hourly">
                                    <i class="fas fa-check-circle check-icon"></i>
                                    <div class="type-icon">
                                        <i class="fas fa-clock"></i>
                                    </div>
                                    <div class="type-name">Per Jam</div>
                                    <div class="type-description">Booking per jam</div>
                                </div>
                                
                                <div class="booking-type-card" data-type="per_person">
                                    <i class="fas fa-check-circle check-icon"></i>
                                    <div class="type-icon">
                                        <i class="fas fa-users"></i>
                                    </div>
                                    <div class="type-name">Per Orang</div>
                                    <div class="type-description">Harga berdasarkan jumlah tamu</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="step-navigation">
                            <div></div>
                            <button type="button" class="btn btn-primary btn-block btn-step" onclick="nextStep(2)" id="selectBookingTypeBtn" disabled>
                                Lanjut <i class="fas fa-arrow-right"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Step 2: Data Tamu (unchanged from original) -->
                    <div class="form-step" id="form-step-2">
                        <div class="step-title">
                            <i class="fas fa-user"></i>
                            Pilih atau Tambah Data Tamu
                        </div>
                        <div class="step-subtitle">Pilih tamu yang sudah terdaftar atau tambahkan tamu baru</div>
                        
                        <div class="guest-section">
                            <div class="section-card">
                                <div class="section-title">
                                    <i class="fas fa-users"></i>
                                    Pilih Tamu Existing
                                </div>
                                <div class="form-group">
                                    <input type="text" id="guestSearch" class="form-control" placeholder="Cari tamu berdasarkan nama / telepon / email">
                                </div>

                                <div id="existingGuests">
                                    <div class="loading-spinner show">
                                        <div class="spinner">
                                            <i class="fas fa-spinner fa-spin"></i>
                                        </div>
                                        <p>Memuat data tamu...</p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="section-card">
                                <div class="section-title">
                                    <i class="fas fa-user-plus"></i>
                                    Atau Tambah Tamu Baru
                                </div>
                                <div class="form-group">
                                     <label for="">Nama Lengkap</label>

                                    <input type="text" class="form-control" id="newGuestName" placeholder="Nama Lengkap *" required>
                                </div>
                                <div class="form-group">
                                     <label for="">No. HP</label>

                                    <input type="text" class="form-control" id="newGuestPhone" placeholder="No. Telepon">
                                </div>
                                <div class="form-group">
                                     <label for="">Email</label>
                                    <input type="email" class="form-control" id="newGuestEmail" placeholder="Email">
                                </div>
                                <div class="form-group">
                                     <label for="">No. Identitas (KTP/Passport)</label>

                                    <input type="text" class="form-control" id="newGuestIdentity" placeholder="No. Identitas (KTP/Passport)">
                                </div>
                                 <div class="form-group">
                                     <label for="">Jenis Kelamin</label>
                                    <select name="gender" id="newGuestGender" class="form-control">
                                        <option value="">Pilih</option>
                                        <option value="L">Laki-laki</option>
                                        <option value="P">Perempuan</option>
                                    </select>
                                </div>
                                 <div class="form-group">
                                    <label for="">Tanggal Lahir</label>
                                    <input type="date" class="form-control" id="newGuestBirthDate" name="birth_date" placeholder="No. Identitas (KTP/Passport)">
                                    <small></small>
                                </div>
                                <div class="form-group mb-0">
                                     <label for="">Alamat</label>

                                    <textarea class="form-control" id="newGuestAddress" rows="2" placeholder="Alamat"></textarea>
                                </div>
                            </div>
                        </div>
                        
                        <div class="step-navigation">
                            <button type="button" class="btn btn-secondary btn-step" onclick="prevStep(1)">
                                <i class="fas fa-arrow-left"></i> Kembali
                            </button>
                            <button type="button" class="btn btn-primary btn-step" onclick="nextStep(3)">
                                Lanjut <i class="fas fa-arrow-right"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Step 3: Tanggal & Durasi (updated) -->
                    <div class="form-step" id="form-step-3">
                        <div class="step-title">
                            <i class="fas fa-calendar"></i>
                            Tanggal & Durasi Booking
                        </div>
                        <div class="step-subtitle">Tentukan tanggal dan durasi sesuai tipe booking yang dipilih</div>
                        
                        <!-- Daily Booking Parameters -->
                        <div class="booking-parameters" id="daily-parameters">
                            <h6><i class="fas fa-bed"></i> Booking Harian</h6>
                            <div class="date-row">
                                <div class="date-input-group">
                                    <label class="parameter-label">
                                        <i class="fas fa-sign-in-alt text-success"></i> 
                                        Tanggal Check-in
                                    </label>
                                    <input type="date" class="form-control" id="checkInDate" required>
                                </div>
                                <div class="date-input-group">
                                    <label class="parameter-label">
                                        <i class="fas fa-sign-out-alt text-danger"></i>
                                        Tanggal Check-out
                                    </label>
                                    <input type="date" class="form-control" id="checkOutDate" required>
                                </div>
                            </div>
                            
                            <div class="night-info" id="dateInfo" style="display: none;">
                                <div class="night-count" id="nightsCount">0</div>
                                <div>malam menginap</div>
                            </div>
                        </div>
                        
                        <!-- Hourly Booking Parameters -->
                        <div class="booking-parameters" id="hourly-parameters">
                            <h6><i class="fas fa-clock"></i> Booking Per Jam</h6>
                            <div class="hourly-datetime">
                                <div class="parameter-group">
                                    <label class="parameter-label">
                                        <i class="fas fa-calendar-day"></i>
                                        Tanggal & Waktu Mulai
                                    </label>
                                    <input type="datetime-local" class="form-control" id="hourlyStartDateTime">
                                </div>
                                
                                <div class="duration-display" id="hourlyDurationDisplay">
                                    <div style="font-size: 24px;" id="selectedHours">3</div>
                                    <div style="font-size: 12px;">jam</div>
                                </div>
                                
                                <div class="parameter-group">
                                    <label class="parameter-label">
                                        <i class="fas fa-clock"></i>
                                        Durasi (Jam)
                                    </label>
                                    <input type="range" class="form-control" id="durationHours" min="3" max="24" value="3" oninput="updateHourlyDuration()">
                                    <small class="text-muted">Minimum 3 jam, Maksimum 24 jam</small>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Per Person Booking Parameters -->
                        <div class="booking-parameters" id="per_person-parameters">
                            <h6><i class="fas fa-users"></i> Booking Per Orang</h6>
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="parameter-group">
                                        <label class="parameter-label">
                                            <i class="fas fa-sign-in-alt text-success"></i> 
                                            Check-in
                                        </label>
                                        <input type="date" class="form-control" id="personCheckInDate" required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="parameter-group">
                                        <label class="parameter-label">
                                            <i class="fas fa-sign-out-alt text-danger"></i>
                                            Check-out
                                        </label>
                                        <input type="date" class="form-control" id="personCheckOutDate" required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="parameter-group">
                                        <label class="parameter-label">
                                            <i class="fas fa-users"></i>
                                            Jumlah Tamu
                                        </label>
                                        <input type="number" class="form-control" id="guestCount" min="1" value="1" required>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="night-info" id="personDateInfo" style="display: none;">
                                <div class="row text-center">
                                    <div class="col-4">
                                        <div class="night-count" id="personNightsCount">0</div>
                                        <div>malam</div>
                                    </div>
                                    <div class="col-4">
                                        <div class="night-count" id="totalPersonsCount">1</div>
                                        <div>tamu</div>
                                    </div>
                                    <div class="col-4">
                                        <div class="night-count" id="totalPersonNights">0</div>
                                        <div>orang-malam</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Price Preview -->
                        <div class="price-preview" id="pricePreview">
                            <h6><i class="fas fa-calculator"></i> Perkiraan Biaya</h6>
                            <div class="price-breakdown" id="priceBreakdown">
                                <!-- Price calculation will be loaded here -->
                            </div>
                        </div>
                        
                        <div class="step-navigation">
                            <button type="button" class="btn btn-secondary btn-step" onclick="prevStep(2)">
                                <i class="fas fa-arrow-left"></i> Kembali
                            </button>
                            <button type="button" class="btn btn-primary btn-step" onclick="checkAvailability()" id="checkAvailabilityBtn">
                                Cek Ketersediaan <i class="fas fa-search"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Step 4: Pilih Kamar (updated to show booking type info) -->
                    <div class="form-step" id="form-step-4">
                        <div class="step-title">
                            <i class="fas fa-bed"></i>
                            Pilih Kamar yang Tersedia
                        </div>
                        <div class="step-subtitle">Pilih kamar yang sesuai dengan tipe booking yang dipilih</div>
                        
                        <div class="loading-spinner" id="roomLoading">
                            <div class="spinner">
                                <i class="fas fa-spinner fa-spin"></i>
                            </div>
                            <p>Mencari kamar yang tersedia...</p>
                        </div>
                        
                        <div class="form-group">
                            <input type="text" id="searchRoomKeyword" class="form-control" placeholder="Cari tipe kamar atau nomor kamar...">
                        </div>
                        
                        <div id="availableRooms">
                            <!-- Available rooms will be loaded here -->
                        </div>
                        
                        <div class="step-navigation">
                            <button type="button" class="btn btn-secondary btn-step" onclick="prevStep(3)">
                                <i class="fas fa-arrow-left"></i> Kembali
                            </button>
                            <button type="button" class="btn btn-primary btn-step" onclick="nextStep(5)" id="selectRoomBtn" disabled>
                                Lanjut ke Konfirmasi <i class="fas fa-arrow-right"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Step 5: Konfirmasi -->
                    <div class="form-step" id="form-step-5">
                        <div class="step-title">
                            <i class="fas fa-check-circle"></i>
                            Konfirmasi Booking
                        </div>
                        <div class="step-subtitle">Periksa kembali detail booking Anda</div>
                        
                        <div class="row">
                            <div class="col-lg-8">
                                <div class="summary-card">
                                    <div class="summary-header">
                                        <h6 class="summary-title">Detail Booking</h6>
                                    </div>
                                    <div class="summary-body" id="bookingSummary">
                                        <!-- Booking summary will be loaded here -->
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-4">
                                <div class="summary-card">
                                    <div class="summary-header">
                                        <h6 class="summary-title">Ringkasan Biaya</h6>
                                    </div>
                                    <div class="summary-body" id="costSummary">
                                        <!-- Cost summary will be loaded here -->
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="step-navigation">
                            <button type="button" class="btn btn-secondary btn-step" onclick="prevStep(4)">
                                <i class="fas fa-arrow-left"></i> Kembali
                            </button>
                            <button type="button" class="btn btn-success btn-step" onclick="confirmBooking()">
                                <i class="fas fa-check"></i> Konfirmasi Booking
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection

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

<script>
// Global variables
let currentStep = 1;
let selectedGuest = null;
let selectedRoom = null;
let selectedBookingType = null;
let bookingData = {};

// Initialize
$(document).ready(function() {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    // Set minimum datetime for hourly booking
    const now = new Date();
    now.setMinutes(now.getMinutes() + 60); // At least 1 hour from now
    $('#hourlyStartDateTime').attr('min', now.toISOString().slice(0, 16));

    // Set minimum date to today
    const today = new Date().toISOString().split('T')[0];
    $('#checkInDate, #checkOutDate, #personCheckInDate, #personCheckOutDate').attr('min', today);
    
    // Set default dates
    $('#checkInDate, #personCheckInDate').val(today);
    
    // Booking type selection
    $('.booking-type-card').click(function() {
        $('.booking-type-card').removeClass('selected');
        $('.booking-type-card .check-icon').hide();
        
        $(this).addClass('selected');
        $(this).find('.check-icon').show();
        
        selectedBookingType = $(this).data('type');
        $('#selectBookingTypeBtn').prop('disabled', false);
        
        // Show appropriate parameters
        $('.booking-parameters').removeClass('active');
        $(`#${selectedBookingType}-parameters`).addClass('active');
        
        // Reset form fields
        resetBookingParameters();
    });

    // Guest search and selection (keep existing code)
    searchGuests();
    let searchTimer;
    $('#guestSearch').on('input', function () {
        clearTimeout(searchTimer);
        const keyword = $(this).val();
        searchTimer = setTimeout(() => {
            searchGuests(keyword);
        }, 400);
    });
    
    // Date change handlers
    $('#checkInDate, #checkOutDate').change(calculateNights);
    $('#personCheckInDate, #personCheckOutDate').change(calculatePersonNights);
    $('#guestCount').change(calculatePersonNights);
    $('#hourlyStartDateTime, #durationHours').change(calculateHourlyPrice);
    
    // Update check-out minimum when check-in changes
    $('#checkInDate').change(function() {
        const checkInDate = new Date($(this).val());
        checkInDate.setDate(checkInDate.getDate() + 1);
        const minCheckOut = checkInDate.toISOString().split('T')[0];
        $('#checkOutDate').attr('min', minCheckOut);
        
        if ($('#checkOutDate').val() <= $(this).val()) {
            $('#checkOutDate').val(minCheckOut);
        }
    });
    
    $('#personCheckInDate').change(function() {
        const checkInDate = new Date($(this).val());
        checkInDate.setDate(checkInDate.getDate() + 1);
        const minCheckOut = checkInDate.toISOString().split('T')[0];
        $('#personCheckOutDate').attr('min', minCheckOut);
        
        if ($('#personCheckOutDate').val() <= $(this).val()) {
            $('#personCheckOutDate').val(minCheckOut);
        }
    });
    
    // New guest form validation
    $('#newGuestName, #newGuestPhone, #newGuestEmail, #newGuestIdentity, #newGuestAddress,#newGuestGender,#newGuestBirthDate').on('input', function() {
        if ($('#newGuestName').val().trim()) {
            $('.guest-card').removeClass('selected');
            $('.guest-card .check-icon').hide();
            
            selectedGuest = {
                name: $('#newGuestName').val(),
                phone: $('#newGuestPhone').val(),
                email: $('#newGuestEmail').val(),
                identity: $('#newGuestIdentity').val(),
                address: $('#newGuestAddress').val(),
                gender: $('#newGuestGender').val(),
                birth_date: $('#newGuestBirthDate').val(),
                type: 'new'
            };
        }
    });

    // Room search with debounce
    $('#searchRoomKeyword').on('input', debounce(function () {
        checkAvailability(false);
    }, 500));
});

// NEW: Reset booking parameters
function resetBookingParameters() {
    $('#checkInDate, #checkOutDate, #personCheckInDate, #personCheckOutDate').val('');
    $('#hourlyStartDateTime').val('');
    $('#durationHours').val(3);
    $('#guestCount').val(1);
    $('#dateInfo, #personDateInfo, #pricePreview').hide();
    updateHourlyDuration();
}

// NEW: Update hourly duration display
function updateHourlyDuration() {
    const hours = $('#durationHours').val();
    $('#selectedHours').text(hours);
    
    if ($('#hourlyStartDateTime').val()) {
        calculateHourlyPrice();
    }
}

// NEW: Calculate hourly booking price
function calculateHourlyPrice() {
    const startDateTime = $('#hourlyStartDateTime').val();
    const hours = parseInt($('#durationHours').val());
    
    if (!startDateTime || !hours) return;
    
    // You can add real-time price calculation here if needed
    // For now, we'll calculate it when checking availability
}

// NEW: Calculate person nights
function calculatePersonNights() {
    const checkIn = new Date($('#personCheckInDate').val());
    const checkOut = new Date($('#personCheckOutDate').val());
    const guestCount = parseInt($('#guestCount').val()) || 1;
    
    if (checkIn && checkOut && checkOut > checkIn) {
        const nights = Math.ceil((checkOut - checkIn) / (1000 * 60 * 60 * 24));
        const totalPersonNights = nights * guestCount;
        
        $('#personNightsCount').text(nights);
        $('#totalPersonsCount').text(guestCount);
        $('#totalPersonNights').text(totalPersonNights);
        $('#personDateInfo').show();
        
        return { nights, guestCount, totalPersonNights };
    } else {
        $('#personDateInfo').hide();
        return { nights: 0, guestCount, totalPersonNights: 0 };
    }
}

function debounce(fn, delay) {
    let timeout;
    return function (...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => fn.apply(this, args), delay);
    };
}

// UPDATED: Step navigation functions
function nextStep(step) {
    if (validateCurrentStep()) {
        currentStep = step;
        updateStepIndicator();
        showStep(step);
        
        if (step === 5) {
            loadBookingSummary();
        }
    }
}

function prevStep(step) {
    currentStep = step;
    updateStepIndicator();
    showStep(step);
}

function showStep(step) {
    $('.form-step').removeClass('active');
    $(`#form-step-${step}`).addClass('active');
}

function updateStepIndicator() {
    $('.step-item').removeClass('active completed');
    
    for (let i = 1; i < currentStep; i++) {
        $(`#step-${i}`).addClass('completed');
    }
    
    $(`#step-${currentStep}`).addClass('active');
    
    // Update indicator progress bar
    $('#stepIndicator').removeClass('step-1 step-2 step-3 step-4 step-5')
                       .addClass(`step-${currentStep}`);
}

// UPDATED: Validation with booking type support
function validateCurrentStep() {
    switch (currentStep) {
        case 1:
            if (!selectedBookingType) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Pilih Tipe Booking',
                    text: 'Silakan pilih tipe booking terlebih dahulu.'
                });
                return false;
            }
            break;
            
        case 2:
            if (!selectedGuest) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Data Tamu Diperlukan',
                    text: 'Silakan pilih tamu existing atau isi data tamu baru.'
                });
                return false;
            }
            
            if (selectedGuest.type === 'new' && !selectedGuest.name.trim()) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Nama Tamu Diperlukan',
                    text: 'Silakan masukkan nama tamu.'
                });
                return false;
            }
            break;
            
        case 3:
            return validateBookingParameters();
            
        case 4:
            if (!selectedRoom) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Pilih Kamar',
                    text: 'Silakan pilih kamar yang tersedia.'
                });
                return false;
            }
            break;
    }
    return true;
}

// NEW: Validate booking parameters based on type
function validateBookingParameters() {
    switch (selectedBookingType) {
        case 'daily':
            if (!$('#checkInDate').val() || !$('#checkOutDate').val()) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Tanggal Diperlukan',
                    text: 'Silakan pilih tanggal check-in dan check-out.'
                });
                return false;
            }
            
            if ($('#checkInDate').val() >= $('#checkOutDate').val()) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Tanggal Tidak Valid',
                    text: 'Tanggal check-out harus setelah tanggal check-in.'
                });
                return false;
            }
            break;
            
        case 'hourly':
            if (!$('#hourlyStartDateTime').val()) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Waktu Mulai Diperlukan',
                    text: 'Silakan pilih tanggal dan waktu mulai booking.'
                });
                return false;
            }
            
            const startTime = new Date($('#hourlyStartDateTime').val());
            const now = new Date();
            if (startTime <= now) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Waktu Tidak Valid',
                    text: 'Waktu mulai harus minimal 1 jam dari sekarang.'
                });
                return false;
            }
            break;
            
        case 'per_person':
            if (!$('#personCheckInDate').val() || !$('#personCheckOutDate').val()) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Tanggal Diperlukan',
                    text: 'Silakan pilih tanggal check-in dan check-out.'
                });
                return false;
            }
            
            if ($('#personCheckInDate').val() >= $('#personCheckOutDate').val()) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Tanggal Tidak Valid',
                    text: 'Tanggal check-out harus setelah tanggal check-in.'
                });
                return false;
            }
            
            if (parseInt($('#guestCount').val()) < 1) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Jumlah Tamu Tidak Valid',
                    text: 'Jumlah tamu minimal 1 orang.'
                });
                return false;
            }
            break;
    }
    return true;
}

function calculateNights() {
    const checkIn = new Date($('#checkInDate').val());
    const checkOut = new Date($('#checkOutDate').val());
    
    if (checkIn && checkOut && checkOut > checkIn) {
        const nights = Math.ceil((checkOut - checkIn) / (1000 * 60 * 60 * 24));
        $('#nightsCount').text(nights);
        $('#dateInfo').show();
        return nights;
    } else {
        $('#dateInfo').hide();
        return 0;
    }
}

// UPDATED: Check availability with booking type support
function checkAvailability(validate = true) {
    if (validate && !validateCurrentStep()) return;

    $('#roomLoading').show();
    $('#availableRooms').empty();

    // Prepare data based on booking type
    let requestData = {
        booking_type: selectedBookingType,
        search: $('#searchRoomKeyword').val()
    };

    switch (selectedBookingType) {
        case 'daily':
            requestData.check_in_date = $('#checkInDate').val();
            requestData.check_out_date = $('#checkOutDate').val();
            requestData.nights = calculateNights();
            break;
            
        case 'hourly':
            requestData.check_in_date = $('#hourlyStartDateTime').val().split('T')[0];
            requestData.duration_hours = parseInt($('#durationHours').val());
            break;
            
        case 'per_person':
            requestData.check_in_date = $('#personCheckInDate').val();
            requestData.check_out_date = $('#personCheckOutDate').val();
            requestData.guest_count = parseInt($('#guestCount').val());
            const personCalc = calculatePersonNights();
            requestData.nights = personCalc.nights;
            break;
    }

    $.ajax({
        url: '{{ route("api.bookings.check-availability") }}',
        method: 'POST',
        data: requestData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        },
        success: function(response) {
            selectedRoom = null;
            $('#selectRoomBtn').prop('disabled', true);
            $('#roomLoading').hide();
            
            if (response.total_available === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Tidak Ada Kamar Tersedia',
                    text: 'Semua kamar telah terisi pada waktu yang Anda pilih. Silakan pilih waktu lain.'
                });
            }

            if (response.success && response.data.length > 0) {
                let roomsHtml = '';

                response.data.forEach(room => {
                    const calculation = room.calculation;
                    
                    roomsHtml += `
                        <div class="room-card" data-room-id="${room.id}" 
                             data-room-calculation='${JSON.stringify(calculation)}'>
                            <div class="row">
                                <div class="col-md-8">
                                    <h6>${room.type_name} - Kamar ${room.room_number}</h6>
                                    <p class="text-muted mb-2">${room.description || 'Kamar dengan fasilitas lengkap'}</p>
                                    <div class="mb-2">
                                        <span class="badge badge-info">${getBookingTypeDisplay(selectedBookingType)}</span>
                                        <small class="ml-2">Max: ${room.max_capacity_adult} Dewasa, ${room.max_capacity_child} Anak</small>
                                    </div>
                                </div>
                                <div class="col-md-4 text-right">
                                    <div class="mb-2">
                                        <small class="text-muted">Harga dasar:</small><br>
                                        <strong>${room.formatted_prices.base_price}</strong>
                                        <small class="text-muted">/ ${getBookingTypeUnit(selectedBookingType)}</small>
                                    </div>
                                    <div class="mb-2">
                                        <small class="text-muted">Total + PPN:</small><br>
                                        <h5 class="text-success mb-0">${room.formatted_prices.grand_total}</h5>
                                        <small class="text-muted">${getCalculationDisplay(selectedBookingType, calculation)}</small>
                                    </div>
                                </div>
                            </div>
                            <i class="fas fa-check-circle text-success position-absolute" style="top: 15px; right: 15px; display: none;"></i>
                        </div>
                    `;
                });

                $('#availableRooms').html(roomsHtml);

                $('.room-card').click(function() {
                    $('.room-card').removeClass('selected');
                    $('.room-card .fas.fa-check-circle').hide();

                    $(this).addClass('selected');
                    $(this).find('.fas.fa-check-circle').show();

                    selectedRoom = {
                        id: $(this).data('room-id'),
                        calculation: $(this).data('room-calculation')
                    };

                    $('#selectRoomBtn').prop('disabled', false);
                });

                if (validate) {
                    nextStep(4);
                }
            } else {
                $('#availableRooms').html(`
                    <div class="alert alert-warning text-center">
                        <i class="fas fa-exclamation-triangle fa-2x mb-3"></i>
                        <h5>Tidak Ada Kamar Tersedia</h5>
                        <p>Maaf, tidak ada kamar yang tersedia pada waktu yang Anda pilih. 
                        Silakan pilih waktu lain.</p>
                    </div>
                `);
            }
        },
        error: function(xhr) {
            $('#roomLoading').hide();
            let errorMsg = 'Terjadi kesalahan saat mengecek ketersediaan kamar';

            if (xhr.responseJSON && xhr.responseJSON.message) {
                errorMsg = xhr.responseJSON.message;
            }

            $('#availableRooms').html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i> ${errorMsg}
                </div>
            `);
        }
    });
}

// NEW: Helper functions for booking type display
function getBookingTypeDisplay(type) {
    const displays = {
        'daily': 'Harian',
        'hourly': 'Per Jam',
        'per_person': 'Per Orang'
    };
    return displays[type] || 'Unknown';
}

function getBookingTypeUnit(type) {
    const units = {
        'daily': 'malam',
        'hourly': 'jam',
        'per_person': 'orang'
    };
    return units[type] || 'unit';
}

function getCalculationDisplay(type, calculation) {
    const details = calculation.calculation_details;
    switch (type) {
        case 'daily':
            return `${details.nights} malam`;
        case 'hourly':
            return `${details.hours} jam`;
        case 'per_person':
            return `${details.persons} orang x ${details.nights} malam`;
        default:
            return '';
    }
}

// UPDATED: Load booking summary with booking type info
function loadBookingSummary() {
    const calculation = selectedRoom.calculation;
    
    let durationInfo = '';
    switch (selectedBookingType) {
        case 'daily':
            const nights = calculateNights();
            durationInfo = `
                <tr><td><strong>Check-in:</strong></td><td>${new Date($('#checkInDate').val()).toLocaleDateString('id-ID')}</td></tr>
                <tr><td><strong>Check-out:</strong></td><td>${new Date($('#checkOutDate').val()).toLocaleDateString('id-ID')}</td></tr>
                <tr><td><strong>Lama Menginap:</strong></td><td>${nights} malam</td></tr>
            `;
            break;
        case 'hourly':
            const startDateTime = new Date($('#hourlyStartDateTime').val());
            const endDateTime = new Date(startDateTime.getTime() + (parseInt($('#durationHours').val()) * 60 * 60 * 1000));
            durationInfo = `
                <tr><td><strong>Mulai:</strong></td><td>${startDateTime.toLocaleString('id-ID')}</td></tr>
                <tr><td><strong>Selesai:</strong></td><td>${endDateTime.toLocaleString('id-ID')}</td></tr>
                <tr><td><strong>Durasi:</strong></td><td>${$('#durationHours').val()} jam</td></tr>
            `;
            break;
        case 'per_person':
            const personCalc = calculatePersonNights();
            durationInfo = `
                <tr><td><strong>Check-in:</strong></td><td>${new Date($('#personCheckInDate').val()).toLocaleDateString('id-ID')}</td></tr>
                <tr><td><strong>Check-out:</strong></td><td>${new Date($('#personCheckOutDate').val()).toLocaleDateString('id-ID')}</td></tr>
                <tr><td><strong>Jumlah Tamu:</strong></td><td>${personCalc.guestCount} orang</td></tr>
                <tr><td><strong>Lama Menginap:</strong></td><td>${personCalc.nights} malam</td></tr>
                <tr><td><strong>Total Orang-Malam:</strong></td><td>${personCalc.totalPersonNights}</td></tr>
            `;
            break;
    }
    
    const summaryHtml = `
        <table class="table table-borderless">
            <tr><td><strong>Tamu:</strong></td><td>${selectedGuest.name}</td></tr>
            <tr><td><strong>Tipe Booking:</strong></td><td><span class="badge badge-info">${getBookingTypeDisplay(selectedBookingType)}</span></td></tr>
            ${durationInfo}
            <tr><td><strong>Kamar:</strong></td><td>${$('.room-card.selected h6').text()}</td></tr>
        </table>
    `;
    
    const costHtml = `
        <div class="summary-item">
            <span>Harga Dasar (${getCalculationDisplay(selectedBookingType, calculation)})</span>
            <span>Rp ${calculation.total_price.toLocaleString('id-ID')}</span>
        </div>
        <div class="summary-item">
            <span>PPN (${(calculation.ppn_rate * 100).toFixed(1)}%)</span>
            <span>Rp ${calculation.ppn_amount.toLocaleString('id-ID')}</span>
        </div>
        <div class="summary-item">
            <span>Total Bayar</span>
            <span>Rp ${calculation.grand_total.toLocaleString('id-ID')}</span>
        </div>
    `;
    
    $('#bookingSummary').html(summaryHtml);
    $('#costSummary').html(costHtml);
}

// UPDATED: Confirm booking with booking type support
function confirmBooking() {
    Swal.fire({
        title: 'Konfirmasi Booking',
        text: `Apakah Anda yakin ingin melakukan booking ${getBookingTypeDisplay(selectedBookingType)}?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Ya, Booking!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Memproses Booking...',
                html: 'Mohon tunggu sebentar',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Prepare booking data based on type
            let bookingData = {
                guest_data: selectedGuest,
                room_id: selectedRoom.id,
                booking_type: selectedBookingType
            };

            switch (selectedBookingType) {
                case 'daily':
                    bookingData.check_in_date = $('#checkInDate').val();
                    bookingData.check_out_date = $('#checkOutDate').val();
                    break;
                case 'hourly':
                    const startDateTime = $('#hourlyStartDateTime').val();
                    bookingData.check_in_date = startDateTime.split('T')[0];
                    bookingData.duration_hours = parseInt($('#durationHours').val());
                    break;
                case 'per_person':
                    bookingData.check_in_date = $('#personCheckInDate').val();
                    bookingData.check_out_date = $('#personCheckOutDate').val();
                    bookingData.guest_count = parseInt($('#guestCount').val());
                    break;
            }
            
            $.ajax({
                url: '{{ route("bookings.store") }}',
                method: 'POST',
                data: bookingData,
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Booking Berhasil!',
                            html: `
                                <div class="text-left">
                                    <p><strong>ID Booking:</strong> #${response.data.booking_id}</p>
                                    <p><strong>Tipe:</strong> ${response.data.booking_type}</p>
                                    <p><strong>Tamu:</strong> ${response.data.guest_name}</p>
                                    <p><strong>Kamar:</strong> ${response.data.room_number}</p>
                                    <p><strong>Durasi:</strong> ${response.data.duration_display}</p>
                                    <p><strong>Total:</strong> Rp ${response.data.total_amount.toLocaleString('id-ID')}</p>
                                </div>
                            `,
                            confirmButtonText: 'Lihat Booking'
                        }).then(() => {
                            window.location.href = `{{ url('bookings') }}`;
                        });
                    }
                },
                error: function(xhr) {
                    let errorMsg = 'Terjadi kesalahan saat memproses booking';
                    
                    if (xhr.responseJSON) {
                        if (xhr.status === 422) {
                            const errors = xhr.responseJSON.errors;
                            let errorList = '';
                            Object.keys(errors).forEach(key => {
                                errorList += `<li>${errors[key][0]}</li>`;
                            });
                            errorMsg = `<ul class="text-left">${errorList}</ul>`;
                        } else {
                            errorMsg = xhr.responseJSON.message || errorMsg;
                        }
                    }
                    
                    Swal.fire({
                        icon: 'error',
                        title: 'Booking Gagal!',
                        html: errorMsg
                    });
                }
            });
        }
    });
}

// Keep existing guest search functions
function searchGuests(keyword = '') {
    $('#existingGuests').html(`
        <div class="loading-spinner show">
            <div class="spinner">
                <i class="fas fa-spinner fa-spin"></i>
            </div>
            <p>Mencari tamu...</p>
        </div>
    `);

    $.ajax({
        url: '{{ route("api.guests.search") }}',
        method: 'GET',
        data: { search: keyword },
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        },
        success: function(response) {
            if (response.success) {
                let guestsHtml = '';
                if (response.data.length === 0) {
                    guestsHtml = `
                        <div class="empty-state">
                            <div class="empty-icon"><i class="fas fa-user-slash"></i></div>
                            <p>Tidak ditemukan tamu yang cocok</p>
                        </div>
                    `;
                } else {
                    response.data.forEach(guest => {
                        guestsHtml += `
                            <div class="guest-card" data-guest-id="${guest.id}">
                                <i class="fas fa-check-circle check-icon"></i>
                                <div class="guest-name">${guest.name}</div>
                                <div class="guest-info">
                                    <i class="fas fa-phone"></i> ${guest.phone || 'No phone'}<br>
                                    <i class="fas fa-envelope"></i> ${guest.email || 'No email'}
                                </div>
                            </div>
                        `;
                    });
                }

                $('#existingGuests').html(guestsHtml);

                $('.guest-card').click(function() {
                    $('.guest-card').removeClass('selected');
                    $('.guest-card .check-icon').hide();

                    $(this).addClass('selected');
                    $(this).find('.check-icon').show();

                    selectedGuest = {
                        id: $(this).data('guest-id'),
                        name: $(this).find('.guest-name').text(),
                        type: 'existing'
                    };
                    $('#newGuestName, #newGuestPhone, #newGuestEmail, #newGuestIdentity, #newGuestAddress,#newGuestGender,#newGuestBirthDate').val('');
                });
            }
        },
        error: function() {
            $('#existingGuests').html(`
                <div class="empty-state">
                    <div class="empty-icon"><i class="fas fa-exclamation-triangle"></i></div>
                    <p>Gagal mencari data tamu</p>
                </div>
            `);
        }
    });
}

// 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