getAllUsers(); $roles = $userModel->getRoles(); $this->view('users/index', [ 'title' => 'จัดการผู้ใช้งานระบบ | ' . APP_NAME, 'activeMenu' => 'users', 'users' => $users, 'roles' => $roles ]); } public function logs() { $userModel = new UserModel(); $userLogModel = new UserLogModel(); $filters = [ 'user_id' => $_GET['user_id'] ?? '', 'action' => $_GET['action'] ?? '', 'date_start' => $_GET['date_start'] ?? '', 'date_end' => $_GET['date_end'] ?? '' ]; $users = $userModel->getAllUsers(); $logs = $userLogModel->getLogs($filters); $this->view('users/logs', [ 'title' => 'ประวัติการใช้งานระบบ | ' . APP_NAME, 'activeMenu' => 'users', 'users' => $users, 'logs' => $logs, 'filters' => $filters ]); } public function store() { if ($_SERVER['REQUEST_METHOD'] === 'POST') { $data = [ 'username' => $_POST['username'] ?? '', 'password' => $_POST['password'] ?? '', 'role_id' => $_POST['role_id'] ?? 2, 'first_name' => $_POST['first_name'] ?? '', 'last_name' => $_POST['last_name'] ?? '', 'status' => isset($_POST['status']) ? 'active' : 'inactive' ]; $userModel = new UserModel(); try { $userModel->createUser($data); $logModel = new UserLogModel(); $logModel->logAction($_SESSION['user_id'], 'CREATE_USER', 'เพิ่มผู้ใช้งานใหม่ Username: ' . $data['username']); $_SESSION['success'] = 'เพิ่มผู้ใช้งานสำเร็จ'; } catch (\PDOException $e) { $_SESSION['error'] = 'ไม่สามารถเพิ่มผู้ใช้งานได้ (Username อาจซ้ำ)'; } header('Location: ' . BASE_URL . '/users'); exit; } } public function update() { if ($_SERVER['REQUEST_METHOD'] === 'POST') { $data = [ 'id' => $_POST['id'] ?? '', 'first_name' => $_POST['first_name'] ?? '', 'last_name' => $_POST['last_name'] ?? '', 'role_id' => $_POST['role_id'] ?? 2, 'password' => $_POST['password'] ?? '' ]; $userModel = new UserModel(); try { $userModel->updateUser($data); $logModel = new UserLogModel(); $logModel->logAction($_SESSION['user_id'], 'UPDATE_USER', 'แก้ไขข้อมูลผู้ใช้งาน ID: ' . $data['id']); $_SESSION['success'] = 'แก้ไขข้อมูลผู้ใช้งานสำเร็จ'; } catch (\PDOException $e) { $_SESSION['error'] = 'ไม่สามารถแก้ไขข้อมูลได้'; } header('Location: ' . BASE_URL . '/users'); exit; } } public function toggle_status() { if ($_SERVER['REQUEST_METHOD'] === 'POST') { $userId = $_POST['user_id'] ?? ''; $status = $_POST['status'] ?? 'inactive'; // Prevent locking out the only admin or self if needed (optional) if ($userId == $_SESSION['user_id'] && $status == 'inactive') { $_SESSION['error'] = 'ไม่สามารถปิดสิทธิ์บัญชีตัวเองได้'; } else { $userModel = new UserModel(); try { $userModel->updateStatus($userId, $status); $logModel = new UserLogModel(); $logModel->logAction($_SESSION['user_id'], 'TOGGLE_STATUS', "เปลี่ยนสถานะผู้ใช้งาน ID: $userId เป็น $status"); $_SESSION['success'] = 'ปรับสถานะการใช้งานสำเร็จ'; } catch (\PDOException $e) { $_SESSION['error'] = 'ไม่สามารถปรับสถานะได้'; } } header('Location: ' . BASE_URL . '/users'); exit; } } }