<?php
/**
 * Users Management Page
 * Research Survey Management System
 */

define('PAGE_TITLE', 'User Management');
require_once __DIR__ . '/../includes/functions.php';
requireRole(['admin']);

$pdo = getDBConnection();

// Handle user creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create') {
    $username = sanitize($_POST['username']);
    $email = sanitize($_POST['email']);
    $password = $_POST['password'];
    $fullName = sanitize($_POST['full_name']);
    $role = $_POST['role'];
    $department = sanitize($_POST['department'] ?? '');
    
    $error = '';
    
    if (empty($username) || empty($email) || empty($password) || empty($fullName)) {
        $error = 'Please fill in all required fields.';
    } elseif (!validateEmail($email)) {
        $error = 'Invalid email address.';
    } elseif (strlen($password) < 6) {
        $error = 'Password must be at least 6 characters.';
    } else {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = :uname OR email = :email");
        $stmt->execute(['uname' => $username, 'email' => $email]);
        if ($stmt->fetchColumn() > 0) {
            $error = 'Username or email already exists.';
        } else {
            $passwordHash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (username, email, password_hash, full_name, role, department, is_active) 
                                   VALUES (:uname, :email, :hash, :name, :role, :dept, 1)");
            $stmt->execute([
                'uname' => $username,
                'email' => $email,
                'hash' => $passwordHash,
                'name' => $fullName,
                'role' => $role,
                'dept' => $department
            ]);
            $newUserId = $pdo->lastInsertId();
            logAudit('create', 'user', $newUserId, null, ['username' => $username, 'role' => $role]);
            $_SESSION['flash_message'] = 'User created successfully!';
            $_SESSION['flash_type'] = 'success';
            header('Location: ' . BASE_URL . '/pages/users.php');
            exit;
        }
    }
}

// Handle user toggle
if (isset($_GET['toggle_user'])) {
    $toggleId = (int)$_GET['toggle_user'];
    $stmt = $pdo->prepare("SELECT is_active FROM users WHERE user_id = :id");
    $stmt->execute(['id' => $toggleId]);
    $isActive = $stmt->fetchColumn();
    
    $stmt = $pdo->prepare("UPDATE users SET is_active = :status WHERE user_id = :id");
    $stmt->execute(['status' => $isActive ? 0 : 1, 'id' => $toggleId]);
    logAudit('update', 'user', $toggleId, ['is_active' => $isActive], ['is_active' => !$isActive]);
    $_SESSION['flash_message'] = 'User status updated.';
    $_SESSION['flash_type'] = 'success';
    header('Location: ' . BASE_URL . '/pages/users.php');
    exit;
}

// Get all users
$stmt = $pdo->prepare("SELECT user_id, username, email, full_name, role, department, is_active, last_login, created_at 
                       FROM users ORDER BY created_at DESC");
$stmt->execute();
$users = $stmt->fetchAll();

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

<div class="dashboard-header">
    <div>
        <h1><i class="fas fa-users-cog me-2 text-primary"></i>User Management</h1>
        <p>Manage system users, roles, and permissions</p>
    </div>
    <div>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createUserModal">
            <i class="fas fa-user-plus me-1"></i> New User
        </button>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th>Name</th>
                        <th>Username</th>
                        <th>Email</th>
                        <th>Role</th>
                        <th>Department</th>
                        <th>Status</th>
                        <th>Last Login</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($users)): ?>
                    <tr><td colspan="8" class="text-center text-muted py-4">No users found</td></tr>
                    <?php else: ?>
                    <?php foreach ($users as $user): ?>
                    <tr>
                        <td>
                            <strong><?php echo htmlspecialchars($user['full_name']); ?></strong>
                            <?php if ($user['user_id'] == $_SESSION['user_id']): ?>
                            <span class="badge bg-secondary ms-1">You</span>
                            <?php endif; ?>
                        </td>
                        <td><?php echo htmlspecialchars($user['username']); ?></td>
                        <td><?php echo htmlspecialchars($user['email']); ?></td>
                        <td>
                            <span class="badge bg-<?php 
                                echo $user['role'] === 'admin' ? 'danger' : 
                                    ($user['role'] === 'researcher' ? 'primary' : 
                                    ($user['role'] === 'analyst' ? 'info' : 'secondary')); 
                            ?>">
                                <?php echo ucfirst($user['role']); ?>
                            </span>
                        </td>
                        <td><?php echo htmlspecialchars($user['department'] ?? 'N/A'); ?></td>
                        <td>
                            <span class="badge bg-<?php echo $user['is_active'] ? 'success' : 'danger'; ?>">
                                <?php echo $user['is_active'] ? 'Active' : 'Inactive'; ?>
                            </span>
                        </td>
                        <td><small><?php echo $user['last_login'] ? formatDate($user['last_login'], 'M d, Y H:i') : 'Never'; ?></small></td>
                        <td>
                            <?php if ($user['user_id'] != $_SESSION['user_id']): ?>
                            <a href="?toggle_user=<?php echo $user['user_id']; ?>" 
                               class="btn btn-sm btn-outline-<?php echo $user['is_active'] ? 'warning' : 'success'; ?>"
                               onclick="return confirm('<?php echo $user['is_active'] ? 'Deactivate' : 'Activate'; ?> this user?')">
                                <i class="fas fa-<?php echo $user['is_active'] ? 'ban' : 'check'; ?>"></i>
                            </a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Create User Modal -->
<div class="modal fade" id="createUserModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="create">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-user-plus me-2 text-primary"></i>Create New User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <?php if (isset($error)): ?>
                    <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Full Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="full_name" required
                                   placeholder="John Doe">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Username <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="username" required
                                   placeholder="jdoe">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Email <span class="text-danger">*</span></label>
                            <input type="email" class="form-control" name="email" required
                                   placeholder="john@example.com">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Password <span class="text-danger">*</span></label>
                            <input type="password" class="form-control" name="password" required
                                   placeholder="Min. 6 characters" minlength="6">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Role <span class="text-danger">*</span></label>
                            <select class="form-select" name="role" required>
                                <option value="viewer">Viewer</option>
                                <option value="analyst">Analyst</option>
                                <option value="researcher">Researcher</option>
                                <option value="admin">Admin</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Department</label>
                            <input type="text" class="form-control" name="department"
                                   placeholder="e.g., Research, Analytics">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-user-plus me-1"></i> Create User
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

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