<?php
session_start();
require_once 'database/db_config.php';
// Check if user has admin privileges
require_admin_privileges('login.php');
// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$user_id = $_SESSION['user_id'];
$first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
$last_name = mysqli_real_escape_string($conn, $_POST['last_name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$bio = mysqli_real_escape_string($conn, $_POST['bio'] ?? '');
// Check if email is already taken by another user
$check_email = $conn->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
$check_email->bind_param("si", $email, $user_id);
$check_email->execute();
$result = $check_email->get_result();
if ($result->num_rows > 0) {
$_SESSION['error_message'] = "Email address is already in use by another account.";
header('Location: profile.php');
exit();
}
// Handle profile image upload if provided
$profile_image_path = null;
if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
$upload_dir = '../assets/img/profile/';
// Create directory if it doesn't exist
if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0755, true);
}
$file_extension = strtolower(pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION));
$allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
if (!in_array($file_extension, $allowed_extensions)) {
$_SESSION['error_message'] = "Only JPG, JPEG, PNG and GIF files are allowed.";
header('Location: profile.php');
exit();
}
$file_name = 'profile_' . $user_id . '_' . time() . '.' . $file_extension;
$target_file = $upload_dir . $file_name;
if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $target_file)) {
$profile_image_path = 'assets/img/profile/' . $file_name;
} else {
$_SESSION['error_message'] = "Failed to upload profile image.";
header('Location: profile.php');
exit();
}
}
// Update user profile
if ($profile_image_path) {
$update_profile = $conn->prepare("UPDATE users SET first_name = ?, last_name = ?, email = ?, bio = ?, profile_image = ? WHERE id = ?");
$update_profile->bind_param("sssssi", $first_name, $last_name, $email, $bio, $profile_image_path, $user_id);
} else {
$update_profile = $conn->prepare("UPDATE users SET first_name = ?, last_name = ?, email = ?, bio = ? WHERE id = ?");
$update_profile->bind_param("ssssi", $first_name, $last_name, $email, $bio, $user_id);
}
if ($update_profile->execute()) {
$_SESSION['success_message'] = "Profile updated successfully.";
} else {
$_SESSION['error_message'] = "Failed to update profile: " . $conn->error;
}
header('Location: profile.php');
exit();
} else {
// Redirect if accessed directly
header('Location: profile.php');
exit();
}
?>