if (!session_id()) {
session_start();
}
global $wpdb;
$table = $wpdb->prefix . 'user_data';
// ✅ Handle logout and login checks **before headers get sent**
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
session_destroy();
wp_redirect(home_url('/login'));
exit;
}
if (empty($_SESSION['user_id'])) {
wp_redirect(home_url('/login'));
exit;
}
$user_id = (int) $_SESSION['user_id'];
$success = false;
$password_error = '';
$update_error = '';
$updated = null;
// ✅ Form handling logic
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$update_data = [];
if (!empty($_POST['fullname'])) {
$update_data['fullname'] = sanitize_text_field($_POST['fullname']);
}
if (!empty($_POST['email_mobile'])) {
$update_data['email_mobile'] = sanitize_text_field($_POST['email_mobile']);
}
if (!empty($_POST['address'])) {
$update_data['address'] = sanitize_text_field($_POST['address']);
}
if (!empty($_POST['gender'])) {
$update_data['gender'] = sanitize_text_field($_POST['gender']);
}
$new_pass = $_POST['new_password'] ?? '';
$confirm_pass = $_POST['confirm_password'] ?? '';
if (!empty($new_pass)) {
if ($new_pass === $confirm_pass) {
$update_data['password'] = wp_hash_password($new_pass);
} else {
$password_error = "⚠️ Passwords do not match.";
}
}
if (!empty($_FILES['profile_picture']['name'])) {
require_once(ABSPATH . 'wp-admin/includes/file.php');
$upload = wp_handle_upload($_FILES['profile_picture'], ['test_form' => false]);
if ($upload && !isset($upload['error'])) {
$update_data['profile_picture'] = esc_url_raw($upload['url']);
} else {
$update_error = "⚠️ Image upload failed: " . ($upload['error'] ?? 'Unknown error');
}
}
if (empty($password_error) && !empty($update_data)) {
$updated = $wpdb->update($table, $update_data, ['id' => $user_id]);
}
if (isset($updated)) {
if ($updated !== false || $updated === 0) {
$success = true;
} else {
$update_error = "⚠️ Update failed: " . $wpdb->last_error;
}
}
}
// ✅ At this point, header logic is already handled. Now load template.
// ✅ Load user data
$user = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE id = %d", $user_id));
$profile_img = !empty($user->profile_picture)
? esc_url($user->profile_picture)
: get_template_directory_uri() . '/images/default-avatar.png';
?>