encapsulate setting api [OOP]

This commit is contained in:
Thanakorn S
2026-05-07 08:56:40 +07:00
parent 47cc2819d3
commit 0d2fa3e3bd
6 changed files with 314 additions and 303 deletions
+8 -22
View File
@@ -4,46 +4,31 @@
*
* action: 'read' → return list of companies the user belongs to
* action: 'update' → switch to the requested company_id
*
* Both actions verify that the user is actually a member of the target company
* via company_map_user before touching the session.
*/
session_start();
require '../../../assets/utils/db_auth.php';
require '../../../assets/utils/classes/UserManager.php';
$action = $data['action'] ?? '';
// ── READ: return all companies this user belongs to ───────────────────────────
if ($action === 'read') {
$sth = $pdo1->prepare(
"SELECT cl.company_id, cl.channel_name, cl.company_name, cl.branch, cmu.role
FROM company_map_user cmu
JOIN company_list cl ON cl.company_id = cmu.company_id
WHERE cmu.user_id = :user_id
ORDER BY cl.company_name ASC"
);
$sth->execute([':user_id' => $user_id]);
$companies = $sth->fetchAll(PDO::FETCH_ASSOC);
$um = new UserManager($pdo1, $company_id, $user_id);
$answer['success'] = 1;
$answer['output'] = $companies;
$answer['current'] = (int) $_SESSION['login_company_id'];
$answer['output'] = $um->getCompanyList();
$answer['current'] = (int)$_SESSION['login_company_id'];
exit(json_encode($answer));
}
// ── UPDATE: switch to a different company ─────────────────────────────────────
if ($action === 'update') {
$target_company_id = (int)($data['company_id'] ?? 0);
if (!$target_company_id) {
http_response_code(400);
$answer['message'] = 'Invalid company.';
http_response_code(400);
exit(json_encode($answer));
}
// Verify user actually belongs to the requested company
$sth = $pdo1->prepare(
"SELECT company_id, role FROM company_map_user
WHERE company_id = :company_id AND user_id = :user_id
@@ -53,8 +38,8 @@ if ($action === 'update') {
$target_map = $sth->fetch(PDO::FETCH_ASSOC);
if (!$target_map) {
http_response_code(403);
$answer['message'] = 'You do not have access to this company.';
http_response_code(403);
exit(json_encode($answer));
}
@@ -66,6 +51,7 @@ if ($action === 'update') {
exit(json_encode($answer));
}
http_response_code(400);
$answer['message'] = 'Invalid action.';
http_response_code(400);
exit(json_encode($answer));
?>