userModel = new UserModel(); } /** * Display profile edit form */ public function index() { $userId = session()->get('user_id'); if (!$userId) { return redirect()->to('/auth/login') ->with('error', 'Silakan login terlebih dahulu.'); } $user = $this->userModel->find($userId); if (!$user) { return redirect()->to('/admin/dashboard') ->with('error', 'User tidak ditemukan.'); } $data = [ 'title' => 'Edit Profile', 'user' => $user, ]; return view('admin/profile/index', $data); } /** * Update profile */ public function update() { $userId = session()->get('user_id'); if (!$userId) { return redirect()->to('/auth/login') ->with('error', 'Silakan login terlebih dahulu.'); } $user = $this->userModel->find($userId); if (!$user) { return redirect()->to('/admin/dashboard') ->with('error', 'User tidak ditemukan.'); } $validation = \Config\Services::validation(); $rules = [ 'username' => 'required|min_length[3]|max_length[100]', 'email' => 'required|valid_email|max_length[255]', 'phone_number' => 'permit_empty|max_length[20]', 'telegram_id' => 'permit_empty|integer', ]; if (!$this->validate($rules)) { return redirect()->back() ->withInput() ->with('errors', $validation->getErrors()); } // Check if username is unique (except current user) $existingUser = $this->userModel->where('username', $this->request->getPost('username')) ->where('id !=', $userId) ->first(); if ($existingUser) { return redirect()->back() ->withInput() ->with('errors', ['username' => 'Username sudah digunakan.']); } // Check if email is unique (except current user) $existingEmail = $this->userModel->where('email', $this->request->getPost('email')) ->where('id !=', $userId) ->first(); if ($existingEmail) { return redirect()->back() ->withInput() ->with('errors', ['email' => 'Email sudah digunakan.']); } $data = [ 'username' => $this->request->getPost('username'), 'email' => $this->request->getPost('email'), 'phone_number' => $this->request->getPost('phone_number') ?: null, 'telegram_id' => $this->request->getPost('telegram_id') ?: null, ]; // Update password if provided $newPassword = $this->request->getPost('password'); if (!empty($newPassword)) { if (strlen($newPassword) < 6) { return redirect()->back() ->withInput() ->with('error', 'Password minimal 6 karakter.'); } $data['password_hash'] = password_hash($newPassword, PASSWORD_DEFAULT); } if ($this->userModel->update($userId, $data)) { // Update session data session()->set([ 'username' => $data['username'], 'email' => $data['email'], ]); return redirect()->to('/admin/profile') ->with('success', 'Profile berhasil diperbarui.'); } return redirect()->back() ->withInput() ->with('error', 'Gagal memperbarui profile.'); } }