Files
2026-09-16 23:20:08 +07:00

72 lines
2.9 KiB
PHP

<?php
namespace app\Controllers;
use app\Models\UserModel;
use app\Models\UserLogModel;
class ProfileController extends Controller {
public function index() {
$userModel = new UserModel();
$user = $userModel->getUserById($_SESSION['user_id']);
$roleName = $user['role_id'] == 1 ? 'ผู้ดูแลระบบ (Admin)' : 'ผู้ใช้งานทั่วไป (User)';
$this->view('profile/index', [
'title' => 'ข้อมูลส่วนตัว | ' . APP_NAME,
'user' => $user,
'roleName' => $roleName
]);
}
public function updatePassword() {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$currentPassword = $_POST['current_password'] ?? '';
$newPassword = $_POST['new_password'] ?? '';
$confirmPassword = $_POST['confirm_password'] ?? '';
if (empty($currentPassword) || empty($newPassword) || empty($confirmPassword)) {
$_SESSION['error'] = 'กรุณากรอกข้อมูลให้ครบถ้วน';
header('Location: ' . BASE_URL . '/profile');
exit;
}
if ($newPassword !== $confirmPassword) {
$_SESSION['error'] = 'รหัสผ่านใหม่ไม่ตรงกัน';
header('Location: ' . BASE_URL . '/profile');
exit;
}
if (strlen($newPassword) < 6) {
$_SESSION['error'] = 'รหัสผ่านใหม่ต้องมีความยาวอย่างน้อย 6 ตัวอักษร';
header('Location: ' . BASE_URL . '/profile');
exit;
}
$userModel = new UserModel();
$user = $userModel->getUserById($_SESSION['user_id']);
if (!$user || !password_verify($currentPassword, $user['password_hash'])) {
$_SESSION['error'] = 'รหัสผ่านปัจจุบันไม่ถูกต้อง';
header('Location: ' . BASE_URL . '/profile');
exit;
}
try {
$userModel->updatePassword($_SESSION['user_id'], $newPassword);
$logModel = new UserLogModel();
$logModel->logAction($_SESSION['user_id'], 'UPDATE_USER', 'เปลี่ยนรหัสผ่านของตนเองผ่านหน้าข้อมูลส่วนตัว');
$_SESSION['success'] = 'เปลี่ยนรหัสผ่านเรียบร้อยแล้ว';
} catch (\Exception $e) {
$_SESSION['error'] = 'เกิดข้อผิดพลาด ไม่สามารถเปลี่ยนรหัสผ่านได้';
}
header('Location: ' . BASE_URL . '/profile');
exit;
}
}
}
?>