<?php
session_start();
require_once '../config/database.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$page_title = 'Appointments Management';
$current_page = 'appointments.php';

$pdo = getDBConnection();

/**
 * Check if a given column exists in a table. Results are cached per request.
 */
function tableHasColumn(PDO $pdo, string $table, string $column): bool
{
    static $columnCache = [];
    $cacheKey = $table . '.' . $column;

    if (isset($columnCache[$cacheKey])) {
        return $columnCache[$cacheKey];
    }

    try {
        $stmt = $pdo->prepare("SHOW COLUMNS FROM `$table` LIKE ?");
        $stmt->execute([$column]);
        $exists = $stmt->fetch() !== false;
    } catch (Exception $e) {
        $exists = false;
    }

    $columnCache[$cacheKey] = $exists;
    return $exists;
}

$hasNumberOfPersonsColumn = tableHasColumn($pdo, 'appointments', 'number_of_persons');

$success_message = '';
$error_message = '';

// Handle status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $appointmentId = (int)$_POST['appointment_id'];
    $newStatus = $_POST['new_status'];
    
    // Validate status
    $validStatuses = ['pending', 'confirmed', 'cancelled', 'completed'];
    if (!in_array($newStatus, $validStatuses)) {
        $error_message = "Invalid status selected";
    } else {
        // Check if appointment exists
        $checkStmt = $pdo->prepare("SELECT id, status FROM appointments WHERE id = ?");
        $checkStmt->execute([$appointmentId]);
        $appointment = $checkStmt->fetch();
        
        if (!$appointment) {
            $error_message = "Appointment not found";
        } else {
            // Update status
            $stmt = $pdo->prepare("UPDATE appointments SET status = ?, updated_at = NOW() WHERE id = ?");
            if ($stmt->execute([$newStatus, $appointmentId])) {
                $statusNames = [
                    'pending' => 'Pending',
                    'confirmed' => 'Confirmed', 
                    'cancelled' => 'Cancelled',
                    'completed' => 'Completed'
                ];
                $success_message = "Appointment status changed to " . $statusNames[$newStatus] . " successfully";
            } else {
                $error_message = "Error updating appointment status. Please try again.";
            }
        }
    }
}

// Handle appointment deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_appointment'])) {
    $appointmentId = (int)$_POST['appointment_id'];
    
    $stmt = $pdo->prepare("DELETE FROM appointments WHERE id = ?");
    if ($stmt->execute([$appointmentId])) {
        $success_message = "Appointment deleted successfully";
    } else {
        $error_message = "Error deleting appointment";
    }
}


// Get appointments with advanced filters - OPTIMIZED
$status_filter = $_GET['status'] ?? 'all';
$date_filter = $_GET['date'] ?? '';
$search_query = $_GET['search'] ?? '';
$consultation_filter = $_GET['consultation_type'] ?? 'all';
$amount_min = $_GET['amount_min'] ?? '';
$amount_max = $_GET['amount_max'] ?? '';

$where_conditions = [];
$params = [];

// Optimized WHERE conditions with proper indexing hints
if ($status_filter !== 'all') {
    $where_conditions[] = "a.status = ?";
    $params[] = $status_filter;
}

if ($date_filter) {
    $where_conditions[] = "a.appointment_date = ?";
    $params[] = $date_filter;
}

if ($search_query) {
    // Optimized search with index-friendly conditions
    $where_conditions[] = "(u.name LIKE ? OR u.mobile LIKE ? OR u.city LIKE ?)";
    $search_param = "%$search_query%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
}

if ($consultation_filter !== 'all') {
    $where_conditions[] = "a.consultation_type = ?";
    $params[] = $consultation_filter;
}

if ($amount_min !== '') {
    $where_conditions[] = "a.amount >= ?";
    $params[] = (float)$amount_min;
}

if ($amount_max !== '') {
    $where_conditions[] = "a.amount <= ?";
    $params[] = (float)$amount_max;
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Optimized pagination with dynamic results per page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 25; // Default to 25
$offset = ($page - 1) * $limit;

// Optimized count query with index hints
$count_query = "SELECT COUNT(*) FROM appointments a USE INDEX (PRIMARY) JOIN users u ON a.user_id = u.id $where_clause";
$stmt = $pdo->prepare($count_query);
$stmt->execute($params);
$total_appointments = $stmt->fetchColumn();
$total_pages = ceil($total_appointments / $limit);

// Optimized main query with specific column selection and index hints
$numberOfPersonsSelect = $hasNumberOfPersonsColumn ? 'a.number_of_persons' : 'NULL';

$query = "
    SELECT 
        a.id, a.appointment_date, a.time_slot, a.consultation_type, 
        a.status, a.amount, a.created_at, {$numberOfPersonsSelect} AS number_of_persons,
        u.name as user_name, 
        u.mobile as user_mobile,
        u.city as user_city
    FROM appointments a USE INDEX (PRIMARY)
    INNER JOIN users u ON a.user_id = u.id
    $where_clause
    ORDER BY a.created_at DESC, a.appointment_date DESC, a.time_slot ASC
    LIMIT ? OFFSET ?
";

$params[] = $limit;
$params[] = $offset;
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$appointments = $stmt->fetchAll();

// Get slot duration for display formatting
$stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'slot_duration'");
$stmt->execute();
$slotDuration = (int)($stmt->fetchColumn() ?: 20);

// Sort appointments by time - current/upcoming first, then past
if (!empty($appointments)) {
    $currentTime = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
    
    // Helper function to parse time slot and get appointment datetime
    $parseAppointmentTime = function($appointmentDate, $timeSlot) {
        // Try to extract start time from time slot
        // Pattern: "09:00 AM - 10:00 AM" or "09:00-10:00"
        $timeStr = '';
        
        // Pattern 1: Extract start time from "09:00 AM - 10:00 AM"
        if (preg_match('/^(\d{1,2}:\d{2}\s*(?:AM|PM|am|pm))/i', $timeSlot, $matches)) {
            $timeStr = trim($matches[1]);
            $dateStr = $appointmentDate . ' ' . $timeStr;
            $datetime = DateTime::createFromFormat('Y-m-d g:i A', $dateStr);
            if ($datetime === false) {
                $datetime = DateTime::createFromFormat('Y-m-d h:i A', $dateStr);
            }
            if ($datetime !== false) {
                return $datetime;
            }
        }
        
        // Pattern 2: Extract start time from "09:00-10:00"
        if (preg_match('/^(\d{1,2}:\d{2})/', $timeSlot, $matches)) {
            $timeStr = trim($matches[1]);
            $dateStr = $appointmentDate . ' ' . $timeStr;
            $datetime = DateTime::createFromFormat('Y-m-d H:i', $dateStr);
            if ($datetime !== false) {
                return $datetime;
            }
        }
        
        // Fallback: use date only at start of day
        return DateTime::createFromFormat('Y-m-d', $appointmentDate);
    };
    
    // Sort appointments
    usort($appointments, function($a, $b) use ($currentTime, $parseAppointmentTime) {
        $timeA = $parseAppointmentTime($a['appointment_date'], $a['time_slot']);
        $timeB = $parseAppointmentTime($b['appointment_date'], $b['time_slot']);
        
        if ($timeA === false || $timeB === false) {
            return 0; // Keep original order if parsing fails
        }
        
        // Check if appointment is in past or future
        $isPastA = $timeA < $currentTime;
        $isPastB = $timeB < $currentTime;
        
        // Future appointments come before past appointments
        if ($isPastA && !$isPastB) {
            return 1; // A is past, B is future, so B comes first
        }
        if (!$isPastA && $isPastB) {
            return -1; // A is future, B is past, so A comes first
        }
        
        // Both are past or both are future - sort by time
        if ($isPastA && $isPastB) {
            // Both past - most recent first
            return $timeB <=> $timeA;
        } else {
            // Both future - soonest first (closest to current time)
            return $timeA <=> $timeB;
        }
    });
}

// Get statistics based on current filters
$stats_where_conditions = [];
$stats_params = [];

// Apply same filters as main query for consistent stats
if ($date_filter) {
    $stats_where_conditions[] = "a.appointment_date = ?";
    $stats_params[] = $date_filter;
}

if ($search_query) {
    $stats_where_conditions[] = "(u.name LIKE ? OR u.mobile LIKE ? OR u.city LIKE ?)";
    $search_param = "%$search_query%";
    $stats_params[] = $search_param;
    $stats_params[] = $search_param;
    $stats_params[] = $search_param;
}

if ($consultation_filter !== 'all') {
    $stats_where_conditions[] = "a.consultation_type = ?";
    $stats_params[] = $consultation_filter;
}

if ($amount_min !== '') {
    $stats_where_conditions[] = "a.amount >= ?";
    $stats_params[] = (float)$amount_min;
}

if ($amount_max !== '') {
    $stats_where_conditions[] = "a.amount <= ?";
    $stats_params[] = (float)$amount_max;
}

$stats_where_clause = !empty($stats_where_conditions) ? 'WHERE ' . implode(' AND ', $stats_where_conditions) : '';

// Generate stats with proper revenue calculation (only confirmed and completed)
$stats_query = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN a.status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN a.status = 'confirmed' THEN 1 ELSE 0 END) as confirmed,
    SUM(CASE WHEN a.status = 'cancelled' THEN 1 ELSE 0 END) as cancelled,
    SUM(CASE WHEN a.status = 'completed' THEN 1 ELSE 0 END) as completed,
    SUM(CASE WHEN a.status IN ('confirmed', 'completed') THEN a.amount ELSE 0 END) as total_revenue
FROM appointments a
JOIN users u ON a.user_id = u.id
$stats_where_clause";

$stats_stmt = $pdo->prepare($stats_query);
$stats_stmt->execute($stats_params);
$stats = $stats_stmt->fetch();
?>

<?php ob_start(); ?>
    <link href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" rel="stylesheet">
    <style>
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            min-height: 100px;
            display: flex;
            align-items: center;
        }
        .stats-card.success {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        }
        .stats-card.warning {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        .stats-card.info {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        .stats-card.danger {
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        }
        .stats-card.revenue-card {
            background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
            color: #333;
        }
        .clickable-stat {
            cursor: pointer;
            transform-origin: center;
        }
        .clickable-stat:hover {
            transform: translateY(-3px) scale(1.02);
            box-shadow: 0 8px 25px rgba(0,0,0,0.2);
        }
        .clickable-stat:active {
            transform: translateY(-1px) scale(0.98);
        }
        .clickable-stat.active {
            border: 3px solid #fff;
            box-shadow: 0 0 20px rgba(255,255,255,0.5);
        }
        .appointment-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transition: transform 0.3s, box-shadow 0.3s;
            border-left: 5px solid #dee2e6;
        }
        .appointment-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        .appointment-card.pending { border-left-color: #ffc107; }
        .appointment-card.confirmed { border-left-color: #28a745; }
        .appointment-card.cancelled { border-left-color: #dc3545; }
        .appointment-card.completed { border-left-color: #17a2b8; }
        .status-badge {
            font-size: 0.8rem;
            padding: 0.5rem 0.8rem;
            border-radius: 20px;
            font-weight: 600;
        }
        .filter-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .search-box {
            border-radius: 25px;
            border: 2px solid #e9ecef;
            padding: 10px 20px;
            transition: all 0.3s;
        }
        .search-box:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        .btn-action {
            border-radius: 20px;
            padding: 5px 15px;
            font-size: 0.8rem;
            margin: 2px;
        }
        .pagination {
            justify-content: center;
            margin-top: 30px;
        }
        .user-info {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .appointment-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }
        .detail-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .detail-item i {
            color: #667eea;
            width: 20px;
        }
        .filters-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        .filter-form {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .filter-group {
            margin-bottom: 15px;
        }
        .filter-label {
            font-weight: 600;
            margin-bottom: 5px;
            color: #495057;
        }
        .loading {
            opacity: 0.6;
            pointer-events: none;
        }
        .no-results {
            text-align: center;
            padding: 50px 20px;
            color: #6c757d;
        }
        .no-results i {
            font-size: 4rem;
            margin-bottom: 20px;
            opacity: 0.5;
        }
        
        /* Performance optimizations */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        
        .appointment-card {
            will-change: transform;
            backface-visibility: hidden;
        }
        
        .stats-card, .filter-card {
            transition: all 0.2s ease-in-out;
        }
        
        /* Faster animations */
        .btn, .form-control, .form-select {
            transition: all 0.15s ease-in-out;
        }

        /* Content card styling to match layout */
        .content-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            padding: 30px;
            margin-bottom: 30px;
        }

        /* Ensure proper spacing and layout */
        .main-content {
            background: transparent;
        }

        /* Fix button styling */
        .btn {
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-warning {
            background: linear-gradient(135deg, #ffc107, #ff8f00);
            border: none;
            color: #000;
        }

        .btn-warning:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(255, 193, 7, 0.4);
            color: #000;
        }

        .btn-outline-success {
            border: 2px solid #28a745;
            color: #28a745;
        }

        .btn-outline-success:hover {
            background: #28a745;
            color: white;
        }

        .btn-outline-primary {
            border: 2px solid #007bff;
            color: #007bff;
        }

        .btn-outline-primary:hover {
            background: #007bff;
            color: white;
        }

        .btn-outline-info {
            border: 2px solid #17a2b8;
            color: #17a2b8;
        }

        .btn-outline-info:hover {
            background: #17a2b8;
            color: white;
        }

        /* Form styling */
        .form-control, .form-select {
            border-radius: 10px;
            border: 2px solid #e9ecef;
            transition: all 0.3s ease;
        }

        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }

        /* Alert styling */
        .alert {
            border-radius: 15px;
            border: none;
            font-weight: 500;
        }

        .alert-success {
            background: rgba(40, 167, 69, 0.1);
            color: #155724;
            border-left: 4px solid #28a745;
        }

        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            color: #721c24;
            border-left: 4px solid #dc3545;
        }

        /* Table styling */
        .table {
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .table thead th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            font-weight: 600;
            padding: 15px;
        }

        .table tbody td {
            border: none;
            padding: 15px;
            vertical-align: middle;
            border-bottom: 1px solid #f8f9fa;
        }

        .table tbody tr:hover {
            background: rgba(102, 126, 234, 0.05);
        }

        /* Badge styling */
        .badge {
            padding: 0.5rem 0.75rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.75rem;
        }

        .bg-success {
            background: linear-gradient(135deg, #28a745, #20c997) !important;
        }

        .bg-warning {
            background: linear-gradient(135deg, #ffc107, #ff8f00) !important;
        }

        .bg-danger {
            background: linear-gradient(135deg, #dc3545, #c82333) !important;
        }

        .bg-info {
            background: linear-gradient(135deg, #17a2b8, #138496) !important;
        }

        .bg-primary {
            background: linear-gradient(135deg, #007bff, #0056b3) !important;
        }

        /* Responsive design */
        @media (max-width: 768px) {
            .filters-row {
                grid-template-columns: 1fr;
            }
            
            
            .appointment-details {
                grid-template-columns: 1fr;
            }
            
            .stats-card {
                padding: 12px;
                min-height: 80px;
            }
            
            .stats-card h4 {
                font-size: 1.2rem;
            }
            
            .stats-card small {
                font-size: 0.75rem;
            }
            
            .appointment-card {
                padding: 15px;
                margin-bottom: 15px;
            }
            
            .user-info {
                padding: 12px;
            }
            
            .detail-item {
                margin-bottom: 8px;
            }
            
            .btn-action {
                padding: 4px 8px;
                font-size: 0.75rem;
                margin: 1px;
            }
            
            .content-card {
                padding: 20px;
                margin-bottom: 20px;
            }
            
            .filter-card .card-body {
                padding: 15px;
            }
            
            .form-control, .form-select {
                font-size: 14px;
                padding: 8px 12px;
            }
        }
        
        @media (max-width: 576px) {
            .stats-card {
                padding: 10px;
                min-height: 70px;
            }
            
            .stats-card h4 {
                font-size: 1rem;
            }
            
            .stats-card .fa-2x {
                font-size: 1.5em !important;
            }
            
            .appointment-card {
                padding: 12px;
            }
            
            .content-card {
                padding: 15px;
                margin-bottom: 15px;
            }
            
            .btn {
                font-size: 0.8rem;
                padding: 6px 12px;
            }
            
        }
    </style>

    <div class="content-card">
        <div class="d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center mb-4 gap-3">
            <h2 class="mb-0"><i class="fas fa-calendar-check me-2"></i>Appointments Management</h2>
            <div class="d-flex gap-2">
                <button class="btn btn-warning" onclick="openHelp()">
                    <i class="fab fa-whatsapp me-2"></i>Help & Support
                    </button>
            </div>
        </div>
                    
                    <?php if ($success_message) { ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($success_message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>
                    
                    <?php if ($error_message) { ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-triangle me-2"></i><?php echo htmlspecialchars($error_message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>
                    
                    <!-- Statistics Cards -->
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0">
                            <i class="fas fa-chart-bar me-2"></i>Appointment Statistics
                        </h5>
                        <button class="btn btn-sm btn-outline-info" onclick="openStatsHelp()">
                            <i class="fas fa-question-circle me-2"></i>Stats Help
                        </button>
                    </div>
                    <div class="row mb-4">
                        <div class="col-lg-2 col-md-4 col-sm-6 col-6 mb-3">
                            <div class="stats-card clickable-stat" onclick="filterByStatus('all')" data-status="all">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h4 class="mb-0"><?php echo $stats['total']; ?></h4>
                                        <small>Total</small>
                                    </div>
                                    <i class="fas fa-calendar fa-2x opacity-75"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 col-6 mb-3">
                            <div class="stats-card warning clickable-stat" onclick="filterByStatus('pending')" data-status="pending">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h4 class="mb-0"><?php echo $stats['pending']; ?></h4>
                                        <small>Pending</small>
                                    </div>
                                    <i class="fas fa-clock fa-2x opacity-75"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 col-6 mb-3">
                            <div class="stats-card success clickable-stat" onclick="filterByStatus('confirmed')" data-status="confirmed">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h4 class="mb-0"><?php echo $stats['confirmed']; ?></h4>
                                        <small>Confirmed</small>
                                    </div>
                                    <i class="fas fa-check-circle fa-2x opacity-75"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 col-6 mb-3">
                            <div class="stats-card info clickable-stat" onclick="filterByStatus('completed')" data-status="completed">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h4 class="mb-0"><?php echo $stats['completed']; ?></h4>
                                        <small>Completed</small>
                                    </div>
                                    <i class="fas fa-trophy fa-2x opacity-75"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 col-6 mb-3">
                            <div class="stats-card danger clickable-stat" onclick="filterByStatus('cancelled')" data-status="cancelled">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h4 class="mb-0"><?php echo $stats['cancelled']; ?></h4>
                                        <small>Cancelled</small>
                                    </div>
                                    <i class="fas fa-times-circle fa-2x opacity-75"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 col-6 mb-3">
                            <div class="stats-card revenue-card">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h4 class="mb-0">₹<?php echo number_format($stats['total_revenue'] ?? 0); ?></h4>
                                        <small>Revenue</small>
                                    </div>
                                    <i class="fas fa-rupee-sign fa-2x opacity-75"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Advanced Filters -->
                    <div class="filter-card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5 class="card-title mb-0">
                                    <i class="fas fa-filter me-2"></i>Advanced Filters
                                </h5>
                                <div class="d-flex gap-2">
                                    <a href="export_csv.php?<?php echo http_build_query($_GET); ?>" class="btn btn-sm btn-outline-success">
                                        <i class="fas fa-file-csv me-2"></i>Export CSV
                                    </a>
                                    <button class="btn btn-sm btn-outline-info" onclick="openFilterHelp()">
                                        <i class="fas fa-question-circle me-2"></i>Filter Help
                                    </button>
                                </div>
                            </div>
                            
                            <form method="GET" id="filterForm" class="filters-row">
                                <div class="filter-group">
                                    <label class="filter-label">Search</label>
                                    <input type="text" class="form-control search-box" name="search" 
                                           placeholder="Name, Mobile, City, Email..." 
                                           value="<?php echo htmlspecialchars($search_query); ?>"
                                           id="searchInput">
                                </div>
                                
                                <div class="filter-group">
                                    <label class="filter-label">Status</label>
                                    <select class="form-select" name="status" id="statusFilter">
                                        <option value="all" <?php echo $status_filter === 'all' ? 'selected' : ''; ?>>All Status</option>
                                        <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                        <option value="confirmed" <?php echo $status_filter === 'confirmed' ? 'selected' : ''; ?>>Confirmed</option>
                                        <option value="cancelled" <?php echo $status_filter === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                                        <option value="completed" <?php echo $status_filter === 'completed' ? 'selected' : ''; ?>>Completed</option>
                                    </select>
                                </div>
                                
                                <div class="filter-group">
                                    <label class="filter-label">Date</label>
                                    <input type="date" class="form-control" name="date" 
                                           value="<?php echo htmlspecialchars($date_filter); ?>"
                                           id="dateFilter">
                                </div>
                                
                                <div class="filter-group">
                                    <label class="filter-label">Consultation Type</label>
                                    <select class="form-select" name="consultation_type" id="consultationFilter">
                                        <option value="all" <?php echo $consultation_filter === 'all' ? 'selected' : ''; ?>>All Types</option>
                                        <option value="office_meeting" <?php echo $consultation_filter === 'office_meeting' ? 'selected' : ''; ?>>Office Meeting</option>
                                        <option value="video_call" <?php echo $consultation_filter === 'video_call' ? 'selected' : ''; ?>>Video Call</option>
                                        <option value="audio_call" <?php echo $consultation_filter === 'audio_call' ? 'selected' : ''; ?>>Audio Call</option>
                                    </select>
                                </div>

                                <div class="filter-group">
                                    <label class="filter-label">Per Page</label>
                                    <select class="form-select" name="limit" id="limitFilter" onchange="this.form.submit()">
                                        <option value="10" <?php echo $limit == 10 ? 'selected' : ''; ?>>10 Results</option>
                                        <option value="25" <?php echo $limit == 25 ? 'selected' : ''; ?>>25 Results</option>
                                        <option value="50" <?php echo $limit == 50 ? 'selected' : ''; ?>>50 Results</option>
                                        <option value="100" <?php echo $limit == 100 ? 'selected' : ''; ?>>100 Results</option>
                                    </select>
                                </div>
                                
                                <div class="filter-group">
                                    <label class="filter-label">Amount Range</label>
                                    <div class="input-group">
                                        <input type="number" class="form-control" name="amount_min" 
                                               placeholder="Min" value="<?php echo htmlspecialchars($amount_min); ?>"
                                               id="amountMinFilter">
                                        <span class="input-group-text">-</span>
                                        <input type="number" class="form-control" name="amount_max" 
                                               placeholder="Max" value="<?php echo htmlspecialchars($amount_max); ?>"
                                               id="amountMaxFilter">
                                    </div>
                                </div>
                                
                                <div class="filter-group d-flex align-items-end">
                                    <button type="submit" class="btn btn-primary me-2" id="applyFilters">
                                        <i class="fas fa-search me-2"></i>Apply Filters
                                    </button>
                                    <a href="appointments.php" class="btn btn-outline-secondary">
                                        <i class="fas fa-times me-2"></i>Clear
                                    </a>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Results Summary -->
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0">
                            <i class="fas fa-list me-2"></i>Appointments 
                            <span class="badge bg-primary"><?php echo $total_appointments; ?></span>
                        </h5>
                        <small class="text-muted">
                            Showing <?php echo ($offset + 1); ?> - <?php echo min($offset + $limit, $total_appointments); ?> 
                            of <?php echo $total_appointments; ?> appointments
                        </small>
                    </div>
                    
                    <!-- Appointments List -->
                    <div id="appointmentsContainer">
                        <?php if (empty($appointments)): ?>
                            <div class="no-results">
                                <i class="fas fa-calendar-times"></i>
                                <h5>No appointments found</h5>
                                <p>Try adjusting your filters or search criteria</p>
                            </div>
                        <?php else: ?>
                            <?php foreach ($appointments as $appointment): ?>
                                <div class="appointment-card <?php echo $appointment['status']; ?>">
                                    <div class="row">
                                        <div class="col-lg-8 col-md-7">
                                            <!-- User Information -->
                                            <div class="user-info">
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <h6 class="mb-2">
                                                            <i class="fas fa-user me-2"></i>
                                                            <?php echo htmlspecialchars($appointment['user_name']); ?>
                                                        </h6>
                                                        <div class="detail-item">
                                                            <i class="fas fa-mobile-alt"></i>
                                                            <span><?php echo htmlspecialchars($appointment['user_mobile']); ?></span>
                                                        </div>
                                                        <div class="detail-item">
                                                            <i class="fas fa-map-marker-alt"></i>
                                                            <span><?php echo htmlspecialchars($appointment['user_city']); ?></span>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="detail-item">
                                                            <i class="fas fa-rupee-sign"></i>
                                                            <span class="fw-bold">₹<?php echo number_format($appointment['amount']); ?></span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Appointment Details -->
                                            <div class="appointment-details">
                                                <div class="detail-item">
                                                    <i class="fas fa-calendar"></i>
                                                    <span><strong>Date:</strong> <?php echo date('d M Y', strtotime($appointment['appointment_date'])); ?></span>
                                                </div>
                                                <div class="detail-item">
                                                    <i class="fas fa-clock"></i>
                                                    <span><strong>Time:</strong> 
                                                        <?php 
                                                        $display_time = $appointment['time_slot'];
                                                        if (strpos($display_time, ' - ') === false && !empty($display_time) && $display_time !== 'Tatkal') {
                                                            // If only start time is provided, add end time based on slot_duration
                                                            $startTime = strtotime($display_time);
                                                            if ($startTime !== false) {
                                                                $endTime = $startTime + ($slotDuration * 60);
                                                                $display_time = date('H:i', $startTime) . ' - ' . date('H:i', $endTime);
                                                            }
                                                        }
                                                        echo htmlspecialchars($display_time); 
                                                        ?>
                                                    </span>
                                                </div>
                                                <div class="detail-item">
                                                    <i class="fas fa-phone"></i>
                                                    <span><strong>Type:</strong> 
                                                        <?php 
                                                        $types = [
                                                            'office_meeting' => 'Office Meeting',
                                                            'video_call' => 'Video Call',
                                                            'audio_call' => 'Audio Call'
                                                        ];
                                                        echo $types[$appointment['consultation_type']] ?? $appointment['consultation_type'];
                                                        ?>
                                                    </span>
                                                </div>
                                                <div class="detail-item">
                                                    <i class="fas fa-users"></i>
                                                    <span><strong>Persons:</strong> <?php echo max(1, (int)($appointment['number_of_persons'] ?? 1)); ?></span>
                                                </div>
                                                <div class="detail-item">
                                                    <i class="fas fa-calendar-plus"></i>
                                                    <span><strong>Booked:</strong> <?php echo date('d M Y H:i', strtotime($appointment['created_at'])); ?></span>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-lg-4 col-md-5 text-end text-md-end text-start mt-3 mt-md-0">
                                            <!-- Status Badge -->
                                            <div class="mb-3">
                                                <?php
                                                $status_colors = [
                                                    'pending' => 'warning',
                                                    'confirmed' => 'success',
                                                    'cancelled' => 'danger',
                                                    'completed' => 'info'
                                                ];
                                                $status_names = [
                                                    'pending' => 'Pending',
                                                    'confirmed' => 'Confirmed',
                                                    'cancelled' => 'Cancelled',
                                                    'completed' => 'Completed'
                                                ];
                                                $color = $status_colors[$appointment['status']] ?? 'secondary';
                                                $name = $status_names[$appointment['status']] ?? ucfirst($appointment['status']);
                                                ?>
                                                <span class="badge bg-<?php echo $color; ?> status-badge">
                                                    <?php echo $name; ?>
                                                </span>
                                            </div>
                                            
                                            <!-- Action Buttons -->
                                            <div class="mb-3 d-flex flex-wrap gap-1">
                                                <button class="btn btn-sm btn-outline-primary btn-action flex-fill" 
                                                        onclick="viewAppointment(<?php echo $appointment['id']; ?>)">
                                                    <i class="fas fa-eye"></i> <span class="d-none d-sm-inline">View</span>
                                                </button>
                                                <button class="btn btn-sm btn-outline-success btn-action flex-fill" 
                                                        onclick="sendNotification(<?php echo $appointment['id']; ?>)">
                                                    <i class="fas fa-bell"></i> <span class="d-none d-sm-inline">Notify</span>
                                                </button>
                                                <button class="btn btn-sm btn-outline-warning btn-action flex-fill" 
                                                        onclick="openAppointmentHelp(<?php echo $appointment['id']; ?>)">
                                                    <i class="fas fa-question-circle"></i> <span class="d-none d-sm-inline">Help</span>
                                                </button>
                                            </div>
                                            
                                            <!-- Status Update -->
                                            <form method="POST" class="d-inline">
                                                <input type="hidden" name="update_status" value="1">
                                                <input type="hidden" name="appointment_id" value="<?php echo $appointment['id']; ?>">
                                                <select name="new_status" class="form-select form-select-sm mb-2" onchange="confirmStatusChange(this)">
                                                    <option value="">Change Status</option>
                                                    <option value="pending" <?php echo $appointment['status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                                    <option value="confirmed" <?php echo $appointment['status'] === 'confirmed' ? 'selected' : ''; ?>>Confirmed</option>
                                                    <option value="cancelled" <?php echo $appointment['status'] === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                                                    <option value="completed" <?php echo $appointment['status'] === 'completed' ? 'selected' : ''; ?>>Completed</option>
                                                </select>
                                            </form>
                                            
                                            <!-- Delete Button -->
                                            <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this appointment?')">
                                                <input type="hidden" name="delete_appointment" value="1">
                                                <input type="hidden" name="appointment_id" value="<?php echo $appointment['id']; ?>">
                                                <button type="submit" class="btn btn-sm btn-outline-danger btn-action">
                                                    <i class="fas fa-trash"></i> Delete
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                        <nav aria-label="Appointments pagination">
                            <ul class="pagination">
                                <?php if ($page > 1): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">
                                            <i class="fas fa-chevron-left"></i> Previous
                                        </a>
                                    </li>
                                <?php endif; ?>
                                
                                <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                    <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>">
                                            <?php echo $i; ?>
                                        </a>
                                    </li>
                                <?php endfor; ?>
                                
                                <?php if ($page < $total_pages): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">
                                            Next <i class="fas fa-chevron-right"></i>
                                        </a>
                                    </li>
                                <?php endif; ?>
                            </ul>
                        </nav>
                    <?php endif; ?>
                </div>
    
    <!-- Help Modal -->
    <div class="modal fade" id="helpModal" tabindex="-1" aria-labelledby="helpModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-warning text-dark">
                    <h5 class="modal-title" id="helpModalLabel">
                        <i class="fab fa-whatsapp me-2"></i>Help & Support
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="text-primary mb-3">
                                <i class="fas fa-phone me-2"></i>Contact Support
                            </h6>
                            <div class="mb-3">
                                <strong>WhatsApp:</strong><br>
                                <a href="https://wa.me/917737357224" target="_blank" class="btn btn-success btn-sm">
                                    <i class="fab fa-whatsapp me-2"></i>+91 77373 57224
                                </a>
                            </div>
                            <div class="mb-3">
                                <strong>Call:</strong><br>
                                <a href="tel:+917737357224" class="btn btn-primary btn-sm">
                                    <i class="fas fa-phone me-2"></i>+91 77373 57224
                                </a>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h6 class="text-primary mb-3">
                                <i class="fas fa-info-circle me-2"></i>Quick Help
                            </h6>
                            <div class="alert alert-info">
                                <strong>Need Help?</strong><br>
                                • Use filters to find appointments<br>
                                • Export data in CSV/PDF format<br>
                                • Update appointment status<br>
                                • Contact support via WhatsApp
                            </div>
                        </div>
                    </div>
                    
                    <div class="mt-4">
                        <h6 class="text-primary mb-3">
                            <i class="fas fa-language me-2"></i>Language Support
                        </h6>
                        <div class="row">
                            <div class="col-md-6">
                                <button class="btn btn-outline-primary w-100 mb-2" onclick="changeLanguage('en')">
                                    <i class="fas fa-flag me-2"></i>English
                                </button>
                            </div>
                            <div class="col-md-6">
                                <button class="btn btn-outline-primary w-100 mb-2" onclick="changeLanguage('hi')">
                                    <i class="fas fa-flag me-2"></i>हिंदी
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <a href="https://wa.me/917737357224?text=Hi, I need help with the Astro Admin Panel" target="_blank" class="btn btn-success">
                        <i class="fab fa-whatsapp me-2"></i>WhatsApp Support
                    </a>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/moment/moment.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
    
    <script>
        // Help Modal
        function openHelp() {
            const helpModal = new bootstrap.Modal(document.getElementById('helpModal'));
            helpModal.show();
        }
        
        // Appointment-specific Help
        function openAppointmentHelp(appointmentId) {
            const message = `Hi, I need help with appointment ID: ${appointmentId}. Can you please assist me?`;
            const whatsappUrl = `https://wa.me/917737357224?text=${encodeURIComponent(message)}`;
            window.open(whatsappUrl, '_blank');
        }
        
        // Stats Help
        function openStatsHelp() {
            const helpText = `
📈 <strong>Statistics Help:</strong>

• <strong>Total Appointments:</strong> All appointments in the system
• <strong>Pending:</strong> Appointments awaiting confirmation
• <strong>Confirmed:</strong> Appointments that are confirmed
• <strong>Completed:</strong> Appointments that have been completed
• <strong>Cancelled:</strong> Appointments that were cancelled
• <strong>Total Revenue:</strong> Sum of all appointment amounts

💡 <strong>Understanding:</strong>
• Statistics update in real-time
• Use filters to see stats for specific criteria
• Revenue includes all confirmed and completed appointments
• Perfect for business analysis and reporting
            `;
            
            const modal = new bootstrap.Modal(document.getElementById('helpModal'));
            document.querySelector('.modal-body').innerHTML = `
                <div class="text-center mb-3">
                    <i class="fas fa-chart-bar fa-3x text-primary"></i>
                </div>
                <div class="alert alert-info">
                    ${helpText}
                </div>
                <div class="text-center">
                    <a href="https://wa.me/917737357224?text=Hi, I need help understanding the appointment statistics" target="_blank" class="btn btn-success">
                        <i class="fab fa-whatsapp me-2"></i>Get More Help
                    </a>
                </div>
            `;
            modal.show();
        }
        
        
        // Filter Help
        function openFilterHelp() {
            const helpText = `
🔍 <strong>Filter Help:</strong>

• <strong>Search:</strong> Type name, mobile, city, or email to find specific users
• <strong>Status:</strong> Filter by appointment status (Pending, Confirmed, Cancelled, Completed)
• <strong>Date:</strong> Pick a specific date to see appointments on that day
• <strong>Type:</strong> Filter by consultation method (Office, Video Call, Audio Call)
• <strong>Amount:</strong> Set min/max price range to filter appointments

💡 <strong>Tips:</strong>
• Use multiple filters together for precise results
• Search updates automatically as you type
• Clear filters to see all appointments
            `;
            
            const modal = new bootstrap.Modal(document.getElementById('helpModal'));
            document.querySelector('.modal-body').innerHTML = `
                <div class="text-center mb-3">
                    <i class="fas fa-filter fa-3x text-primary"></i>
                </div>
                <div class="alert alert-info">
                    ${helpText}
                </div>
                <div class="text-center">
                    <a href="https://wa.me/917737357224?text=Hi, I need help with the appointment filters" target="_blank" class="btn btn-success">
                        <i class="fab fa-whatsapp me-2"></i>Get More Help
                    </a>
                </div>
            `;
            modal.show();
        }
        
        // Language Support
        function changeLanguage(lang) {
            if (lang === 'hi') {
                // Hindi translations
                document.getElementById('helpModalLabel').innerHTML = '<i class="fab fa-whatsapp me-2"></i>सहायता और समर्थन';
                document.querySelector('.modal-body h6:first-child').innerHTML = '<i class="fas fa-phone me-2"></i>समर्थन से संपर्क करें';
                document.querySelector('.modal-body h6:nth-child(2)').innerHTML = '<i class="fas fa-info-circle me-2"></i>त्वरित सहायता';
                document.querySelector('.modal-body h6:last-child').innerHTML = '<i class="fas fa-language me-2"></i>भाषा समर्थन';
                
                // Update help text
                const helpText = document.querySelector('.alert-info strong');
                if (helpText) helpText.textContent = 'सहायता चाहिए?';
                
                // Update button text
                document.querySelector('.modal-footer .btn-success').innerHTML = '<i class="fab fa-whatsapp me-2"></i>व्हाट्सएप समर्थन';
            } else {
                // English translations
                document.getElementById('helpModalLabel').innerHTML = '<i class="fab fa-whatsapp me-2"></i>Help & Support';
                document.querySelector('.modal-body h6:first-child').innerHTML = '<i class="fas fa-phone me-2"></i>Contact Support';
                document.querySelector('.modal-body h6:nth-child(2)').innerHTML = '<i class="fas fa-info-circle me-2"></i>Quick Help';
                document.querySelector('.modal-body h6:last-child').innerHTML = '<i class="fas fa-language me-2"></i>Language Support';
                
                // Update help text
                const helpText = document.querySelector('.alert-info strong');
                if (helpText) helpText.textContent = 'Need Help?';
                
                // Update button text
                document.querySelector('.modal-footer .btn-success').innerHTML = '<i class="fab fa-whatsapp me-2"></i>WhatsApp Support';
            }
        }
        
        // View appointment details
        function viewAppointment(id) {
            // You can implement a modal or redirect to detailed view
            alert('View appointment ' + id + ' details');
        }
        
        // Send notification
        function sendNotification(id) {
            // You can implement notification sending
            alert('Send notification for appointment ' + id);
        }
        
        // Confirm status change
        function confirmStatusChange(selectElement) {
            const newStatus = selectElement.value;
            const currentStatus = selectElement.options[selectElement.selectedIndex].text;
            
            if (newStatus === '') {
                return; // Don't submit if no status selected
            }
            
            const statusMessages = {
                'pending': 'Are you sure you want to set this appointment as Pending?',
                'confirmed': 'Are you sure you want to confirm this appointment?',
                'cancelled': 'Are you sure you want to cancel this appointment?',
                'completed': 'Are you sure you want to mark this appointment as completed?'
            };
            
            const message = statusMessages[newStatus] || `Are you sure you want to change the status to ${currentStatus}?`;
            
            if (confirm(message)) {
                selectElement.form.submit();
            } else {
                // Reset to original value if user cancels
                selectElement.selectedIndex = 0;
            }
        }
        
        
        // Auto-refresh filters
        document.addEventListener('DOMContentLoaded', function() {
            const filterForm = document.getElementById('filterForm');
            const searchInput = document.getElementById('searchInput');
            const statusFilter = document.getElementById('statusFilter');
            const dateFilter = document.getElementById('dateFilter');
            const consultationFilter = document.getElementById('consultationFilter');
            const amountMinFilter = document.getElementById('amountMinFilter');
            const amountMaxFilter = document.getElementById('amountMaxFilter');
            const applyFiltersBtn = document.getElementById('applyFilters');
            const appointmentsContainer = document.getElementById('appointmentsContainer');
            
            // Auto-submit form when filters change
            [statusFilter, dateFilter, consultationFilter].forEach(filter => {
                filter.addEventListener('change', function() {
                    filterForm.submit();
                });
            });
            
            // OPTIMIZED Search with faster delay
            let searchTimeout;
            searchInput.addEventListener('input', function() {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    showLoading();
                    filterForm.submit();
                }, 500); // Reduced from 800ms to 500ms for faster response
            }, { passive: true }); // Better performance
            
            // OPTIMIZED Amount filters with faster delay
            [amountMinFilter, amountMaxFilter].forEach(filter => {
                let amountTimeout;
                filter.addEventListener('input', function() {
                    clearTimeout(amountTimeout);
                    amountTimeout = setTimeout(() => {
                        showLoading();
                        filterForm.submit();
                    }, 600); // Reduced from 1000ms to 600ms
                }, { passive: true }); // Better performance
            });
            
            // Show loading indicator for better UX
            function showLoading() {
                const loadingDiv = document.createElement('div');
                loadingDiv.className = 'loading-overlay';
                loadingDiv.innerHTML = '<div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div>';
                document.body.appendChild(loadingDiv);
                
                setTimeout(() => {
                    if (loadingDiv.parentNode) {
                        loadingDiv.parentNode.removeChild(loadingDiv);
                    }
                }, 1000);
            }
            
            // Show loading state
            filterForm.addEventListener('submit', function() {
                appointmentsContainer.classList.add('loading');
                applyFiltersBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Loading...';
                applyFiltersBtn.disabled = true;
            });
            
            // Reset form button functionality
            document.querySelector('a[href="appointments.php"]').addEventListener('click', function(e) {
                e.preventDefault();
                window.location.href = 'appointments.php';
            });
        });
        
        // Filter by status when clicking stats cards
        function filterByStatus(status) {
            console.log('Filtering by status:', status);
            
            // Update active state
            document.querySelectorAll('.clickable-stat').forEach(card => {
                card.classList.remove('active');
            });
            
            if (status !== 'all') {
                document.querySelector(`[data-status="${status}"]`).classList.add('active');
            }
            
            // Update URL and reload with filter
            const url = new URL(window.location);
            
            if (status === 'all') {
                // Clear status filter but keep other filters
                url.searchParams.delete('status');
            } else {
                url.searchParams.set('status', status);
            }
            
            url.searchParams.delete('page'); // Reset to first page
            window.location.href = url.toString();
        }
        
        // Set active state based on current filter
        document.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);
            const currentStatus = urlParams.get('status') || 'all';
            
            if (currentStatus !== 'all') {
                const activeCard = document.querySelector(`[data-status="${currentStatus}"]`);
                if (activeCard) {
                    activeCard.classList.add('active');
                }
            }
        });
        
        // Auto-refresh page every 30 seconds to show latest data
        setInterval(function() {
            if (!document.querySelector('.loading')) {
                location.reload();
            }
        }, 30000);
    </script>
    </div> <!-- Close content-card -->

<?php
$content = ob_get_clean();
include 'layout.php';
?> 