<?php
require_once __DIR__ . '/../includes/auth.php';
requireLogin();
requirePermission('users.manage');

require_once __DIR__ . '/../config/database.php';

/* =============================
   HANDLE STATUS TOGGLE
============================= */

if (isset($_GET['toggle'])) {

    $userId = (int)$_GET['toggle'];

    // Prevent admin from suspending himself
    if ($userId !== (int)$_SESSION['user_id']) {

        $pdo->prepare("
            UPDATE users
            SET status = IF(status='ACTIVE','SUSPENDED','ACTIVE')
            WHERE id = ?
        ")->execute([$userId]);

        // Log audit
        $pdo->prepare("
            INSERT INTO audit_logs (user_id, action)
            VALUES (?, ?)
        ")->execute([
            $_SESSION['user_id'],
            "Toggled user status for user ID {$userId}"
        ]);
    }

    header("Location: users.php");
    exit;
}

/* =============================
   FILTERS
============================= */

$search = $_GET['search'] ?? '';
$roleFilter = $_GET['role'] ?? '';
$statusFilter = $_GET['status'] ?? '';

$sql = "
    SELECT u.*, r.name AS role_name
    FROM users u
    LEFT JOIN roles r ON u.role_id = r.id
    WHERE 1=1
";

$params = [];

if ($search) {
    $sql .= " AND (u.full_name LIKE ? OR u.email LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($roleFilter) {
    $sql .= " AND u.role_id = ?";
    $params[] = $roleFilter;
}

if ($statusFilter) {
    $sql .= " AND u.status = ?";
    $params[] = $statusFilter;
}

$sql .= " ORDER BY u.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* =============================
   FETCH ROLES
============================= */

$roles = $pdo->query("SELECT id, name FROM roles")->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>

<div class="main-content">

<div class="page-header">
    <h2>User Management</h2>
    <p class="page-subtitle">Manage system users and access levels.</p>
</div>

<div class="topbar" style="margin-bottom:20px;">
    <a href="add_user.php" class="btn-primary">+ Add User</a>
</div>

<form method="GET" class="filter-bar">

    <input type="text" name="search"
           placeholder="Search name or email"
           value="<?= htmlspecialchars($search) ?>">

    <select name="role">
        <option value="">All Roles</option>
        <?php foreach ($roles as $r): ?>
            <option value="<?= $r['id'] ?>"
                <?= $roleFilter == $r['id'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($r['name']) ?>
            </option>
        <?php endforeach; ?>
    </select>

    <select name="status">
        <option value="">All Status</option>
        <option value="ACTIVE" <?= $statusFilter=='ACTIVE'?'selected':'' ?>>ACTIVE</option>
        <option value="SUSPENDED" <?= $statusFilter=='SUSPENDED'?'selected':'' ?>>SUSPENDED</option>
    </select>

    <button type="submit" class="btn-secondary">Filter</button>

</form>

<div class="table-wrap">

<table>
<thead>
<tr>
<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><?= htmlspecialchars($u['full_name']) ?></td>
<td><?= htmlspecialchars($u['email']) ?></td>
<td><?= htmlspecialchars($u['role_name']) ?></td>

<td>
    <span class="status-badge <?= strtolower($u['status']) ?>">
        <?= $u['status'] ?>
    </span>
</td>

<td><?= htmlspecialchars($u['created_at']) ?></td>

<td style="white-space:nowrap;">

    <!-- Edit -->
    <a href="edit_user.php?id=<?= $u['id'] ?>"
       class="action-link">Edit</a>

    &nbsp;|&nbsp;

    <!-- Toggle Status -->
    <?php if ($u['id'] != $_SESSION['user_id']): ?>
        <a href="?toggle=<?= $u['id'] ?>"
           class="action-link">
            <?= $u['status']=='ACTIVE'?'Suspend':'Activate' ?>
        </a>
        &nbsp;|&nbsp;
    <?php endif; ?>

    <!-- Reset Password -->
    <a href="reset_user_password.php?id=<?= $u['id'] ?>"
       class="action-link"
       onclick="return confirm('Reset password for this user?');">
       Reset Password
    </a>

    &nbsp;|&nbsp;

    <!-- User Activity -->
    <a href="user_activity.php?id=<?= $u['id'] ?>"
       class="action-link">
       Activity
    </a>

</td>

</tr>
<?php endforeach; ?>

</tbody>
</table>

</div>

</div>

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