<?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;
}

$pdo = getDBConnection();

$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'];
    
    $stmt = $pdo->prepare("UPDATE appointments SET status = ? WHERE id = ?");
    if ($stmt->execute([$newStatus, $appointmentId])) {
        $success_message = "Appointment status updated successfully";
    } else {
        $error_message = "Error updating appointment status";
    }
}

// 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";
    }
}

// Handle CSV Export
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="appointments_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // CSV Headers
    fputcsv($output, [
        'ID', 'User Name', 'Mobile', 'Email', 'City', 'Date', 'Time', 'Type', 
        'Status', 'Amount', 'Booked Date'
    ]);
    
    // Get all appointments for export
    $export_query = "
        SELECT 
            a.*, 
            u.name as user_name, 
            u.mobile as user_mobile,
            u.city as user_city
        FROM appointments a
        JOIN users u ON a.user_id = u.id
        ORDER BY a.appointment_date DESC, a.time_slot ASC
    ";
    
    $export_stmt = $pdo->query($export_query);
    while ($row = $export_stmt->fetch()) {
        fputcsv($output, [
            $row['id'],
            $row['user_name'],
            $row['user_mobile'],
            $row['user_city'],
            $row['appointment_date'],
            $row['time_slot'],
            $row['consultation_type'],
            $row['status'],
            $row['amount'],
            $row['created_at']
        ]);
    }
    
    fclose($output);
    exit;
}

// Handle PDF Export
if (isset($_GET['export']) && $_GET['export'] === 'pdf') {
    // For PDF export, we'll redirect to a PDF generation script
    // You can implement this using TCPDF, FPDF, or similar libraries
    header('Location: generate_pdf.php?' . http_build_query($_GET));
    exit;
}

// 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 smaller page size for faster loading
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 15; // Reduced from 25 to 15 for faster loading
$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
$query = "
    SELECT 
        a.id, a.appointment_date, a.time_slot, a.consultation_type, 
        a.status, a.amount, a.created_at,
        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.appointment_date DESC, a.time_slot ASC
    LIMIT ? OFFSET ?
";

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

// Get statistics - OPTIMIZED with caching
$cache_file = '../cache/stats_cache.json';
$cache_time = 300; // 5 minutes cache

if (file_exists($cache_file) && (time() - filemtime($cache_file)) < $cache_time) {
    // Use cached stats
    $stats = json_decode(file_get_contents($cache_file), true);
} else {
    // Generate fresh stats
    $stats_query = "SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN status = 'confirmed' THEN 1 ELSE 0 END) as confirmed,
        SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
        SUM(amount) as total_revenue
    FROM appointments";
    $stats = $pdo->query($stats_query)->fetch();
    
    // Cache the stats
    if (!is_dir('../cache')) {
        mkdir('../cache', 0755, true);
    }
    file_put_contents($cache_file, json_encode($stats));
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Appointments Management - Astro Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
        }
        .sidebar .nav-link {
            color: #fff;
            padding: 12px 20px;
            margin: 5px 0;
            border-radius: 8px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            background: rgba(255, 193, 7, 0.2);
            color: #ffc107;
        }
        .main-content {
            background: #f8f9fa;
        }
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        .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%);
        }
        .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;
        }
        .export-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .export-btn {
            border-radius: 20px;
            padding: 8px 20px;
            font-size: 0.9rem;
        }
        .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;
        }
        .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;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 px-0">
                <div class="sidebar p-3">
                    <div class="text-center mb-4">
                        <h4 class="text-warning">
                            <i class="fas fa-star"></i> ASTRO ADMIN
                        </h4>
                    </div>
                    
                    <nav class="nav flex-column">
                        <a class="nav-link" href="index.php">
                            <i class="fas fa-tachometer-alt me-2"></i> Dashboard
                        </a>
                        <a class="nav-link" href="users.php">
                            <i class="fas fa-users me-2"></i> Users
                        </a>
                        <a class="nav-link active" href="appointments.php">
                            <i class="fas fa-calendar-check me-2"></i> Appointments
                        </a>
                        <a class="nav-link" href="notifications.php">
                            <i class="fas fa-bell me-2"></i> Push Notifications
                        </a>
                        <a class="nav-link" href="settings.php">
                            <i class="fas fa-cog me-2"></i> Settings
                        </a>
                        <a class="nav-link" href="logout.php">
                            <i class="fas fa-sign-out-alt me-2"></i> Logout
                        </a>
                        <hr class="text-light">
                        <a class="nav-link text-warning" href="#" onclick="openHelp()">
                            <i class="fab fa-whatsapp me-2"></i> Help & Support
                        </a>
                        <a class="nav-link text-info" href="HELP_GUIDE.md" target="_blank">
                            <i class="fas fa-book me-2"></i> Help Guide
                        </a>
                        <a class="nav-link text-success" href="help_utility.php">
                            <i class="fas fa-tools me-2"></i> Admin Tools
                        </a>
                        <a class="nav-link text-warning" href="../optimize_database.php" target="_blank">
                            <i class="fas fa-rocket me-2"></i> Speed Up Database
                        </a>
                    </nav>
                </div>
            </div>
            
            <!-- Main Content -->
            <div class="col-md-9 col-lg-10 main-content">
                <div class="p-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><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 class="export-buttons">
                            <button class="btn btn-outline-success export-btn" onclick="exportToCSV()">
                                <i class="fas fa-download me-2"></i>Export CSV
                            </button>
                            <button class="btn btn-outline-primary export-btn" onclick="exportToPDF()">
                                <i class="fas fa-file-pdf me-2"></i>Export PDF
                            </button>
                            <button class="btn btn-outline-info export-btn" onclick="openExportHelp()">
                                <i class="fas fa-question-circle me-2"></i>Export Help
                            </button>
                        </div>
                        </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-md-2 col-sm-6">
                            <div class="stats-card">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4 class="mb-0"><?php echo $stats['total']; ?></h4>
                                        <small>Total Appointments</small>
                                    </div>
                                    <i class="fas fa-calendar fa-2x opacity-75"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2 col-sm-6">
                            <div class="stats-card warning">
                                <div class="d-flex justify-content-between">
                                    <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-md-2 col-sm-6">
                            <div class="stats-card success">
                                <div class="d-flex justify-content-between">
                                    <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-md-2 col-sm-6">
                            <div class="stats-card info">
                                <div class="d-flex justify-content-between">
                                    <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-md-2 col-sm-6">
                            <div class="stats-card danger">
                                <div class="d-flex justify-content-between">
                                    <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-md-2 col-sm-6">
                            <div class="stats-card" style="background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%); color: #333;">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4 class="mb-0">₹<?php echo number_format($stats['total_revenue'] ?? 0); ?></h4>
                                        <small>Total 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>
                                <button class="btn btn-sm btn-outline-info" onclick="openFilterHelp()">
                                    <i class="fas fa-question-circle me-2"></i>Filter Help
                                </button>
                            </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">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-md-8">
                                            <!-- 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 echo $appointment['time_slot']; ?></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-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-md-4 text-end">
                                            <!-- 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">
                                                <button class="btn btn-sm btn-outline-primary btn-action" 
                                                        onclick="viewAppointment(<?php echo $appointment['id']; ?>)">
                                                    <i class="fas fa-eye"></i> View
                                                </button>
                                                <button class="btn btn-sm btn-outline-success btn-action" 
                                                        onclick="sendNotification(<?php echo $appointment['id']; ?>)">
                                                    <i class="fas fa-bell"></i> Notify
                                                </button>
                                                <button class="btn btn-sm btn-outline-warning btn-action" 
                                                        onclick="openAppointmentHelp(<?php echo $appointment['id']; ?>)">
                                                    <i class="fas fa-question-circle"></i> Help
                                                </button>
                                            </div>
                                            
                                            <!-- Status Update -->
                                            <form method="POST" class="d-inline">
                                                <input type="hidden" name="appointment_id" value="<?php echo $appointment['id']; ?>">
                                                <select name="new_status" class="form-select form-select-sm mb-2" onchange="this.form.submit()">
                                                    <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>
            </div>
        </div>
    </div>
    
    <!-- Floating Help Button -->
    <div class="floating-help">
        <button class="btn btn-warning btn-lg" onclick="openHelp()" title="Help & Support">
            <i class="fab fa-whatsapp fa-lg"></i>
        </button>
    </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/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <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();
        }
        
        // Export Help
        function openExportHelp() {
            const helpText = `
📊 <strong>Export Help:</strong>

• <strong>CSV Export:</strong> Download appointment data in Excel-compatible format
• <strong>PDF Export:</strong> Generate professional HTML report for printing/sharing

💡 <strong>Features:</strong>
• Exports respect all applied filters
• Includes user details and appointment information
• Perfect for record keeping and analysis
• Can be opened in Excel, Google Sheets, or any text editor

🔧 <strong>How to Use:</strong>
1. Apply your desired filters
2. Click Export CSV or Export PDF
3. File will download automatically
4. Open in your preferred application
            `;
            
            const modal = new bootstrap.Modal(document.getElementById('helpModal'));
            document.querySelector('.modal-body').innerHTML = `
                <div class="text-center mb-3">
                    <i class="fas fa-download fa-3x text-success"></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 exporting appointment data" 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);
        }
        
        // Export to CSV
        function exportToCSV() {
            const currentUrl = new URL(window.location);
            currentUrl.searchParams.set('export', 'csv');
            window.location.href = currentUrl.toString();
        }
        
        // Export to PDF
        function exportToPDF() {
            const currentUrl = new URL(window.location);
            currentUrl.searchParams.set('export', 'pdf');
            window.location.href = currentUrl.toString();
        }
        
        // 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';
            });
        });
        
        // Auto-refresh page every 30 seconds to show latest data
        setInterval(function() {
            if (!document.querySelector('.loading')) {
                location.reload();
            }
        }, 30000);
    </script>
</body>
</html> 