Files

85 lines
2.7 KiB
PHP

<?php
/**
* Profile API — any logged-in user can view/update their own profile
* GET ?action=get — Get current user's profile
* POST ?action=update — Update current user's profile (except personnel_code)
*/
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
header('Content-Type: application/json; charset=utf-8');
requireLogin();
$action = $_GET['action'] ?? '';
switch ($action) {
case 'get':
getProfile();
break;
case 'update':
updateProfile();
break;
default:
jsonResponse(['error' => 'Invalid action'], 400);
}
function getProfile() {
$userId = $_SESSION['user_id'];
$db = getDB();
$stmt = $db->prepare("SELECT id, username, role, full_name, personnel_code, subject_area, branch_code, email, created_at FROM users WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();
if (!$user) {
jsonResponse(['error' => 'ไม่พบข้อมูลผู้ใช้'], 404);
}
jsonResponse(['user' => $user]);
}
function updateProfile() {
$userId = $_SESSION['user_id'];
$input = getInput();
$fullName = trim($input['full_name'] ?? '');
$subjectArea = trim($input['subject_area'] ?? '');
$branchCode = trim($input['branch_code'] ?? '');
$email = trim($input['email'] ?? '');
$db = getDB();
$fields = [];
$params = [];
if (!empty($fullName)) { $fields[] = "full_name = ?"; $params[] = $fullName; }
if ($subjectArea !== '') { $fields[] = "subject_area = ?"; $params[] = $subjectArea; }
if ($branchCode !== '') { $fields[] = "branch_code = ?"; $params[] = $branchCode; }
if (isset($input['email'])) { $fields[] = "email = ?"; $params[] = trim($input['email']); }
// Update password if provided
if (!empty($input['password'])) {
if (strlen($input['password']) < 4) {
jsonResponse(['error' => 'รหัสผ่านต้องมีอย่างน้อย 4 ตัวอักษร'], 400);
}
$fields[] = "password_hash = ?";
$params[] = password_hash($input['password'], PASSWORD_DEFAULT);
}
if (empty($fields)) {
jsonResponse(['error' => 'ไม่มีข้อมูลที่ต้องอัปเดต'], 400);
}
$params[] = $userId;
$sql = "UPDATE users SET " . implode(', ', $fields) . " WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->execute($params);
// Update session name if changed
if (!empty($fullName)) {
$_SESSION['full_name'] = $fullName;
}
jsonResponse(['success' => true, 'message' => 'อัปเดตข้อมูลส่วนตัวสำเร็จ']);
}