<?php
session_start();
require_once 'database/db_config.php';
// Check if user has admin privileges
require_admin_privileges('login.php');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$user_id = (int)$_POST['user_id'];
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
$first_name = trim($_POST['first_name'] ?? '');
$last_name = trim($_POST['last_name'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$bio = trim($_POST['bio'] ?? '');
$role = $_POST['role'] ?? 'student';
$status = $_POST['status'] ?? 'active';
$errors = [];
// Validate username
if (empty($username)) {
$errors[] = "Username is required";
} elseif (strlen($username) < 3) {
$errors[] = "Username must be at least 3 characters long";
} elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
$errors[] = "Username can only contain letters, numbers, and underscores";
}
// Check if username exists (excluding current user)
$stmt = $conn->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
$stmt->bind_param("si", $username, $user_id);
$stmt->execute();
if ($stmt->get_result()->num_rows > 0) {
$errors[] = "Username already exists";
}
// Validate email
if (empty($email)) {
$errors[] = "Email is required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
// Check if email exists (excluding current user)
$stmt = $conn->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
$stmt->bind_param("si", $email, $user_id);
$stmt->execute();
if ($stmt->get_result()->num_rows > 0) {
$errors[] = "Email already exists";
}
// Validate password if provided
if (!empty($password) && strlen($password) < 6) {
$errors[] = "Password must be at least 6 characters long";
}
// Validate role
$valid_roles = ['admin', 'instructor', 'student', 'director', 'developer'];
if (!in_array($role, $valid_roles)) {
$errors[] = "Invalid role";
}
// Validate status
$valid_statuses = ['active', 'pending', 'suspended'];
if (!in_array($status, $valid_statuses)) {
$errors[] = "Invalid status";
}
// Handle profile image upload if provided
$profile_image_path = null;
if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
$allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
$max_size = 5 * 1024 * 1024; // 5MB
if (!in_array($_FILES['profile_image']['type'], $allowed_types)) {
$errors[] = "Invalid file type. Only JPG, PNG and GIF are allowed.";
} elseif ($_FILES['profile_image']['size'] > $max_size) {
$errors[] = "File size too large. Maximum size is 5MB.";
} else {
$upload_dir = '../uploads/profiles/';
if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0777, true);
}
$file_extension = pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION);
$file_name = uniqid() . '.' . $file_extension;
$target_path = $upload_dir . $file_name;
if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $target_path)) {
$profile_image_path = 'uploads/profiles/' . $file_name;
// Get current profile image to delete old one if exists
$stmt = $conn->prepare("SELECT profile_image FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
if ($row = $result->fetch_assoc()) {
$old_image = $row['profile_image'];
if (!empty($old_image) && file_exists('../' . $old_image)) {
unlink('../' . $old_image);
}
}
} else {
$errors[] = "Failed to upload profile image";
}
}
}
if (empty($errors)) {
// Prepare update query based on whether password and profile image are provided
if (!empty($password) && $profile_image_path) {
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $conn->prepare("
UPDATE users
SET username = ?, email = ?, password = ?, first_name = ?, last_name = ?,
phone = ?, bio = ?, role = ?, status = ?, profile_image = ?
WHERE id = ?
");
$stmt->bind_param("ssssssssssi", $username, $email, $hashed_password, $first_name, $last_name,
$phone, $bio, $role, $status, $profile_image_path, $user_id);
} elseif (!empty($password)) {
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $conn->prepare("
UPDATE users
SET username = ?, email = ?, password = ?, first_name = ?, last_name = ?,
phone = ?, bio = ?, role = ?, status = ?
WHERE id = ?
");
$stmt->bind_param("sssssssssi", $username, $email, $hashed_password, $first_name, $last_name,
$phone, $bio, $role, $status, $user_id);
} elseif ($profile_image_path) {
$stmt = $conn->prepare("
UPDATE users
SET username = ?, email = ?, first_name = ?, last_name = ?,
phone = ?, bio = ?, role = ?, status = ?, profile_image = ?
WHERE id = ?
");
$stmt->bind_param("sssssssssi", $username, $email, $first_name, $last_name,
$phone, $bio, $role, $status, $profile_image_path, $user_id);
} else {
$stmt = $conn->prepare("
UPDATE users
SET username = ?, email = ?, first_name = ?, last_name = ?,
phone = ?, bio = ?, role = ?, status = ?
WHERE id = ?
");
$stmt->bind_param("ssssssssi", $username, $email, $first_name, $last_name,
$phone, $bio, $role, $status, $user_id);
}
if ($stmt->execute()) {
$_SESSION['success_message'] = "User updated successfully";
// Redirect based on role
if ($role === 'instructor') {
header('Location: instructors.php');
exit();
} else {
// Add anchor to scroll to user
header('Location: users.php?updated=' . $user_id . '#user' . $user_id);
exit();
}
} else {
$errors[] = "Error updating user: " . $conn->error;
}
}
// If there are errors, store them in session and redirect back
$_SESSION['error_messages'] = $errors;
$_SESSION['form_data'] = $_POST;
header('Location: users.php');
exit();
}
// If not POST request, redirect to users page
header('Location: users.php');
exit();