<?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 = 'Users Management';
$current_page = 'users.php';

$pdo = getDBConnection();

// Handle CSV export
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="users_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    fputcsv($output, ['ID', 'Name', 'Mobile', 'City', 'Email', 'Appointments', 'Joined Date']);
    
    $stmt = $pdo->prepare("
        SELECT users.*, 
        (SELECT COUNT(*) FROM appointments WHERE user_id = users.id) as appointment_count
        FROM users 
        ORDER BY users.created_at DESC
    ");
    $stmt->execute();
    $all_users = $stmt->fetchAll();
    
    foreach ($all_users as $user) {
        fputcsv($output, [
            $user['id'],
            $user['name'],
            $user['mobile'],
            $user['city'] ?? 'N/A',
            $user['email'] ?? 'N/A',
            $user['appointment_count'],
            date('Y-m-d H:i:s', strtotime($user['created_at']))
        ]);
    }
    
    fclose($output);
    exit;
}

// Handle user deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_user'])) {
    $userId = (int)$_POST['user_id'];
    
    $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
    if ($stmt->execute([$userId])) {
        $success_message = "User deleted successfully";
    } else {
        $error_message = "Error deleting user";
    }
}

// Search functionality
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$search_condition = '';
$search_params = [];

if (!empty($search)) {
    // Search by name, mobile, and city
    // Note: email column might not exist in all database versions
    // Using COALESCE to handle missing email column gracefully
    $search_condition = "WHERE users.name LIKE ? OR users.mobile LIKE ? OR users.city LIKE ?";
    $search_params = ["%$search%", "%$search%", "%$search%"];
    
    // Try to include email in search if column exists (using error handling)
    try {
        $test_query = $pdo->query("SELECT email FROM users LIMIT 1");
        // If no error, email column exists - add it to search
        $search_condition = "WHERE users.name LIKE ? OR users.mobile LIKE ? OR users.city LIKE ? OR users.email LIKE ?";
        $search_params = ["%$search%", "%$search%", "%$search%", "%$search%"];
    } catch (PDOException $e) {
        // Email column doesn't exist, use search without email (already set above)
    }
}

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 50; // Increased for table view
$offset = ($page - 1) * $limit;

// Count total users with search
if (!empty($search)) {
    $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM users $search_condition");
    $count_stmt->execute($search_params);
} else {
    $count_stmt = $pdo->query("SELECT COUNT(*) FROM users");
}
$total_users = $count_stmt->fetchColumn();
$total_pages = ceil($total_users / $limit);

// Get users with search
// Fix: Use integer casting for LIMIT/OFFSET since PDO doesn't always handle placeholders correctly
$limit = (int)$limit;
$offset = (int)$offset;

$query = "
    SELECT users.*, 
    (SELECT COUNT(*) FROM appointments WHERE user_id = users.id) as appointment_count
    FROM users 
    $search_condition
    ORDER BY users.created_at DESC 
    LIMIT $limit OFFSET $offset
";

if (!empty($search)) {
    $stmt = $pdo->prepare($query);
    $stmt->execute($search_params);
} else {
    $stmt = $pdo->query($query);
}

$users = $stmt->fetchAll();
?>

<?php ob_start(); ?>
    <style>
        /* Main Container */
        .table-container {
            background: linear-gradient(145deg, #ffffff 0%, #f8f9fa 100%);
            border-radius: 20px;
            padding: 25px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            overflow-x: auto;
            border: 1px solid rgba(255,255,255,0.2);
        }
        
        /* Table Styling */
        .users-table {
            margin-bottom: 0;
            border-collapse: separate;
            border-spacing: 0;
        }
        
        .users-table th {
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 50%, #ec4899 100%);
            color: white;
            border: none;
            font-weight: 600;
            padding: 18px 12px;
            text-align: center;
            white-space: nowrap;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        
        .users-table th:first-child {
            border-top-left-radius: 15px;
        }
        
        .users-table th:last-child {
            border-top-right-radius: 15px;
        }
        
        .users-table td {
            padding: 15px 12px;
            vertical-align: middle;
            border-bottom: 1px solid rgba(0,0,0,0.05);
            text-align: center;
            background: white;
            transition: all 0.3s ease;
        }
        
        .users-table tbody tr {
            transition: all 0.3s ease;
        }
        
        .users-table tbody tr:hover {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0e7ff 100%) !important;
            transform: translateY(-2px);
            box-shadow: 0 4px 20px rgba(79, 70, 229, 0.1);
        }
        
        .users-table tbody tr:hover td {
            background: transparent;
        }
        
        /* Action Buttons */
        .btn-action {
            padding: 8px 12px;
            margin: 0 3px;
            border-radius: 10px;
            font-size: 0.8rem;
            transition: all 0.3s ease;
            border: none;
            min-width: 40px;
        }
        
        .btn-action:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
        
        .btn-outline-primary {
            color: #4f46e5;
            border: 2px solid #4f46e5;
        }
        
        .btn-outline-primary:hover {
            background: #4f46e5;
            color: white;
        }
        
        .btn-outline-danger {
            color: #ef4444;
            border: 2px solid #ef4444;
        }
        
        .btn-outline-danger:hover {
            background: #ef4444;
            color: white;
        }
        
        /* Search Box */
        .search-box {
            background: linear-gradient(145deg, #ffffff 0%, #f8f9fa 100%);
            border-radius: 20px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.08);
            border: 1px solid rgba(255,255,255,0.2);
        }
        
        .search-box .form-control {
            border-radius: 15px;
            border: 2px solid #e5e7eb;
            padding: 12px 20px;
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        
        .search-box .form-control:focus {
            border-color: #4f46e5;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }
        
        .search-box .btn {
            border-radius: 15px;
            padding: 12px 25px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .search-box .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
        
        /* Pagination */
        .pagination {
            justify-content: center;
            margin-top: 30px;
        }
        
        .pagination .page-link {
            border-radius: 12px;
            margin: 0 3px;
            padding: 10px 15px;
            border: 2px solid #e5e7eb;
            color: #4f46e5;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .pagination .page-item.active .page-link {
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
            border-color: #4f46e5;
        }
        
        .pagination .page-link:hover {
            background: #4f46e5;
            border-color: #4f46e5;
            color: white;
            transform: translateY(-2px);
        }
        
        /* Badges */
        .badge {
            font-size: 0.8rem;
            padding: 8px 12px;
            border-radius: 20px;
            font-weight: 600;
        }
        
        .badge.bg-info {
            background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%) !important;
        }
        
        .badge.bg-primary {
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%) !important;
        }
        
        /* User Avatar */
        .user-avatar {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 50%, #ec4899 100%);
            display: inline-flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            margin-right: 12px;
            font-size: 1rem;
            box-shadow: 0 4px 15px rgba(79, 70, 229, 0.3);
        }
        
        /* Alert Messages */
        .alert {
            border-radius: 15px;
            border: none;
            padding: 15px 20px;
            margin-bottom: 20px;
        }
        
        .alert-success {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
        }
        
        .alert-danger {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
        }
        
        /* Mobile Responsive */
        @media (max-width: 768px) {
            .table-container {
                padding: 15px;
                margin: 0 -10px;
                border-radius: 15px;
            }
            
            .users-table th,
            .users-table td {
                padding: 10px 6px;
                font-size: 0.85rem;
            }
            
            .btn-action {
                padding: 6px 8px;
                font-size: 0.75rem;
                margin: 0 1px;
            }
            
            .user-avatar {
                width: 35px;
                height: 35px;
                font-size: 0.85rem;
                margin-right: 8px;
            }
            
            .search-box {
                padding: 20px 15px;
                margin: 0 -10px 20px;
                border-radius: 15px;
            }
            
            .search-box .form-control {
                padding: 10px 15px;
                font-size: 0.9rem;
            }
            
            .search-box .btn {
                padding: 10px 20px;
                font-size: 0.9rem;
            }
            
            .d-flex.justify-content-between {
                flex-direction: column;
                gap: 15px;
            }
            
            .d-flex.gap-2 {
                justify-content: center;
            }
        }
        
        @media (max-width: 576px) {
            /* Hide City and Email columns on mobile */
            .users-table th:nth-child(4),
            .users-table td:nth-child(4),
            .users-table th:nth-child(5),
            .users-table td:nth-child(5) {
                display: none;
            }
            
            .users-table th,
            .users-table td {
                padding: 8px 4px;
                font-size: 0.8rem;
            }
            
            .btn-action {
                padding: 4px 6px;
                font-size: 0.7rem;
            }
            
            .user-avatar {
                width: 30px;
                height: 30px;
                font-size: 0.75rem;
                margin-right: 6px;
            }
            
            .search-box {
                padding: 15px 10px;
            }
            
            .pagination .page-link {
                padding: 8px 12px;
                font-size: 0.85rem;
            }
        }
        
        /* Modal appointments table styling */
        .modal-body .table-responsive {
            border-radius: 10px;
            border: 1px solid #e9ecef;
        }
        
        .modal-body .table thead {
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
            color: white;
        }
        
        .modal-body .table thead th {
            border: none;
            padding: 12px;
            font-weight: 600;
            font-size: 0.85rem;
        }
        
        .modal-body .table tbody td {
            padding: 10px 12px;
            vertical-align: middle;
            font-size: 0.9rem;
        }
        
        .modal-body .table tbody tr:hover {
            background-color: #f8f9fa;
        }
        
        /* Dark mode support */
        @media (prefers-color-scheme: dark) {
            .table-container {
                background: linear-gradient(145deg, #1f2937 0%, #111827 100%);
                color: white;
            }
            
            .users-table td {
                background: #374151;
                color: white;
                border-bottom-color: rgba(255,255,255,0.1);
            }
            
            .search-box {
                background: linear-gradient(145deg, #1f2937 0%, #111827 100%);
                color: white;
            }
        }
    </style>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fas fa-users me-2"></i>Users Management</h2>
        <div class="d-flex gap-2">
            <button class="btn btn-primary" onclick="refreshUsers()">
                <i class="fas fa-sync-alt me-2"></i>Refresh
            </button>
            <button class="btn btn-success" onclick="exportUsers()">
                <i class="fas fa-download me-2"></i>Export CSV
            </button>
        </div>
    </div>
    
    <!-- Search Box -->
    <div class="search-box">
        <form method="GET" class="row g-3 align-items-end">
            <div class="col-md-8">
                <label class="form-label fw-bold">
                    <i class="fas fa-search me-2"></i>Search Users
                </label>
                <input type="text" class="form-control" name="search" 
                       value="<?php echo htmlspecialchars($search); ?>" 
                       placeholder="Search by name, mobile, or city...">
            </div>
            <div class="col-md-4">
                <div class="d-flex gap-2">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-search me-2"></i>Search
                    </button>
                    <?php if (!empty($search)) { ?>
                        <a href="users.php" class="btn btn-outline-secondary">
                            <i class="fas fa-times me-2"></i>Clear
                        </a>
                    <?php } ?>
                </div>
            </div>
        </form>
    </div>
    
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="mb-0">
            <i class="fas fa-list me-2"></i>Users 
            <span class="badge bg-primary"><?php echo number_format($total_users); ?></span>
            <?php if (!empty($search)) { ?>
                <small class="text-muted ms-2">
                    (filtered from <?php echo number_format($total_users); ?> total)
                </small>
            <?php } ?>
        </h5>
        <small class="text-muted">
            Showing <?php echo number_format($offset + 1); ?> - <?php echo number_format(min($offset + $limit, $total_users)); ?> 
            of <?php echo number_format($total_users); ?> users
        </small>
    </div>
                    
    <?php if (isset($success_message)) { ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo htmlspecialchars($success_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php } ?>
    
    <?php if (isset($error_message)) { ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo htmlspecialchars($error_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php } ?>
    
    <!-- Users Table -->
    <div class="table-container">
        <table class="table table-hover users-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>User</th>
                    <th>Mobile</th>
                    <th>City</th>
                    <th>Email</th>
                    <th>Appointments</th>
                    <th>Joined</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($users as $user) { ?>
                    <tr>
                        <td>
                            <strong>#<?php echo $user['id']; ?></strong>
                        </td>
                        <td>
                            <div class="d-flex align-items-center justify-content-center">
                                <div class="user-avatar">
                                    <?php echo strtoupper(substr($user['name'], 0, 1)); ?>
                                </div>
                                <div>
                                    <strong><?php echo htmlspecialchars($user['name']); ?></strong>
                                </div>
                            </div>
                        </td>
                        <td>
                            <i class="fas fa-phone me-1 text-muted"></i>
                            <?php echo htmlspecialchars($user['mobile']); ?>
                        </td>
                        <td>
                            <i class="fas fa-map-marker-alt me-1 text-muted"></i>
                            <?php echo htmlspecialchars($user['city'] ?? 'N/A'); ?>
                        </td>
                        <td>
                            <?php if (!empty($user['email'])) { ?>
                                <i class="fas fa-envelope me-1 text-muted"></i>
                                <?php echo htmlspecialchars($user['email']); ?>
                            <?php } else { ?>
                                <span class="text-muted">N/A</span>
                            <?php } ?>
                        </td>
                        <td>
                            <span class="badge bg-info">
                                <?php echo $user['appointment_count']; ?>
                            </span>
                        </td>
                        <td>
                            <small class="text-muted">
                                <?php echo date('M d, Y', strtotime($user['created_at'])); ?>
                            </small>
                        </td>
                        <td>
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-sm btn-outline-primary btn-action" 
                                        data-bs-toggle="modal" 
                                        data-bs-target="#userModal<?php echo $user['id']; ?>"
                                        title="View Details">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <form method="POST" class="d-inline" 
                                      onsubmit="return confirm('Are you sure you want to delete this user?')">
                                    <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                    <button type="submit" name="delete_user" 
                                            class="btn btn-sm btn-outline-danger btn-action"
                                            title="Delete User">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                <?php } ?>
            </tbody>
        </table>
    </div>
    
    <!-- User Details Modals -->
    <?php foreach ($users as $user) { 
        // Fetch appointments for this user
        $appointments_stmt = $pdo->prepare("
            SELECT * FROM appointments 
            WHERE user_id = ? 
            ORDER BY appointment_date DESC, time_slot ASC
        ");
        $appointments_stmt->execute([$user['id']]);
        $user_appointments = $appointments_stmt->fetchAll();
    ?>
        <div class="modal fade" id="userModal<?php echo $user['id']; ?>" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <div class="user-avatar me-2" style="width: 30px; height: 30px; font-size: 0.8rem;">
                                <?php echo strtoupper(substr($user['name'], 0, 1)); ?>
                            </div>
                            User Details - <?php echo htmlspecialchars($user['name']); ?>
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-6">
                                <strong>ID:</strong><br>
                                #<?php echo $user['id']; ?>
                            </div>
                            <div class="col-6">
                                <strong>Name:</strong><br>
                                <?php echo htmlspecialchars($user['name']); ?>
                            </div>
                        </div>
                        <hr>
                        <div class="row">
                            <div class="col-6">
                                <strong>Mobile:</strong><br>
                                <i class="fas fa-phone me-1 text-muted"></i>
                                <?php echo htmlspecialchars($user['mobile']); ?>
                            </div>
                            <div class="col-6">
                                <strong>City:</strong><br>
                                <i class="fas fa-map-marker-alt me-1 text-muted"></i>
                                <?php echo htmlspecialchars($user['city'] ?? 'N/A'); ?>
                            </div>
                        </div>
                        <?php if (!empty($user['email'])) { ?>
                        <hr>
                        <div class="row">
                            <div class="col-12">
                                <strong>Email:</strong><br>
                                <i class="fas fa-envelope me-1 text-muted"></i>
                                <?php echo htmlspecialchars($user['email']); ?>
                            </div>
                        </div>
                        <?php } ?>
                        <hr>
                        <div class="row">
                            <div class="col-6">
                                <strong>Total Appointments:</strong><br>
                                <span class="badge bg-info fs-6">
                                    <?php echo $user['appointment_count']; ?> appointments
                                </span>
                            </div>
                            <div class="col-6">
                                <strong>Joined:</strong><br>
                                <?php echo date('M d, Y H:i', strtotime($user['created_at'])); ?>
                            </div>
                        </div>
                        
                        <!-- Appointments Section -->
                        <hr>
                        <div class="row">
                            <div class="col-12">
                                <h6 class="mb-3">
                                    <i class="fas fa-calendar-check me-2"></i>Appointments
                                    <span class="badge bg-primary"><?php echo count($user_appointments); ?></span>
                                </h6>
                                <?php if (empty($user_appointments)) { ?>
                                    <div class="alert alert-info">
                                        <i class="fas fa-info-circle me-2"></i>No appointments found for this user.
                                    </div>
                                <?php } else { ?>
                                    <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
                                        <table class="table table-sm table-hover">
                                            <thead class="table-light sticky-top">
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Time</th>
                                                    <th>Type</th>
                                                    <th>Amount</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($user_appointments as $apt) { 
                                                    $status_colors = [
                                                        'pending' => 'warning',
                                                        'confirmed' => 'success',
                                                        'cancelled' => 'danger',
                                                        'completed' => 'info',
                                                        'pending_payment' => 'secondary'
                                                    ];
                                                    $status_names = [
                                                        'pending' => 'Pending',
                                                        'confirmed' => 'Confirmed',
                                                        'cancelled' => 'Cancelled',
                                                        'completed' => 'Completed',
                                                        'pending_payment' => 'Pending Payment'
                                                    ];
                                                    $type_names = [
                                                        'office_meeting' => 'Office',
                                                        'video_call' => 'Video',
                                                        'audio_call' => 'Audio'
                                                    ];
                                                    $color = $status_colors[$apt['status']] ?? 'secondary';
                                                    $status_name = $status_names[$apt['status']] ?? ucfirst($apt['status']);
                                                    $type_name = $type_names[$apt['consultation_type']] ?? $apt['consultation_type'];
                                                ?>
                                                    <tr>
                                                        <td><?php echo date('d M Y', strtotime($apt['appointment_date'])); ?></td>
                                                        <td><?php echo htmlspecialchars($apt['time_slot']); ?></td>
                                                        <td><?php echo $type_name; ?></td>
                                                        <td><strong>₹<?php echo number_format($apt['amount'], 2); ?></strong></td>
                                                        <td>
                                                            <span class="badge bg-<?php echo $color; ?>">
                                                                <?php echo $status_name; ?>
                                                            </span>
                                                        </td>
                                                    </tr>
                                                <?php } ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php } ?>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <a href="appointments.php?search=<?php echo urlencode($user['mobile']); ?>" class="btn btn-primary">
                            <i class="fas fa-calendar me-2"></i>View All Appointments
                        </a>
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    <?php } ?>
    
    <!-- Pagination -->
    <?php if ($total_pages > 1) { ?>
        <nav>
            <ul class="pagination">
                <?php 
                $search_param = !empty($search) ? '&search=' . urlencode($search) : '';
                ?>
                
                <?php if ($page > 1) { ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page - 1; ?><?php echo $search_param; ?>">Previous</a>
                    </li>
                <?php } ?>
                
                <?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="?page=<?php echo $i; ?><?php echo $search_param; ?>"><?php echo $i; ?></a>
                    </li>
                <?php } ?>
                
                <?php if ($page < $total_pages) { ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?><?php echo $search_param; ?>">Next</a>
                    </li>
                <?php } ?>
            </ul>
        </nav>
    <?php } ?>

    <script>
        function refreshUsers() {
            location.reload();
        }
        
        function exportUsers() {
            window.location.href = 'users.php?export=csv';
        }
        
        function deleteUser(userId) {
            if (confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="delete_user" value="1">
                    <input type="hidden" name="user_id" value="${userId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
    </script>

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