<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Super Admin - Subscriptions | DELUXE SYSTEM</title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome 6 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <!-- SweetAlert2 -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    <!-- Moment.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
    
    <style>
        :root {
            --primary-color: #059669;
            --primary-dark: #047857;
            --primary-light: #10b981;
            --primary-soft: #d1fae5;
            --secondary-color: #6b7280;
            --success-color: #10b981;
            --warning-color: #f59e0b;
            --danger-color: #ef4444;
            --info-color: #3b82f6;
            
            /* Package Colors */
            --silver: #6c757d;
            --gold: #f59e0b;
            --platinum: #3b82f6;
            --custom: #8b5cf6;
        }
        
        body {
            background-color: #f8fafc;
            font-family: 'Nunito', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        /* Navbar Styles */
        .navbar {
            background: linear-gradient(135deg, #059669, #047857);
            padding: 0.75rem 1.5rem;
            box-shadow: 0 4px 12px rgba(5, 150, 105, 0.2);
        }
        
        .navbar-brand {
            font-size: 1.5rem;
            font-weight: 700;
            color: white !important;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .navbar-brand i {
            font-size: 1.8rem;
            color: #d1fae5;
        }
        
        .nav-link {
            color: rgba(255, 255, 255, 0.9) !important;
            font-weight: 500;
            padding: 0.5rem 1rem !important;
            border-radius: 0.5rem;
            transition: all 0.3s;
        }
        
        .nav-link:hover {
            color: white !important;
            background-color: rgba(209, 250, 229, 0.2);
            transform: translateY(-2px);
        }
        
        .nav-link i {
            margin-right: 0.5rem;
            color: #d1fae5;
        }
        
        .nav-link.active {
            color: white !important;
            background-color: rgba(209, 250, 229, 0.15);
            border-bottom: 3px solid #d1fae5;
        }
        
        .user-dropdown {
            background-color: rgba(209, 250, 229, 0.2);
            border-radius: 2rem;
            padding: 0.25rem 0.25rem 0.25rem 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .user-dropdown .dropdown-toggle {
            color: white;
            background-color: transparent;
            border: none;
            padding: 0.25rem 0.75rem;
            border-radius: 2rem;
        }
        
        .user-dropdown .dropdown-toggle::after {
            color: white;
        }
        
        .dropdown-menu {
            border: 2px solid #d1fae5;
            border-radius: 1rem;
            box-shadow: 0 10px 15px -3px rgba(5, 150, 105, 0.2);
        }
        
        .dropdown-item {
            padding: 0.75rem 1.5rem;
            font-weight: 500;
            color: #1f2937;
        }
        
        .dropdown-item i {
            margin-right: 0.75rem;
            color: var(--primary-color);
            width: 1.25rem;
        }
        
        .dropdown-item:hover {
            background-color: #f0fdf4;
            color: var(--primary-dark);
        }
        
        .dropdown-divider {
            border-top-color: #d1fae5;
        }
        
        /* Main Content */
        .main-content {
            padding: 2rem;
            max-width: 1600px;
            margin: 0 auto;
        }
        
        /* Page Header */
        .page-header {
            margin-bottom: 2rem;
            border-bottom: 2px solid #a7f3d0;
            padding-bottom: 1rem;
        }
        
        .page-title {
            color: var(--primary-color);
            font-weight: 700;
            margin: 0;
            font-size: 2rem;
        }
        
        .page-title i {
            color: var(--primary-color);
        }
        
        .breadcrumb {
            background: transparent;
            padding: 0;
            margin: 0;
        }
        
        .breadcrumb-item a {
            color: var(--primary-color);
            text-decoration: none;
        }
        
        .breadcrumb-item a:hover {
            color: var(--primary-dark);
            text-decoration: underline;
        }
        
        /* Stats Cards */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 1rem;
            padding: 1.25rem;
            box-shadow: 0 4px 6px -1px rgba(5, 150, 105, 0.1);
            border: 1px solid #d1fae5;
            transition: all 0.3s;
            position: relative;
            overflow: hidden;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 25px -5px rgba(5, 150, 105, 0.2);
        }
        
        .stat-icon {
            font-size: 2.5rem;
            opacity: 0.2;
            position: absolute;
            right: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: var(--primary-color);
        }
        
        .stat-label {
            color: var(--secondary-color);
            font-size: 0.85rem;
            text-transform: uppercase;
            letter-spacing: 0.05rem;
            margin-bottom: 0.5rem;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: var(--primary-color);
        }
        
        /* Filter Section */
        .filter-card {
            background: white;
            border-radius: 1rem;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(5, 150, 105, 0.1);
            border: 1px solid #d1fae5;
        }
        
        .filter-card h6 {
            color: var(--primary-color);
            font-weight: 600;
        }
        
        .filter-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1rem;
        }
        
        .filter-group {
            margin-bottom: 1rem;
        }
        
        .filter-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: var(--primary-dark);
            font-size: 0.9rem;
        }
        
        .filter-group select,
        .filter-group input {
            width: 100%;
            padding: 0.5rem 0.75rem;
            border: 1px solid #d1fae5;
            border-radius: 0.5rem;
            transition: all 0.3s;
        }
        
        .filter-group select:focus,
        .filter-group input:focus {
            outline: none;
            border-color: var(--primary-light);
            box-shadow: 0 0 0 3px rgba(5, 150, 105, 0.1);
        }
        
        .filter-actions {
            display: flex;
            justify-content: flex-end;
            gap: 0.5rem;
            margin-top: 1rem;
        }
        
        /* Table Card */
        .table-card {
            background: white;
            border-radius: 1rem;
            box-shadow: 0 4px 6px -1px rgba(5, 150, 105, 0.1);
            border: 1px solid #d1fae5;
            overflow: hidden;
        }
        
        .card-header {
            background: white;
            border-bottom: 2px solid #d1fae5;
            padding: 1.25rem;
        }
        
        .card-header h5 {
            color: var(--primary-color);
            font-weight: 600;
            margin: 0;
        }
        
        .table {
            margin: 0;
        }
        
        .table thead th {
            background-color: #f0fdf4;
            border-bottom: 2px solid #d1fae5;
            color: var(--primary-dark);
            font-weight: 600;
            font-size: 0.85rem;
            text-transform: uppercase;
            letter-spacing: 0.05rem;
            padding: 1rem;
        }
        
        .table td {
            padding: 1rem;
            vertical-align: middle;
            border-bottom: 1px solid #d1fae5;
        }
        
        .table tbody tr:hover {
            background-color: #f0fdf4;
        }
        
        /* Package Badges */
        .badge-package {
            padding: 0.5rem 1rem;
            font-size: 0.85rem;
            font-weight: 600;
            border-radius: 2rem;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            color: white;
        }
        
        .badge-silver {
            background: linear-gradient(135deg, #6c757d, #5a6268);
        }
        
        .badge-gold {
            background: linear-gradient(135deg, #f59e0b, #d97706);
        }
        
        .badge-platinum {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
        }
        
        .badge-custom {
            background: linear-gradient(135deg, #8b5cf6, #7c3aed);
        }
        
        /* Status Badges */
        .badge-status {
            padding: 0.5rem 1rem;
            font-size: 0.85rem;
            font-weight: 600;
            border-radius: 2rem;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            color: white;
        }
        
        .badge-active {
            background: linear-gradient(135deg, #10b981, #059669);
        }
        
        .badge-trial {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
        }
        
        .badge-expiring {
            background: linear-gradient(135deg, #f59e0b, #d97706);
        }
        
        .badge-suspended {
            background: linear-gradient(135deg, #ef4444, #dc2626);
        }
        
        .badge-expired {
            background: linear-gradient(135deg, #6b7280, #4b5563);
        }
        
        /* Buttons */
        .btn {
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #059669, #10b981);
            border: none;
            color: white;
        }
        
        .btn-primary:hover {
            background: linear-gradient(135deg, #047857, #059669);
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(5, 150, 105, 0.2);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #10b981, #34d399);
            border: none;
            color: white;
        }
        
        .btn-warning {
            background: linear-gradient(135deg, #f59e0b, #fbbf24);
            border: none;
            color: white;
        }
        
        .btn-danger {
            background: linear-gradient(135deg, #ef4444, #f87171);
            border: none;
            color: white;
        }
        
        .btn-info {
            background: linear-gradient(135deg, #3b82f6, #60a5fa);
            border: none;
            color: white;
        }
        
        .btn-outline-primary {
            background: transparent;
            border: 2px solid #059669;
            color: #059669;
        }
        
        .btn-outline-primary:hover {
            background: #059669;
            color: white;
        }
        
        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
        
        .btn-icon {
            width: 32px;
            height: 32px;
            padding: 0;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
            margin: 0 2px;
            transition: all 0.2s;
        }
        
        .btn-icon:hover {
            transform: translateY(-2px);
        }
        
        .action-group {
            display: flex;
            gap: 0.25rem;
            flex-wrap: wrap;
        }
        
        /* Modal Styles */
        .modal-content {
            border: none;
            border-radius: 1rem;
            border: 2px solid #d1fae5;
        }
        
        .modal-header {
            background: linear-gradient(135deg, #059669, #10b981);
            color: white;
            border-radius: 1rem 1rem 0 0;
            padding: 1.25rem;
        }
        
        .modal-header .btn-close {
            filter: brightness(0) invert(1);
        }
        
        .modal-title {
            font-weight: 600;
        }
        
        .modal-body {
            padding: 1.5rem;
        }
        
        .modal-footer {
            border-top: 2px solid #d1fae5;
            padding: 1.25rem;
        }
        
        .form-label {
            font-weight: 600;
            color: var(--primary-dark);
            margin-bottom: 0.5rem;
        }
        
        .form-control, .form-select {
            border: 1px solid #d1fae5;
            border-radius: 0.5rem;
            padding: 0.5rem 0.75rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary-light);
            box-shadow: 0 0 0 3px rgba(5, 150, 105, 0.1);
        }
        
        /* Detail View */
        .detail-section {
            margin-bottom: 1.5rem;
        }
        
        .detail-title {
            font-size: 1rem;
            font-weight: 700;
            color: var(--primary-dark);
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #d1fae5;
        }
        
        .detail-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
        }
        
        .detail-item {
            margin-bottom: 0.75rem;
        }
        
        .detail-label {
            font-size: 0.85rem;
            color: var(--secondary-color);
            margin-bottom: 0.25rem;
        }
        
        .detail-value {
            font-weight: 600;
            color: #1f2937;
        }
        
        /* Pagination */
        .pagination {
            margin: 0;
        }
        
        .page-link {
            color: #059669;
            border: 1px solid #d1fae5;
        }
        
        .page-item.active .page-link {
            background-color: #059669;
            border-color: #059669;
            color: white;
        }
        
        .page-link:hover {
            color: #047857;
            background-color: #f0fdf4;
            border-color: #d1fae5;
        }
        
        /* Export-modal multi-select checkboxes */
        .export-include {
            display: flex;
            align-items: flex-start;
            gap: 12px;
            padding: 10px 12px;
            border: 1px solid #d1fae5;
            border-radius: 10px;
            background: #f8fdfa;
            cursor: pointer;
            transition: all 0.15s ease;
            margin-bottom: 8px;
            user-select: none;
        }
        .export-include:hover { border-color: #059669; background: #ecfdf5; }
        .export-include__input {
            position: absolute;
            opacity: 0;
            width: 0;
            height: 0;
            pointer-events: none;
        }
        .export-include__box {
            width: 22px;
            height: 22px;
            border: 2px solid #9ca3af;
            border-radius: 6px;
            background: #fff;
            flex-shrink: 0;
            position: relative;
            margin-top: 2px;
            transition: all 0.15s ease;
        }
        .export-include__box::after {
            content: '';
            position: absolute;
            left: 6px;
            top: 2px;
            width: 6px;
            height: 11px;
            border: solid #fff;
            border-width: 0 2px 2px 0;
            transform: rotate(45deg);
            opacity: 0;
            transition: opacity 0.15s ease;
        }
        .export-include__input:checked + .export-include__box {
            background: #059669;
            border-color: #047857;
        }
        .export-include__input:checked + .export-include__box::after { opacity: 1; }
        .export-include__input:focus-visible + .export-include__box {
            outline: 3px solid rgba(5, 150, 105, 0.25);
            outline-offset: 2px;
        }
        .export-include__text { display: flex; flex-direction: column; line-height: 1.35; }
        .export-include__text strong { color: #064e3b; font-size: 0.92rem; font-weight: 600; }
        .export-include__text small { color: #6b7280; font-size: 0.78rem; margin-top: 1px; }

        /* Loading Overlay */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.8);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        
        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #d1fae5;
            border-top-color: var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* Empty State */
        .empty-state {
            padding: 3rem 1rem;
            text-align: center;
        }
        
        .empty-state i {
            font-size: 4rem;
            color: #d1fae5;
            margin-bottom: 1rem;
        }
        
        .empty-state h5 {
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .empty-state p {
            color: #6b7280;
            margin-bottom: 1.5rem;
        }
        
        /* Responsive */
        @media (max-width: 1200px) {
            .stats-row {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .filter-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
        
        @media (max-width: 768px) {
            .main-content {
                padding: 1rem;
            }
            
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .filter-grid {
                grid-template-columns: 1fr;
            }
            
            .detail-grid {
                grid-template-columns: 1fr;
            }
            
            .navbar-brand span {
                display: none;
            }
        }
        /* 2026 elegance refresh */
        body {
            background:
                radial-gradient(circle at 10% 3%, rgba(16, 185, 129, 0.09), transparent 35%),
                radial-gradient(circle at 92% 7%, rgba(5, 150, 105, 0.08), transparent 32%),
                #f4f8f5;
            color: #0f172a;
        }

        .navbar {
            box-shadow: 0 10px 30px rgba(5, 150, 105, 0.25);
        }

        .main-content {
            padding-top: 2.4rem;
        }

        .page-header {
            background: rgba(255, 255, 255, 0.82);
            border: 1px solid rgba(5, 150, 105, 0.12);
            border-radius: 16px;
            padding: 1.2rem 1.4rem;
            backdrop-filter: blur(6px);
        }

        .stat-card,
        .card {
            border-radius: 16px !important;
            border: 1px solid rgba(5, 150, 105, 0.1) !important;
            box-shadow: 0 12px 26px rgba(5, 150, 105, 0.1) !important;
        }

        .stat-card:hover,
        .card:hover {
            transform: translateY(-4px);
            box-shadow: 0 18px 34px rgba(5, 150, 105, 0.16) !important;
        }

        .table thead th {
            background: #ecfdf5 !important;
            color: #065f46 !important;
            border-bottom-color: #a7f3d0 !important;
        }

        .btn {
            border-radius: 999px;
            font-weight: 600;
        }
    </style>
    <link rel="stylesheet" href="{{ asset('css/admin-elegant-theme.css') }}">
</head>
<body class="super-admin-elegant">
    <!-- Loading Overlay -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-spinner"></div>
    </div>

    <!-- Navigation Bar -->
    <nav class="navbar navbar-expand-lg">
        <div class="container-fluid">
            <div class="navbar-brand"></div>
            
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('super.admin.dashboard') }}">
                            <i class="fas fa-chart-pie"></i>Dashboard
                        </a>
                    </li>
                   
            </div>
        </div>
    </nav>
    
    <!-- Main Content -->
    <div class="main-content">
        <!-- Page Header -->
        <div class="page-header d-flex justify-content-between align-items-center">
            <div>
                <h2 class="page-title">
                    <i class="fas fa-credit-card me-2"></i>
                    Subscription Management
                </h2>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="{{ route('super.admin.dashboard') }}">Dashboard</a></li>
                        <li class="breadcrumb-item active">Subscriptions</li>
                    </ol>
                </nav>
            </div>
            <div>
                <a href="{{ route('super.admin.dashboard') }}" class="btn btn-outline-primary me-2">
                    <i class="fas fa-arrow-left me-2"></i>Back to Dashboard
                </a>
                <button class="btn btn-primary me-2" onclick="openCreateModal()">
                    <i class="fas fa-plus me-2"></i>New Subscription
                </button>
                <button class="btn btn-warning me-2" onclick="sendRemindersNow()">
                    <i class="fas fa-paper-plane me-2"></i>Send Due Reminders
                </button>
                <button class="btn btn-success" onclick="openExportModal()">
                    <i class="fas fa-download me-2"></i>Export
                </button>
            </div>
        </div>
        
        <!-- Statistics Cards -->
        <div class="stats-row">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-building"></i>
                </div>
                <div class="stat-label">Total Hotels</div>
                <div class="stat-value">{{ $totalHotels ?? 0 }}</div>
                <small class="text-muted">Registered properties</small>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-check-circle"></i>
                </div>
                <div class="stat-label">Active Subscriptions</div>
                <div class="stat-value">{{ $activeSubscriptions ?? 0 }}</div>
                <small class="text-muted">Paid & active</small>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-clock"></i>
                </div>
                <div class="stat-label">Expiring Soon</div>
                <div class="stat-value">{{ $expiringSoon ?? 0 }}</div>
                <small class="text-muted">Within 30 days</small>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-pause-circle"></i>
                </div>
                <div class="stat-label">Suspended</div>
                <div class="stat-value">{{ $suspendedSubscriptions ?? 0 }}</div>
                <small class="text-muted">Inactive accounts</small>
            </div>
        </div>
        
        <!-- Filter Section -->
        <div class="filter-card">
            <form method="GET" action="{{ route('super.admin.subscriptions.index') }}" id="filterForm">
                <div class="filter-grid">
                    <div class="filter-group">
                        <label><i class="fas fa-tag me-1"></i>Status</label>
                        <select name="status" class="form-select">
                            <option value="all">All Status</option>
                            <option value="active" {{ request('status') == 'active' ? 'selected' : '' }}>Active</option>
                            <option value="trial" {{ request('status') == 'trial' ? 'selected' : '' }}>Trial</option>
                            <option value="expiring" {{ request('status') == 'expiring' ? 'selected' : '' }}>Expiring Soon</option>
                            <option value="expired" {{ request('status') == 'expired' ? 'selected' : '' }}>Expired</option>
                            <option value="suspended" {{ request('status') == 'suspended' ? 'selected' : '' }}>Suspended</option>
                            <option value="cancelled" {{ request('status') == 'cancelled' ? 'selected' : '' }}>Cancelled</option>
                        </select>
                    </div>
                    
                    <div class="filter-group">
                        <label><i class="fas fa-box me-1"></i>Package</label>
                        <select name="package" class="form-select">
                            <option value="all">All Packages</option>
                            <option value="silver" {{ request('package') == 'silver' ? 'selected' : '' }}>Silver</option>
                            <option value="gold" {{ request('package') == 'gold' ? 'selected' : '' }}>Gold</option>
                            <option value="platinum" {{ request('package') == 'platinum' ? 'selected' : '' }}>Platinum</option>
                            <option value="custom" {{ request('package') == 'custom' ? 'selected' : '' }}>Custom</option>
                        </select>
                    </div>
                    
                    <div class="filter-group">
                        <label><i class="fas fa-calendar me-1"></i>Date Range</label>
                        <select name="date_range" class="form-select">
                            <option value="all">All Time</option>
                            <option value="today" {{ request('date_range') == 'today' ? 'selected' : '' }}>Today</option>
                            <option value="week" {{ request('date_range') == 'week' ? 'selected' : '' }}>This Week</option>
                            <option value="month" {{ request('date_range') == 'month' ? 'selected' : '' }}>This Month</option>
                            <option value="quarter" {{ request('date_range') == 'quarter' ? 'selected' : '' }}>This Quarter</option>
                            <option value="year" {{ request('date_range') == 'year' ? 'selected' : '' }}>This Year</option>
                        </select>
                    </div>
                    
                    <div class="filter-group">
                        <label><i class="fas fa-search me-1"></i>Search</label>
                        <input type="text" name="search" class="form-control" placeholder="Hotel name, email..." value="{{ request('search') }}">
                    </div>
                </div>
                
                <div class="filter-actions">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-filter me-2"></i>Apply Filters
                    </button>
                    <a href="{{ route('super.admin.subscriptions.index') }}" class="btn btn-outline-primary">
                        <i class="fas fa-times me-2"></i>Clear
                    </a>
                </div>
            </form>
        </div>
        
        <!-- Subscriptions Table -->
        <div class="table-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5>
                    <i class="fas fa-list me-2"></i>
                    Hotel Subscriptions
                </h5>
                <div class="d-flex gap-2">
                    <input type="text" class="form-control form-control-sm" id="tableSearch" placeholder="Search in table..." style="width: 200px;">
                    <select class="form-select form-select-sm" id="perPage" onchange="changePerPage(this.value)">
                        <option value="15" {{ request('per_page', 15) == 15 ? 'selected' : '' }}>15</option>
                        <option value="25" {{ request('per_page') == 25 ? 'selected' : '' }}>25</option>
                        <option value="50" {{ request('per_page') == 50 ? 'selected' : '' }}>50</option>
                        <option value="100" {{ request('per_page') == 100 ? 'selected' : '' }}>100</option>
                    </select>
                </div>
            </div>
            
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Hotel</th>
                            <th>Contact</th>
                            <th>Package</th>
                            <th>Start Date</th>
                            <th>End Date</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($subscriptions ?? [] as $subscription)
                        <tr id="subscription-row-{{ $subscription->id }}">
                            <td>
                                <div class="fw-bold">{{ $subscription->hotel->name ?? 'N/A' }}</div>
                                <small class="text-muted">ID: #{{ $subscription->hotel->id ?? '' }}</small>
                            </td>
                            <td>
                                <div><i class="fas fa-envelope me-1 text-muted"></i>{{ $subscription->hotel->email ?? 'N/A' }}</div>
                                <div><i class="fas fa-phone me-1 text-muted"></i>{{ $subscription->hotel->phone ?? 'N/A' }}</div>
                            </td>
                            <td>
                                @php
                                    $planName = strtolower($subscription->plan_name ?? 'silver');
                                    $planPrice = $subscription->plan_price ?? 0;
                                    
                                    // Package configuration
                                    $packageConfig = [
                                        'silver' => [
                                            'class' => 'badge-silver',
                                            'icon' => 'fa-tag',
                                            'name' => 'Silver'
                                        ],
                                        'gold' => [
                                            'class' => 'badge-gold',
                                            'icon' => 'fa-star',
                                            'name' => 'Gold'
                                        ],
                                        'platinum' => [
                                            'class' => 'badge-platinum',
                                            'icon' => 'fa-crown',
                                            'name' => 'Platinum'
                                        ],
                                        'custom' => [
                                            'class' => 'badge-custom',
                                            'icon' => 'fa-gem',
                                            'name' => 'Custom'
                                        ]
                                    ];
                                    
                                    $config = $packageConfig[$planName] ?? $packageConfig['silver'];
                                @endphp
                                
                                <span class="badge-package {{ $config['class'] }}">
                                    <i class="fas {{ $config['icon'] }}"></i>
                                    {{ $config['name'] }}
                                </span>
                                <div class="small text-muted mt-1">
                                    {{ number_format($planPrice) }} UGX
                                </div>
                            </td>
                            <td>
                                @if($subscription->start_date)
                                    {{ \Carbon\Carbon::parse($subscription->start_date)->format('M d, Y') }}
                                @else
                                    <span class="text-muted">N/A</span>
                                @endif
                            </td>
                            <td>
                                @php
                                    $endDate = $subscription->end_date ?? null;
                                    $daysLeft = $endDate ? now()->diffInDays(\Carbon\Carbon::parse($endDate), false) : null;
                                @endphp
                                
                                @if($endDate)
                                    {{ \Carbon\Carbon::parse($endDate)->format('M d, Y') }}
                                    @if($daysLeft !== null)
                                        <br>
                                        <small class="{{ $daysLeft < 0 ? 'text-danger' : ($daysLeft <= 7 ? 'text-warning' : 'text-success') }}">
                                            <i class="fas fa-{{ $daysLeft < 0 ? 'exclamation-circle' : ($daysLeft <= 7 ? 'clock' : 'check-circle') }} me-1"></i>
                                            {{ $daysLeft < 0 ? 'Expired' : $daysLeft . ' days left' }}
                                        </small>
                                    @endif
                                @else
                                    <span class="text-muted">N/A</span>
                                @endif
                            </td>
                            <td>
                                @php
                                    $status = strtolower($subscription->status ?? 'unknown');
                                    $daysLeft = $subscription->end_date ? now()->diffInDays(\Carbon\Carbon::parse($subscription->end_date), false) : null;
                                    
                                    $statusConfig = [
                                        'active' => [
                                            'class' => 'badge-active',
                                            'icon' => 'fa-check-circle',
                                            'text' => 'Active'
                                        ],
                                        'trial' => [
                                            'class' => 'badge-trial',
                                            'icon' => 'fa-clock',
                                            'text' => 'Trial'
                                        ],
                                        'suspended' => [
                                            'class' => 'badge-suspended',
                                            'icon' => 'fa-pause-circle',
                                            'text' => 'Suspended'
                                        ],
                                        'cancelled' => [
                                            'class' => 'badge-expired',
                                            'icon' => 'fa-times-circle',
                                            'text' => 'Cancelled'
                                        ],
                                        'expired' => [
                                            'class' => 'badge-expired',
                                            'icon' => 'fa-calendar-times',
                                            'text' => 'Expired'
                                        ]
                                    ];
                                    
                                    // Determine if expiring soon
                                    if ($status == 'active' && $daysLeft !== null && $daysLeft <= 7) {
                                        $displayStatus = 'expiring';
                                        $statusText = 'Expiring Soon';
                                        $statusIcon = 'fa-exclamation-triangle';
                                        $statusClass = 'badge-expiring';
                                    } else {
                                        $displayStatus = $status;
                                        $statusText = $statusConfig[$status]['text'] ?? ucfirst($status);
                                        $statusIcon = $statusConfig[$status]['icon'] ?? 'fa-question-circle';
                                        $statusClass = $statusConfig[$status]['class'] ?? 'badge-secondary';
                                    }
                                @endphp
                                
                                <span class="badge-status {{ $statusClass }}">
                                    <i class="fas {{ $statusIcon }}"></i>
                                    {{ $statusText }}
                                </span>
                                @if($status == 'trial' && $subscription->trial_end_date)
                                    <br>
                                    <small class="text-muted">Until {{ \Carbon\Carbon::parse($subscription->trial_end_date)->format('M d, Y') }}</small>
                                @endif
                            </td>
                            <td>
                                <div class="action-group">
                                    <button class="btn btn-info btn-sm btn-icon" title="View Details" onclick="viewSubscription({{ $subscription->id }})">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <button class="btn btn-primary btn-sm btn-icon" title="Edit" onclick="editSubscription({{ $subscription->id }})">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-warning btn-sm btn-icon" title="Renew" onclick="renewSubscription({{ $subscription->id }})">
                                        <i class="fas fa-sync-alt"></i>
                                    </button>
                                    <button class="btn btn-success btn-sm btn-icon" title="Upgrade" onclick="upgradeSubscription({{ $subscription->id }})">
                                        <i class="fas fa-arrow-up"></i>
                                    </button>
                                    @if($subscription->status != 'suspended')
                                    <button class="btn btn-secondary btn-sm btn-icon" title="Suspend" onclick="suspendSubscription({{ $subscription->id }})">
                                        <i class="fas fa-pause"></i>
                                    </button>
                                    @else
                                    <button class="btn btn-success btn-sm btn-icon" title="Activate" onclick="activateSubscription({{ $subscription->id }})">
                                        <i class="fas fa-play"></i>
                                    </button>
                                    @endif
                                    <button class="btn btn-danger btn-sm btn-icon" title="Delete" onclick="deleteSubscription({{ $subscription->id }})">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="7" class="text-center py-5">
                                <div class="empty-state">
                                    <i class="fas fa-credit-card fa-4x mb-3" style="color: #d1fae5;"></i>
                                    <h5>No Subscriptions Found</h5>
                                    <p class="mb-3">
                                        @if(request('status') || request('package') || request('search'))
                                            No subscriptions match your filter criteria.
                                        @else
                                            There are no hotel subscriptions to display at the moment.
                                        @endif
                                    </p>
                                    @if(request('status') || request('package') || request('search'))
                                        <a href="{{ route('super.admin.subscriptions.index') }}" class="btn btn-outline-primary">
                                            <i class="fas fa-times me-2"></i>Clear Filters
                                        </a>
                                    @else
                                        <button class="btn btn-primary" onclick="openCreateModal()">
                                            <i class="fas fa-plus me-2"></i>Add New Subscription
                                        </button>
                                    @endif
                                </div>
                            </td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            
            @if(isset($subscriptions) && method_exists($subscriptions, 'links'))
            <div class="card-footer bg-white d-flex justify-content-between align-items-center">
                <div class="text-muted">
                    Showing {{ $subscriptions->firstItem() ?? 0 }} to {{ $subscriptions->lastItem() ?? 0 }} of {{ $subscriptions->total() ?? 0 }} entries
                </div>
                <div>
                    {{ $subscriptions->appends(request()->query())->links() }}
                </div>
            </div>
            @endif
        </div>
    </div>
    
    <!-- Create/Edit Subscription Modal -->
    <div class="modal fade" id="subscriptionModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">
                        <i class="fas fa-plus-circle me-2"></i>
                        Create New Subscription
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="subscriptionForm">
                    @csrf
                    <input type="hidden" name="_method" id="formMethod" value="POST">
                    
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Hotel</label>
                                <select class="form-select" name="hotel_id" id="hotel_id" required>
                                    <option value="">Select Hotel</option>
                                    @foreach($hotels ?? [] as $hotel)
                                    <option value="{{ $hotel->id }}">{{ $hotel->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Plan Name</label>
                                <select class="form-select" name="plan_name" id="plan_name" required onchange="updatePlanDetails()">
                                    <option value="">Select Plan</option>
                                    <option value="silver" data-price="150000" data-rooms="20" data-users="2">Silver - 150,000 UGX (20 Rooms, 2 Users)</option>
                                    <option value="gold" data-price="350000" data-rooms="40" data-users="5">Gold - 350,000 UGX (40 Rooms, 5 Users)</option>
                                    <option value="platinum" data-price="500000" data-rooms="60" data-users="10">Platinum - 500,000 UGX (60 Rooms, 10 Users)</option>
                                    <option value="custom" data-price="0" data-rooms="0" data-users="0">Custom</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Plan Price (UGX)</label>
                                <input type="number" class="form-control" name="plan_price" id="plan_price" step="1000" required>
                                <small class="text-muted">Price auto-updates based on selected plan</small>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Billing Cycle</label>
                                <select class="form-select" name="billing_cycle" id="billing_cycle" required>
                                    <option value="monthly">Monthly</option>
                                    <option value="quarterly">Quarterly</option>
                                    <option value="yearly">Yearly</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Start Date</label>
                                <input type="date" class="form-control" name="start_date" id="start_date" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">End Date</label>
                                <input type="date" class="form-control" name="end_date" id="end_date" required>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Trial Start Date</label>
                                <input type="date" class="form-control" name="trial_start_date" id="trial_start_date">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Trial End Date</label>
                                <input type="date" class="form-control" name="trial_end_date" id="trial_end_date">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Status</label>
                                <select class="form-select" name="status" id="status" required>
                                    <option value="trial">Trial</option>
                                    <option value="active">Active</option>
                                    <option value="expired">Expired</option>
                                    <option value="suspended">Suspended</option>
                                    <option value="cancelled">Cancelled</option>
                                </select>
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Max Rooms</label>
                                <input type="number" class="form-control" name="max_rooms" id="max_rooms" required>
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="form-label">Max Users</label>
                                <input type="number" class="form-control" name="max_users" id="max_users" required>
                            </div>
                        </div>
                        
                        <div class="row" id="customFields" style="display: none;">
                            <div class="col-md-12 mb-3">
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i>
                                    For custom plans, you can manually edit the price, rooms, and users fields.
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" name="notes" id="notes" rows="2"></textarea>
                        </div>
                    </div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" id="submitBtn">
                            <i class="fas fa-save me-2"></i>Save Subscription
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- View Details Modal -->
    <div class="modal fade" id="viewModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-info-circle me-2"></i>
                        Subscription Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="detail-section">
                        <h6 class="detail-title">Hotel Information</h6>
                        <div class="detail-grid">
                            <div class="detail-item">
                                <div class="detail-label">Hotel Name</div>
                                <div class="detail-value" id="view_hotel_name"></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">Email</div>
                                <div class="detail-value" id="view_email"></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">Phone</div>
                                <div class="detail-value" id="view_phone"></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">Location</div>
                                <div class="detail-value" id="view_location"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="detail-section">
                        <h6 class="detail-title">Package Details</h6>
                        <div class="detail-grid">
                            <div class="detail-item">
                                <div class="detail-label">Package</div>
                                <div class="detail-value" id="view_package"></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">Monthly Price</div>
                                <div class="detail-value" id="view_price"></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">Billing Cycle</div>
                                <div class="detail-value" id="view_billing_cycle"></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">Status</div>
                                <div class="detail-value" id="view_status"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="detail-section">
                        <h6 class="detail-title">Subscription Period</h6>
                        <div class="detail-grid">
                            <div class="detail-item">
                                <div class="detail-label">Start Date</div>
                                <div class="detail-value" id="view_start_date"></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">End Date</div>
                                <div class="detail-value" id="view_end_date"></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">Days Remaining</div>
                                <div class="detail-value" id="view_days_remaining"></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">Trial Ends</div>
                                <div class="detail-value" id="view_trial_ends"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="detail-section">
                        <h6 class="detail-title">Limits</h6>
                        <div class="detail-grid">
                            <div class="detail-item">
                                <div class="detail-label">Max Rooms</div>
                                <div class="detail-value" id="view_max_rooms"></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">Max Users</div>
                                <div class="detail-value" id="view_max_users"></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">Used Rooms</div>
                                <div class="detail-value" id="view_used_rooms"></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">Used Users</div>
                                <div class="detail-value" id="view_used_users"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="detail-section" id="notesSection" style="display: none;">
                        <h6 class="detail-title">Notes</h6>
                        <p id="view_notes" class="mb-0"></p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" onclick="editFromView()">
                        <i class="fas fa-edit me-2"></i>Edit
                    </button>
                    <button type="button" class="btn btn-success" onclick="renewFromView()">
                        <i class="fas fa-sync-alt me-2"></i>Renew
                    </button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Renew Modal -->
    <div class="modal fade" id="renewModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-sync-alt me-2"></i>
                        Renew Subscription
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="renewForm">
                    @csrf
                    <input type="hidden" name="subscription_id" id="renew_id">
                    
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Renewal Period</label>
                            <select class="form-select" name="renewal_period" id="renewal_period" required onchange="updateRenewalDetails()">
                                <option value="1">1 Month</option>
                                <option value="3">3 Months</option>
                                <option value="6">6 Months</option>
                                <option value="12">12 Months</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">New End Date</label>
                            <input type="date" class="form-control" name="new_end_date" id="new_end_date" readonly>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Amount to Charge (UGX)</label>
                            <input type="number" class="form-control" name="amount" id="renew_amount" readonly>
                        </div>
                        
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            The subscription will be extended by the selected period.
                        </div>
                    </div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-sync-alt me-2"></i>Process Renewal
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Upgrade Modal -->
    <div class="modal fade" id="upgradeModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-arrow-up me-2"></i>
                        Upgrade Package
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="upgradeForm">
                    @csrf
                    <input type="hidden" name="subscription_id" id="upgrade_id">
                    
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Current Package</label>
                            <input type="text" class="form-control" id="current_package" readonly>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Upgrade To</label>
                            <select class="form-select" name="new_package" id="new_package" required onchange="updateUpgradeDetails()">
                                <option value="">Select Package</option>
                                <option value="silver" data-price="150000" data-rooms="20" data-users="2">Silver - 150,000 UGX</option>
                                <option value="gold" data-price="350000" data-rooms="40" data-users="5">Gold - 350,000 UGX</option>
                                <option value="platinum" data-price="500000" data-rooms="60" data-users="10">Platinum - 500,000 UGX</option>
                                <option value="custom" data-price="0" data-rooms="0" data-users="0">Custom</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">New Monthly Price (UGX)</label>
                            <input type="number" class="form-control" name="new_price" id="new_price" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">New Limits</label>
                            <div class="row">
                                <div class="col-6">
                                    <input type="number" class="form-control" name="new_max_rooms" id="new_max_rooms" placeholder="Max Rooms" required>
                                </div>
                                <div class="col-6">
                                    <input type="number" class="form-control" name="new_max_users" id="new_max_users" placeholder="Max Users" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            Upgrading will immediately update the hotel's limits and price.
                        </div>
                    </div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-arrow-up me-2"></i>Upgrade Package
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Export Modal -->
    <div class="modal fade" id="exportModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-download me-2"></i>
                        Export Subscriptions
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="exportForm" method="GET" action="{{ route('super.admin.subscriptions.export') }}">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Export Format</label>
                            <select class="form-select" name="format" required>
                                <option value="pdf">PDF Document</option>
                                <option value="excel">Excel Spreadsheet</option>
                                <option value="csv">CSV File</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Date Range</label>
                            <div class="row">
                                <div class="col-6">
                                    <input type="date" class="form-control" name="start_date" placeholder="Start">
                                </div>
                                <div class="col-6">
                                    <input type="date" class="form-control" name="end_date" placeholder="End">
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label d-flex justify-content-between align-items-center">
                                <span>Include Data <small class="text-muted" style="font-weight:400">(select all that apply)</small></span>
                                <button type="button" class="btn btn-link btn-sm p-0" id="toggleAllIncludes" style="text-decoration:none;font-size:0.8rem;">Toggle all</button>
                            </label>

                            <label class="export-include">
                                <input class="export-include__input" type="checkbox" name="include_hotels" value="1" checked>
                                <span class="export-include__box" aria-hidden="true"></span>
                                <span class="export-include__text">
                                    <strong>Hotel information</strong>
                                    <small>Adds the hotel name, email, phone and location columns.</small>
                                </span>
                            </label>
                            <label class="export-include">
                                <input class="export-include__input" type="checkbox" name="include_payments" value="1" checked>
                                <span class="export-include__box" aria-hidden="true"></span>
                                <span class="export-include__text">
                                    <strong>Payment history</strong>
                                    <small>Totals received plus last payment date per subscription.</small>
                                </span>
                            </label>
                            <label class="export-include">
                                <input class="export-include__input" type="checkbox" name="include_stats" value="1" checked>
                                <span class="export-include__box" aria-hidden="true"></span>
                                <span class="export-include__text">
                                    <strong>Statistics summary</strong>
                                    <small>Counts (active/expired) and total revenue summary block.</small>
                                </span>
                            </label>
                        </div>
                    </div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-download me-2"></i>Export Now
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Confirm Delete
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete this subscription?</p>
                    <p class="text-danger"><strong>Warning:</strong> This action cannot be undone and will affect hotel access.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger" onclick="confirmDelete()">
                        <i class="fas fa-trash me-2"></i>Delete Permanently
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
    $(document).ready(function() {
        // Set up CSRF token for all AJAX requests
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        // Table search
        $('#tableSearch').on('keyup', function() {
            var value = $(this).val().toLowerCase();
            $('table tbody tr').filter(function() {
                $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
            });
        });
        
        // Form submissions
        $('#subscriptionForm').on('submit', function(e) {
            e.preventDefault();
            saveSubscription();
        });
        
        $('#renewForm').on('submit', function(e) {
            e.preventDefault();
            processRenewal();
        });
        
        $('#upgradeForm').on('submit', function(e) {
            e.preventDefault();
            processUpgrade();
        });

        // Initialize date inputs with defaults
        var today = new Date();
        var nextMonth = new Date();
        nextMonth.setMonth(nextMonth.getMonth() + 1);
        
        var todayStr = today.toISOString().split('T')[0];
        var nextMonthStr = nextMonth.toISOString().split('T')[0];
        
        $('#start_date').val(todayStr);
        $('#end_date').val(nextMonthStr);
    });
    
    // Loading overlay functions
    function showLoading() {
        $('#loadingOverlay').fadeIn();
    }
    
    function hideLoading() {
        $('#loadingOverlay').fadeOut();
    }
    
    // Change per page
    function changePerPage(value) {
        var url = new URL(window.location.href);
        url.searchParams.set('per_page', value);
        window.location.href = url.toString();
    }
    
    // Open create modal
    function openCreateModal() {
        $('#formMethod').val('POST');
        $('#subscriptionId').remove(); // Remove any existing hidden field
        $('#modalTitle').html('<i class="fas fa-plus-circle me-2"></i>Create New Subscription');
        $('#submitBtn').html('<i class="fas fa-save me-2"></i>Save Subscription');
        $('#subscriptionForm')[0].reset();
        
        // Reset readonly fields
        $('#plan_price').prop('readonly', true);
        $('#max_rooms').prop('readonly', true);
        $('#max_users').prop('readonly', true);
        $('#customFields').hide();
        
        // Set default dates
        var today = new Date();
        var nextMonth = new Date();
        nextMonth.setMonth(nextMonth.getMonth() + 1);
        
        $('#start_date').val(today.toISOString().split('T')[0]);
        $('#end_date').val(nextMonth.toISOString().split('T')[0]);
        
        $('#subscriptionModal').modal('show');
    }
    
    // Update plan details based on selected package
    function updatePlanDetails() {
        var select = document.getElementById('plan_name');
        var selectedOption = select.options[select.selectedIndex];
        
        var price = selectedOption.getAttribute('data-price');
        var rooms = selectedOption.getAttribute('data-rooms');
        var users = selectedOption.getAttribute('data-users');
        
        if (select.value === 'custom') {
            // For custom plans, make fields editable
            $('#plan_price').prop('readonly', false).val('');
            $('#max_rooms').prop('readonly', false).val('');
            $('#max_users').prop('readonly', false).val('');
            $('#customFields').show();
        } else if (select.value !== '') {
            // For standard plans, set values and make readonly
            $('#plan_price').prop('readonly', true).val(price);
            $('#max_rooms').prop('readonly', true).val(rooms);
            $('#max_users').prop('readonly', true).val(users);
            $('#customFields').hide();
        } else {
            // No plan selected
            $('#plan_price').val('');
            $('#max_rooms').val('');
            $('#max_users').val('');
        }
    }
    
    // Update renewal details
    function updateRenewalDetails() {
        var id = $('#renew_id').val();
        var period = $('#renewal_period').val();
        
        if (id && period) {
            $.get('/super-admin/subscriptions/' + id + '/renewal-info?period=' + period, function(data) {
                if (data.success) {
                    $('#new_end_date').val(moment(data.new_end_date).format('YYYY-MM-DD'));
                    $('#renew_amount').val(data.amount);
                }
            });
        }
    }
    
    // Update upgrade details
    function updateUpgradeDetails() {
        var select = document.getElementById('new_package');
        var selectedOption = select.options[select.selectedIndex];
        
        var price = selectedOption.getAttribute('data-price');
        var rooms = selectedOption.getAttribute('data-rooms');
        var users = selectedOption.getAttribute('data-users');
        
        $('#new_price').val(price);
        $('#new_max_rooms').val(rooms);
        $('#new_max_users').val(users);
    }
    
    // View subscription
    function viewSubscription(id) {
        showLoading();
        $.get('/super-admin/subscriptions/' + id, function(data) {
            if (data.success) {
                $('#view_hotel_name').text(data.hotel.name);
                $('#view_email').text(data.hotel.email);
                $('#view_phone').text(data.hotel.phone || 'N/A');
                $('#view_location').text((data.hotel.city || '') + ', ' + (data.hotel.country || ''));
                $('#view_package').text(data.plan_name.charAt(0).toUpperCase() + data.plan_name.slice(1));
                $('#view_price').text(new Intl.NumberFormat().format(data.plan_price) + ' UGX');
                $('#view_billing_cycle').text(data.billing_cycle || 'Monthly');
                $('#view_status').html(getStatusBadge(data.status, data.days_remaining));
                $('#view_start_date').text(moment(data.start_date).format('MMMM D, YYYY'));
                $('#view_end_date').text(moment(data.end_date).format('MMMM D, YYYY'));
                $('#view_days_remaining').text(data.days_remaining + ' days');
                $('#view_trial_ends').text(data.trial_end_date ? moment(data.trial_end_date).format('MMMM D, YYYY') : 'No trial');
                $('#view_max_rooms').text(data.max_rooms);
                $('#view_max_users').text(data.max_users);
                $('#view_used_rooms').text(data.usage?.rooms?.used || 0);
                $('#view_used_users').text(data.usage?.users?.used || 0);
                
                if (data.notes) {
                    $('#view_notes').text(data.notes);
                    $('#notesSection').show();
                } else {
                    $('#notesSection').hide();
                }
                
                // Store the ID for later use
                $('#viewSubscriptionId').remove();
                $('<input>').attr({
                    type: 'hidden',
                    id: 'viewSubscriptionId',
                    value: id
                }).appendTo('#viewModal');
                
                hideLoading();
                $('#viewModal').modal('show');
            }
        }).fail(function(xhr) {
            hideLoading();
            Swal.fire('Error', xhr.responseJSON?.message || 'Could not load subscription details', 'error');
        });
    }
    
    // Edit subscription
    function editSubscription(id) {
        showLoading();
        $.ajax({
            url: '/super-admin/subscriptions/' + id + '/edit',
            type: 'GET',
            success: function(data) {
                if (data.success) {
                    $('#formMethod').val('PUT');
                    
                    // Remove any existing subscription_id field and add a new one
                    $('#subscriptionId').remove();
                    $('<input>').attr({
                        type: 'hidden',
                        id: 'subscriptionId',
                        name: 'subscription_id',
                        value: id
                    }).appendTo('#subscriptionForm');
                    
                    $('#modalTitle').html('<i class="fas fa-edit me-2"></i>Edit Subscription');
                    $('#submitBtn').html('<i class="fas fa-save me-2"></i>Update Subscription');
                    
                    // Fill in the form fields
                    $('#hotel_id').val(data.hotel_id);
                    $('#plan_name').val(data.plan_name);
                    $('#plan_price').val(data.plan_price);
                    $('#billing_cycle').val(data.billing_cycle || 'monthly');
                    $('#start_date').val(moment(data.start_date).format('YYYY-MM-DD'));
                    $('#end_date').val(moment(data.end_date).format('YYYY-MM-DD'));
                    $('#trial_start_date').val(data.trial_start_date ? moment(data.trial_start_date).format('YYYY-MM-DD') : '');
                    $('#trial_end_date').val(data.trial_end_date ? moment(data.trial_end_date).format('YYYY-MM-DD') : '');
                    $('#status').val(data.status);
                    $('#max_rooms').val(data.max_rooms);
                    $('#max_users').val(data.max_users);
                    $('#notes').val(data.notes || '');
                    
                    // Update readonly status based on plan
                    if (data.plan_name === 'custom') {
                        $('#plan_price').prop('readonly', false);
                        $('#max_rooms').prop('readonly', false);
                        $('#max_users').prop('readonly', false);
                        $('#customFields').show();
                    } else {
                        $('#plan_price').prop('readonly', true);
                        $('#max_rooms').prop('readonly', true);
                        $('#max_users').prop('readonly', true);
                        $('#customFields').hide();
                    }
                    
                    hideLoading();
                    $('#subscriptionModal').modal('show');
                }
            },
            error: function(xhr) {
                hideLoading();
                Swal.fire('Error', xhr.responseJSON?.message || 'Could not load subscription data', 'error');
            }
        });
    }
    
    // Edit from view modal
    function editFromView() {
        var id = $('#viewSubscriptionId').val();
        $('#viewModal').modal('hide');
        setTimeout(function() {
            editSubscription(id);
        }, 500);
    }
    
    // Save subscription (handles both create and update)
    function saveSubscription() {
        var form = $('#subscriptionForm');
        var method = $('#formMethod').val();
        var id = $('#subscriptionId').val();
        var formData = form.serialize();
        
        // Determine the correct URL based on method
        var url;
        if (method === 'PUT' || method === 'PATCH') {
            if (!id) {
                Swal.fire('Error', 'Subscription ID is missing for update', 'error');
                return;
            }
            url = '/super-admin/subscriptions/' + id;
        } else {
            url = '{{ route("super.admin.subscriptions.store") }}';
        }
        
        showLoading();
        $.ajax({
            url: url,
            type: 'POST', // Always use POST, Laravel reads _method field
            data: formData,
            success: function(response) {
                hideLoading();
                $('#subscriptionModal').modal('hide');
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: response.message || 'Subscription saved successfully',
                    timer: 2000,
                    showConfirmButton: false
                }).then(function() {
                    location.reload();
                });
            },
            error: function(xhr) {
                hideLoading();
                let errorMessage = 'Something went wrong';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMessage = xhr.responseJSON.message;
                } else if (xhr.responseJSON && xhr.responseJSON.errors) {
                    errorMessage = Object.values(xhr.responseJSON.errors).flat().join(', ');
                } else if (xhr.responseJSON && xhr.responseJSON.error) {
                    errorMessage = xhr.responseJSON.error;
                }
                Swal.fire('Error', errorMessage, 'error');
                console.error('Error details:', xhr);
            }
        });
    }
    
    // Renew subscription
    function renewSubscription(id) {
        showLoading();
        $.get('/super-admin/subscriptions/' + id + '/renewal-info?period=1', function(data) {
            if (data.success) {
                $('#renew_id').val(id);
                $('#new_end_date').val(moment(data.new_end_date).format('YYYY-MM-DD'));
                $('#renew_amount').val(data.amount);
                hideLoading();
                $('#renewModal').modal('show');
            }
        }).fail(function(xhr) {
            hideLoading();
            Swal.fire('Error', xhr.responseJSON?.message || 'Could not load renewal info', 'error');
        });
    }
    
    function renewFromView() {
        var id = $('#viewSubscriptionId').val();
        $('#viewModal').modal('hide');
        setTimeout(function() {
            renewSubscription(id);
        }, 500);
    }
    
    function processRenewal() {
        var form = $('#renewForm');
        var url = '/super-admin/subscriptions/' + $('#renew_id').val() + '/renew';
        var data = form.serialize();
        
        showLoading();
        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            success: function(response) {
                hideLoading();
                $('#renewModal').modal('hide');
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: response.message || 'Subscription renewed successfully',
                    timer: 2000,
                    showConfirmButton: false
                }).then(function() {
                    location.reload();
                });
            },
            error: function(xhr) {
                hideLoading();
                Swal.fire('Error', xhr.responseJSON?.message || 'Something went wrong', 'error');
            }
        });
    }
    
    // Upgrade subscription
    function upgradeSubscription(id) {
        showLoading();
        $.get('/super-admin/subscriptions/' + id + '/upgrade-info', function(data) {
            if (data.success) {
                $('#upgrade_id').val(id);
                $('#current_package').val(data.current_package);
                $('#new_package').val(data.suggested_package.toLowerCase());
                $('#new_price').val(data.suggested_price);
                $('#new_max_rooms').val(data.suggested_rooms);
                $('#new_max_users').val(data.suggested_users);
                hideLoading();
                $('#upgradeModal').modal('show');
            }
        }).fail(function(xhr) {
            hideLoading();
            Swal.fire('Error', xhr.responseJSON?.message || 'Could not load upgrade info', 'error');
        });
    }
    
    function processUpgrade() {
        var form = $('#upgradeForm');
        var url = '/super-admin/subscriptions/' + $('#upgrade_id').val() + '/upgrade';
        var data = form.serialize();
        
        showLoading();
        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            success: function(response) {
                hideLoading();
                $('#upgradeModal').modal('hide');
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: response.message || 'Subscription upgraded successfully',
                    timer: 2000,
                    showConfirmButton: false
                }).then(function() {
                    location.reload();
                });
            },
            error: function(xhr) {
                hideLoading();
                Swal.fire('Error', xhr.responseJSON?.message || 'Something went wrong', 'error');
            }
        });
    }
    
    // Suspend subscription
    function suspendSubscription(id) {
        Swal.fire({
            title: 'Suspend Subscription?',
            text: 'This will temporarily disable hotel access. You can activate it later.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#6b7280',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, suspend it'
        }).then((result) => {
            if (result.isConfirmed) {
                showLoading();
                $.ajax({
                    url: '/super-admin/subscriptions/' + id + '/suspend',
                    type: 'POST',
                    success: function(response) {
                        hideLoading();
                        Swal.fire({
                            icon: 'success',
                            title: 'Suspended!',
                            text: response.message || 'Subscription has been suspended',
                            timer: 2000
                        }).then(function() {
                            location.reload();
                        });
                    },
                    error: function(xhr) {
                        hideLoading();
                        Swal.fire('Error', xhr.responseJSON?.message || 'Something went wrong', 'error');
                    }
                });
            }
        });
    }
    
    // Activate subscription
    function activateSubscription(id) {
        Swal.fire({
            title: 'Activate Subscription?',
            text: 'This will restore hotel access.',
            icon: 'info',
            showCancelButton: true,
            confirmButtonColor: '#059669',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, activate it'
        }).then((result) => {
            if (result.isConfirmed) {
                showLoading();
                $.ajax({
                    url: '/super-admin/subscriptions/' + id + '/activate',
                    type: 'POST',
                    success: function(response) {
                        hideLoading();
                        Swal.fire({
                            icon: 'success',
                            title: 'Activated!',
                            text: response.message || 'Subscription has been activated',
                            timer: 2000
                        }).then(function() {
                            location.reload();
                        });
                    },
                    error: function(xhr) {
                        hideLoading();
                        Swal.fire('Error', xhr.responseJSON?.message || 'Something went wrong', 'error');
                    }
                });
            }
        });
    }
    
    // Delete subscription
    var deleteId = null;
    
    function deleteSubscription(id) {
        deleteId = id;
        $('#deleteModal').modal('show');
    }
    
    function confirmDelete() {
        if (!deleteId) return;
        
        showLoading();
        $.ajax({
            url: '/super-admin/subscriptions/' + deleteId,
            type: 'DELETE',
            data: {
                _token: '{{ csrf_token() }}'
            },
            success: function(response) {
                hideLoading();
                $('#deleteModal').modal('hide');
                Swal.fire({
                    icon: 'success',
                    title: 'Deleted!',
                    text: response.message || 'Subscription deleted successfully',
                    timer: 2000,
                    showConfirmButton: false
                }).then(function() {
                    location.reload();
                });
            },
            error: function(xhr) {
                hideLoading();
                Swal.fire('Error', xhr.responseJSON?.message || 'Something went wrong', 'error');
            }
        });
    }
    
    // Open export modal
    function openExportModal() {
        $('#exportModal').modal('show');
    }

    // Toggle all "Include data" checkboxes in the export modal
    $(document).on('click', '#toggleAllIncludes', function (e) {
        e.preventDefault();
        var $boxes = $('#exportForm .export-include__input');
        var anyUnchecked = $boxes.toArray().some(function (b) { return !b.checked; });
        $boxes.prop('checked', anyUnchecked).trigger('change');
    });

    // Submit the export form by opening in a new tab so we don't navigate away from the inbox.
    $(document).on('submit', '#exportForm', function () {
        $(this).attr('target', '_blank');
        // Close the modal shortly after so the user sees the download begin.
        setTimeout(function () { $('#exportModal').modal('hide'); }, 250);
    });

    function sendRemindersNow() {
        Swal.fire({
            title: 'Send due reminders now?',
            text: 'This sends reminders to clients that are due/overdue only (not upcoming paid clients).',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#059669',
            cancelButtonColor: '#6b7280',
            confirmButtonText: 'Yes, send now'
        }).then((result) => {
            if (!result.isConfirmed) return;

            showLoading();
            $.ajax({
                url: '{{ route("super.admin.subscriptions.send-reminders") }}',
                type: 'POST',
                data: {
                    days: 7,
                    force: 0,
                    due_only: 1
                },
                success: function(response) {
                    hideLoading();
                    const summary = response.summary || {sent: 0, skipped: 0, failed: 0};
                    Swal.fire({
                        icon: 'success',
                        title: 'Reminder Run Complete',
                        html: `
                            <div class="text-start">
                                <div><strong>Sent:</strong> ${summary.sent ?? 0}</div>
                                <div><strong>Skipped:</strong> ${summary.skipped ?? 0}</div>
                                <div><strong>Failed:</strong> ${summary.failed ?? 0}</div>
                            </div>
                        `,
                    });
                },
                error: function(xhr) {
                    hideLoading();
                    Swal.fire('Error', xhr.responseJSON?.message || 'Failed to send reminders', 'error');
                }
            });
        });
    }
    
    // Helper function for status badge
    function getStatusBadge(status, daysLeft) {
        var badgeClass = 'badge-secondary';
        var statusText = status;
        
        if (status == 'active') {
            if (daysLeft <= 7) {
                badgeClass = 'badge-expiring';
                statusText = 'Expiring Soon';
            } else {
                badgeClass = 'badge-active';
                statusText = 'Active';
            }
        } else if (status == 'trial') {
            badgeClass = 'badge-trial';
            statusText = 'Trial';
        } else if (status == 'suspended') {
            badgeClass = 'badge-suspended';
            statusText = 'Suspended';
        } else if (status == 'expired') {
            badgeClass = 'badge-expired';
            statusText = 'Expired';
        } else if (status == 'cancelled') {
            badgeClass = 'badge-expired';
            statusText = 'Cancelled';
        }
        
        return '<span class="badge-status ' + badgeClass + '">' + statusText + '</span>';
    }
    
    // Auto-refresh data every 5 minutes
    setInterval(function() {
        console.log('Refreshing data...');
        // location.reload();
    }, 350000);
</script>
</body>
</html>