using InstaVibe.Models; using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Web.Mvc; namespace InstaVibe.Controllers { public class AdminController : Controller { public string connectionString = ConfigurationManager.ConnectionStrings["InstaVibe"].ConnectionString.ToString(); // ============================================= // SUPERADMIN LOGIN // ============================================= public ActionResult Index() { return View(); // Views/Admin/Index.cshtml (SuperAdmin Login) } [HttpPost] public ActionResult Index(string username, string password) { using (SqlConnection con = new SqlConnection(connectionString)) { string query = "SELECT * FROM Admins WHERE username=@Username AND password=@Password"; SqlCommand cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("@Username", username); cmd.Parameters.AddWithValue("@Password", password); con.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { Session["AdminType"] = "SuperAdmin"; Session["AdminUsername"] = username; return RedirectToAction("Dashboard"); } else { ViewBag.Error = "Invalid username or password!"; return View(); } } } // SuperAdmin Dashboard - only accessible by SuperAdmin public ActionResult Dashboard() { if (Session["AdminType"] == null || Session["AdminType"].ToString() != "SuperAdmin") return RedirectToAction("Index"); return View(); // Views/Admin/Dashboard.cshtml (SuperAdmin Dashboard) } // SuperAdmin Logout public ActionResult Logout() { Session.Clear(); return RedirectToAction("Index"); } // ============================================= // SUBADMIN LOGIN // ============================================= public ActionResult SubAdminLogin() { return View(); // Views/Admin/SubAdminLogin.cshtml } [HttpPost] public ActionResult SubAdminLogin(string username, string password) { using (SqlConnection con = new SqlConnection(connectionString)) { // Allow multi-task roles (comma-separated) // Also ensure role is not null/empty (only assigned staff should login here) string query = @"SELECT sub_admin_id, username, role FROM SubAdmins WHERE username=@Username AND password=@Password AND role IS NOT NULL AND LTRIM(RTRIM(role)) <> ''"; SqlCommand cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("@Username", username); cmd.Parameters.AddWithValue("@Password", password); con.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { reader.Read(); Session["AdminType"] = "SubAdmin"; Session["SubAdminId"] = reader["sub_admin_id"].ToString(); Session["SubAdminUsername"] = reader["username"].ToString(); Session["SubAdminRole"] = reader["role"].ToString(); return RedirectToAction("SubAdminDashboard"); } else { ViewBag.Error = "Invalid username or password!"; return View(); } } } // SubAdmin Dashboard - role passed to view via ViewBag public ActionResult SubAdminDashboard() { if (Session["AdminType"] == null || Session["AdminType"].ToString() != "SubAdmin") return RedirectToAction("SubAdminLogin"); ViewBag.Role = Session["SubAdminRole"]?.ToString() ?? "users"; ViewBag.Username = Session["SubAdminUsername"]?.ToString(); return View(); // Views/Admin/SubAdminDashboard.cshtml } // SubAdmin Logout public ActionResult SubAdminLogout() { Session.Clear(); return RedirectToAction("SubAdminLogin"); } // ============================================= // SUBADMIN MANAGEMENT (SuperAdmin only) // ============================================= // Get all sub admins public JsonResult GetSubAdmins() { if (Session["AdminType"]?.ToString() != "SuperAdmin") return Json(new { error = "Unauthorized" }, JsonRequestBehavior.AllowGet); List list = new List(); using (SqlConnection con = new SqlConnection(connectionString)) { // SubAdmin list is derived from staff task assignments string query = @"SELECT staff_id, username, email, assigned_roles FROM Staffs WHERE assigned_roles IS NOT NULL AND LTRIM(RTRIM(assigned_roles)) <> '' ORDER BY staff_id DESC"; SqlCommand cmd = new SqlCommand(query, con); con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { list.Add(new SubAdminModel { SubAdminId = Convert.ToInt32(reader["staff_id"]), Username = reader["username"].ToString(), Email = reader["email"].ToString(), Role = reader["assigned_roles"].ToString() }); } } return Json(list, JsonRequestBehavior.AllowGet); } // Create a new sub admin [HttpPost] public JsonResult CreateSubAdmin(string username, string email, string password, string role) { if (Session["AdminType"]?.ToString() != "SuperAdmin") return Json(new { success = false, message = "Unauthorized" }); // Validate role var validRoles = new HashSet { "users", "posts", "complaints" }; if (!validRoles.Contains(role)) return Json(new { success = false, message = "Invalid role." }); try { using (SqlConnection con = new SqlConnection(connectionString)) { // Check if username already exists string checkQuery = "SELECT COUNT(*) FROM SubAdmins WHERE username=@Username"; SqlCommand checkCmd = new SqlCommand(checkQuery, con); checkCmd.Parameters.AddWithValue("@Username", username); con.Open(); int exists = (int)checkCmd.ExecuteScalar(); if (exists > 0) return Json(new { success = false, message = "Username already exists." }); string query = @"INSERT INTO SubAdmins (username, email, password, role, created_at) VALUES (@Username, @Email, @Password, @Role, GETDATE())"; SqlCommand cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("@Username", username); cmd.Parameters.AddWithValue("@Email", email); cmd.Parameters.AddWithValue("@Password", password); cmd.Parameters.AddWithValue("@Role", role); cmd.ExecuteNonQuery(); } return Json(new { success = true }); } catch (Exception ex) { return Json(new { success = false, message = ex.Message }); } } // Delete a sub admin [HttpPost] public JsonResult DeleteSubAdmin(int subAdminId) { if (Session["AdminType"]?.ToString() != "SuperAdmin") return Json(new { success = false, message = "Unauthorized" }); using (SqlConnection con = new SqlConnection(connectionString)) { // Removing subadmin means clearing assigned tasks (keeps staff account) string query = @" DECLARE @Username VARCHAR(50); SELECT @Username = username FROM Staffs WHERE staff_id=@Id; UPDATE Staffs SET assigned_roles = NULL WHERE staff_id = @Id; DELETE FROM SubAdmins WHERE username = @Username;"; SqlCommand cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("@Id", subAdminId); con.Open(); cmd.ExecuteNonQuery(); } return Json(new { success = true }); } // ============================================= // STAFF MANAGEMENT (SuperAdmin only) // ============================================= public JsonResult GetStaffs() { if (Session["AdminType"]?.ToString() != "SuperAdmin") return Json(new { error = "Unauthorized" }, JsonRequestBehavior.AllowGet); var list = new List(); using (SqlConnection con = new SqlConnection(connectionString)) { string query = "SELECT staff_id, username, email, assigned_roles FROM Staffs ORDER BY staff_id DESC"; SqlCommand cmd = new SqlCommand(query, con); con.Open(); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { list.Add(new { StaffId = Convert.ToInt32(reader["staff_id"]), Username = reader["username"].ToString(), Email = reader["email"].ToString(), AssignedRoles = reader["assigned_roles"] == DBNull.Value ? "" : reader["assigned_roles"].ToString() }); } } } return Json(list, JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult AssignStaffTasks(int staffId, string rolesCsv) { if (Session["AdminType"]?.ToString() != "SuperAdmin") return Json(new { success = false, message = "Unauthorized" }); rolesCsv = (rolesCsv ?? "").Trim(); // Normalize roles: users,posts,complaints (unique) var valid = new HashSet(StringComparer.OrdinalIgnoreCase) { "users", "posts", "complaints" }; var normalized = new List(); foreach (var raw in rolesCsv.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { var r = raw.Trim().ToLower(); if (!valid.Contains(r)) return Json(new { success = false, message = "Invalid task selected." }); if (!normalized.Contains(r)) normalized.Add(r); } string finalRoles = string.Join(",", normalized); if (string.IsNullOrWhiteSpace(finalRoles)) return Json(new { success = false, message = "Select at least one task." }); using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); // Fetch staff info string staffQuery = "SELECT staff_id, username, email, password FROM Staffs WHERE staff_id = @Id"; using (var staffCmd = new SqlCommand(staffQuery, con)) { staffCmd.Parameters.AddWithValue("@Id", staffId); using (var reader = staffCmd.ExecuteReader()) { if (!reader.Read()) return Json(new { success = false, message = "Staff not found." }); string username = reader["username"].ToString(); string email = reader["email"].ToString(); string password = reader["password"].ToString(); reader.Close(); // Update Staffs string updateStaff = "UPDATE Staffs SET assigned_roles = @Roles WHERE staff_id = @Id"; using (var up = new SqlCommand(updateStaff, con)) { up.Parameters.AddWithValue("@Roles", finalRoles); up.Parameters.AddWithValue("@Id", staffId); up.ExecuteNonQuery(); } // Upsert SubAdmins by username (used for SubAdminLogin) string upsert = @" IF EXISTS (SELECT 1 FROM SubAdmins WHERE username = @Username) UPDATE SubAdmins SET email=@Email, password=@Password, role=@Role WHERE username=@Username; ELSE INSERT INTO SubAdmins (username, email, password, role, created_at) VALUES (@Username, @Email, @Password, @Role, GETDATE());"; using (var cmd = new SqlCommand(upsert, con)) { cmd.Parameters.AddWithValue("@Username", username); cmd.Parameters.AddWithValue("@Email", email); cmd.Parameters.AddWithValue("@Password", password); cmd.Parameters.AddWithValue("@Role", finalRoles); cmd.ExecuteNonQuery(); } // Insert staff notification string msg = "New tasks assigned: " + finalRoles.Replace(",", ", "); string notif = @"INSERT INTO StaffNotifications (staff_id, message, is_read, created_at) VALUES (@Id, @Msg, 0, GETDATE())"; using (var ncmd = new SqlCommand(notif, con)) { ncmd.Parameters.AddWithValue("@Id", staffId); ncmd.Parameters.AddWithValue("@Msg", msg); ncmd.ExecuteNonQuery(); } } } } return Json(new { success = true }); } // ============================================= // USERS (SuperAdmin + SubAdmin with role=users) // ============================================= public JsonResult GetAllUsers() { if (!IsAuthorized("users")) return Json(new { error = "Unauthorized" }, JsonRequestBehavior.AllowGet); List users = new List(); using (SqlConnection con = new SqlConnection(connectionString)) { string query = "SELECT user_id, username, email, registration_no FROM Users"; SqlCommand cmd = new SqlCommand(query, con); con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { users.Add(new AdminUserModel { UserId = Convert.ToInt32(reader["user_id"]), Username = reader["username"].ToString(), Email = reader["email"].ToString(), RegistrationNo = reader["registration_no"].ToString() }); } } return Json(users, JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult DeleteUser(int userId) { if (!IsAuthorized("users")) return Json(new { success = false, message = "Unauthorized" }); try { using (SqlConnection con = new SqlConnection(connectionString)) { string query = @" BEGIN TRANSACTION; BEGIN TRY -- 1. Alumni Profiles DELETE FROM alumni_profiles WHERE user_id = @UserId; -- 2. Friend Requests DELETE FROM FriendRequests WHERE from_user_id = @UserId OR to_user_id = @UserId; -- 3. Followers DELETE FROM followers WHERE follower_user_id = @UserId OR following_user_id = @UserId; -- 4. Messages & ScheduledMessages DELETE FROM Messages WHERE sender_id = @UserId OR receiver_id = @UserId; DELETE FROM ScheduledMessages WHERE sender_id = @UserId OR receiver_id = @UserId; -- 5. Notifications DELETE FROM Notifications WHERE sender_user_id = @UserId OR receiver_user_id = @UserId; -- 6. Reports DELETE FROM Reports WHERE reported_user_id = @UserId OR reported_by_user_id = @UserId; DELETE FROM Reports WHERE post_id IN (SELECT post_id FROM Posts WHERE user_id = @UserId); -- 7. Likes & Comments on the user's posts DELETE FROM Likes WHERE post_id IN (SELECT post_id FROM Posts WHERE user_id = @UserId); DELETE FROM Comments WHERE post_id IN (SELECT post_id FROM Posts WHERE user_id = @UserId); -- 8. Likes & Comments made by the user DELETE FROM Likes WHERE user_id = @UserId; DELETE FROM Comments WHERE user_id = @UserId; -- 9. Opportunities DELETE FROM Opportunities WHERE user_id = @UserId; -- 10. Notes DELETE FROM Notes WHERE UploadedBy = @UserId; -- 11. Posts DELETE FROM Posts WHERE user_id = @UserId; -- 12. Users DELETE FROM Users WHERE user_id = @UserId; COMMIT TRANSACTION; END TRY BEGIN CATCH ROLLBACK TRANSACTION; THROW; END CATCH"; SqlCommand cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("@UserId", userId); con.Open(); cmd.ExecuteNonQuery(); } return Json(new { success = true }); } catch (Exception ex) { return Json(new { success = false, message = "Error: " + ex.Message }); } } public ActionResult PendingUsers() { if (!IsAuthorized("users")) return Json(new { error = "Unauthorized" }, JsonRequestBehavior.AllowGet); List pendingUsers = new List(); using (SqlConnection con = new SqlConnection(connectionString)) { string query = "SELECT user_id, username, registration_no, email FROM Users WHERE IsApproved = 0"; using (SqlCommand cmd = new SqlCommand(query, con)) { con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { pendingUsers.Add(new User { UserId = Convert.ToInt32(reader["user_id"]), Username = reader["username"].ToString(), RegistrationNo = reader["registration_no"].ToString(), Email = reader["email"].ToString() }); } } } return Json(pendingUsers, JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult ApproveUser(int userId) { if (!IsAuthorized("users")) return Json(new { success = false, message = "Unauthorized" }); using (SqlConnection con = new SqlConnection(connectionString)) { string query = "UPDATE Users SET IsApproved = 1 WHERE user_id = @userId"; using (SqlCommand cmd = new SqlCommand(query, con)) { cmd.Parameters.AddWithValue("@userId", userId); con.Open(); cmd.ExecuteNonQuery(); } } return Json(new { success = true }); } [HttpPost] public JsonResult RejectUser(int userId) { if (!IsAuthorized("users")) return Json(new { success = false, message = "Unauthorized" }); using (SqlConnection con = new SqlConnection(connectionString)) { string query = "DELETE FROM Users WHERE user_id = @userId"; using (SqlCommand cmd = new SqlCommand(query, con)) { cmd.Parameters.AddWithValue("@userId", userId); con.Open(); cmd.ExecuteNonQuery(); } } return Json(new { success = true }); } // ============================================= // POSTS (SuperAdmin + SubAdmin with role=posts) // ============================================= public JsonResult GetAllPosts() { if (!IsAuthorized("posts")) return Json(new { error = "Unauthorized" }, JsonRequestBehavior.AllowGet); List posts = new List(); using (SqlConnection con = new SqlConnection(connectionString)) { string query = @"SELECT post_id, user_id, caption, media_url, Accepted, IsDeleted FROM Posts WHERE Accepted = 0 AND IsDeleted = 0"; SqlCommand cmd = new SqlCommand(query, con); con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { posts.Add(new AdminPostModel { PostId = Convert.ToInt32(reader["post_id"]), UserId = Convert.ToInt32(reader["user_id"]), Caption = reader["caption"].ToString(), MediaUrl = reader["media_url"].ToString(), Accepted = Convert.ToBoolean(reader["Accepted"]), IsDeleted = Convert.ToBoolean(reader["IsDeleted"]) }); } } return Json(posts, JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult AcceptPost(int postId) { if (!IsAuthorized("posts")) return Json(new { success = false, message = "Unauthorized" }); using (SqlConnection con = new SqlConnection(connectionString)) { string query = "UPDATE Posts SET Accepted = 1 WHERE post_id=@PostId"; SqlCommand cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("@PostId", postId); con.Open(); cmd.ExecuteNonQuery(); } return Json(new { success = true }); } [HttpPost] public JsonResult DeletePost(int postId) { if (!IsAuthorized("posts")) return Json(new { success = false, message = "Unauthorized" }); using (SqlConnection con = new SqlConnection(connectionString)) { string query = "UPDATE Posts SET IsDeleted = 1 WHERE post_id=@PostId"; SqlCommand cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("@PostId", postId); con.Open(); cmd.ExecuteNonQuery(); } return Json(new { success = true }); } // ============================================= // HELPER: Authorization Check // ============================================= /// /// Returns true if: /// - Current session is SuperAdmin (can do everything), OR /// - Current session is SubAdmin with matching role /// private bool IsAuthorized(string requiredRole) { string adminType = Session["AdminType"]?.ToString(); if (adminType == "SuperAdmin") return true; if (adminType == "SubAdmin") { string subRole = Session["SubAdminRole"]?.ToString() ?? ""; var roles = subRole.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(r => r.Trim()) .Where(r => !string.IsNullOrEmpty(r)) .ToHashSet(StringComparer.OrdinalIgnoreCase); return roles.Contains(requiredRole); } return false; } } }