@extends('admin-layouts.master')

@section('title', 'Daftar Check-out')

@section('content')
<div class="container-fluid py-4" style="background-color: #f8f9fa; min-height: 100vh;">
    <!-- Header Section -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h2 class="mb-1 font-weight-bold text-dark">Daftar Check-out</h2>
                    <p class="text-muted mb-0">Kelola dan pantau check-out tamu hotel</p>
                </div>
                <div class="col-md-6">
                    <div class="d-flex justify-content-md-end align-items-center flex-wrap">
                        <!-- Search Form -->
                        <form method="GET" action="{{ route('checkouts.index') }}" class="mr-2 mb-2" style="min-width: 250px;">
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text bg-white border-right-0">
                                        <i class="fas fa-search text-muted"></i>
                                    </span>
                                </div>
                                <input type="text" 
                                       name="search" 
                                       class="form-control border-left-0" 
                                       placeholder="Cari nama, phone, booking ID..." 
                                       value="{{ request('search') }}"
                                       id="searchInput">
                                @if(request('search'))
                                    <div class="input-group-append">
                                        <a href="{{ route('checkouts.index', request()->except('search')) }}" 
                                           class="btn btn-outline-secondary border-left-0"
                                           data-toggle="tooltip"
                                           title="Hapus pencarian">
                                            <i class="fas fa-times"></i>
                                        </a>
                                    </div>
                                @endif
                                <!-- Hidden inputs untuk preserve filter lain -->
                                @if(request('date'))
                                    <input type="hidden" name="date" value="{{ request('date') }}">
                                @endif
                                @if(request('sort'))
                                    <input type="hidden" name="sort" value="{{ request('sort') }}">
                                @endif
                                @if(request('direction'))
                                    <input type="hidden" name="direction" value="{{ request('direction') }}">
                                @endif
                            </div>
                        </form>

                        <!-- Filter Dropdown -->
                        <div class="dropdown mr-2 mb-2">
                            <button class="btn btn-outline-secondary dropdown-toggle d-flex align-items-center" type="button" id="filterDropdown" data-toggle="dropdown">
                                <i class="fas fa-filter mr-1"></i>
                                Filter
                                @php
                                    $activeFilters = collect([request('date')])->filter()->count();
                                @endphp
                                @if($activeFilters > 0)
                                    <span class="badge badge-primary badge-sm ml-1">{{ $activeFilters }}</span>
                                @endif
                            </button>
                            <div class="dropdown-menu dropdown-menu-right" style="min-width: 200px;">
                                <h6 class="dropdown-header">
                                    <i class="fas fa-calendar mr-1"></i>
                                    Tanggal Check-out
                                </h6>
                                <a class="dropdown-item {{ !request('date') ? 'active' : '' }}" 
                                   href="{{ route('checkouts.index', request()->except('date')) }}">
                                    <i class="fas fa-calendar mr-2 text-muted"></i>Semua Tanggal
                                </a>
                                <a class="dropdown-item {{ request('date') === 'today' ? 'active' : '' }}" 
                                   href="{{ route('checkouts.index', array_merge(request()->all(), ['date' => 'today'])) }}">
                                    <i class="fas fa-calendar-day text-primary mr-2"></i>Hari Ini
                                </a>
                                <a class="dropdown-item {{ request('date') === 'yesterday' ? 'active' : '' }}" 
                                   href="{{ route('checkouts.index', array_merge(request()->all(), ['date' => 'yesterday'])) }}">
                                    <i class="fas fa-calendar-minus text-info mr-2"></i>Kemarin
                                </a>
                                <a class="dropdown-item {{ request('date') === 'week' ? 'active' : '' }}" 
                                   href="{{ route('checkouts.index', array_merge(request()->all(), ['date' => 'week'])) }}">
                                    <i class="fas fa-calendar-week text-info mr-2"></i>Minggu Ini
                                </a>
                                <a class="dropdown-item {{ request('date') === 'month' ? 'active' : '' }}" 
                                   href="{{ route('checkouts.index', array_merge(request()->all(), ['date' => 'month'])) }}">
                                    <i class="fas fa-calendar-alt text-warning mr-2"></i>Bulan Ini
                                </a>
                                
                                @if(request('date'))
                                    <div class="dropdown-divider"></div>
                                    <a class="dropdown-item text-center" href="{{ route('checkouts.index') }}">
                                        <i class="fas fa-times mr-1"></i>
                                        <small>Reset Filter</small>
                                    </a>
                                @endif
                            </div>
                        </div>

                        {{-- <a href="{{ route('checkouts.create') }}" class="btn btn-success d-flex align-items-center mb-2">
                            <i class="fas fa-sign-out-alt mr-2"></i>
                            Check-out Baru
                        </a> --}}
                    </div>
                </div>
            </div>

            <!-- Active Filters Display -->
            @if(request('search') || request('date'))
                <div class="row mt-3">
                    <div class="col-12">
                        <div class="d-flex align-items-center flex-wrap">
                            <span class="text-muted mr-2 small">
                                <i class="fas fa-filter mr-1"></i>
                                Filter aktif:
                            </span>
                            
                            @if(request('search'))
                                <span class="badge badge-primary mr-2 mb-1 d-flex align-items-center">
                                    <i class="fas fa-search mr-1"></i>
                                    "{{ Str::limit(request('search'), 20) }}"
                                    <a href="{{ route('checkouts.index', request()->except('search')) }}" 
                                       class="text-white ml-1 text-decoration-none"
                                       data-toggle="tooltip"
                                       title="Hapus filter pencarian">
                                        <i class="fas fa-times"></i>
                                    </a>
                                </span>
                            @endif

                            @if(request('date'))
                                <span class="badge badge-info mr-2 mb-1 d-flex align-items-center">
                                    <i class="fas fa-calendar mr-1"></i>
                                    @switch(request('date'))
                                        @case('today') Hari Ini @break
                                        @case('yesterday') Kemarin @break
                                        @case('week') Minggu Ini @break
                                        @case('month') Bulan Ini @break
                                        @default {{ ucfirst(request('date')) }}
                                    @endswitch
                                    <a href="{{ route('checkouts.index', request()->except('date')) }}" 
                                       class="text-white ml-1 text-decoration-none"
                                       data-toggle="tooltip"
                                       title="Hapus filter tanggal">
                                        <i class="fas fa-times"></i>
                                    </a>
                                </span>
                            @endif

                            <a href="{{ route('checkouts.index') }}" 
                               class="btn btn-sm btn-outline-secondary mb-1 d-flex align-items-center"
                               data-toggle="tooltip"
                               title="Reset semua filter">
                                <i class="fas fa-eraser mr-1"></i>
                                Reset
                            </a>
                        </div>
                    </div>
                </div>
            @endif
        </div>
    </div>

    <!-- Alert Messages -->
    @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show d-flex align-items-center" role="alert">
            <i class="fas fa-check-circle mr-3"></i>
            <span>{{ session('success') }}</span>
            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
        </div>
    @endif

    @if(session('error'))
        <div class="alert alert-danger alert-dismissible fade show d-flex align-items-center" role="alert">
            <i class="fas fa-exclamation-circle mr-3"></i>
            <span>{{ session('error') }}</span>
            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
        </div>
    @endif

    <!-- Search Results Info -->
    @if(request('search') || request('date'))
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-body py-3">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-info-circle text-primary mr-2"></i>
                            <span class="text-dark">
                                Menampilkan <strong>{{ $checkOuts->count() }}</strong> dari <strong>{{ $checkOuts->total() }}</strong> hasil
                                @if(request('search'))
                                    untuk pencarian "<strong>{{ request('search') }}</strong>"
                                @endif
                                @if(request('date'))
                                    dengan filter yang dipilih
                                @endif
                            </span>
                        </div>
                    </div>
                    @if($checkOuts->count() > 0)
                        <div class="col-md-4 text-md-right">
                            <small class="text-muted">
                                <i class="fas fa-file mr-1"></i>
                                Halaman {{ $checkOuts->currentPage() }} dari {{ $checkOuts->lastPage() }}
                            </small>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    @endif

    <!-- Stats Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-3">
            <div class="card border-0 shadow-sm h-100 stats-card">
                <div class="card-body">
                    <div class="d-flex align-items-center justify-content-between">
                        <div>
                            <div class="text-muted small font-weight-medium">Check-out Hari Ini</div>
                            <div class="h4 font-weight-bold mb-0">{{ $checkOuts->where('created_at', '>=', today())->count() }}</div>
                            <small class="text-success">
                                <i class="fas fa-arrow-up mr-1"></i>
                                +8% dari kemarin
                            </small>
                        </div>
                        <div class="bg-success rounded p-3">
                            <i class="fas fa-sign-out-alt fa-lg text-white"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <div class="card border-0 shadow-sm h-100 stats-card">
                <div class="card-body">
                    <div class="d-flex align-items-center justify-content-between">
                        <div>
                            <div class="text-muted small font-weight-medium">Total Check-out</div>
                            <div class="h4 font-weight-bold mb-0">{{ $checkOuts->total() }}</div>
                            <small class="text-info">
                                <i class="fas fa-chart-line mr-1"></i>
                                All time
                            </small>
                        </div>
                        <div class="bg-info rounded p-3">
                            <i class="fas fa-chart-bar fa-lg text-white"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <div class="card border-0 shadow-sm h-100 stats-card">
                <div class="card-body">
                    <div class="d-flex align-items-center justify-content-between">
                        <div>
                            <div class="text-muted small font-weight-medium">Kamar Dibersihkan</div>
                            <div class="h4 font-weight-bold mb-0">{{ $checkOuts->where('created_at', '>=', today())->count() }}</div>
                            <small class="text-warning">
                                <i class="fas fa-broom mr-1"></i>
                                Ready for cleaning
                            </small>
                        </div>
                        <div class="bg-warning rounded p-3">
                            <i class="fas fa-broom fa-lg text-white"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <div class="card border-0 shadow-sm h-100 stats-card">
                <div class="card-body">
                    <div class="d-flex align-items-center justify-content-between">
                        <div>
                            <div class="text-muted small font-weight-medium">Rata-rata Check-out</div>
                            <div class="h4 font-weight-bold mb-0">{{$mostFrequentHourFormatted}}</div>
                            <small class="text-muted">
                                <i class="fas fa-clock mr-1"></i>
                                Peak hour
                            </small>
                        </div>
                        <div class="bg-secondary rounded p-3">
                            <i class="fas fa-clock fa-lg text-white"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Check-out Table -->
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white border-bottom">
            <div class="d-flex align-items-center justify-content-between flex-wrap">
                <h5 class="mb-0 font-weight-semibold">
                    <i class="fas fa-sign-out-alt mr-2 text-success"></i>
                    Riwayat Check-out
                </h5>
                
                <!-- Sort Options dan Export -->
                <div class="d-flex align-items-center">
                    <div class="dropdown mr-2">
                        <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown">
                            <i class="fas fa-sort mr-1"></i>
                            @if(request('sort') === 'guest_name')
                                Nama Tamu
                            @elseif(request('sort') === 'check_out_time')
                                Waktu Check-out
                            @elseif(request('sort') === 'booking_id')
                                ID Booking
                            @else
                                Terbaru
                            @endif
                        </button>
                        <div class="dropdown-menu dropdown-menu-right">
                            <a class="dropdown-item {{ !request('sort') ? 'active' : '' }}" 
                               href="{{ route('checkouts.index', request()->except(['sort', 'direction'])) }}">
                                <i class="fas fa-clock mr-2"></i>Terbaru
                            </a>
                            <a class="dropdown-item {{ request('sort') === 'guest_name' ? 'active' : '' }}" 
                               href="{{ route('checkouts.index', array_merge(request()->all(), ['sort' => 'guest_name', 'direction' => 'asc'])) }}">
                                <i class="fas fa-user mr-2"></i>Nama Tamu
                            </a>
                            <a class="dropdown-item {{ request('sort') === 'check_out_time' ? 'active' : '' }}" 
                               href="{{ route('checkouts.index', array_merge(request()->all(), ['sort' => 'check_out_time', 'direction' => 'desc'])) }}">
                                <i class="fas fa-calendar mr-2"></i>Waktu Check-out
                            </a>
                            <a class="dropdown-item {{ request('sort') === 'booking_id' ? 'active' : '' }}" 
                               href="{{ route('checkouts.index', array_merge(request()->all(), ['sort' => 'booking_id', 'direction' => 'desc'])) }}">
                                <i class="fas fa-hashtag mr-2"></i>ID Booking
                            </a>
                        </div>
                    </div>

                    <!-- Export Button -->
                    <div class="dropdown">
                        <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button" data-toggle="dropdown">
                            <i class="fas fa-download mr-1"></i>
                            Export
                        </button>
                        {{-- <div class="dropdown-menu dropdown-menu-right">
                            <a class="dropdown-item" href="#" onclick="exportData('excel')">
                                <i class="fas fa-file-excel text-success mr-2"></i>Excel
                            </a>
                            <a class="dropdown-item" href="#" onclick="exportData('pdf')">
                                <i class="fas fa-file-pdf text-danger mr-2"></i>PDF
                            </a>
                        </div> --}}
                    </div>
                </div>
            </div>
        </div>
        
        @if($checkOuts->count() > 0)
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="bg-light">
                            <tr>
                                <th class="border-0 font-weight-semibold text-muted small">BOOKING INFO</th>
                                <th class="border-0 font-weight-semibold text-muted small">TAMU</th>
                                <th class="border-0 font-weight-semibold text-muted small">KAMAR</th>
                                <th class="border-0 font-weight-semibold text-muted small">CHECK-IN</th>
                                <th class="border-0 font-weight-semibold text-muted small">CHECK-OUT</th>
                                <th class="border-0 font-weight-semibold text-muted small">DURASI</th>
                                {{-- <th class="border-0 font-weight-semibold text-muted small text-right">AKSI</th> --}}
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($checkOuts as $checkOut)
                                <tr class="checkout-row" data-checkout-id="{{ $checkOut->id }}">
                                    <td class="align-middle">
                                        <div>
                                            <div class="font-weight-semibold text-dark">#{{ $checkOut->booking->id }}</div>
                                            <small class="text-muted">
                                                {{ \Carbon\Carbon::parse($checkOut->booking->check_in_date)->format('d M Y') }} - 
                                                {{ \Carbon\Carbon::parse($checkOut->booking->check_out_date)->format('d M Y') }}
                                            </small>
                                        </div>
                                    </td>
                                    <td class="align-middle">
                                        <div class="d-flex align-items-center">
                                            <div class="avatar avatar-sm bg-success text-white rounded-circle d-flex align-items-center justify-content-center mr-3" style="width: 40px; height: 40px;">
                                                <span class="font-weight-bold small">{{ substr($checkOut->booking->guest->name, 0, 2) }}</span>
                                            </div>
                                            <div>
                                                <div class="font-weight-semibold text-dark">{{ $checkOut->booking->guest->name }}</div>
                                                <small class="text-muted">{{ $checkOut->booking->guest->phone ?? 'No phone' }}</small>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="align-middle">
                                        <div>
                                            @foreach($checkOut->booking->bookingDetails as $detail)
                                                <span class="badge badge-success mb-1 d-inline-block">
                                                    {{ $detail->room->room_number }} - {{ $detail->room->typeRoom->name ?? 'N/A' }}
                                                </span>
                                            @endforeach
                                        </div>
                                    </td>
                                    <td class="align-middle">
                                        @if($checkOut->booking->checkIn)
                                            <div>
                                                <div class="text-dark">{{ \Carbon\Carbon::parse($checkOut->booking->checkIn->check_in_time)->format('d M Y') }}</div>
                                                <small class="text-muted">{{ \Carbon\Carbon::parse($checkOut->booking->checkIn->check_in_time)->format('H:i') }}</small>
                                            </div>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                    <td class="align-middle">
                                        <div>
                                            <div class="text-dark">{{ \Carbon\Carbon::parse($checkOut->check_out_time)->format('d M Y') }}</div>
                                            <small class="text-muted">{{ \Carbon\Carbon::parse($checkOut->check_out_time)->format('H:i') }}</small>
                                        </div>
                                    </td>
                                    <td class="align-middle">
                                        @if($checkOut->booking->checkIn)
                                            @php
                                                $checkInTime = \Carbon\Carbon::parse($checkOut->booking->checkIn->check_in_time);
                                                $checkOutTime = \Carbon\Carbon::parse($checkOut->check_out_time);
                                                $duration = $checkInTime->diffInHours($checkOutTime);
                                                $days = intval($duration / 24);
                                                $hours = $duration % 24;
                                            @endphp
                                            <div class="text-dark">
                                                @if($days > 0)
                                                    {{ $days }} hari
                                                @endif
                                                @if($hours > 0)
                                                    {{ $hours }} jam
                                                @endif
                                            </div>
                                            <small class="text-muted">{{ $duration }} jam total</small>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                    {{-- <td class="align-middle text-right">
                                        <div class="btn-group" role="group">
                                            <a href="{{ route('checkouts.show', $checkOut) }}" 
                                               class="btn btn-sm btn-outline-primary"
                                               data-toggle="tooltip" 
                                               title="Lihat Detail">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="{{ route('checkouts.edit', $checkOut) }}" 
                                               class="btn btn-sm btn-outline-warning"
                                               data-toggle="tooltip" 
                                               title="Edit Check-out">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <button type="button" 
                                                    class="btn btn-sm btn-outline-info"
                                                    data-toggle="tooltip" 
                                                    title="Print Receipt"
                                                    onclick="printReceipt({{ $checkOut->booking->id }})">
                                                <i class="fas fa-print"></i>
                                            </button>
                                        </div>
                                    </td> --}}
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Enhanced Pagination -->
            @if($checkOuts->hasPages())
                <div class="card-footer bg-white border-top">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <small class="text-muted">
                                <i class="fas fa-info-circle mr-1"></i>
                                Menampilkan {{ $checkOuts->firstItem() }} sampai {{ $checkOuts->lastItem() }} dari {{ $checkOuts->total() }} check-out
                            </small>
                        </div>
                        <div class="col-md-6">
                            <div class="d-flex justify-content-md-end">
                                {{ $checkOuts->appends(request()->query())->links() }}
                            </div>
                        </div>
                    </div>
                </div>
            @endif
        @else
            <div class="card-body text-center py-5">
                <div class="mb-4">
                    @if(request('search') || request('date'))
                        <i class="fas fa-search fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted font-weight-semibold">Tidak ada hasil ditemukan</h5>
                        <p class="text-muted mb-4">
                            Coba ubah kata kunci pencarian atau filter yang digunakan.
                        </p>
                        <a href="{{ route('checkouts.index') }}" class="btn btn-outline-primary mr-2">
                            <i class="fas fa-times mr-2"></i>
                            Reset Filter
                        </a>
                    @else
                        <i class="fas fa-sign-out-alt fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted font-weight-semibold">Belum ada check-out</h5>
                        <p class="text-muted mb-4">Belum ada tamu yang check-out hari ini.</p>
                    @endif
                    
                    <a href="{{ route('checkouts.create') }}" class="btn btn-success">
                        <i class="fas fa-sign-out-alt mr-2"></i>
                        Check-out Baru
                    </a>
                </div>
            </div>
        @endif
    </div>
</div>

<style>
.badge-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    display: inline-block;
}

.avatar {
    font-size: 0.75rem;
}

.card {
    transition: all 0.3s ease;
}

.stats-card:hover {
    transform: translateY(-2px);
}

.table td {
    border-top: 1px solid #f1f3f4;
    padding: 1rem 0.75rem;
}

.table thead th {
    border-bottom: 2px solid #f1f3f4;
    font-size: 0.75rem;
    letter-spacing: 0.05em;
    padding: 1rem 0.75rem;
}

.btn-group .btn {
    border-radius: 0.375rem;
    margin-right: 0.25rem;
}

.btn-group .btn:last-child {
    margin-right: 0;
}

.input-group-text {
    border-color: #e9ecef;
}

.form-control:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.dropdown-item.active {
    background-color: #007bff;
    color: white;
}

.dropdown-item:hover {
    background-color: #f8f9fa;
}

.badge {
    font-size: 0.75rem;
}

/* Row hover effect */
.table-hover tbody tr:hover {
    background-color: rgba(40, 167, 69, 0.05);
}

/* Responsive improvements */
@media (max-width: 768px) {
    .d-flex.justify-content-md-end {
        flex-direction: column;
        align-items: stretch;
    }
    
    .input-group {
        margin-bottom: 1rem;
        max-width: 100% !important;
    }
    
    .dropdown {
        margin-bottom: 1rem;
    }
    
    .btn-group {
        flex-direction: column;
    }
    
    .btn-group .btn {
        margin-right: 0;
        margin-bottom: 0.25rem;
        border-radius: 0.375rem !important;
    }
    
    .btn-group .btn:last-child {
        margin-bottom: 0;
    }
    
    .table-responsive {
        font-size: 0.875rem;
    }
}

/* Animation for badges */
.badge {
    transition: all 0.2s ease;
}

.badge:hover {
    transform: scale(1.05);
}

/* Enhanced button styles */
.btn {
    font-weight: 500;
    letter-spacing: 0.025em;
}

.btn-sm {
    font-size: 0.8rem;
    padding: 0.375rem 0.75rem;
}

/* Focus styles */
.btn:focus,
.form-control:focus,
.dropdown-toggle:focus {
    outline: none;
    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

/* Custom alert styles */
.alert {
    border: none;
    border-radius: 0.5rem;
    font-weight: 500;
}

.alert-success {
    background-color: #d1ecf1;
    color: #0c5460;
}

.alert-danger {
    background-color: #f8d7da;
    color: #721c24;
}

/* Badge counter in filter button */
.badge-sm {
    font-size: 0.6rem;
    padding: 0.2rem 0.4rem;
}

/* Search highlighting */
mark.bg-warning {
    background-color: #fff3cd !important;
    padding: 0.1rem 0.2rem;
    border-radius: 0.2rem;
}

/* Print styles */
@media print {
    .btn, .dropdown, .pagination, .alert {
        display: none !important;
    }
    
    .card {
        border: 1px solid #dee2e6 !important;
        box-shadow: none !important;
    }
    
    .table {
        font-size: 0.8rem;
    }
    
    .badge {
        border: 1px solid #000;
        color: #000 !important;
    }
}
</style>

<script>
$(document).ready(function() {
    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();

    // Auto submit search form with delay
    let searchTimeout;
    $('#searchInput').on('input', function() {
        clearTimeout(searchTimeout);
        const searchValue = $(this).val();
        
        searchTimeout = setTimeout(function() {
            if (searchValue.length >= 3 || searchValue.length === 0) {
                $('#searchInput').closest('form').submit();
            }
        }, 800);
    });

    // Highlight search terms
    const searchTerm = '{{ request("search") }}';
    if (searchTerm && searchTerm.length >= 3) {
        highlightSearchTerms(searchTerm);
    }

    function highlightSearchTerms(term) {
        const searchRegex = new RegExp(`(${escapeRegExp(term)})`, 'gi');
        
        $('.checkout-row').each(function() {
            const row = $(this);
            
            // Only highlight in specific columns (not action buttons)
            row.find('td:lt(6)').each(function() {
                const cell = $(this);
                const originalHtml = cell.html();
                
                // Skip if cell contains HTML elements we want to preserve
                if (cell.find('.badge, .avatar').length === 0) {
                    const highlightedHtml = originalHtml.replace(searchRegex, '<mark class="bg-warning">$1</mark>');
                    cell.html(highlightedHtml);
                }
            });
        });
    }

    function escapeRegExp(string) {
        return string.replace(/[.*+?^${}()|[\]\\]/g, '\\/* Custom alert styles */
.alert {
    border: none;
    border-radius: 0.5rem');
    }

    // Print receipt function
   

    // Export function
   
    // Auto-refresh stats every 5 minutes
   
    // Refresh stats every 5 minutes
    setInterval(refreshStats, 300000);

    // Add loading states for better UX
    $('.btn').on('click', function() {
        if ($(this).attr('type') === 'submit' || $(this).hasClass('export-btn')) {
            const btn = $(this);
            const originalText = btn.html();
            
            btn.prop('disabled', true)
               .html('<i class="fas fa-spinner fa-spin mr-1"></i> Loading...');
            
            setTimeout(() => {
                btn.prop('disabled', false).html(originalText);
            }, 3000);
        }
    });

    // Enhanced table interactions
    $('.checkout-row').on('click', function(e) {
        if (!$(e.target).closest('.btn-group').length) {
            const checkoutId = $(this).data('checkout-id');
            window.location.href = '{{ route("checkouts.show", ":id") }}'.replace(':id', checkoutId);
        }
    });

    // Add row highlighting on hover
    $('.checkout-row').hover(
        function() {
            $(this).addClass('table-active');
        },
        function() {
            $(this).removeClass('table-active');
        }
    );

    // Keyboard shortcuts
    $(document).on('keydown', function(e) {
        // Ctrl/Cmd + K to focus search
        if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
            e.preventDefault();
            $('#searchInput').focus().select();
        }
        
        // Escape to clear search
        if (e.key === 'Escape' && $('#searchInput').is(':focus')) {
            $('#searchInput').val('').trigger('input');
        }

        // N key to create new checkout
        if (e.key === 'n' && !$('input, textarea').is(':focus')) {
            window.location.href = '{{ route("checkouts.create") }}';
        }
    });

    // Show keyboard shortcuts help
    $(document).on('keydown', function(e) {
        if (e.key === '?' && !$('input, textarea').is(':focus')) {
            showKeyboardShortcuts();
        }
    });

    function showKeyboardShortcuts() {
        const modal = `
            <div class="modal fade" id="shortcutsModal" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="fas fa-keyboard mr-2"></i>
                                Keyboard Shortcuts
                            </h5>
                            <button type="button" class="close" data-dismiss="modal">
                                <span>&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <h6>Navigation</h6>
                                    <ul class="list-unstyled">
                                        <li><kbd>Ctrl</kbd> + <kbd>K</kbd> - Focus search</li>
                                        <li><kbd>Esc</kbd> - Clear search</li>
                                        <li><kbd>N</kbd> - New checkout</li>
                                    </ul>
                                </div>
                                <div class="col-md-6">
                                    <h6>Help</h6>
                                    <ul class="list-unstyled">
                                        <li><kbd>?</kbd> - Show shortcuts</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        if (!$('#shortcutsModal').length) {
            $('body').append(modal);
        }
        $('#shortcutsModal').modal('show');
    }

    // Show welcome message for first-time users
    if (localStorage.getItem('checkout_welcome_shown') !== 'true') {
        setTimeout(() => {
            showWelcomeToast();
            localStorage.setItem('checkout_welcome_shown', 'true');
        }, 1000);
    }

    function showWelcomeToast() {
        const toast = `
            <div class="toast" style="position: fixed; top: 20px; right: 20px; z-index: 9999;" data-delay="5000">
                <div class="toast-header">
                    <i class="fas fa-info-circle text-primary mr-2"></i>
                    <strong class="mr-auto">Tips</strong>
                    <button type="button" class="ml-2 mb-1 close" data-dismiss="toast">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="toast-body">
                    Press <kbd>?</kbd> untuk melihat keyboard shortcuts yang tersedia!
                </div>
            </div>
        `;
        
        $('body').append(toast);
        $('.toast').toast('show');
        
        $('.toast').on('hidden.bs.toast', function() {
            $(this).remove();
        });
    }

    // Table row animations
    $('.checkout-row').each(function(index) {
        $(this).css('animation-delay', (index * 0.05) + 's');
        $(this).addClass('animate-fade-in');
    });
});

// Global utility functions
window.refreshTable = function() {
    window.location.reload();
};

window.clearAllFilters = function() {
    window.location.href = '{{ route("checkouts.index") }}';
};
</script>

<!-- Add CSS animations -->
<style>
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.animate-fade-in {
    animation: fadeIn 0.5s ease forwards;
}

.table-active {
    background-color: rgba(40, 167, 69, 0.1) !important;
}

kbd {
    background-color: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 0.25rem;
    padding: 0.1rem 0.3rem;
    font-size: 0.8rem;
    color: #495057;
}

.toast {
    min-width: 300px;
}

/* Enhanced hover effects */
.stats-card {
    cursor: pointer;
}

.stats-card:hover .bg-primary,
.stats-card:hover .bg-success,
.stats-card:hover .bg-info,
.stats-card:hover .bg-warning,
.stats-card:hover .bg-secondary {
    transform: scale(1.1);
    transition: transform 0.2s ease;
}

/* Loading spinner */
.fa-spinner {
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* Improved badge styles */
.badge-success {
    background-color: #28a745;
    box-shadow: 0 2px 4px rgba(40, 167, 69, 0.2);
}

.badge-primary {
    background-color: #007bff;
    box-shadow: 0 2px 4px rgba(0, 123, 255, 0.2);
}

/* Enhanced table styles */
.table thead th {
    position: sticky;
    top: 0;
    background-color: #f8f9fa;
    z-index: 10;
}

/* Custom scrollbar for mobile */
.table-responsive::-webkit-scrollbar {
    height: 8px;
}

.table-responsive::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.table-responsive::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

.table-responsive::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}
</style>
@endsection