72 lines
2.4 KiB
PHP
72 lines
2.4 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
|
|
*
|
|
* 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';
|
|
|
|
$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);
|
|
|
|
$answer['success'] = 1;
|
|
$answer['output'] = $companies;
|
|
$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.';
|
|
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
|
|
LIMIT 1"
|
|
);
|
|
$sth->execute([':company_id' => $target_company_id, ':user_id' => $user_id]);
|
|
$target_map = $sth->fetch(PDO::FETCH_ASSOC);
|
|
|
|
if (!$target_map) {
|
|
http_response_code(403);
|
|
$answer['message'] = 'You do not have access to this company.';
|
|
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));
|
|
}
|
|
|
|
http_response_code(400);
|
|
$answer['message'] = 'Invalid action.';
|
|
exit(json_encode($answer));
|