<?php
/**
 * Admin — User Management
 * Approve/deny pending users, manage active users.
 */
if (!hasRole('captain')) {
    header('Location: ../dashboard.php?error=forbidden');
    exit;
}

$db = getDB();
$message = '';

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCsrf();
    $action = $_POST['user_action'] ?? '';
    $targetId = (int)($_POST['target_user_id'] ?? 0);

    if ($targetId > 0) {
        switch ($action) {
            case 'approve':
                $db->prepare("UPDATE users SET status = 'active', approved_by = :admin, approved_at = NOW() WHERE id = :id AND status = 'pending'")
                   ->execute([':admin' => $user['id'], ':id' => $targetId]);
                auditLog('user_approved', $user['id'], "Approved user ID: $targetId");
                $message = 'User approved successfully.';
                break;

            case 'deny':
                $db->prepare("DELETE FROM users WHERE id = :id AND status = 'pending'")
                   ->execute([':id' => $targetId]);
                auditLog('user_denied', $user['id'], "Denied/deleted user ID: $targetId");
                $message = 'User request denied.';
                break;

            case 'suspend':
                $db->prepare("UPDATE users SET status = 'suspended' WHERE id = :id AND id != :admin")
                   ->execute([':id' => $targetId, ':admin' => $user['id']]);
                auditLog('user_suspended', $user['id'], "Suspended user ID: $targetId");
                $message = 'User suspended.';
                break;

            case 'activate':
                $db->prepare("UPDATE users SET status = 'active' WHERE id = :id")
                   ->execute([':id' => $targetId]);
                auditLog('user_activated', $user['id'], "Reactivated user ID: $targetId");
                $message = 'User reactivated.';
                break;

            case 'change_role':
                $newRole = $_POST['new_role'] ?? '';
                if (array_key_exists($newRole, ROLES)) {
                    $db->prepare("UPDATE users SET role = :role WHERE id = :id")
                       ->execute([':role' => $newRole, ':id' => $targetId]);
                    auditLog('role_changed', $user['id'], "Changed user $targetId role to: $newRole");
                    $message = 'Role updated.';
                }
                break;
        }
    }
}

$pending = $db->query("SELECT * FROM users WHERE status = 'pending' ORDER BY created_at DESC")->fetchAll();
$active = $db->query("SELECT * FROM users WHERE status = 'active' ORDER BY last_name, first_name")->fetchAll();
$suspended = $db->query("SELECT * FROM users WHERE status = 'suspended' ORDER BY last_name, first_name")->fetchAll();
?>

<div class="page-header">
    <h1>Manage Users</h1>
    <a href="dashboard.php?page=admin" class="btn btn-sm btn-secondary">&larr; Back to Admin</a>
</div>

<?php if ($message): ?>
    <div class="alert alert-success" style="margin-bottom:20px;"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<!-- Pending Users -->
<?php if (!empty($pending)): ?>
<div class="card" style="margin-bottom:24px; border:2px solid var(--ios-orange);">
    <div class="card-header">
        <h2 class="card-title">Pending Approval (<?= count($pending) ?>)</h2>
    </div>
    <div class="table-wrapper">
        <table>
            <thead><tr><th>Name</th><th>Username</th><th>Email</th><th>Station</th><th>Badge</th><th>Role</th><th>Requested</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach ($pending as $p): ?>
            <tr>
                <td><strong><?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?></strong></td>
                <td><?= htmlspecialchars($p['username']) ?></td>
                <td><?= htmlspecialchars($p['email']) ?></td>
                <td><?= htmlspecialchars($p['station'] ?? '') ?></td>
                <td><?= htmlspecialchars($p['badge_number'] ?? '') ?></td>
                <td><span class="role-badge"><?= htmlspecialchars(ROLES[$p['role']]['label'] ?? $p['role']) ?></span></td>
                <td style="font-size:13px; color:var(--ios-secondary);"><?= date('M j, Y', strtotime($p['created_at'])) ?></td>
                <td style="white-space:nowrap;">
                    <form method="POST" style="display:inline;">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                        <input type="hidden" name="target_user_id" value="<?= $p['id'] ?>">
                        <input type="hidden" name="user_action" value="approve">
                        <button type="submit" class="btn btn-sm btn-success">Approve</button>
                    </form>
                    <form method="POST" style="display:inline;">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                        <input type="hidden" name="target_user_id" value="<?= $p['id'] ?>">
                        <input type="hidden" name="user_action" value="deny">
                        <button type="submit" class="btn btn-sm btn-outline" onclick="return confirm('Deny and delete this user request?');">Deny</button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- Active Users -->
<div class="card" style="margin-bottom:24px;">
    <div class="card-header">
        <h2 class="card-title">Active Users (<?= count($active) ?>)</h2>
    </div>
    <div class="table-wrapper">
        <table>
            <thead><tr><th>Name</th><th>Username</th><th>Role</th><th>Station</th><th>Badge</th><th>Last Login</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach ($active as $a): ?>
            <tr>
                <td><strong><?= htmlspecialchars($a['first_name'] . ' ' . $a['last_name']) ?></strong></td>
                <td><?= htmlspecialchars($a['username']) ?></td>
                <td>
                    <form method="POST" style="display:inline-flex; align-items:center; gap:4px;">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                        <input type="hidden" name="target_user_id" value="<?= $a['id'] ?>">
                        <input type="hidden" name="user_action" value="change_role">
                        <select name="new_role" class="form-control" style="padding:4px 8px; font-size:12px; width:auto;" onchange="this.form.submit();">
                            <?php foreach (ROLES as $rk => $rv): ?>
                                <option value="<?= $rk ?>" <?= $a['role'] === $rk ? 'selected' : '' ?>><?= htmlspecialchars($rv['label']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </form>
                </td>
                <td><?= htmlspecialchars($a['station'] ?? '-') ?></td>
                <td><?= htmlspecialchars($a['badge_number'] ?? '-') ?></td>
                <td style="font-size:13px; color:var(--ios-secondary);">
                    <?= $a['last_login'] ? date('M j g:i A', strtotime($a['last_login'])) : 'Never' ?>
                </td>
                <td>
                    <?php if ($a['id'] != $user['id']): ?>
                    <form method="POST" style="display:inline;">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                        <input type="hidden" name="target_user_id" value="<?= $a['id'] ?>">
                        <input type="hidden" name="user_action" value="suspend">
                        <button type="submit" class="btn btn-sm btn-outline" onclick="return confirm('Suspend this user?');">Suspend</button>
                    </form>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Suspended Users -->
<?php if (!empty($suspended)): ?>
<div class="card">
    <div class="card-header">
        <h2 class="card-title">Suspended Users (<?= count($suspended) ?>)</h2>
    </div>
    <div class="table-wrapper">
        <table>
            <thead><tr><th>Name</th><th>Username</th><th>Role</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach ($suspended as $s): ?>
            <tr>
                <td><?= htmlspecialchars($s['first_name'] . ' ' . $s['last_name']) ?></td>
                <td><?= htmlspecialchars($s['username']) ?></td>
                <td><span class="role-badge"><?= htmlspecialchars(ROLES[$s['role']]['label'] ?? $s['role']) ?></span></td>
                <td>
                    <form method="POST" style="display:inline;">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                        <input type="hidden" name="target_user_id" value="<?= $s['id'] ?>">
                        <input type="hidden" name="user_action" value="activate">
                        <button type="submit" class="btn btn-sm btn-success">Reactivate</button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>
