<?php
// pages/users.php
requireRole('admin');

// Handle Add User
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_user') {
    $username = clean_input($_POST['username']);
    $role = clean_input($_POST['role']);
    $password = $_POST['password']; // In real app, enforce complexity
    
    // Check if username exists
    $check = $pdo->prepare("SELECT id FROM users WHERE username = ?");
    $check->execute([$username]);
    if ($check->rowCount() > 0) {
        $error = "Username already exists";
    } else {
        $member_id = !empty($_POST['member_id']) ? (int)$_POST['member_id'] : null;
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("INSERT INTO users (username, password_hash, role, member_id) VALUES (?, ?, ?, ?)"); 
        if ($stmt->execute([$username, $hash, $role, $member_id])) {
            $success = "User added successfully";
        } else {
            $error = "Failed to add user";
        }
    }
}

// Handle Delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    if ($id !== (int)$_SESSION['user_id']) { // Explicit type cast self-protection
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
        if ($stmt->execute([$id])) {
            $success = "User deleted successfully";
        } else {
            $errInfo = $stmt->errorInfo();
            $error = "Database Error: " . ($errInfo[2] ?? "Unknown error occurred while deleting.");
        }
    } else {
        $error = "Security Error: You cannot delete your own account while logged in.";
    }
}

// Fetch Users
$users = $pdo->query("SELECT * FROM users ORDER BY username ASC")->fetchAll();
?>

<h1>User Management</h1>

<?php if (isset($error)): ?>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>
<?php if (isset($success)): ?>
<div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>

<div class="card" style="margin-bottom: 20px;">
    <h3>Add New User</h3>
    <form method="POST" style="display: flex; gap: 10px; align-items: flex-end; flex-wrap: wrap;">
        <input type="hidden" name="action" value="add_user">
        <div class="form-group" style="margin-bottom: 0;">
            <label>Username</label>
            <input type="text" name="username" class="form-control" required>
        </div>
        <div class="form-group" style="margin-bottom: 0;">
            <label>Password</label>
            <input type="password" name="password" class="form-control" required>
        </div>
        <div class="form-group" style="margin-bottom: 0;">
            <label>Role</label>
            <select name="role" class="form-control">
                <option value="viewer">Viewer</option>
                <option value="member">Member</option>
                <option value="roster_manager">Roster Manager</option>
                <option value="coordinator">Coordinator</option>
                <option value="admin">Admin</option>
            </select>
        </div>
        <!-- Link to Member -->
        <div class="form-group" style="margin-bottom: 0;">
            <label>Link Member (Optional)</label>
            <select name="member_id" class="form-control">
                <option value="">-- None --</option>
                <?php 
                $avail_m = $pdo->query("SELECT id, full_name FROM members ORDER BY full_name ASC")->fetchAll();
                foreach($avail_m as $am) {
                    echo "<option value='{$am['id']}'>" . htmlspecialchars($am['full_name']) . "</option>";
                }
                ?>
            </select>
        </div>
        <button type="submit" class="btn">Add User</button>
    </form>
</div>

<div class="table-responsive">
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Username</th>
                <th>Role</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($users as $u): ?>
            <tr>
                <td><?php echo $u['id']; ?></td>
                <td><?php echo htmlspecialchars($u['username']); ?></td>
                <td>
                    <span style="padding: 2px 5px; border-radius: 4px; background: #444;">
                        <?php echo htmlspecialchars($u['role']); ?>
                    </span>
                </td>
                <td>
                    <?php if ($u['id'] !== $_SESSION['user_id']): ?>
                    <a href="index.php?page=users&delete=<?php echo $u['id']; ?>" class="btn" style="background-color: var(--danger-color); padding: 5px 10px; font-size: 0.8rem;" onclick="return confirm('Are you sure?')">Delete</a>
                    <?php else: ?>
                    <span style="color: #666;">Current User</span>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
