<?php
require_once __DIR__ . '/../../includes/functions.php';
requireLogin();
requireAdmin();

$pageTitle = 'User Management';

// Handle delete / toggle status
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger', 'Invalid request token.'); header('Location: users.php'); exit;
    }
    $action = $_POST['action'] ?? '';
    $uid    = (int)($_POST['user_id'] ?? 0);

    if ($action === 'toggle' && $uid && $uid !== currentUserId()) {
        $pdo->prepare("UPDATE users SET status = IF(status=1,0,1) WHERE id=?")->execute([$uid]);
        setFlash('success', 'User status updated.');
    }
    if ($action === 'delete' && $uid && $uid !== currentUserId()) {
        $pdo->prepare("DELETE FROM users WHERE id=?")->execute([$uid]);
        setFlash('success', 'User deleted.');
    }
    header('Location: users.php'); exit;
}

$users = $pdo->query("SELECT id, name, email, role, status, created_at, tab_permissions FROM users ORDER BY id ASC")->fetchAll();

require_once __DIR__ . '/../../includes/header.php';
?>
<div class="page-header">
    <h2>User Management</h2>
    <a href="user_create.php" class="btn btn-primary"><?= icon('user-plus') ?> Add User</a>
</div>

<div class="card">
<table class="table">
<thead>
<tr>
    <th>#</th>
    <th>Name</th>
    <th>Email</th>
    <th>Role</th>
    <th>Status</th>
    <th>Created</th>
    <th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $u): ?>
<tr>
    <td><?= $u['id'] ?></td>
    <td><?= sanitize($u['name']) ?></td>
    <td><?= sanitize($u['email']) ?></td>
    <td><span class="badge badge-<?= $u['role']==='admin'?'primary':'secondary' ?>"><?= $u['role'] ?></span></td>
    <td><span class="badge badge-<?= $u['status']?'success':'danger' ?>"><?= $u['status']?'Active':'Inactive' ?></span></td>
    <td><?= formatDate($u['created_at']) ?></td>
    <td>
        <a href="user_edit.php?id=<?= $u['id'] ?>" class="btn btn-sm btn-secondary"><?= icon('pencil') ?> Edit</a>
        <a href="user_change_password.php?id=<?= $u['id'] ?>" class="btn btn-sm btn-secondary"><?= icon('key') ?> Password</a>
        <?php if ($u['id'] !== currentUserId()): ?>
        <form method="POST" style="display:inline">
            <input type="hidden" name="csrf_token" value="<?= generateCSRFToken() ?>">
            <input type="hidden" name="action" value="toggle">
            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
            <button class="btn btn-sm btn-<?= $u['status']?'warning':'success' ?>"><?= $u['status']?'Deactivate':'Activate' ?></button>
        </form>
        <form method="POST" style="display:inline" onsubmit="return confirm('Delete this user?')">
            <input type="hidden" name="csrf_token" value="<?= generateCSRFToken() ?>">
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
            <button class="btn btn-sm btn-danger"><?= icon('trash') ?> Delete</button>
        </form>
        <?php endif; ?>
    </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>

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