Files
wms-app/app/setting/api/engine/switch_branch.php
T

58 lines
1.6 KiB
PHP

<?php
/**
* switch_branch.php — Switch the active company for the current session.
*
* action: 'read' → return list of companies the user belongs to
* action: 'update' → switch to the requested company_id
*/
session_start();
require '../../../assets/utils/db_auth.php';
require '../../../assets/utils/classes/UserManager.php';
$action = $data['action'] ?? '';
if ($action === 'read') {
$um = new UserManager($pdo1, $company_id, $user_id);
$answer['success'] = 1;
$answer['output'] = $um->getCompanyList();
$answer['current'] = (int)$_SESSION['login_company_id'];
exit(json_encode($answer));
}
if ($action === 'update') {
$target_company_id = (int)($data['company_id'] ?? 0);
if (!$target_company_id) {
$answer['message'] = 'Invalid company.';
http_response_code(400);
exit(json_encode($answer));
}
$sth = $pdo1->prepare(
"SELECT company_id, role FROM company_map_user
WHERE company_id = :company_id AND user_id = :user_id
LIMIT 1"
);
$sth->execute([':company_id' => $target_company_id, ':user_id' => $user_id]);
$target_map = $sth->fetch(PDO::FETCH_ASSOC);
if (!$target_map) {
$answer['message'] = 'You do not have access to this company.';
http_response_code(403);
exit(json_encode($answer));
}
$_SESSION['login_company_id'] = $target_company_id;
$_SESSION['login_role'] = $target_map['role'] ?? 'viewer';
$answer['success'] = 1;
$answer['message'] = 'Switched successfully.';
exit(json_encode($answer));
}
$answer['message'] = 'Invalid action.';
http_response_code(400);
exit(json_encode($answer));
?>