@extends('admin-layouts.master')

@section('title', $title)

@section('content')
<style>
    .badge-lg {
        font-size: 0.9rem;
        padding: 0.5rem 0.75rem;
    }
    
    .border-left-primary { border-left: 0.25rem solid #4e73df !important; }
    .border-left-success { border-left: 0.25rem solid #1cc88a !important; }
    .border-left-info { border-left: 0.25rem solid #36b9cc !important; }
    .border-left-warning { border-left: 0.25rem solid #f6c23e !important; }
    
    .timeline {
        position: relative;
        padding-left: 2rem;
    }
    
    .timeline::before {
        content: '';
        position: absolute;
        left: 0.75rem;
        top: 0;
        bottom: 0;
        width: 2px;
        background: #e3e6f0;
    }
    
    .timeline-item {
        position: relative;
        margin-bottom: 1rem;
    }
    
    .timeline-marker {
        position: absolute;
        left: -1.5rem;
        width: 0.75rem;
        height: 0.75rem;
        border-radius: 50%;
        border: 2px solid #fff;
        z-index: 1;
    }
    
    .timeline-content {
        padding-left: 0.5rem;
    }
    
    .table th {
        border-top: none;
        font-weight: 600;
    }
    
    .d-grid {
        display: grid;
    }
    
    .gap-2 {
        gap: 0.5rem;
    }
</style>
<div class="container-fluid">
    <!-- Page Header -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <div>
            <h1 class="h3 mb-2 text-gray-800">
                <i class="fas fa-eye text-primary me-2"></i>{{ $title }}
            </h1>
            <p class="mb-0 text-gray-600">{{ $subtitle }}</p>
        </div>
        <div class="d-flex gap-2">
            <a href="{{ route($route.'.index') }}" class="btn btn-secondary shadow-sm mr-2">
                <i class="fas fa-arrow-left fa-sm me-1"></i> Kembali ke Daftar
            </a>
            <a href="{{ route($route.'.edit', $room->id) }}" class="btn btn-warning shadow-sm mr-2">
                <i class="fas fa-edit fa-sm me-1"></i> Edit Kamar
            </a>
            <div class="dropdown">
                <button class="btn btn-primary dropdown-toggle shadow-sm" type="button" data-toggle="dropdown">
                    <i class="fas fa-cog fa-sm me-1"></i> Status: 
                    @php
                        $statusLabels = [
                            'available' => 'Tersedia',
                            'occupied' => 'Terisi',
                            'maintenance' => 'Maintenance',
                            'cleaning' => 'Cleaning'
                        ];
                    @endphp
                    {{ $statusLabels[$room->status] ?? $room->status }}
                </button>
                <div class="dropdown-menu">
                    <h6 class="dropdown-header">Ubah Status:</h6>
                    <a class="dropdown-item" href="#" onclick="changeStatus('available')">
                        <i class="fas fa-check-circle text-success"></i> Tersedia
                    </a>
                    <a class="dropdown-item" href="#" onclick="changeStatus('occupied')">
                        <i class="fas fa-user text-danger"></i> Terisi
                    </a>
                    <a class="dropdown-item" href="#" onclick="changeStatus('maintenance')">
                        <i class="fas fa-tools text-warning"></i> Maintenance
                    </a>
                    <a class="dropdown-item" href="#" onclick="changeStatus('cleaning')">
                        <i class="fas fa-broom text-info"></i> Cleaning
                    </a>
                </div>
            </div>
        </div>
    </div>

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

    <!-- Room Statistics Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Booking</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $room_stats['total_bookings'] }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-calendar-check fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Booking Selesai</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $room_stats['completed_bookings'] }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-check-circle fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Okupansi Bulan Ini</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $room_stats['occupancy_rate'] }}%</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-percentage fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Revenue Bulan Ini</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">Rp {{ number_format($room_stats['revenue_this_month'], 0, ',', '.') }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-money-bill-wave fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Room Information -->
        <div class="col-lg-8">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-info-circle me-1"></i>Informasi Kamar
                    </h6>
                    @php
                        $statusConfig = [
                            'available' => ['class' => 'success', 'icon' => 'check-circle', 'text' => 'Tersedia'],
                            'occupied' => ['class' => 'danger', 'icon' => 'user', 'text' => 'Terisi'],
                            'maintenance' => ['class' => 'warning', 'icon' => 'tools', 'text' => 'Maintenance'],
                            'cleaning' => ['class' => 'info', 'icon' => 'broom', 'text' => 'Cleaning']
                        ];
                        $config = $statusConfig[$room->status] ?? ['class' => 'secondary', 'icon' => 'question', 'text' => 'Unknown'];
                    @endphp
                    <span class="badge badge-{{ $config['class'] }} badge-lg">
                        <i class="fas fa-{{ $config['icon'] }} me-1"></i>{{ $config['text'] }}
                    </span>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-borderless">
                                <tr>
                                    <td width="40%" class="font-weight-bold text-gray-800">Nomor Kamar:</td>
                                    <td class="text-primary font-weight-bold h5">{{ $room->room_number }}</td>
                                </tr>
                                <tr>
                                    <td class="font-weight-bold text-gray-800">Tipe Kamar:</td>
                                    <td>
                                        <span class="badge badge-primary badge-lg">{{ $room->typeRoom->name ?? 'Unknown' }}</span>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="font-weight-bold text-gray-800">Kapasitas Dewasa:</td>
                                    <td>
                                        <i class="fas fa-user text-primary me-1"></i>
                                        <strong>{{ $room->max_capacity_adult }} orang</strong>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="font-weight-bold text-gray-800">Kapasitas Anak:</td>
                                    <td>
                                        <i class="fas fa-child text-info me-1"></i>
                                        <strong>{{ $room->max_capacity_child }} anak</strong>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-borderless">
                                <tr>
                                    <td width="40%" class="font-weight-bold text-gray-800">Harga per Malam:</td>
                                    <td class="text-success font-weight-bold h6">
                                        Rp {{ number_format($room->typeRoom->harga_per_malam ?? 0, 0, ',', '.') }}
                                    </td>
                                </tr>
                                @if($room->typeRoom && $room->typeRoom->harga_per_orang > 0)
                                <tr>
                                    <td class="font-weight-bold text-gray-800">Harga per Orang:</td>
                                    <td class="text-info font-weight-bold">
                                        Rp {{ number_format($room->typeRoom->harga_per_orang, 0, ',', '.') }}
                                    </td>
                                </tr>
                                @endif
                                @if($room->typeRoom)
                                <tr>
                                    <td class="font-weight-bold text-gray-800">PPN:</td>
                                    <td>
                                        <span class="badge badge-warning">{{ $room->typeRoom->ppn ?? 11 }}%</span>
                                    </td>
                                </tr>
                                @endif
                                <tr>
                                    <td class="font-weight-bold text-gray-800">Dibuat:</td>
                                    <td class="text-muted">{{ $room->created_at->format('d/m/Y H:i') }}</td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    
                    @if($room->description)
                    <hr>
                    <div class="row">
                        <div class="col-12">
                            <h6 class="font-weight-bold text-gray-800 mb-2">Deskripsi:</h6>
                            <p class="text-gray-700">{{ $room->description }}</p>
                        </div>
                    </div>
                    @endif
                </div>
            </div>

            <!-- Booking History -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-history me-1"></i>Riwayat Booking (10 Terakhir)
                    </h6>
                </div>
                <div class="card-body">
                    @if($booking_history->count() > 0)
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover">
                                <thead class="thead-light">
                                    <tr>
                                        <th width="5%">No</th>
                                        <th width="15%">Booking ID</th>
                                        <th width="20%">Nama Tamu</th>
                                        <th width="15%">Check-in</th>
                                        <th width="15%">Check-out</th>
                                        <th width="15%">Total</th>
                                        <th width="15%">Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($booking_history as $booking)
                                    <tr>
                                        <td>{{ $loop->iteration }}</td>
                                        <td>
                                            <strong class="text-primary">#{{ $booking->booking_code ?? $booking->id }}</strong>
                                        </td>
                                        <td>{{ $booking->guest->name ?? 'Unknown' }}</td>
                                        <td>{{ \Carbon\Carbon::parse($booking->check_in_date)->format('d/m/Y') }}</td>
                                        <td>{{ \Carbon\Carbon::parse($booking->check_out_date)->format('d/m/Y') }}</td>
                                        <td class="text-success font-weight-bold">
                                            Rp {{ number_format($booking->total_amount ?? 0, 0, ',', '.') }}
                                        </td>
                                        <td>
                                            @php
                                                $statusBookingConfig = [
                                                    'booked' => ['class' => 'info', 'text' => 'Booked'],
                                                    'checked_in' => ['class' => 'warning', 'text' => 'Check-in'],
                                                    'checked_out' => ['class' => 'success', 'text' => 'Check-out'],
                                                    'cancelled' => ['class' => 'danger', 'text' => 'Cancelled'],
                                                ];
                                                $bookingConfig = $statusBookingConfig[$booking->status] ?? ['class' => 'secondary', 'text' => $booking->status];
                                            @endphp
                                            <span class="badge badge-{{ $bookingConfig['class'] }}">
                                                {{ $bookingConfig['text'] }}
                                            </span>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @else
                        <div class="text-center py-4">
                            <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">Belum ada riwayat booking</h5>
                            <p class="text-muted">Kamar ini belum pernah dibooking oleh tamu</p>
                        </div>
                    @endif
                </div>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-4">
            <!-- Quick Actions -->
            <div class="card shadow mb-4">
                <div class="card-header bg-primary text-white">
                    <h6 class="mb-0"><i class="fas fa-bolt me-1"></i>Aksi Cepat</h6>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <a href="{{ route($route.'.edit', $room->id) }}" class="btn btn-warning btn-block">
                            <i class="fas fa-edit me-1"></i> Edit Kamar
                        </a>
                        <button class="btn btn-info btn-block" onclick="checkAvailability()">
                            <i class="fas fa-calendar-check me-1"></i> Cek Ketersediaan
                        </button>
                        <button class="btn btn-success btn-block mb-2" onclick="createBooking()">
                            <i class="fas fa-plus-circle me-1"></i> Buat Booking
                        </button>
                        <div class="dropdown">
                            <button class="btn btn-secondary btn-block dropdown-toggle" type="button" data-toggle="dropdown">
                                <i class="fas fa-cog me-1"></i> Ubah Status
                            </button>
                            <div class="dropdown-menu w-100">
                                <a class="dropdown-item" href="#" onclick="changeStatus('available')">
                                    <i class="fas fa-check-circle text-success"></i> Set Tersedia
                                </a>
                                <a class="dropdown-item" href="#" onclick="changeStatus('occupied')">
                                    <i class="fas fa-user text-danger"></i> Set Terisi
                                </a>
                                <a class="dropdown-item" href="#" onclick="changeStatus('maintenance')">
                                    <i class="fas fa-tools text-warning"></i> Set Maintenance
                                </a>
                                <a class="dropdown-item" href="#" onclick="changeStatus('cleaning')">
                                    <i class="fas fa-broom text-info"></i> Set Cleaning
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Type Room Details -->
            @if($room->typeRoom)
            <div class="card shadow mb-4">
                <div class="card-header bg-info text-white">
                    <h6 class="mb-0"><i class="fas fa-bed me-1"></i>Detail Tipe Kamar</h6>
                </div>
                <div class="card-body">
                    <h6 class="font-weight-bold text-primary">{{ $room->typeRoom->name }}</h6>
                    @if($room->typeRoom->description)
                        <p class="text-muted small">{{ Str::limit($room->typeRoom->description, 150) }}</p>
                    @endif
                    
                    <hr>
                    
                    <div class="row text-center">
                        <div class="col-6">
                            <div class="border-right">
                                <i class="fas fa-users text-primary"></i>
                                <div class="font-weight-bold">{{ $room->typeRoom->kapasitas ?? 2 }}</div>
                                <small class="text-muted">Kapasitas</small>
                            </div>
                        </div>
                        <div class="col-6">
                            <i class="fas fa-percentage text-warning"></i>
                            <div class="font-weight-bold">{{ $room->typeRoom->ppn ?? 11 }}%</div>
                            <small class="text-muted">PPN</small>
                        </div>
                    </div>

                    @if($room->typeRoom->fasilitas)
                    <hr>
                    <h6 class="font-weight-bold text-gray-800 mb-2">Fasilitas:</h6>
                    <p class="text-muted small">{{ $room->typeRoom->fasilitas }}</p>
                    @endif
                </div>
            </div>
            @endif

            <!-- Activity Log -->
            <div class="card shadow mb-4">
                <div class="card-header bg-dark text-white">
                    <h6 class="mb-0"><i class="fas fa-clock me-1"></i>Log Aktivitas</h6>
                </div>
                <div class="card-body">
                    <div class="timeline">
                        <div class="timeline-item">
                            <div class="timeline-marker bg-primary"></div>
                            <div class="timeline-content">
                                <small class="text-muted">{{ $room->created_at->format('d/m/Y H:i') }}</small>
                                <p class="mb-0">Kamar dibuat</p>
                            </div>
                        </div>
                        @if($room->updated_at != $room->created_at)
                        <div class="timeline-item">
                            <div class="timeline-marker bg-warning"></div>
                            <div class="timeline-content">
                                <small class="text-muted">{{ $room->updated_at->format('d/m/Y H:i') }}</small>
                                <p class="mb-0">Kamar diperbarui</p>
                            </div>
                        </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Availability Check Modal -->
<div class="modal fade" id="availabilityModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title">
                    <i class="fas fa-calendar-check me-2"></i>Cek Ketersediaan Kamar
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="availabilityForm">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Check-in</label>
                            <input type="date" class="form-control" id="check_in_date" name="check_in_date" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Check-out</label>
                            <input type="date" class="form-control" id="check_out_date" name="check_out_date" required>
                        </div>
                    </div>
                    <div id="availabilityResult"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
                <button type="button" class="btn btn-primary" onclick="checkRoomAvailability()">
                    <i class="fas fa-search me-1"></i> Cek Ketersediaan
                </button>
            </div>
        </div>
    </div>
</div>
@endsection



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

<script>
// Change room status
function changeStatus(status) {
    const statusLabels = {
        'available': 'Tersedia',
        'occupied': 'Terisi',
        'maintenance': 'Maintenance',
        'cleaning': 'Cleaning'
    };
    
    Swal.fire({
        title: 'Konfirmasi',
        text: `Ubah status kamar menjadi ${statusLabels[status]}?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Ya, Ubah!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: `{{ route($route.'.index') }}/{{ $room->id }}/status`,
                method: 'PUT',
                data: {
                    status: status,
                    _token: $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            title: 'Berhasil!',
                            text: response.message,
                            icon: 'success',
                            timer: 2000,
                            showConfirmButton: false
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire('Error!', response.message, 'error');
                    }
                },
                error: function() {
                    Swal.fire('Error!', 'Terjadi kesalahan saat mengubah status', 'error');
                }
            });
        }
    });
}

// Check availability
function checkAvailability() {
    $('#availabilityModal').modal('show');
    
    // Set minimum date to today
    const today = new Date().toISOString().split('T')[0];
    $('#check_in_date').attr('min', today);
    $('#check_out_date').attr('min', today);
}

function checkRoomAvailability() {
    const checkIn = $('#check_in_date').val();
    const checkOut = $('#check_out_date').val();
    
    if (!checkIn || !checkOut) {
        Swal.fire('Error!', 'Harap isi tanggal check-in dan check-out', 'error');
        return;
    }
    
    if (checkIn >= checkOut) {
        Swal.fire('Error!', 'Tanggal check-out harus setelah check-in', 'error');
        return;
    }
    
    $('#availabilityResult').html(`
        <div class="text-center">
            <i class="fas fa-spinner fa-spin fa-2x text-primary"></i>
            <p class="mt-2">Mengecek ketersediaan...</p>
        </div>
    `);
    
    // You can implement AJAX call here to check availability
    // For demo purposes, we'll show a success message
    setTimeout(() => {
        const nights = Math.ceil((new Date(checkOut) - new Date(checkIn)) / (1000 * 60 * 60 * 24));
        const pricePerNight = {{ $room->typeRoom->harga_per_malam ?? 0 }};
        const totalPrice = nights * pricePerNight;
        const ppn = totalPrice * ({{ $room->typeRoom->ppn ?? 11 }} / 100);
        const grandTotal = totalPrice + ppn;
        
        $('#availabilityResult').html(`
            <div class="alert alert-success">
                <h6><i class="fas fa-check-circle me-1"></i>Kamar Tersedia!</h6>
                <hr>
                <div class="row">
                    <div class="col-6"><strong>Malam:</strong></div>
                    <div class="col-6">${nights} malam</div>
                    <div class="col-6"><strong>Harga per malam:</strong></div>
                    <div class="col-6">Rp ${new Intl.NumberFormat('id-ID').format(pricePerNight)}</div>
                    <div class="col-6"><strong>Subtotal:</strong></div>
                    <div class="col-6">Rp ${new Intl.NumberFormat('id-ID').format(totalPrice)}</div>
                    <div class="col-6"><strong>PPN ({{ $room->typeRoom->ppn ?? 11 }}%):</strong></div>
                    <div class="col-6">Rp ${new Intl.NumberFormat('id-ID').format(ppn)}</div>
                    <div class="col-6"><strong>Total:</strong></div>
                    <div class="col-6 text-success font-weight-bold">Rp ${new Intl.NumberFormat('id-ID').format(grandTotal)}</div>
                </div>
            </div>
        `);
    }, 1500);
}

// Create booking
function createBooking() {
    Swal.fire({
        title: 'Buat Booking',
        text: 'Fitur ini akan mengarahkan ke halaman booking baru',
        icon: 'info',
        showCancelButton: true,
        confirmButtonText: 'Lanjutkan',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            // Redirect to booking create page with room pre-selected
            window.location.href = `{{ url('bookings/create') }}?room_id={{ $room->id }}`;
        }
    });
}

// Set check-out date minimum when check-in changes
$('#check_in_date').change(function() {
    const checkInDate = new Date($(this).val());
    checkInDate.setDate(checkInDate.getDate() + 1);
    const minCheckOut = checkInDate.toISOString().split('T')[0];
    $('#check_out_date').attr('min', minCheckOut);
});

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

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