<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/menu_config.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in and has Super Admin role
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get user details and role verification
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details || $user_details['role_name'] !== 'Super Admin') {
    header('Location: dashboard.php');
    exit();
}

$full_name = $user_details['full_name'];
$role_name = $user_details['role_name'];

// Handle user actions (suspend, activate, delete)
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'suspend_user':
            $target_user_id = (int)$_POST['user_id'];
            if ($target_user_id !== $user_id) { // Prevent self-suspension
                $sql_suspend = "UPDATE users SET status = 'SUSPENDED' WHERE user_id = ?";
                $stmt_suspend = $conn->prepare($sql_suspend);
                $stmt_suspend->bind_param("i", $target_user_id);
                if ($stmt_suspend->execute()) {
                    $message = "User suspended successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error suspending user.";
                    $message_type = "error";
                }
            }
            break;
            
        case 'activate_user':
            $target_user_id = (int)$_POST['user_id'];
            $sql_activate = "UPDATE users SET status = 'ACTIVE' WHERE user_id = ?";
            $stmt_activate = $conn->prepare($sql_activate);
            $stmt_activate->bind_param("i", $target_user_id);
            if ($stmt_activate->execute()) {
                $message = "User activated successfully!";
                $message_type = "success";
            } else {
                $message = "Error activating user.";
                $message_type = "error";
            }
            break;
            
        case 'reset_password':
            $target_user_id = (int)$_POST['user_id'];
            $new_password = 'laundry123'; // Default password
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            
            $sql_reset = "UPDATE users SET password = ?, last_password_change = CURRENT_TIMESTAMP WHERE user_id = ?";
            $stmt_reset = $conn->prepare($sql_reset);
            $stmt_reset->bind_param("si", $hashed_password, $target_user_id);
            if ($stmt_reset->execute()) {
                $message = "Password reset successfully! New password: $new_password";
                $message_type = "success";
            } else {
                $message = "Error resetting password.";
                $message_type = "error";
            }
            break;
    }
}

// Handle search and filter parameters
$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';
$role_filter = isset($_GET['role']) ? $_GET['role'] : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 15;
$offset = ($page - 1) * $limit;

// Build WHERE clause for filtering
$where_conditions = [];
$params = [];
$param_types = '';

if (!empty($search_query)) {
    $where_conditions[] = "(u.username LIKE ? OR u.full_name LIKE ? OR u.email LIKE ? OR u.phone LIKE ?)";
    $search_param = '%' . $search_query . '%';
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
    $param_types .= 'ssss';
}

if (!empty($role_filter)) {
    $where_conditions[] = "u.role_id = ?";
    $params[] = $role_filter;
    $param_types .= 'i';
}

if (!empty($status_filter)) {
    $where_conditions[] = "u.status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

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

// Get total count for pagination
$count_sql = "SELECT COUNT(*) as total 
              FROM users u 
              INNER JOIN user_roles ur ON u.role_id = ur.role_id 
              $where_clause";
$count_stmt = $conn->prepare($count_sql);
if (!empty($params)) {
    $count_stmt->bind_param($param_types, ...$params);
}
$count_stmt->execute();
$total_records = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $limit);

// Get users with role information and activity stats
$sql_users = "SELECT 
    u.*,
    ur.role_name,
    ur.description as role_description,
    COALESCE(order_stats.total_orders, 0) as total_orders_created,
    COALESCE(customer_stats.total_customers, 0) as total_customers_created,
    COALESCE(GREATEST(
        COALESCE(order_stats.last_order_date, '1900-01-01'),
        COALESCE(customer_stats.last_customer_date, '1900-01-01')
    ), NULL) as last_activity_date,
    DATEDIFF(CURRENT_DATE, DATE(u.last_login)) as days_since_login
FROM users u
INNER JOIN user_roles ur ON u.role_id = ur.role_id
LEFT JOIN (
    SELECT 
        o.created_by,
        COUNT(*) as total_orders,
        MAX(o.order_date) as last_order_date
    FROM orders o
    GROUP BY o.created_by
) order_stats ON u.user_id = order_stats.created_by
LEFT JOIN (
    SELECT 
        c.created_by,
        COUNT(*) as total_customers,
        MAX(c.registration_date) as last_customer_date
    FROM customers c
    GROUP BY c.created_by
) customer_stats ON u.user_id = customer_stats.created_by
$where_clause
ORDER BY u.created_at DESC, u.user_id DESC
LIMIT ? OFFSET ?";

$final_params = array_merge($params, [$limit, $offset]);
$final_param_types = $param_types . 'ii';

$stmt_users = $conn->prepare($sql_users);
$stmt_users->bind_param($final_param_types, ...$final_params);
$stmt_users->execute();
$result_users = $stmt_users->get_result();

// Get summary statistics
$sql_summary = "SELECT 
    COUNT(*) as total_users,
    SUM(CASE WHEN u.status = 'ACTIVE' THEN 1 ELSE 0 END) as active_users,
    SUM(CASE WHEN u.status = 'INACTIVE' THEN 1 ELSE 0 END) as inactive_users,
    SUM(CASE WHEN u.status = 'SUSPENDED' THEN 1 ELSE 0 END) as suspended_users,
    SUM(CASE WHEN u.last_login >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) THEN 1 ELSE 0 END) as active_last_30_days,
    SUM(CASE WHEN u.last_login >= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY) THEN 1 ELSE 0 END) as active_last_7_days
FROM users u 
INNER JOIN user_roles ur ON u.role_id = ur.role_id 
$where_clause";

$stmt_summary = $conn->prepare($sql_summary);
if (!empty($params)) {
    $stmt_summary->bind_param($param_types, ...$params);
}
$stmt_summary->execute();
$summary = $stmt_summary->get_result()->fetch_assoc();

// Get roles for filter dropdown
$sql_roles = "SELECT role_id, role_name FROM user_roles ORDER BY role_name";
$result_roles = $conn->query($sql_roles);

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'All Users - User Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Header Section */
        .page-header {
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .header-title h1 {
            font-size: 1.875rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .header-subtitle {
            opacity: 0.9;
            font-size: 1rem;
        }
        
        .header-actions {
            display: flex;
            gap: 1rem;
            align-items: center;
        }
        
        .btn-primary {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.2s ease;
        }
        
        .btn-primary:hover {
            background: rgba(255, 255, 255, 0.3);
            color: white;
            transform: translateY(-1px);
        }
        
        /* Alert Messages */
        .alert {
            padding: 1rem 1.5rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            border: none;
            font-weight: 500;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
            border-left: 4px solid #22c55e;
        }
        
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }
        
        /* Statistics Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            transition: all 0.2s ease;
        }
        
        .stat-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }
        
        .stat-title {
            font-size: 0.875rem;
            font-weight: 500;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.025em;
            margin-bottom: 0.5rem;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .stat-change {
            font-size: 0.875rem;
            color: #64748b;
        }
        
        /* Filters Section */
        .filters-section {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .filters-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            align-items: end;
        }
        
        .form-group {
            margin-bottom: 0;
        }
        
        .form-label {
            font-size: 0.875rem;
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .form-control {
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
            transition: border-color 0.2s ease;
            width: 100%;
        }
        
        .form-control:focus {
            border-color: #6366f1;
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
            outline: none;
        }
        
        .btn-secondary, .btn-outline-secondary {
            padding: 0.75rem 1.5rem;
            font-weight: 600;
            border-radius: 8px;
            font-size: 0.875rem;
            transition: all 0.2s ease;
            cursor: pointer;
            border: 1px solid;
        }
        
        .btn-secondary {
            background: #6366f1;
            border-color: #6366f1;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #4f46e5;
            border-color: #4f46e5;
            transform: translateY(-1px);
        }
        
        .btn-outline-secondary {
            background: transparent;
            border-color: #d1d5db;
            color: #374151;
        }
        
        .btn-outline-secondary:hover {
            background: #f3f4f6;
            border-color: #9ca3af;
        }
        
        /* Users Table */
        .users-table-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 700;
            color: #1e293b;
            margin: 0;
        }
        
        .results-info {
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .users-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .users-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #374151;
            border-bottom: 1px solid #e2e8f0;
            white-space: nowrap;
        }
        
        .users-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
            vertical-align: middle;
        }
        
        .users-table tbody tr:hover {
            background: #f8fafc;
        }
        
        /* User Avatar */
        .user-avatar {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            background: #6366f1;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 1rem;
            flex-shrink: 0;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .user-details {
            min-width: 0;
        }
        
        .user-name {
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .user-username {
            color: #6366f1;
            font-size: 0.875rem;
            font-weight: 600;
            margin-bottom: 0.25rem;
        }
        
        .user-meta {
            color: #64748b;
            font-size: 0.75rem;
            line-height: 1.4;
        }
        
        /* Status Badges */
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.025em;
        }
        
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #f3f4f6; color: #374151; }
        .status-suspended { background: #fee2e2; color: #991b1b; }
        
        .role-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            background: #e0e7ff;
            color: #3730a3;
        }
        
        /* Activity Indicators */
        .activity-indicator {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.75rem;
        }
        
        .activity-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
        }
        
        .activity-online { background: #22c55e; }
        .activity-recent { background: #eab308; }
        .activity-offline { background: #94a3b8; }
        
        /* Action Buttons */
        .action-buttons {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }
        
        .btn-sm {
            padding: 0.375rem 0.75rem;
            font-size: 0.75rem;
            border-radius: 6px;
            font-weight: 600;
            border: 1px solid;
            cursor: pointer;
            transition: all 0.2s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .btn-info {
            background: #0ea5e9;
            border-color: #0ea5e9;
            color: white;
        }
        
        .btn-info:hover {
            background: #0284c7;
            border-color: #0284c7;
        }
        
        .btn-warning {
            background: #f59e0b;
            border-color: #f59e0b;
            color: white;
        }
        
        .btn-warning:hover {
            background: #d97706;
            border-color: #d97706;
        }
        
        .btn-success {
            background: #10b981;
            border-color: #10b981;
            color: white;
        }
        
        .btn-success:hover {
            background: #059669;
            border-color: #059669;
        }
        
        .btn-danger {
            background: #ef4444;
            border-color: #ef4444;
            color: white;
        }
        
        .btn-danger:hover {
            background: #dc2626;
            border-color: #dc2626;
        }
        
        /* Pagination */
        .pagination-section {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-top: 2rem;
        }
        
        .pagination-info {
            color: #64748b;
            font-size: 0.875rem;
            margin-bottom: 1rem;
        }
        
        .pagination {
            display: flex;
            gap: 0.5rem;
            justify-content: center;
            flex-wrap: wrap;
        }
        
        .pagination a, .pagination span {
            padding: 0.5rem 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            text-decoration: none;
            color: #374151;
            font-weight: 500;
            transition: all 0.2s ease;
        }
        
        .pagination a:hover {
            background: #f3f4f6;
            border-color: #9ca3af;
        }
        
        .pagination .current {
            background: #6366f1;
            border-color: #6366f1;
            color: white;
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .header-content {
                flex-direction: column;
                text-align: center;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .filters-grid {
                grid-template-columns: 1fr;
            }
            
            .users-table-container {
                overflow-x: auto;
            }
            
            .users-table {
                min-width: 900px;
            }
            
            .action-buttons {
                flex-direction: column;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="header-content">
                            <div class="header-title">
                                <h1>All Users Management</h1>
                                <div class="header-subtitle">Manage system users, roles, and permissions</div>
                            </div>
                            <div class="header-actions">
                                <a href="add_user.php" class="btn-primary">
                                    <i class="ph-plus"></i> Add User
                                </a>
                                <a href="user_roles.php" class="btn-primary">
                                    <i class="ph-users"></i> Manage Roles
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Alert Messages -->
                    <?php if (!empty($message)): ?>
                    <div class="alert alert-<?php echo $message_type; ?>">
                        <?php echo htmlspecialchars($message); ?>
                    </div>
                    <?php endif; ?>

                    <!-- Statistics Cards -->
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-title">Total Users</div>
                            <div class="stat-value"><?php echo number_format($summary['total_users']); ?></div>
                            <div class="stat-change">System-wide users</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Active Users</div>
                            <div class="stat-value"><?php echo number_format($summary['active_users']); ?></div>
                            <div class="stat-change">Currently enabled</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Active Last 7 Days</div>
                            <div class="stat-value"><?php echo number_format($summary['active_last_7_days']); ?></div>
                            <div class="stat-change">Recent activity</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Active Last 30 Days</div>
                            <div class="stat-value"><?php echo number_format($summary['active_last_30_days']); ?></div>
                            <div class="stat-change">Monthly activity</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Suspended Users</div>
                            <div class="stat-value"><?php echo number_format($summary['suspended_users']); ?></div>
                            <div class="stat-change">Need attention</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Inactive Users</div>
                            <div class="stat-value"><?php echo number_format($summary['inactive_users']); ?></div>
                            <div class="stat-change">Disabled accounts</div>
                        </div>
                    </div>

                    <!-- Filters Section -->
                    <div class="filters-section">
                        <form method="GET" class="filters-form">
                            <div class="filters-grid">
                                <div class="form-group">
                                    <label class="form-label">Search Users</label>
                                    <input type="text" name="search" class="form-control" 
                                           placeholder="Name, username, email, phone..." 
                                           value="<?php echo htmlspecialchars($search_query); ?>">
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Role</label>
                                    <select name="role" class="form-control">
                                        <option value="">All Roles</option>
                                        <?php while($role = $result_roles->fetch_assoc()): ?>
                                        <option value="<?php echo $role['role_id']; ?>" 
                                                <?php echo $role_filter == $role['role_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($role['role_name']); ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Status</label>
                                    <select name="status" class="form-control">
                                        <option value="">All Statuses</option>
                                        <option value="ACTIVE" <?php echo $status_filter === 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                        <option value="INACTIVE" <?php echo $status_filter === 'INACTIVE' ? 'selected' : ''; ?>>Inactive</option>
                                        <option value="SUSPENDED" <?php echo $status_filter === 'SUSPENDED' ? 'selected' : ''; ?>>Suspended</option>
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <button type="submit" class="btn-secondary">
                                        <i class="ph-funnel"></i> Filter
                                    </button>
                                    <a href="list_users.php" class="btn-outline-secondary">
                                        <i class="ph-x"></i> Clear
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Users Table -->
                    <div class="users-table-container">
                        <div class="table-header">
                            <h3 class="table-title">System Users</h3>
                            <div class="results-info">
                                Showing <?php echo number_format(min($limit, $total_records)); ?> of <?php echo number_format($total_records); ?> users
                            </div>
                        </div>
                        
                        <table class="users-table">
                            <thead>
                                <tr>
                                    <th>User Details</th>
                                    <th>Role</th>
                                    <th>Status</th>
                                    <th>Activity</th>
                                    <th>Performance</th>
                                    <th>Last Login</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($result_users->num_rows > 0): ?>
                                    <?php while($user = $result_users->fetch_assoc()): ?>
                                    <tr>
                                        <td>
                                            <div class="user-info">
                                                <div class="user-avatar">
                                                    <?php echo strtoupper(substr($user['full_name'], 0, 2)); ?>
                                                </div>
                                                <div class="user-details">
                                                    <div class="user-name"><?php echo htmlspecialchars($user['full_name']); ?></div>
                                                    <div class="user-username">@<?php echo htmlspecialchars($user['username']); ?></div>
                                                    <div class="user-meta">
                                                        📧 <?php echo htmlspecialchars($user['email']); ?>
                                                        <?php if ($user['phone']): ?>
                                                        <br>📱 <?php echo htmlspecialchars($user['phone']); ?>
                                                        <?php endif; ?>
                                                        <br>ID: <?php echo $user['user_id']; ?> | Created: <?php echo date('M j, Y', strtotime($user['created_at'])); ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                        
                                        <td>
                                            <span class="role-badge">
                                                <?php echo htmlspecialchars($user['role_name']); ?>
                                            </span>
                                            <div class="user-meta" style="margin-top: 0.5rem;">
                                                <?php echo htmlspecialchars($user['role_description'] ?: 'No description'); ?>
                                            </div>
                                        </td>
                                        
                                        <td>
                                            <span class="status-badge status-<?php echo strtolower($user['status']); ?>">
                                                <?php echo $user['status']; ?>
                                            </span>
                                            <?php if ($user['failed_attempts'] > 0): ?>
                                            <div class="user-meta" style="margin-top: 0.5rem; color: #dc2626;">
                                                ⚠️ <?php echo $user['failed_attempts']; ?> failed attempts
                                            </div>
                                            <?php endif; ?>
                                        </td>
                                        
                                        <td>
                                            <?php 
                                            $days_since_login = $user['days_since_login'];
                                            if ($days_since_login === null || $user['last_login'] === null): 
                                            ?>
                                                <div class="activity-indicator">
                                                    <div class="activity-dot activity-offline"></div>
                                                    <span>Never logged in</span>
                                                </div>
                                            <?php elseif ($days_since_login <= 1): ?>
                                                <div class="activity-indicator">
                                                    <div class="activity-dot activity-online"></div>
                                                    <span>Online recently</span>
                                                </div>
                                            <?php elseif ($days_since_login <= 7): ?>
                                                <div class="activity-indicator">
                                                    <div class="activity-dot activity-recent"></div>
                                                    <span><?php echo $days_since_login; ?> days ago</span>
                                                </div>
                                            <?php else: ?>
                                                <div class="activity-indicator">
                                                    <div class="activity-dot activity-offline"></div>
                                                    <span><?php echo $days_since_login; ?> days ago</span>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                        
                                        <td>
                                            <div class="user-meta">
                                                <div>📋 <?php echo number_format($user['total_orders_created']); ?> orders created</div>
                                                <div>👥 <?php echo number_format($user['total_customers_created']); ?> customers added</div>
                                                <?php if ($user['last_activity_date']): ?>
                                                <div>📅 Last activity: <?php echo date('M j, Y', strtotime($user['last_activity_date'])); ?></div>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        
                                        <td>
                                            <?php if ($user['last_login']): ?>
                                                <div style="font-weight: 600; color: #1e293b;">
                                                    <?php echo date('M j, Y', strtotime($user['last_login'])); ?>
                                                </div>
                                                <div class="user-meta">
                                                    <?php echo date('g:i A', strtotime($user['last_login'])); ?>
                                                </div>
                                            <?php else: ?>
                                                <span class="user-meta">Never</span>
                                            <?php endif; ?>
                                        </td>
                                        
                                        <td>
                                            <div class="action-buttons">
                                                <a href="view_user.php?id=<?php echo $user['user_id']; ?>" 
                                                   class="btn-sm btn-info" title="View User">
                                                    <i class="ph-eye"></i>
                                                </a>
                                                <a href="edit_user.php?id=<?php echo $user['user_id']; ?>" 
                                                   class="btn-sm btn-warning" title="Edit User">
                                                    <i class="ph-pencil"></i>
                                                </a>
                                                
                                                <?php if ($user['user_id'] !== $user_id): // Prevent self-actions ?>
                                                    <?php if ($user['status'] === 'ACTIVE'): ?>
                                                    <form method="POST" style="display: inline;" onsubmit="return confirm('Suspend this user?')">
                                                        <input type="hidden" name="action" value="suspend_user">
                                                        <input type="hidden" name="user_id" value="<?php echo $user['user_id']; ?>">
                                                        <button type="submit" class="btn-sm btn-danger" title="Suspend User">
                                                            <i class="ph-user-minus"></i>
                                                        </button>
                                                    </form>
                                                    <?php else: ?>
                                                    <form method="POST" style="display: inline;" onsubmit="return confirm('Activate this user?')">
                                                        <input type="hidden" name="action" value="activate_user">
                                                        <input type="hidden" name="user_id" value="<?php echo $user['user_id']; ?>">
                                                        <button type="submit" class="btn-sm btn-success" title="Activate User">
                                                            <i class="ph-user-plus"></i>
                                                        </button>
                                                    </form>
                                                    <?php endif; ?>
                                                    
                                                    <form method="POST" style="display: inline;" onsubmit="return confirm('Reset password for this user? New password will be: laundry123')">
                                                        <input type="hidden" name="action" value="reset_password">
                                                        <input type="hidden" name="user_id" value="<?php echo $user['user_id']; ?>">
                                                        <button type="submit" class="btn-sm btn-warning" title="Reset Password">
                                                            <i class="ph-lock-key"></i>
                                                        </button>
                                                    </form>
                                                <?php else: ?>
                                                    <span class="btn-sm" style="background: #f3f4f6; color: #64748b; border-color: #e2e8f0;">
                                                        Current User
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="7" style="text-align: center; padding: 3rem; color: #64748b;">
                                            <div style="font-size: 3rem; margin-bottom: 1rem;">👥</div>
                                            <div style="font-size: 1.125rem; font-weight: 600; margin-bottom: 0.5rem;">No Users Found</div>
                                            <div>Try adjusting your search criteria or add a new user.</div>
                                            <a href="add_user.php" style="color: #6366f1; text-decoration: none; font-weight: 600; margin-top: 1rem; display: inline-block;">
                                                Add New User →
                                            </a>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                    <div class="pagination-section">
                        <div class="pagination-info">
                            Showing <?php echo (($page - 1) * $limit) + 1; ?> to <?php echo min($page * $limit, $total_records); ?> 
                            of <?php echo number_format($total_records); ?> users
                        </div>
                        
                        <div class="pagination">
                            <?php if ($page > 1): ?>
                                <a href="?page=1<?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>">First</a>
                                <a href="?page=<?php echo $page - 1; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>">Previous</a>
                            <?php endif; ?>
                            
                            <?php
                            $start_page = max(1, $page - 2);
                            $end_page = min($total_pages, $page + 2);
                            
                            for ($i = $start_page; $i <= $end_page; $i++):
                            ?>
                                <?php if ($i == $page): ?>
                                    <span class="current"><?php echo $i; ?></span>
                                <?php else: ?>
                                    <a href="?page=<?php echo $i; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>"><?php echo $i; ?></a>
                                <?php endif; ?>
                            <?php endfor; ?>
                            
                            <?php if ($page < $total_pages): ?>
                                <a href="?page=<?php echo $page + 1; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>">Next</a>
                                <a href="?page=<?php echo $total_pages; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>">Last</a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
</body>
</html>