{{-- File: resources/views/bookings/create.blade.php --}}

@extends('admin-layouts.master')

@section('title', $title)


<style>
    .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: 33.33%; }
    .step-indicator.step-3::after { width: 66.66%; }
    .step-indicator.step-4::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;
        }
    }

    .date-input-group {
        position: relative;
    }

    .date-icon {
        position: absolute;
        left: 15px;
        top: 50%;
        transform: translateY(-50%);
        color: #636e72;
        z-index: 2;
    }

    .date-input {
        padding-left: 45px;
    }

    .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);
    }

    .room-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 15px;
    }

    .room-title {
        font-size: 18px;
        font-weight: bold;
        color: #2d3436;
        margin-bottom: 5px;
    }

    .room-description {
        color: #636e72;
        font-size: 14px;
        margin-bottom: 10px;
    }

    .room-capacity {
        color: #636e72;
        font-size: 13px;
    }

    .room-pricing {
        text-align: right;
    }

    .price-per-night {
        color: #636e72;
        font-size: 13px;
        margin-bottom: 5px;
    }

    .price-total {
        font-size: 20px;
        font-weight: bold;
        color: #28a745;
    }

    .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">
        <!-- Back Button -->
        {{-- <div class="mb-4">
            <a href="{{ route('bookings.index') }}" class="btn btn-light">
                <i class="fas fa-arrow-left"></i> Kembali ke Daftar Booking
            </a>
        </div> --}}

        <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">Ikuti langkah-langkah mudah untuk melakukan 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">Data Tamu</div>
                    </div>
                    <div class="step-item" id="step-2">
                        <div class="step-number">2</div>
                        <div class="step-label">Tanggal</div>
                    </div>
                    <div class="step-item" id="step-3">
                        <div class="step-number">3</div>
                        <div class="step-label">Pilih Kamar</div>
                    </div>
                    <div class="step-item" id="step-4">
                        <div class="step-number">4</div>
                        <div class="step-label">Konfirmasi</div>
                    </div>
                </div>
            </div>

            <!-- Form Content -->
            <div class="form-content">
                <form id="bookingForm">
                    @csrf

                    <!-- Step 1: Data Tamu -->
                    <div class="form-step active" id="form-step-1">
                        <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">
                            <div></div>
                            <button type="button" class="btn btn-primary btn-block btn-step" onclick="nextStep(2)">
                                Lanjut <i class="fas fa-arrow-right"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Step 2: Pilih Tanggal -->
                    <div class="form-step" id="form-step-2">
                        <div class="step-title">
                            <i class="fas fa-calendar"></i>
                            Pilih Tanggal Menginap
                        </div>
                        <div class="step-subtitle">Tentukan tanggal check-in dan check-out Anda</div>

                        <div class="date-row">
                            <div class="date-input-group">
                                <label class="form-label">
                                    <i class="fas fa-sign-in-alt text-success"></i>
                                    Tanggal Check-in
                                </label>
                                <div class="position-relative">
                                    {{-- <i class="fas fa-calendar-day date-icon"></i> --}}
                                    <input type="date" class="form-control date-input" id="checkInDate" required>
                                </div>
                            </div>
                            <div class="date-input-group">
                                <label class="form-label">
                                    <i class="fas fa-sign-out-alt text-danger"></i>
                                    Tanggal Check-out
                                </label>
                                <div class="position-relative">
                                    {{-- <i class="fas fa-calendar-day date-icon"></i> --}}
                                    <input type="date" class="form-control date-input" id="checkOutDate" required>
                                </div>
                            </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 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="checkAvailability()">
                                Cek Ketersediaan <i class="fas fa-search"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Step 3: Pilih Kamar -->
                    <div class="form-step" id="form-step-3">
                        <div class="step-title">
                            <i class="fas fa-bed"></i>
                            Pilih Kamar yang Tersedia
                        </div>
                        <div class="step-subtitle">Pilih kamar yang sesuai dengan kebutuhan Anda</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(2)">
                                <i class="fas fa-arrow-left"></i> Kembali
                            </button>
                            <button type="button" class="btn btn-primary btn-step" onclick="nextStep(4)" id="selectRoomBtn" disabled>
                                Lanjut ke Konfirmasi <i class="fas fa-arrow-right"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Step 4: Konfirmasi -->
                    <div class="form-step" id="form-step-4">
                        <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(3)">
                                <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 bookingData = {};

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

    $('#searchRoomKeyword').on('input', debounce(function () {
    checkAvailability(false); // jangan validasi step saat search
}, 500));



     searchGuests(); // load default 5 tamu

    let searchTimer;
    $('#guestSearch').on('input', function () {
        clearTimeout(searchTimer);
        const keyword = $(this).val();

        searchTimer = setTimeout(() => {
            searchGuests(keyword);
        }, 400); // delay 400ms
    });

    // Set minimum date to today
    const today = new Date().toISOString().split('T')[0];
    $('#checkInDate').attr('min', today);
    $('#checkOutDate').attr('min', today);

    // Set default check-in to today
    $('#checkInDate').val(today);

    // Load existing guests
    loadExistingGuests();

    // Pre-select guest if coming from guest page
    const urlParams = new URLSearchParams(window.location.search);
    const guestId = urlParams.get('guest_id');
    if (guestId) {
        setTimeout(() => {
            $(`.guest-card[data-guest-id="${guestId}"]`).trigger('click');
        }, 1000);
    }

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

        // Reset check-out if it's before new minimum
        if ($('#checkOutDate').val() <= $(this).val()) {
            $('#checkOutDate').val(minCheckOut);
        }

        calculateNights();
    });

    $('#checkOutDate').change(calculateNights);

    // New guest form validation
    $('#newGuestName, #newGuestPhone, #newGuestEmail').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(),
                birth_date: $('#newGuestBirthDate').val(),
                gender: $('#newGuestGender').val(),


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

// Load existing guests from database
function loadExistingGuests() {
    $.ajax({
        url: '{{ route("api.guests.index") }}',
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        },
        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-users"></i>
                            </div>
                            <p>Belum ada data tamu.<br>Silakan tambah tamu baru di sebelah kanan.</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);

                // Add click handlers for guest cards
                $('.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'
                    };

                    // Clear new guest form
                    $('#newGuestName, #newGuestPhone, #newGuestEmail, #newGuestIdentity, #newGuestAddress,#newGuestBirthDate,#newGuestGender').val('');
                });
            }
        },
        error: function() {
            $('#existingGuests').html(`
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="fas fa-exclamation-triangle"></i>
                    </div>
                    <p>Gagal memuat data tamu</p>
                </div>
            `);
        }
    });
}

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' // <-- Tambahkan ini
        },
        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);

                // Klik pilih tamu
                $('.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'
                    };

                    // Reset form tamu baru
                    $('#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>
            `);
        }
    });
}


// Step navigation functions
function nextStep(step) {
    if (validateCurrentStep()) {
        currentStep = step;
        updateStepIndicator();
        showStep(step);

        if (step === 4) {
            loadBookingSummary();
        }
    }
}

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

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

function updateStepIndicator() {
    $('.step').removeClass('active completed');

    for (let i = 1; i < currentStep; i++) {
        $(`#step-${i}`).addClass('completed');
    }

    $(`#step-${currentStep}`).addClass('active');
}

function validateCurrentStep() {
    switch (currentStep) {
        case 1:
            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 2:
            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 3:
            if (!selectedRoom) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Pilih Kamar',
                    text: 'Silakan pilih kamar yang tersedia.'
                });
                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;
    }
}

function checkAvailability(validate = true) {
    if (validate && !validateCurrentStep()) return;

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

    $.ajax({
        url: '{{ route("api.bookings.check-availability") }}',
        method: 'POST',
        data: {
            check_in_date: $('#checkInDate').val(),
            check_out_date: $('#checkOutDate').val(),
            search: $('#searchRoomKeyword').val()
        },
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        },
        success: function(response) {
            selectedRoom = null;
            $('#selectRoomBtn').prop('disabled', true);
            $('#roomLoading').hide();
            // Tambahkan pengecekan total_available === 0
            if (response.total_available === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Tidak Ada Kamar Tersedia',
                    text: 'Semua kamar telah terisi pada tanggal yang Anda pilih. Silakan pilih tanggal lain.'
                });
            }
            if (response.success && response.data.length > 0) {
                const nights = calculateNights();
                let roomsHtml = '';

                response.data.forEach(room => {
                    const totalPrice = room.price_per_night * nights;
                    const ppn = Math.round(totalPrice * (room.ppn / 100));
                    const grandTotal = totalPrice + ppn;

                    roomsHtml += `
                        <div class="room-card" data-room-id="${room.id}"
                             data-room-price="${room.price_per_night}"
                             data-room-ppn="${room.ppn}">
                            <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>
                                    <small><i class="fas fa-users"></i> Max: ${room.max_capacity_adult} Dewasa, ${room.max_capacity_child} Anak</small>
                                </div>
                                <div class="col-md-4 text-right">
                                    <div class="mb-2">
                                        <small class="text-muted">Per malam:</small><br>
                                        <strong>Rp ${room.price_per_night.toLocaleString('id-ID')}</strong>
                                    </div>
                                    <div class="mb-2">
                                        <small class="text-muted">${nights} malam + PPN ${room.ppn}%:</small><br>
                                        <h5 class="text-success mb-0">Rp ${grandTotal.toLocaleString('id-ID')}</h5>
                                    </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'),
                        price: $(this).data('room-price'),
                        ppn: $(this).data('room-ppn')
                    };

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

                nextStep(3); // ini boleh kamu sesuaikan jika kamu hanya ingin next step saat submit, bukan saat search
            } 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 tanggal yang Anda pilih.
                        Silakan pilih tanggal 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>
            `);
        }
    });
}


function loadBookingSummary() {
    const nights = calculateNights();
    const totalPrice = selectedRoom.price * nights;
    const ppn = Math.round(totalPrice * (selectedRoom.ppn / 100));
    const grandTotal = totalPrice + ppn;

    const summaryHtml = `
        <table class="table table-borderless">
            <tr>
                <td><strong>Tamu:</strong></td>
                <td>${selectedGuest.name}</td>
            </tr>
            <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>
            <tr>
                <td><strong>Kamar:</strong></td>
                <td>${$('.room-card.selected h6').text()}</td>
            </tr>
        </table>
    `;

    const costHtml = `
        <div class="summary-item">
            <span>Harga Kamar (${nights} malam)</span>
            <span>Rp ${totalPrice.toLocaleString('id-ID')}</span>
        </div>
        <div class="summary-item">
            <span>PPN (${selectedRoom.ppn}%)</span>
            <span>Rp ${ppn.toLocaleString('id-ID')}</span>
        </div>
        <div class="summary-item">
            <span>Total Bayar</span>
            <span>Rp ${grandTotal.toLocaleString('id-ID')}</span>
        </div>
    `;

    $('#bookingSummary').html(summaryHtml);
    $('#costSummary').html(costHtml);
}

function confirmBooking() {
    Swal.fire({
        title: 'Konfirmasi Booking',
        text: 'Apakah Anda yakin ingin melakukan booking?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Ya, Booking!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            // Show loading
            Swal.fire({
                title: 'Memproses Booking...',
                html: 'Mohon tunggu sebentar',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            // AJAX call to save booking
            $.ajax({
                url: '{{ route("bookings.store") }}',
                method: 'POST',
                data: {
                    guest_data: selectedGuest,
                    room_id: selectedRoom.id,
                    check_in_date: $('#checkInDate').val(),
                    check_out_date: $('#checkOutDate').val()
                },
                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>Tamu:</strong> ${response.data.guest_name}</p>
                                    <p><strong>Kamar:</strong> ${response.data.room_number}</p>
                                    <p><strong>Check-in:</strong> ${new Date(response.data.check_in_date).toLocaleDateString('id-ID')}</p>
                                    <p><strong>Check-out:</strong> ${new Date(response.data.check_out_date).toLocaleDateString('id-ID')}</p>
                                    <p><strong>Total:</strong> Rp ${response.data.total_amount.toLocaleString('id-ID')}</p>
                                </div>
                            `,
                            confirmButtonText: 'Lihat Booking'
                        }).then(() => {
                            // Redirect to booking detail or list
                            window.location.href = `{{ url('bookings') }}`;
                        });
                    }
                },
                error: function(xhr) {
                    let errorMsg = 'Terjadi kesalahan saat memproses booking';

                    if (xhr.responseJSON) {
                        if (xhr.status === 422) {
                            // Validation errors
                            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
                    });
                }
            });
        }
    });
}

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