<?php
/**
 * Enterprise HRM ERP System - User Management
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

$pageTitle = 'User Management';
$currentModule = 'settings';

$siteId = getCurrentSiteId();
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Filters
$search = sanitize($_GET['search'] ?? '');
$roleId = isset($_GET['role_id']) ? (int)$_GET['role_id'] : 0;
$status = sanitize($_GET['status'] ?? '');

// Data Isolation: Super Admin can see all users, HR Admin can see their site users
if (isSuperAdmin()) {
    // Super Admin can see all users
    $where = ["1=1"];
    $params = [];
} else {
    // HR Admin can only see users from their accessible sites
    $accessibleSiteIds = getAccessibleSiteIds();
    if (!empty($accessibleSiteIds)) {
        $placeholders = implode(',', array_fill(0, count($accessibleSiteIds), '?'));
        $where = ["EXISTS (SELECT 1 FROM user_sites us WHERE us.user_id = u.user_id AND us.site_id IN ($placeholders))"];
        $params = $accessibleSiteIds;
    } else {
        $where = ["1=0"];
        $params = [];
    }
}

if (!empty($search)) {
    $where[] = "(u.username LIKE ? OR u.email LIKE ? OR u.full_name LIKE ?)";
    $searchParam = "%{$search}%";
    $params = array_merge($params, [$searchParam, $searchParam, $searchParam]);
}

if ($roleId > 0) {
    $where[] = "u.role_id = ?";
    $params[] = $roleId;
}

if (!empty($status)) {
    $where[] = "u.user_status = ?";
    $params[] = $status;
}

$whereClause = implode(' AND ', $where);

try {
    $db = getDB();
    
    // Get roles for filter
    $stmt = $db->prepare("SELECT role_id, role_name FROM roles ORDER BY role_name");
    $stmt->execute();
    $roles = $stmt->fetchAll();
    
    // Get total count
    $countSql = "SELECT COUNT(*) FROM users u WHERE {$whereClause}";
    $stmt = $db->prepare($countSql);
    $stmt->execute($params);
    $totalRecords = $stmt->fetchColumn();
    $totalPages = ceil($totalRecords / $perPage);
    
    // Get users
    $sql = "
        SELECT 
            u.*,
            r.role_name, r.role_code
        FROM users u
        INNER JOIN roles r ON u.role_id = r.role_id
        WHERE {$whereClause}
        ORDER BY u.created_at DESC
        LIMIT ? OFFSET ?
    ";
    $params[] = $perPage;
    $params[] = $offset;
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $users = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("User list error: " . $e->getMessage());
    $users = [];
    $roles = [];
    $totalRecords = 0;
    $totalPages = 0;
}

include __DIR__ . '/../includes/header.php';
?>

<div class="table-container">
    <div class="table-header">
        <h2 class="table-title">User Management</h2>
        <div class="table-actions">
            <a href="<?php echo BASE_URL; ?>/admin/users_create.php" class="btn btn-primary">Add New User</a>
        </div>
    </div>
    
    <div class="table-filters">
        <div class="filter-group">
            <label>Search</label>
            <input type="text" name="search" class="form-control" placeholder="Username, Email, Name..." 
                   value="<?php echo htmlspecialchars($search); ?>" 
                   onkeypress="if(event.key==='Enter') filterTable()">
        </div>
        <div class="filter-group">
            <label>Role</label>
            <select name="role_id" class="form-control" onchange="filterTable()">
                <option value="0">All Roles</option>
                <?php foreach ($roles as $role): ?>
                <option value="<?php echo $role['role_id']; ?>" <?php echo $roleId == $role['role_id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($role['role_name']); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="filter-group">
            <label>Status</label>
            <select name="status" class="form-control" onchange="filterTable()">
                <option value="">All Status</option>
                <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>Active</option>
                <option value="inactive" <?php echo $status === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                <option value="locked" <?php echo $status === 'locked' ? 'selected' : ''; ?>>Locked</option>
            </select>
        </div>
        <div class="filter-group">
            <button type="button" class="btn btn-secondary" onclick="resetFilters()">Reset</button>
        </div>
    </div>
    
    <?php if (count($users) > 0): ?>
    <table class="data-table">
        <thead>
            <tr>
                <th class="sortable">Username</th>
                <th class="sortable">Full Name</th>
                <th class="sortable">Email</th>
                <th class="sortable">Role</th>
                <th class="sortable">Status</th>
                <th class="sortable">Last Login</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($users as $user): ?>
            <tr>
                <td><strong><?php echo htmlspecialchars($user['username']); ?></strong></td>
                <td><?php echo htmlspecialchars($user['full_name']); ?></td>
                <td><?php echo htmlspecialchars($user['email']); ?></td>
                <td>
                    <span class="status-badge" style="background: #e0e7ff; color: #3730a3;">
                        <?php echo htmlspecialchars($user['role_name']); ?>
                    </span>
                </td>
                <td>
                    <span class="status-badge status-<?php echo htmlspecialchars($user['user_status']); ?>">
                        <?php echo ucfirst($user['user_status']); ?>
                    </span>
                </td>
                <td><?php echo $user['last_login'] ? formatDateTime($user['last_login']) : 'Never'; ?></td>
                <td class="table-actions-cell">
                    <a href="<?php echo BASE_URL; ?>/admin/users_view.php?id=<?php echo $user['user_id']; ?>" 
                       class="btn btn-sm btn-secondary">View</a>
                    <a href="<?php echo BASE_URL; ?>/admin/users_edit.php?id=<?php echo $user['user_id']; ?>" 
                       class="btn btn-sm btn-primary">Edit</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    
    <div class="table-footer">
        <div class="table-info">
            Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $perPage, $totalRecords); ?> of <?php echo number_format($totalRecords); ?> users
        </div>
        <div class="pagination">
            <?php if ($page > 1): ?>
            <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&role_id=<?php echo $roleId; ?>&status=<?php echo urlencode($status); ?>" 
               class="btn btn-sm">Previous</a>
            <?php endif; ?>
            <span class="pagination-info">Page <?php echo $page; ?> of <?php echo $totalPages; ?></span>
            <?php if ($page < $totalPages): ?>
            <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&role_id=<?php echo $roleId; ?>&status=<?php echo urlencode($status); ?>" 
               class="btn btn-sm">Next</a>
            <?php endif; ?>
        </div>
    </div>
    <?php else: ?>
    <div class="table-empty">
        <div class="table-empty-icon">👤</div>
        <div class="table-empty-message">No users found</div>
        <div class="table-empty-submessage">
            <a href="<?php echo BASE_URL; ?>/admin/users_create.php" class="btn btn-primary">Add First User</a>
        </div>
    </div>
    <?php endif; ?>
</div>

<style>
.status-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 11px;
    font-weight: 500;
    text-transform: uppercase;
}

.status-active {
    background-color: #d1fae5;
    color: #065f46;
}

.status-inactive {
    background-color: #e5e7eb;
    color: #374151;
}

.status-locked {
    background-color: #fee2e2;
    color: #991b1b;
}
</style>

<script>
function filterTable() {
    const search = document.querySelector('[name="search"]').value;
    const roleId = document.querySelector('[name="role_id"]').value;
    const status = document.querySelector('[name="status"]').value;
    
    const params = new URLSearchParams();
    if (search) params.append('search', search);
    if (roleId) params.append('role_id', roleId);
    if (status) params.append('status', status);
    
    window.location.href = '?' + params.toString();
}

function resetFilters() {
    window.location.href = '<?php echo BASE_URL; ?>/admin/users.php';
}
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>

