<?php
require_once '../../includes/auth.php';
require_once '../../db.php';
require_once '../../includes/header.php';
require_once '../../includes/sidebar.php';

$loggedInId = (int)$_SESSION['user_id'];
$isAdmin    = ($_SESSION['user_role'] ?? '') === 'admin';

// Staff can only see their own record
$whereClause = $isAdmin ? '' : "WHERE u.id = $loggedInId";
$users = $conn->query("
    SELECT u.*, r.name AS role_name,
           (SELECT COUNT(*) FROM user_companies uc WHERE uc.user_id = u.id) AS company_count
    FROM users u
    LEFT JOIN roles r ON r.id = u.role_id
    $whereClause
    ORDER BY u.name
");

$success = isset($_GET['success']);
$deleted = isset($_GET['deleted']);
?>

<div class="page-header">
    <h2><i class="fas fa-users-cog" style="color:var(--primary);margin-right:8px;"></i><?= $isAdmin ? 'User Management' : 'My Profile' ?></h2>
    <?php if ($isAdmin): ?>
    <a href="form.php" class="btn btn-primary"><i class="fas fa-plus"></i> Add User</a>
    <?php endif; ?>
</div>

<?php if ($success): ?>
<div class="alert alert-success" style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;padding:12px 16px;margin-bottom:16px;color:#166534;display:flex;align-items:center;gap:8px;">
    <i class="fas fa-check-circle"></i> User saved successfully.
</div>
<?php endif; ?>
<?php if ($deleted): ?>
<div class="alert alert-success" style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;padding:12px 16px;margin-bottom:16px;color:#166534;display:flex;align-items:center;gap:8px;">
    <i class="fas fa-check-circle"></i> User deleted successfully.
</div>
<?php endif; ?>

<div class="panel">
    <div class="panel-header">
        <span class="panel-title">All Users</span>
        <span style="font-size:12px;color:var(--text-muted);"><?= $users->num_rows ?> records</span>
    </div>
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Username</th>
                    <th>Role</th>
                    <th>Companies</th>
                    <th style="text-align:center;">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if ($users->num_rows > 0): while ($u = $users->fetch_assoc()): ?>
            <tr>
                <td><strong><?= htmlspecialchars($u['name']) ?></strong></td>
                <td style="font-family:monospace;font-size:13px;"><?= htmlspecialchars($u['username']) ?></td>
                <td>
                    <?php if ($u['role'] === 'admin'): ?>
                        <span class="badge badge-warning">Admin</span>
                    <?php elseif ($u['role_name']): ?>
                        <span class="badge badge-gray"><?= htmlspecialchars($u['role_name']) ?></span>
                    <?php else: ?>
                        <span class="badge badge-gray"><?= htmlspecialchars(ucfirst($u['role'])) ?></span>
                    <?php endif; ?>
                </td>
                <td style="color:var(--text-muted);"><?= (int)$u['company_count'] ?></td>
                <td>
                    <div class="action-links" style="justify-content:center;">
                        <a href="form.php?id=<?= $u['id'] ?>" class="action-btn edit" title="Edit">
                            <i class="fas fa-edit"></i>
                        </a>
                        <?php if ($u['role'] === 'admin' || $u['id'] === $loggedInId): ?>
                            <span class="action-btn delete" title="<?= $u['role'] === 'admin' ? 'Cannot delete admin' : 'Cannot delete yourself' ?>"
                                  style="opacity:0.35;cursor:not-allowed;">
                                <i class="fas fa-trash-alt"></i>
                            </span>
                        <?php else: ?>
                            <a href="delete.php?id=<?= $u['id'] ?>"
                               onclick="return confirm('Delete user &quot;<?= htmlspecialchars($u['name'], ENT_QUOTES) ?>&quot;? This cannot be undone.')"
                               class="action-btn delete" title="Delete">
                                <i class="fas fa-trash-alt"></i>
                            </a>
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
            <?php endwhile; else: ?>
            <tr><td colspan="5" style="text-align:center;padding:40px;color:var(--text-muted);">
                <i class="fas fa-inbox" style="font-size:28px;display:block;margin-bottom:8px;"></i>
                No users found.
            </td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require_once '../../includes/footer.php'; ?>
