File "edit_user.php"
Full path: /home/itsevak/public_html/prepaiddev.itsevak.com/admin/edit_user.php
File
size: 5.29 B (5.29 KB bytes)
MIME-type: text/x-php
Charset: utf-8
Download Open Edit Advanced Editor Back
<?php
require_once '../includes/functions.php';
// Require Admin or SuperAdmin access
requireAdminAccess();
// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonResponse(['success' => false, 'message' => 'Invalid request method'], 405);
}
// Validate CSRF token
if (!validateCSRFToken($_POST['csrf_token'] ?? '')) {
jsonResponse(['success' => false, 'message' => 'Invalid request. Please try again.'], 403);
}
// Validate required fields
$userId = sanitizeInput($_POST['user_id'] ?? '');
$userTable = sanitizeInput($_POST['user_table'] ?? '');
$userType = sanitizeInput($_POST['userType'] ?? '');
$name = sanitizeInput($_POST['name'] ?? '');
$email = sanitizeInput($_POST['email'] ?? '');
$phone = sanitizeInput($_POST['phone'] ?? '');
$status = sanitizeInput($_POST['status'] ?? '');
$password = $_POST['password'] ?? '';
if (empty($userId) || empty($userTable) || empty($userType) || empty($name) || empty($email) || empty($status)) {
jsonResponse(['success' => false, 'message' => 'All required fields must be filled.'], 400);
}
// Validate user type
$validTypes = ['operator', 'validator', 'admin'];
if (!in_array($userType, $validTypes)) {
jsonResponse(['success' => false, 'message' => 'Invalid user type.'], 400);
}
// Admin users can only edit operators and validators, not other admins or super_admins
if ($_SESSION['user_type'] === 'admin' && in_array($userType, ['admin', 'super_admin'])) {
jsonResponse(['success' => false, 'message' => 'Admin users can only edit operators and validators.'], 400);
}
// Validate table name
$validTables = ['operators', 'validators', 'admins'];
if (!in_array($userTable, $validTables)) {
jsonResponse(['success' => false, 'message' => 'Invalid table name.'], 400);
}
// Admin users can only edit operators and validators
if ($_SESSION['user_type'] === 'admin' && in_array($userTable, ['admins', 'super_admins'])) {
jsonResponse(['success' => false, 'message' => 'Admin users can only edit operators and validators.'], 400);
}
// Validate status
$validStatuses = ['active', 'inactive', 'pending'];
if (!in_array($status, $validStatuses)) {
jsonResponse(['success' => false, 'message' => 'Invalid status.'], 400);
}
// Validate email format
if (!validateEmail($email)) {
jsonResponse(['success' => false, 'message' => 'Please enter a valid email address.'], 400);
}
// Validate password strength if provided
if (!empty($password) && !validatePassword($password)) {
jsonResponse(['success' => false, 'message' => 'Password must be at least 8 characters long and contain uppercase, lowercase, and number.'], 400);
}
// Validate phone if provided
if (!empty($phone) && !validatePhone($phone)) {
jsonResponse(['success' => false, 'message' => 'Please enter a valid phone number.'], 400);
}
try {
$db = Database::getInstance();
// Check if email already exists in any other user table (excluding current user)
$tables = ['auto_owners', 'passengers', 'operators', 'validators', 'admins', 'super_admins'];
foreach ($tables as $table) {
if ($table === $userTable) {
// Check in same table but exclude current user
$existingUser = $db->fetch("SELECT id FROM $table WHERE email = ? AND id != ?", [$email, $userId]);
} else {
// Check in other tables
$existingUser = $db->fetch("SELECT id FROM $table WHERE email = ?", [$email]);
}
if ($existingUser) {
jsonResponse(['success' => false, 'message' => 'An account with this email already exists in another table.'], 400);
}
}
// Check if user exists in current table
$existingUser = $db->fetch("SELECT id, name FROM $userTable WHERE id = ?", [$userId]);
if (!$existingUser) {
jsonResponse(['success' => false, 'message' => 'User not found.'], 404);
}
// Prepare update data
$updateData = [
'name' => $name,
'email' => $email,
'phone' => $phone,
'status' => $status
];
$sql = "UPDATE $userTable SET name = ?, email = ?, phone = ?, status = ?, updated_at = CURRENT_TIMESTAMP";
$params = [$name, $email, $phone, $status];
// Add password update if provided
if (!empty($password)) {
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$sql .= ", password = ?";
$params[] = $hashedPassword;
}
$sql .= " WHERE id = ?";
$params[] = $userId;
// Execute update
$result = $db->query($sql, $params);
if (!$result) {
throw new Exception('Database update failed');
}
// Log the action
logError('SuperAdmin updated user: ' . $existingUser['name'] . ' (ID: ' . $userId . ') in table ' . $userTable);
jsonResponse([
'success' => true,
'message' => 'User updated successfully!',
'user' => [
'id' => $userId,
'name' => $name,
'email' => $email,
'type' => $userType,
'status' => $status
]
]);
} catch (Exception $e) {
logError('Backend user update error: ' . $e->getMessage());
jsonResponse(['success' => false, 'message' => 'Failed to update user: ' . $e->getMessage()], 500);
}