using System; using System.Collections.Generic; using System.Linq; using System.Web; using instavibe.Models; using InstaVibe.Models; using System.Web.Mvc; using System.Data.SqlClient; using System.IO; using System.Configuration; using System.Globalization; namespace InstaVibe.Controllers { public class ProfileController : Controller { public string connectionString = ConfigurationManager.ConnectionStrings["InstaVibe"].ConnectionString.ToString(); // ======================= GET: Profile/Edit ========================== public ActionResult Edit() { // Check if user is logged in by verifying session if (Session["UserId"] == null) { TempData["ErrorMessage"] = "You must be logged in to edit your profile."; return RedirectToAction("Login", "Account"); } // Get the userId from session int userId = Convert.ToInt32(Session["UserId"]); User user = null; using (SqlConnection connection = new SqlConnection(connectionString)) { string query = "SELECT * FROM Users WHERE user_id = @UserId"; SqlCommand command = new SqlCommand(query, connection); command.Parameters.AddWithValue("@UserId", userId); connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { user = new User { UserId = Convert.ToInt32(reader["user_id"]), Username = reader["username"].ToString(), FirstName = reader["firstname"].ToString(), LastName = reader["lastname"].ToString(), Department = reader["department"].ToString(), Email = reader["email"].ToString(), Phone = reader["PhoneNo"].ToString(), Birthday = reader["birthday"] == DBNull.Value ? (DateTime?)null : Convert.ToDateTime(reader["birthday"]), ProfilePicture = reader["profile_picture"].ToString() }; } } } if (user == null) { TempData["ErrorMessage"] = "User not found."; return RedirectToAction("Login", "Account"); } return View(user); } // ======================= POST: Profile/UpdateProfile ========================== [HttpPost] public JsonResult UpdateProfile(User model, HttpPostedFileBase ProfilePic, string CurrentPassword, string NewPassword, string ConfirmPassword) { // Check if the user is logged in if (Session["UserId"] == null) { return Json(new { success = false, message = "Session expired. Please log in again." }); } // Get the userId from session int userId = Convert.ToInt32(Session["UserId"]); string profileImagePath = null; // Handle profile picture upload if (ProfilePic != null && ProfilePic.ContentLength > 0) { string path = Path.Combine(Server.MapPath("~/Content/images/"), Path.GetFileName(ProfilePic.FileName)); ProfilePic.SaveAs(path); profileImagePath = "/Content/images/" + Path.GetFileName(ProfilePic.FileName); } using (SqlConnection connection = new SqlConnection(connectionString)) { string query = @"UPDATE Users SET username = @Username, firstname = @FirstName, lastname = @LastName, department = @Department, email = @Email, PhoneNo = @Phone, Birthday = @Birthday, profile_picture = @ProfileImage WHERE user_id = @UserId"; SqlCommand command = new SqlCommand(query, connection); command.Parameters.AddWithValue("@UserId", userId); command.Parameters.AddWithValue("@Username", model.Username); command.Parameters.AddWithValue("@FirstName", model.FirstName); command.Parameters.AddWithValue("@LastName", model.LastName); command.Parameters.AddWithValue("@Department", string.IsNullOrEmpty(model.Department) ? (object)DBNull.Value : model.Department); command.Parameters.AddWithValue("@Email", model.Email); command.Parameters.AddWithValue("@Phone", string.IsNullOrEmpty(model.Phone) ? (object)DBNull.Value : model.Phone); command.Parameters.AddWithValue("@Birthday", model.Birthday.HasValue ? (object)model.Birthday.Value : DBNull.Value); command.Parameters.AddWithValue("@ProfileImage", string.IsNullOrEmpty(profileImagePath) ? (object)DBNull.Value : profileImagePath); connection.Open(); int rowsAffected = command.ExecuteNonQuery(); if (rowsAffected > 0) { // CHECK IF PASSWORD FIELDS WERE FILLED if (!string.IsNullOrEmpty(CurrentPassword) && !string.IsNullOrEmpty(NewPassword) && !string.IsNullOrEmpty(ConfirmPassword)) { if (NewPassword != ConfirmPassword) { return Json(new { success = false, message = "New password and confirmation do not match." }); } // Check if current password matches string checkPasswordQuery = "SELECT password FROM Users WHERE user_id = @UserId"; SqlCommand checkCmd = new SqlCommand(checkPasswordQuery, connection); checkCmd.Parameters.AddWithValue("@UserId", userId); string currentPasswordInDb = (string)checkCmd.ExecuteScalar(); if (currentPasswordInDb != CurrentPassword) { return Json(new { success = false, message = "Current password is incorrect." }); } // Update password string updatePasswordQuery = "UPDATE Users SET password = @NewPassword WHERE user_id = @UserId"; SqlCommand updateCmd = new SqlCommand(updatePasswordQuery, connection); updateCmd.Parameters.AddWithValue("@NewPassword", NewPassword); updateCmd.Parameters.AddWithValue("@UserId", userId); updateCmd.ExecuteNonQuery(); } return Json(new { success = true, message = "Profile updated successfully" }); } else { return Json(new { success = false, message = "Update failed. Try again." }); } } } } }