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

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

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

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name, b.branch_name, b.branch_code 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     LEFT JOIN branches b ON u.branch_id = b.branch_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) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
    $branch_name = $user_details['branch_name'];
    $staff_number = $user_details['staff_number'];
}

// Get search parameters
$search = $_GET['search'] ?? '';
$role_filter = $_GET['role_filter'] ?? '';
$status_filter = $_GET['status_filter'] ?? '';
$page = $_GET['page'] ?? 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Build query with filters
$where_conditions = array("1=1");
$params = array();
$param_types = "";

if (!empty($search)) {
    $where_conditions[] = "(u.full_name LIKE ? OR u.username LIKE ? OR u.email LIKE ? OR u.staff_number LIKE ?)";
    $search_param = "%$search%";
    $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 = implode(" AND ", $where_conditions);

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

// Get users with pagination
$query = "SELECT u.*, ur.role_name, b.branch_name 
          FROM users u 
          LEFT JOIN user_roles ur ON u.role_id = ur.role_id 
          LEFT JOIN branches b ON u.branch_id = b.branch_id 
          WHERE $where_clause
          ORDER BY u.created_at DESC 
          LIMIT ? OFFSET ?";

$stmt = $conn->prepare($query);
$params[] = $limit;
$params[] = $offset;
$param_types .= "ii";

if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$users = $stmt->get_result();

// Get roles for filter dropdown
$roles_query = "SELECT role_id, role_name FROM user_roles WHERE is_active = 1 ORDER BY role_name";
$roles_result = $conn->query($roles_query);

// Get user counts by status
$status_counts_query = "SELECT status, COUNT(*) as count FROM users GROUP BY status";
$status_counts_result = $conn->query($status_counts_query);
$status_counts = [];
while ($row = $status_counts_result->fetch_assoc()) {
    $status_counts[$row['status']] = $row['count'];
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Users & Staff - Healthcare EMR System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        /* Use the same styling from dashboard */
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        /* Filter Card */
        .filter-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;
            margin-bottom: 2rem;
        }
        
        /* Stats Cards */
        .stats-row {
            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;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        /* Table Card */
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .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: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        /* 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.05em;
        }
        
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #f1f5f9; color: #475569; }
        .status-suspended { background: #fee2e2; color: #991b1b; }
        .status-pending { background: #fef3c7; color: #92400e; }
        
        /* Action Buttons */
        .btn-action {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            margin: 0 0.25rem;
            transition: all 0.2s ease;
        }
        
        .btn-primary { background: #3b82f6; color: white; }
        .btn-primary:hover { background: #1d4ed8; color: white; }
        
        .btn-success { background: #059669; color: white; }
        .btn-success:hover { background: #047857; color: white; }
        
        .btn-warning { background: #d97706; color: white; }
        .btn-warning:hover { background: #b45309; color: white; }
        
        .btn-danger { background: #dc2626; color: white; }
        .btn-danger:hover { background: #b91c1c; color: white; }
        
        /* Pagination */
        .pagination-wrapper {
            padding: 1.5rem;
            background: #f8fafc;
            border-top: 1px solid #e2e8f0;
            display: flex;
            justify-content: between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .pagination-info {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .pagination {
            display: flex;
            gap: 0.5rem;
            margin: 0;
        }
        
        .page-link {
            padding: 0.5rem 0.75rem;
            background: white;
            border: 1px solid #e2e8f0;
            color: #374151;
            text-decoration: none;
            border-radius: 6px;
            font-size: 0.875rem;
        }
        
        .page-link:hover {
            background: #f8fafc;
            border-color: #3b82f6;
            color: #3b82f6;
        }
        
        .page-link.active {
            background: #3b82f6;
            border-color: #3b82f6;
            color: white;
        }
        
        /* Form Controls */
        .form-control, .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-primary {
            background: #3b82f6;
            color: white;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
        }
        
        .btn-outline-secondary {
            background: transparent;
            border: 1px solid #e2e8f0;
            color: #64748b;
        }
        
        .btn-outline-secondary:hover {
            background: #f8fafc;
            border-color: #64748b;
        }
        
        /* Avatar */
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #3b82f6;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .table-header {
                flex-direction: column;
                gap: 1rem;
                align-items: stretch;
            }
            
            .data-table {
                font-size: 0.75rem;
            }
            
            .data-table th,
            .data-table td {
                padding: 0.5rem;
            }
        }
        
        /* Footer spacing fix */
        .main-content {
            padding-bottom: 2rem;
        }
        
        .page-content {
            margin-bottom: 3rem;
        }
    </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">
                        <h1 class="page-title">Users & Staff Management</h1>
                        <p class="page-subtitle">Manage system users, staff members, and their roles</p>
                    </div>

                    <!-- Stats Row -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $status_counts['ACTIVE'] ?? 0; ?></div>
                            <div class="stat-label">Active Users</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $status_counts['PENDING'] ?? 0; ?></div>
                            <div class="stat-label">Pending Users</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $status_counts['INACTIVE'] ?? 0; ?></div>
                            <div class="stat-label">Inactive Users</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $total_users; ?></div>
                            <div class="stat-label">Total Users</div>
                        </div>
                    </div>

                    <!-- Filter Card -->
                    <div class="filter-card">
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">Search</label>
                                <input type="text" class="form-control" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="Search by name, username, email...">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Role</label>
                                <select class="form-select" name="role_filter">
                                    <option value="">All Roles</option>
                                    <?php while ($role = $roles_result->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="col-md-3">
                                <label class="form-label">Status</label>
                                <select class="form-select" name="status_filter">
                                    <option value="">All Status</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="PENDING" <?php echo $status_filter == 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="SUSPENDED" <?php echo $status_filter == 'SUSPENDED' ? 'selected' : ''; ?>>Suspended</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">&nbsp;</label>
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary">Filter</button>
                                    <a href="list_users.php" class="btn btn-outline-secondary">Clear</a>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Users Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Users List (<?php echo $total_users; ?> total)</h3>
                            <a href="add_user.php" class="btn btn-primary">
                                <i class="ph-user-plus me-1"></i> Add New User
                            </a>
                        </div>
                        
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>User</th>
                                    <th>Role</th>
                                    <th>Contact</th>
                                    <th>Branch</th>
                                    <th>Status</th>
                                    <th>Last Login</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($user = $users->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="user-avatar me-3">
                                                <?php echo strtoupper(substr($user['full_name'], 0, 2)); ?>
                                            </div>
                                            <div>
                                                <div style="font-weight: 600; color: #1e293b;">
                                                    <?php echo htmlspecialchars($user['full_name']); ?>
                                                </div>
                                                <div style="color: #64748b; font-size: 0.75rem;">
                                                    @<?php echo htmlspecialchars($user['username']); ?>
                                                    <?php if ($user['staff_number']): ?>
                                                        | <?php echo htmlspecialchars($user['staff_number']); ?>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="status-badge status-active">
                                            <?php echo htmlspecialchars($user['role_name']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div style="font-weight: 500; color: #1e293b;">
                                            <?php echo htmlspecialchars($user['email']); ?>
                                        </div>
                                        <?php if ($user['phone_number']): ?>
                                            <div style="color: #64748b; font-size: 0.75rem;">
                                                <?php echo htmlspecialchars($user['phone_number']); ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($user['branch_name']): ?>
                                            <span style="color: #1e293b; font-weight: 500;">
                                                <?php echo htmlspecialchars($user['branch_name']); ?>
                                            </span>
                                        <?php else: ?>
                                            <span style="color: #64748b;">Not assigned</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php 
                                        $status_class = match($user['status']) {
                                            'ACTIVE' => 'status-active',
                                            'INACTIVE' => 'status-inactive',
                                            'PENDING' => 'status-pending',
                                            'SUSPENDED' => 'status-suspended',
                                            default => 'status-inactive'
                                        };
                                        ?>
                                        <span class="status-badge <?php echo $status_class; ?>">
                                            <?php echo ucfirst(strtolower($user['status'])); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($user['last_login']): ?>
                                            <span style="color: #1e293b;">
                                                <?php echo date('M j, Y', strtotime($user['last_login'])); ?>
                                            </span>
                                            <div style="color: #64748b; font-size: 0.75rem;">
                                                <?php echo date('g:i A', strtotime($user['last_login'])); ?>
                                            </div>
                                        <?php else: ?>
                                            <span style="color: #64748b;">Never</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="d-flex gap-1">
                                            <a href="view_user.php?id=<?php echo $user['user_id']; ?>" class="btn-action btn-primary" title="View Details">
                                                <i class="ph-eye"></i>
                                            </a>
                                            <a href="edit_user.php?id=<?php echo $user['user_id']; ?>" class="btn-action btn-warning" title="Edit User">
                                                <i class="ph-pencil"></i>
                                            </a>
                                            <?php if ($user['status'] == 'ACTIVE'): ?>
                                                <a href="suspend_user.php?id=<?php echo $user['user_id']; ?>" class="btn-action btn-danger" title="Suspend User" onclick="return confirm('Are you sure you want to suspend this user?')">
                                                    <i class="ph-prohibit"></i>
                                                </a>
                                            <?php else: ?>
                                                <a href="activate_user.php?id=<?php echo $user['user_id']; ?>" class="btn-action btn-success" title="Activate User">
                                                    <i class="ph-check"></i>
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>

                        <!-- Pagination -->
                        <div class="pagination-wrapper">
                            <div class="pagination-info">
                                Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $total_users); ?> of <?php echo $total_users; ?> entries
                            </div>
                            
                            <?php if ($total_pages > 1): ?>
                                <div class="pagination">
                                    <?php if ($page > 1): ?>
                                        <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&role_filter=<?php echo $role_filter; ?>&status_filter=<?php echo $status_filter; ?>" class="page-link">
                                            <i class="ph-caret-left"></i>
                                        </a>
                                    <?php endif; ?>
                                    
                                    <?php 
                                    $start = max(1, $page - 2);
                                    $end = min($total_pages, $page + 2);
                                    
                                    for ($i = $start; $i <= $end; $i++): 
                                    ?>
                                        <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&role_filter=<?php echo $role_filter; ?>&status_filter=<?php echo $status_filter; ?>" 
                                           class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                                            <?php echo $i; ?>
                                        </a>
                                    <?php endfor; ?>
                                    
                                    <?php if ($page < $total_pages): ?>
                                        <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&role_filter=<?php echo $role_filter; ?>&status_filter=<?php echo $status_filter; ?>" class="page-link">
                                            <i class="ph-caret-right"></i>
                                        </a>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        // Auto-submit form on filter change
        $(document).ready(function() {
            $('.form-select').on('change', function() {
                $(this).closest('form').submit();
            });
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>

<?php $conn->close(); ?>