'danger', 'message' => 'All fields are required.']; header('Location: profile.php'); exit(); } if ($new_password !== $confirm_new_password) { $_SESSION['flash_message'] = ['type' => 'danger', 'message' => 'New passwords do not match.']; header('Location: profile.php'); exit(); } try { $pdo = db(); // 2. Fetch current user from DB to verify current password $stmt = $pdo->prepare("SELECT password FROM users WHERE id = ?"); $stmt->execute([$_SESSION['user']['id']]); $user = $stmt->fetch(PDO::FETCH_ASSOC); if (!$user || !password_verify($current_password, $user['password'])) { $_SESSION['flash_message'] = ['type' => 'danger', 'message' => 'Incorrect current password.']; header('Location: profile.php'); exit(); } // 3. Hash new password $new_password_hash = password_hash($new_password, PASSWORD_DEFAULT); // 4. Update password in the database $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?"); $stmt->execute([$new_password_hash, $_SESSION['user']['id']]); $_SESSION['flash_message'] = ['type' => 'success', 'message' => 'Password updated successfully.']; header('Location: profile.php'); exit(); } catch (PDOException $e) { // Log error and show a generic message error_log("Password update failed: " . $e->getMessage()); $_SESSION['flash_message'] = ['type' => 'danger', 'message' => 'An error occurred. Please try again.']; header('Location: profile.php'); exit(); } } else { // Redirect if not a POST request header('Location: profile.php'); exit(); }