<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tickets Dashboard - Admin Panel</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="description" content="PACE Events" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <!-- Primary Meta Tags -->
        <meta name="title" content="PACE" />
        <meta name="description" content="Welcome to Pacesetter Entertainment, Nairobi's premier party and events company. Since 2023, we have been crafting unforgettable experiences that educate, motivate, and entertain. Specializing in event management and organization across Kenya, we bring innovation and excellence to every occasion. From corporate events to private celebrations, trust us to make your events remarkable." />
    
        <!-- Open Graph / Facebook -->
        <meta property="og:type" content="website" />
        <meta property="og:url" content="https://events.pacesetter.co.ke/" />
        <meta property="og:title" content="PACE" />
        <meta property="og:description" content="Welcome to Pacesetter Entertainment, Nairobi's premier party and events company. Since 2023, we have been crafting unforgettable experiences that educate, motivate, and entertain. Specializing in event management and organization across Kenya, we bring innovation and excellence to every occasion. From corporate events to private celebrations, trust us to make your events remarkable." />
        <meta property="og:image" content="https://events.pacesetter.co.ke/assets/img/logo/logo.png" />
    
        <!-- Twitter -->
        <meta property="twitter:card" content="summary_large_image" />
        <meta property="twitter:url" content="https://events.pacesetter.co.ke/" />
        <meta property="twitter:title" content="PACE" />
        <meta property="twitter:description" content="Welcome to Pacesetter Entertainment, Nairobi's premier party and events company. Since 2023, we have been crafting unforgettable experiences that educate, motivate, and entertain. Specializing in event management and organization across Kenya, we bring innovation and excellence to every occasion. From corporate events to private celebrations, trust us to make your events remarkable." />
        <meta property="twitter:image" content="https://events.pacesetter.co.ke/assets/img/logo/logo.png" />
    
    
        <link
          rel="shortcut icon"
          type="image/x-icon"
          href="assets/img/logo/logo.png"
        />
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet">

     @vite(['resources/css/app.css', 'resources/js/app.js'])

    <style>
    /* Main Container Styles */
.tickets-container {
    max-width: 100%;
    margin: 0 auto;
    padding: 1.5rem;
    overflow-x: auto;
}

/* Stats Cards */
.stats-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 10px;
    padding: 1.5rem;
    margin-bottom: 2rem;
    text-align: center;
    min-width: 200px;
}

.stats-card.success {
    background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
}

.stats-card.warning {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stats-card.info {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-card.danger {
    background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

/* Buttons */
.btn-primary {
    background-color: #6c04f5;
    border-color: #6c04f5;
}

.btn-primary:hover {
    background-color: #5a03d1;
    border-color: #5a03d1;
}

/* Search Filters */
.search-filters {
    background: #f8f9fa;
    border-radius: 10px;
    padding: 1.5rem;
    margin-bottom: 2rem;
    min-width: 1200px;
}

/* Table Container */
/* Update the table container styles */
.table-responsive-container {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  margin: 0 2rem; /* Increased from 1rem to 2rem */
  background: white;
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0,0,0,0.1);
  min-width: 100%;
}

/* Update the table width to be auto */
.table {
  width: auto; /* Changed from 100% to auto */
  min-width: 100%; /* Changed from fixed width to 100% */
  margin-bottom: 0;
}

/* Add more padding to the container */
.tickets-container {
    max-width: 100%;
    margin: 0 auto;
    padding: 1.5rem 2rem; /* Added right/left padding */
    overflow-x: auto;
}

/* Update scrollbar styling */
.table-responsive-container::-webkit-scrollbar {
    height: 10px; /* Increased from 8px */
}

.table-responsive-container::-webkit-scrollbar-track {
    background: #f8f9fa;
    border-radius: 5px;
}

.table-responsive-container::-webkit-scrollbar-thumb {
    background: #6c04f5;
    border-radius: 5px;
}

.table-responsive-container::-webkit-scrollbar-thumb:hover {
    background: #5a03d1;
}
.scrollable-contact,
.scrollable-payment-date {
  max-width: 200px;
  overflow-x: auto;
  white-space: nowrap;
  padding-right: 5px;
}

/* Custom Scrollbars for scrollable columns */
.scrollable-contact::-webkit-scrollbar,
.scrollable-payment-date::-webkit-scrollbar {
  height: 4px;
}

.scrollable-contact::-webkit-scrollbar-thumb,
.scrollable-payment-date::-webkit-scrollbar-thumb {
  background: #6c04f5;
  border-radius: 2px;
}
.table th {
    background-color: #6c04f5;
    color: white;
    border: none;
    font-weight: 600;
    padding: 0.75rem;
    position: sticky;
    top: 0;
    z-index: 10;
    white-space: nowrap;
}

.table td {
    vertical-align: middle;
    padding: 0.75rem;
    white-space: nowrap;
}

/* Column Specific Styles */
.table th:nth-child(1), .table td:nth-child(1) { /* ID */
  width: 60px;
  min-width: 60px;
}

.table th:nth-child(6), .table td:nth-child(6) { /* Qty */
  width: 70px;
  min-width: 70px;
  text-align: center;
}

/* Status Badges */
.status-badge {
    font-size: 0.75rem;
    padding: 0.25rem 0.5rem;
    border-radius: 0.25rem;
    display: inline-block;
    white-space: nowrap;
}

.status-completed {
    background-color: #28a745;
    color: white;
}

.status-pending {
    background-color: #ffc107;
    color: #212529;
}

.status-failed {
    background-color: #dc3545;
    color: white;
}

.stk-status-success {
    background-color: #28a745;
    color: white;
}

.stk-status-pending {
    background-color: #ffc107;
    color: #212529;
}

.stk-status-failed {
    background-color: #dc3545;
    color: white;
}

.stk-status-insufficient {
    background-color: #fd7e14;
    color: white;
}

.stk-status-canceled {
    background-color: #ffc107;
    color: #212529;
}

.stk-status-timeout {
    background-color: #fd7e14;
    color: white;
}

.stk-status-invalid-input {
    background-color: #ffc107;
    color: #212529;
}

/* Special Elements */
.ticket-reference {
    font-family: 'Courier New', monospace;
    font-size: 0.85rem;
    background-color: #f8f9fa;
    padding: 0.25rem 0.5rem;
    border-radius: 0.25rem;
    white-space: nowrap;
}

.amount-display {
    font-weight: 600;
    color: #28a745;
    white-space: nowrap;
}

.school-badge {
    font-size: 0.7rem;
    padding: 0.25rem 0.5rem;
    border-radius: 0.25rem;
    background-color: #6c757d;
    color: white;
    display: inline-block;
    white-space: nowrap;
}

/* Pagination */
.pagination {
    --bs-pagination-padding-x: 0.75rem;
    --bs-pagination-padding-y: 0.375rem;
    --bs-pagination-font-size: 0.875rem;
    --bs-pagination-color: #6c04f5;
    --bs-pagination-bg: #fff;
    --bs-pagination-border-width: 1px;
    --bs-pagination-border-color: #dee2e6;
    --bs-pagination-border-radius: 0.375rem;
    --bs-pagination-hover-color: #5a03d1;
    --bs-pagination-hover-bg: #f8f9ff;
    --bs-pagination-hover-border-color: #6c04f5;
    --bs-pagination-focus-color: #5a03d1;
    --bs-pagination-focus-bg: #f8f9ff;
    --bs-pagination-focus-box-shadow: 0 0 0 0.25rem rgba(108, 4, 245, 0.25);
    --bs-pagination-active-color: #fff;
    --bs-pagination-active-bg: #6c04f5;
    --bs-pagination-active-border-color: #6c04f5;
    --bs-pagination-disabled-color: #6c757d;
    --bs-pagination-disabled-bg: #fff;
    --bs-pagination-disabled-border-color: #dee2e6;
}

.pagination .page-link {
    border-radius: 0.375rem !important;
    margin: 0 0.125rem;
}

/* DataTables Custom Styling */
.dataTables_wrapper {
    margin: 0.5rem 0;
    min-width: 100%;
}

.dataTables_wrapper .dataTables_length,
.dataTables_wrapper .dataTables_filter,
.dataTables_wrapper .dataTables_info,
.dataTables_wrapper .dataTables_paginate {
    padding: 0.75rem;
    background-color: #f8f9fa;
    border-radius: 0.5rem;
    margin: 0.5rem 0;
    white-space: nowrap;
}

.dataTables_wrapper .dataTables_length select,
.dataTables_wrapper .dataTables_filter input {
    border: 1px solid #dee2e6;
    border-radius: 0.375rem;
    padding: 0.375rem 0.75rem;
}

.dataTables_wrapper .dataTables_paginate {
    text-align: center;
    float: none;
}

.dataTables_wrapper .dataTables_paginate .paginate_button {
    border-radius: 0.375rem !important;
    margin: 0 0.125rem;
    border: 1px solid #dee2e6;
    padding: 0.375rem 0.75rem !important;
}

.dataTables_wrapper .dataTables_paginate .paginate_button.current {
    background: #6c04f5 !important;
    border-color: #6c04f5 !important;
    color: white !important;
}

.dataTables_wrapper .dataTables_paginate .paginate_button:hover {
    background: #5a03d1 !important;
    border-color: #5a03d1 !important;
    color: white !important;
}

/* Scrollbar Styling */
.table-responsive-container::-webkit-scrollbar {
    height: 8px;
}

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

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

.table-responsive-container::-webkit-scrollbar-thumb:hover {
    background: #5a03d1;
}
.table th {
  position: sticky;
  top: 0;
  background-color: #6c04f5;
  color: white;
  white-space: nowrap;
}

/* Responsive Adjustments */
@media (max-width: 1400px) {
    .tickets-container {
        padding: 1rem;
        overflow-x: auto;
    }
    
    .search-filters {
        min-width: 1000px;
    }
    
    .table {
        min-width: 1000px;
    }
}

@media (max-width: 1200px) {
    .tickets-container {
        padding: 1rem;
    }
    
    .stats-card {
        padding: 1rem;
        margin-bottom: 1rem;
        min-width: 150px;
    }
    
    .search-filters {
        padding: 1rem;
        min-width: 900px;
    }
    
    .table {
        min-width: 900px;
    }
}

@media (max-width: 992px) {
    .stats-card {
        min-width: 120px;
    }
    
    .search-filters {
        min-width: 800px;
    }
    
    .table {
        min-width: 800px;
        font-size: 0.85rem;
    }
    
    .scrollable-contact,
    .scrollable-payment-date {
        max-width: 150px;
    }
}

@media (max-width: 768px) {
    .tickets-container {
        padding: 0.75rem;
    }
    
    .stats-card {
        min-width: 100px;
        padding: 0.75rem;
    }
    
    .search-filters {
        min-width: 700px;
        padding: 0.75rem;
    }
    
    .table {
        min-width: 700px;
        font-size: 0.8rem;
    }
    
    .table th,
    .table td {
        padding: 0.5rem;
    }
    
    .dataTables_wrapper .dataTables_length,
    .dataTables_wrapper .dataTables_filter,
    .dataTables_wrapper .dataTables_info,
    .dataTables_wrapper .dataTables_paginate {
        padding: 0.5rem;
    }
    
    .scrollable-contact,
    .scrollable-payment-date {
        max-width: 120px;
    }
    
    .btn-group {
        width: 100%;
        flex-wrap: wrap;
    }
    
    .btn-group .btn {
        margin-bottom: 0.5rem;
        flex: 1 0 auto;
    }
}

@media (max-width: 576px) {
    .tickets-container {
        padding: 0.5rem;
    }
    
    .stats-card {
        min-width: 80px;
        padding: 0.5rem;
    }
    
    .search-filters {
        min-width: 600px;
        padding: 0.5rem;
    }
    
    .table {
        min-width: 600px;
        font-size: 0.75rem;
    }
    
    .table th,
    .table td {
        padding: 0.4rem;
    }
    
    .ticket-reference,
    .status-badge,
    .school-badge {
        font-size: 0.7rem;
    }
    
    .dataTables_wrapper .dataTables_paginate .paginate_button {
        padding: 0.25rem 0.5rem !important;
        margin: 0 0.1rem !important;
    }
    
    .scrollable-contact,
    .scrollable-payment-date {
        max-width: 100px;
    }
}

/* Hover Effects */
.table tbody tr:hover {
    background-color: rgba(108, 4, 245, 0.05);
}

/* Text Alignment Helpers */
.text-center {
    text-align: center !important;
}

.text-end {
    text-align: right !important;
}

.text-start {
    text-align: left !important;
}

/* Navigation Row */
.navigation-row {
    min-width: 100%;
    display: flex;
    flex-wrap: nowrap;
    overflow-x: auto;
}

/* Stats Row */
.stats-row {
    min-width: 100%;
    display: flex;
    flex-wrap: nowrap;
    overflow-x: auto;
}

/* Stats Column */
.stats-col {
    flex: 0 0 auto;
    padding-right: 15px;
    padding-left: 15px;
}

/* Force horizontal scroll on smaller screens */
@media (max-width: 1200px) {
    .stats-row,
    .navigation-row {
        flex-wrap: nowrap;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }
    
    .stats-col {
        flex: 0 0 auto;
    }
}
</style>
</head>
<body class="bg-light">
    <div class="container-fluid tickets-container">
        <div class="mt-0 mb-6">
        @include('layouts.navigation')
        </div>
        <!-- Header -->
       {{-- <div class="mb-4 shadow-sm card w-100">
        <div class="card-body">
            <!-- Second Row: Buttons -->
            <div class="flex-wrap gap-3 d-flex justify-content-evenly align-items-center">
                @can('view-users')
                <a href="{{ route('users.index') }}" class="btn btn-primary @if(Route::currentRouteName() == 'users.index') active @endif">
                    <i class="fas fa-users"></i> Users
                </a>
                @endcan
                @can('view-tickets')
                <a href="{{ route('tickets.index') }}" class="btn btn-primary @if(Route::currentRouteName() == 'tickets.index') active @endif">
                    <i class="fas fa-list"></i> All Tickets
                </a>
                @endcan
                @can('view-metrics')
                <a href="{{ route('tickets.analytics') }}" class="btn btn-outline-primary @if(Route::currentRouteName() == 'tickets.analytics') active @endif">
                    <i class="fas fa-chart-bar"></i> Analytics
                </a>
                @endcan
                @can('access-messages')
                <a href="{{ route('sms.index') }}" class="btn btn-outline-secondary @if(Route::currentRouteName() == 'sms.index') active @endif">
                    <i class="fas fa-sms"></i> SMS Manager
                </a>
                @endcan
                @can('access-complimentary')
                <a href="{{ route('complimentary.tickets.index') }}" class="btn btn-outline-dark @if(Route::currentRouteName() == 'complimentary.tickets.index') active @endif">
                    <i class="fas fa-home"></i> Manage Complimentary tickets
                </a>
                @endcan
            </div>
        </div>
    </div> --}}

<!-- Messages -->
@if (session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle"></i>
        {!! session('success') !!}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
@endif

@if (session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle"></i>
        {{ session('error') }}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
@endif

    </div>

<!-- Ticket Stats -->
<div class="mt-4 row stats-row">
    @can('view-metrics')
    <div class="mb-3 col-md-3 col-sm-6 stats-col">
        <div class="stats-card success">
            <div class="text-center">
                <h4><i class="fas fa-ticket-alt"></i> {{ number_format($ticketStats['total_tickets']) }}</h4>
                <p class="mb-0">Total Tickets</p>
            </div>
        </div>
    </div>
    @endcan
    <div class="mb-3 col-md-3 col-sm-6 stats-col">
        <div class="stats-card info">
            <div class="text-center">
                <h4><i class="fas fa-check-circle"></i> {{ number_format($ticketStats['total_paid']) }}</h4>
                <p class="mb-0">Paid Tickets</p>
            </div>
        </div>
    </div>
    <div class="mb-3 col-md-3 col-sm-6 stats-col">
        <div class="stats-card warning">
            <div class="text-center">
                <h4><i class="fas fa-clock"></i> {{ number_format($ticketStats['total_pending']) }}</h4>
                <p class="mb-0">Pending</p>
            </div>
        </div>
    </div>
    <div class="mb-3 col-md-3 col-sm-6 stats-col">
        <div class="stats-card danger">
            <div class="text-center">
                <h4><i class="fas fa-times-circle"></i> {{ number_format($ticketStats['total_failed']) }}</h4>
                <p class="mb-0">Failed</p>
            </div>
        </div>
    </div>
</div>

<!-- Revenue Stats -->
<div class="row stats-row">
    @can('view-metrics')
        <div class="mb-3 col-md-3 col-sm-6 stats-col">
            <div class="stats-card">
                <div class="text-center">
                    <h4><i class="fas fa-money-bill-wave"></i> KSH {{ number_format($ticketStats['total_revenue'], 2) }}</h4>
                    <p class="mb-0">Total Revenue</p>
                </div>
            </div>
        </div>
        <div class="mb-3 col-md-3 col-sm-6 stats-col">
            <div class="stats-card success">
                <div class="text-center">
                    <h4><i class="fas fa-calendar-day"></i> {{ number_format($ticketStats['today_sales']) }}</h4>
                    <p class="mb-0">Today's Sales</p>
                </div>
            </div>
        </div>
        <div class="mb-3 col-md-3 col-sm-6 stats-col">
            <div class="stats-card info">
                <div class="text-center">
                    <h4><i class="fas fa-money-bill"></i> KSH {{ number_format($ticketStats['today_revenue'], 2) }}</h4>
                    <p class="mb-0">Today's Revenue</p>
                </div>
            </div>
        </div>
        <div class="mb-3 col-md-3 col-sm-6 stats-col">
            <div class="stats-card warning">
                <div class="text-center">
                    <h4><i class="fas fa-calendar-alt"></i> {{ number_format($ticketStats['this_month_sales']) }}</h4>
                    <p class="mb-0">This Month</p>
                </div>
            </div>
        </div>
    @endcan
</div>

<!-- Search and Filters -->
<div class="search-filters">
    <form method="GET" action="{{ route('tickets.index') }}" id="filter-form">
        <div class="row align-items-end">
            <div class="col-md-3">
                <label for="search" class="form-label">Search Tickets</label>
                <input type="text" class="form-control" id="search" name="search" 
                       value="{{ $search }}" placeholder="Name, phone, email, school, or reference">
            </div>
            <div class="col-md-2">
                <label for="status" class="form-label">Status</label>
                <select class="form-select" id="status" name="status">
                    <option value="">All Status</option>
                    <option value="completed" {{ $status === 'completed' ? 'selected' : '' }}>Completed</option>
                    <option value="pending" {{ $status === 'pending' ? 'selected' : '' }}>Pending</option>
                    <option value="failed" {{ $status === 'failed' ? 'selected' : '' }}>Failed</option>
                </select>
            </div>
            <div class="col-md-2">
                <label for="school" class="form-label">School</label>
                <select class="form-select" id="school" name="school">
                    <option value="">All Schools</option>
                    @foreach($schools as $schoolName)
                        <option value="{{ $schoolName }}" {{ $school === $schoolName ? 'selected' : '' }}>
                            {{ $schoolName }}
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-2">
                <label for="stk_status" class="form-label">STK Status</label>
                <select class="form-select" id="stk_status" name="stk_status">
                    <option value="">All STK Status</option>
                    <option value="Success" {{ $stkStatus === 'Success' ? 'selected' : '' }}>Success</option>
                    <option value="Launched" {{ $stkStatus === 'Launched' ? 'selected' : '' }}>Launched</option>
                    <option value="Failed" {{ $stkStatus === 'Failed' ? 'selected' : '' }}>Failed</option>
                    <option value="Canceled" {{ $stkStatus === 'Canceled' ? 'selected' : '' }}>Canceled</option>
                    <option value="Timeout" {{ $stkStatus === 'Timeout' ? 'selected' : '' }}>Timeout</option>
                    <option value="Invalid-user-input" {{ $stkStatus === 'Invalid-user-input' ? 'selected' : '' }}>Invalid User Input</option>
                    <option value="insufficient-funds" {{ $stkStatus === 'insufficient-funds' ? 'selected' : '' }}>Insufficient Funds</option>
                    <option value="User-cannot-be-reached" {{ $stkStatus === 'User-cannot-be-reached' ? 'selected' : '' }}>User Cannot be Reached</option>
                    <option value="No-response-from-user" {{ $stkStatus === 'No-response-from-user' ? 'selected' : '' }}>No Response from User</option>
                </select>
            </div>
            <div class="col-md-1">
                <label for="per_page" class="form-label">Per Page</label>
                <select class="form-select" id="per_page" name="per_page">
                    <option value="25" {{ $perPage == 25 ? 'selected' : '' }}>25</option>
                    <option value="50" {{ $perPage == 50 ? 'selected' : '' }}>50</option>
                    <option value="100" {{ $perPage == 100 ? 'selected' : '' }}>100</option>
                    <option value="200" {{ $perPage == 200 ? 'selected' : '' }}>200</option>
                </select>
            </div>
            <div class="col-md-1">
                <button type="submit" class="btn btn-outline-primary">
                    <i class="fas fa-search"></i>
                </button>
            </div>
        </div>
        <div class="mt-2 row">
            <div class="col-md-12">
                <a href="{{ route('tickets.index') }}" class="btn btn-outline-secondary btn-sm">
                    <i class="fas fa-times"></i> Clear Filters
                </a>
                @can('view-tickets')
                    <a href="{{ route('tickets.export') }}?{{ http_build_query(request()->all()) }}" class="btn btn-outline-success btn-sm">
                        <i class="fas fa-download"></i> Export CSV
                    </a>
                @endcan
            </div>
        </div>
    </form>
</div>

<!-- Test Button for Debugging -->
{{-- <div class="mb-3">
    <button type="button" class="btn btn-sm btn-outline-primary resend-sms-btn" 
            data-ticket-id="1" 
            data-reference="TEST-REF"
            data-phone="254700000000"
            data-first-name="Test"
            data-last-name="User"
            data-quantity="1"
            data-event-name="Test Event">
        <i class="fas fa-sms"></i> Test Resend SMS
    </button>
</div> --}}

<!-- Tickets Table -->
<div class="table-responsive-container">
    <table class="table table-hover" id="ticketsTable">
        <thead>
            <tr>
                <th>ID</th>
                <th>Reference</th>
                <th>Customer</th>
                <th>Contact</th>
                <th>School</th>
                <th>Qty</th>
                <th>Amount</th>
                <th>Status</th>
                <th>STK Status</th>
                <th>Payment Date</th>
                <th>Created</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            @php $checkDuplicate = []; $count = 1; @endphp
            @forelse($tickets as $ticket)
                <tr>
                    <td>{{ $count++ }}</td>
                    <td>
                        <span class="ticket-reference">{{ $ticket->reference }}</span>
                    </td>
                    <td>
                        <strong>{{ $ticket->first_name }} {{ $ticket->last_name }}</strong>
                    </td>
                    <td>
                        <div class="scrollable-contact">
                            <div>
                                <i class="fas fa-phone text-primary"></i> {{ $ticket->phone }}<br>
                                <i class="fas fa-envelope text-info"></i> {{ $ticket->email }}
                            </div>
                        </div>
                    </td>
                    <td>
                        @if($ticket->school)
                            <span class="badge bg-secondary school-badge">{{ $ticket->school }}</span>
                        @else
                            <span class="text-muted">-</span>
                        @endif
                    </td>
                    <td class="text-center">
                        <span class="badge bg-info">{{ $ticket->quantity }}</span>
                    </td>
                    <td>
                        <div class="amount-display">
                            KSH {{ number_format($ticket->total_amount, 2) }}
                        </div>
                        <small class="text-muted">@ KSH {{ number_format($ticket->amount, 2) }}/ticket</small>
                    </td>
                    <td>
                        @if($ticket->payment_status === 'completed')
                            <span class="badge status-badge status-completed">
                                <i class="fas fa-check"></i> Paid
                            </span>
                            @if($ticket->mpesa_receipt_number)
                                <br><small class="text-muted">{{ $ticket->mpesa_receipt_number }}</small>
                            @endif
                        @elseif($ticket->payment_status === 'pending')
                            <span class="badge status-badge bg-warning text-dark status-pending">
                                <i class="fas fa-clock"></i> Pending
                            </span>
                        @else
                            <span class="bg-white badge status-badge text-danger status-failed">
                                <i class="fas fa-times"></i> Failed
                            </span>
                        @endif
                    </td>
                    <td>
                        @if($ticket->stk_status)
                            @if($ticket->stk_status === 'Success')
                                <span class="text-white badge status-badge bg-success stk-status-success">
                                    <i class="fas fa-check"></i> Success
                                </span>
                            @elseif($ticket->stk_status === 'Launched')
                                <span class="text-white badge status-badge bg-success stk-status-pending">
                                    <i class="fas fa-clock"></i> Launched
                                </span>
                            @elseif($ticket->stk_status === 'Failed')
                                <span class="text-white badge status-badge bg-danger stk-status-failed">
                                    <i class="fas fa-times"></i> Failed
                                </span>
                            @elseif($ticket->stk_status === 'Canceled')
                                <span class="text-white badge status-badge bg-info stk-status-canceled">
                                    <i class="fas fa-ban"></i> Canceled
                                </span>
                            @elseif($ticket->stk_status === 'Timeout')
                                <span class="text-white badge status-badge bg-danger stk-status-timeout">
                                    <i class="fas fa-clock"></i> Timeout
                                </span>
                            @elseif($ticket->stk_status === 'insufficient-funds')
                                <span class="badge status-badge stk-status-insufficient">
                                    <i class="fas fa-wallet"></i> Insufficient
                                </span>
                            @elseif($ticket->stk_status === 'User-cannot-be-reached')
                                <span class="badge status-badge bg-secondary" style="background:#424242;color:#fff;">
                                    <i class="fas fa-user-times"></i> No Contact
                                </span>
                            @elseif($ticket->stk_status === 'No-response-from-user')
                                <span class="badge status-badge bg-secondary" style="background:#424242;color:#fff;">
                                    <i class="fas fa-user-times"></i> No Response
                                </span>
                            @elseif($ticket->stk_status === 'Invalid-user-input')
                                <span class="text-white badge status-badge bg-info stk-status-invalid-input">
                                    <i class="fas fa-exclamation-triangle"></i> Invalid Input
                                </span>
                            @else
                                <span class="badge bg-info status-badge">
                                    {{ ucfirst($ticket->stk_status) }}
                                </span>
                            @endif
                        @else
                            <span class="text-muted">-</span>
                        @endif
                    </td>
                    <td>
                        <div class="scrollable-payment-date">
                            @if($ticket->payment_date && $ticket->payment_date instanceof \Carbon\Carbon)
                                {{ $ticket->payment_date->format('d/m/Y H:i') }}
                            @elseif($ticket->payment_date)
                                {{ \Carbon\Carbon::parse($ticket->payment_date)->format('d/m/Y H:i') }}
                            @else
                                <span class="text-muted">-</span>
                            @endif
                        </div>
                    </td>
                    <td>
                        {{ $ticket->created_at ? $ticket->created_at->format('d/m/Y H:i') : '-' }}
                    </td>
                    <td>
                        <button type="button" class="btn btn-sm btn-outline-primary resend-sms-btn" 
                                data-ticket-id="{{ $ticket->id }}" 
                                data-reference="{{ $ticket->reference }}"
                                data-phone="{{ $ticket->phone }}"
                                data-first-name="{{ $ticket->first_name }}"
                                data-last-name="{{ $ticket->last_name }}"
                                data-quantity="{{ $ticket->quantity }}"
                                data-event-name="{{ $ticket->event ? $ticket->event->name : 'Event' }}">
                            <i class="fas fa-sms"></i> Resend SMS
                        </button>
                    </td>
                </tr>
            @empty
                <tr>
                    <td colspan="12" class="py-5 text-center">
                        <i class="mb-3 fas fa-ticket-alt fa-3x text-muted"></i>
                        <h4 class="text-muted">No tickets found</h4>
                        <p class="text-muted">Try adjusting your search filters</p>
                    </td>
                </tr>
            @endforelse
        </tbody>
    </table>
</div>

<!-- Summary -->
<div class="mt-3 text-center">
    <small class="text-muted">
        Showing {{ $tickets->firstItem() ?? 0 }} to {{ $tickets->lastItem() ?? 0 }} 
        of {{ $tickets->total() }} total tickets
    </small>
</div>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<!-- DataTables JS -->
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>

<script>
$(document).ready(function() {
    // Test if jQuery and event handlers are working
    console.log('Document ready, jQuery loaded:', typeof $ !== 'undefined');
    console.log('Number of resend buttons found:', $('.resend-sms-btn').length);
    console.log('CSRF token:', $('meta[name="csrf-token"]').attr('content'));
    
    // Simple test click handler
    $('.resend-sms-btn').on('click', function() {
        console.log('Direct click handler triggered');
    });
    
    // Initialize DataTable with responsive settings
    var ticketsTable = $('#ticketsTable').DataTable({
        responsive: false, // Disable responsive hiding of columns
        scrollX: true,
        scrollCollapse: true,
        paging: false, // Disable paging to use Laravel pagination
        searching: false, // Disable search to use server-side filtering
        ordering: false, // Disable ordering to use server-side sorting
        info: false, // Disable info display
        lengthChange: false, // Disable length change
        deferRender: true,
        processing: false,
        language: {
            search: "_INPUT_",
            searchPlaceholder: "Search tickets...",
            lengthMenu: "Show _MENU_ tickets",
            info: "Showing _START_ to _END_ of _TOTAL_ tickets",
            infoEmpty: "No tickets found",
            infoFiltered: "(filtered from _MAX_ total tickets)",
            paginate: {
                first: "First",
                last: "Last",
                next: "Next",
                previous: "Prev"
            }
        },
        initComplete: function() {
            // Change "Quantity" to "Qty" in header
            $('th:contains("Qty")').html('Qty');
            
            // Fix header alignment
            $('.dataTables_scrollHeadInner').css('width', 'auto');
            $('.table').css('width', 'auto');
            
            // Re-bind event handlers after DataTable initialization
            console.log('DataTable initialized, buttons found:', $('.resend-sms-btn').length);
        },
        drawCallback: function() {
            // Fix responsive display after each draw
            if ($(window).width() < 768) {
                $('.dataTables_paginate').addClass('pagination-sm');
            } else {
                $('.dataTables_paginate').removeClass('pagination-sm');
            }
            
            // Ensure proper column count handling
            var api = this.api();
            var columnCount = api.columns().count();
            var headerCount = $('thead th').length;
            
            if (columnCount !== headerCount) {
                console.warn('Column count mismatch detected. Headers:', headerCount, 'Columns:', columnCount);
            }
            
            // Re-bind event handlers after table redraw
            console.log('Table redrawn, buttons found:', $('.resend-sms-btn').length);
        },
        columnDefs: [
            { 
                targets: 0, // ID column
                width: "60px",
                className: 'text-center'
            },
            { 
                targets: 5, // Qty column
                width: "70px",
                className: 'text-center'
            },
            { 
                targets: '_all',
                className: 'text-left',
                render: function(data, type, row) {
                    if (type === 'display' && data) {
                        return '<div style="white-space: nowrap;">' + data + '</div>';
                    }
                    return data;
                }
            }
        ]
    });

    // Auto-submit filters on change
    $('#status, #school, #stk_status, #per_page').change(function() {
        $('#filter-form').submit();
    });

    // Window resize handler
    $(window).on('resize', function() {
        ticketsTable.columns.adjust();
    }).trigger('resize');

    // Handle Resend SMS button clicks - using event delegation
    $(document).on('click', '.resend-sms-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log('Resend SMS button clicked'); // Debug log
        
        var btn = $(this);
        var ticketId = btn.data('ticket-id');
        var originalHtml = btn.html();
        
        console.log('Ticket ID:', ticketId); // Debug log
        console.log('Button data:', btn.data()); // Debug log
        
        if (!ticketId) {
            alert('Error: No ticket ID found');
            return;
        }
        
        // Confirm action
        if (!confirm('Are you sure you want to resend SMS for ticket #' + ticketId + '?')) {
            return;
        }
        
        // Disable button and show loading state
        btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Sending...');
        
        $.ajax({
            url: '/admin/tickets/' + ticketId + '/resend-sms',
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            beforeSend: function() {
                console.log('Sending SMS request...'); // Debug log
            },
            success: function(response) {
                console.log('SMS sent successfully:', response); // Debug log
                btn.prop('disabled', false).html('<i class="fas fa-check"></i> Sent!');
                btn.removeClass('btn-outline-primary').addClass('btn-success');
                
                // Show success message
                var alertHtml = '<div class="alert alert-success alert-dismissible fade show" role="alert">' +
                    '<i class="fas fa-check-circle"></i> SMS sent successfully to ' + btn.data('phone') +
                    '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>' +
                    '</div>';
                $('.tickets-container').prepend(alertHtml);
                
                // Reset button after 3 seconds
                setTimeout(function() {
                    btn.html(originalHtml);
                    btn.removeClass('btn-success').addClass('btn-outline-primary');
                }, 3000);
            },
            error: function(xhr) {
                console.log('SMS send failed:', xhr); // Debug log
                btn.prop('disabled', false).html(originalHtml);
                
                var errorMsg = 'Failed to send SMS';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMsg = xhr.responseJSON.message;
                } else if (xhr.responseText) {
                    errorMsg = 'Server error: ' + xhr.status;
                }
                
                var alertHtml = '<div class="alert alert-danger alert-dismissible fade show" role="alert">' +
                    '<i class="fas fa-exclamation-circle"></i> ' + errorMsg +
                    '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>' +
                    '</div>';
                $('.tickets-container').prepend(alertHtml);
            }
        });
    });
});
</script>
</body>
</html>