90 lines
3.1 KiB
PHP
90 lines
3.1 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'config/db.php';
|
|
require_once 'includes/functions.php';
|
|
|
|
// Must be logged in and be a superadmin
|
|
if (!isset($_SESSION['cid']) || $_SESSION['role'] !== 'superadmin') {
|
|
header("location: index.php");
|
|
exit;
|
|
}
|
|
|
|
$action = $_POST['action'] ?? $_GET['action'] ?? '';
|
|
|
|
if ($action == 'create') {
|
|
$cid = trim($_POST['cid'] ?? '');
|
|
$role = $_POST['role'] ?? 'admin';
|
|
|
|
if (empty($cid) || strlen($cid) != 13) {
|
|
header("location: users.php?error=" . urlencode("เลขบัตรประชาชนต้องมี 13 หลัก"));
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
// 1. Check if user exists in hr_person (HOSxP)
|
|
$stmt_check = $pdo_hos->prepare("SELECT HR_CID FROM hr_person WHERE HR_CID = :cid");
|
|
$stmt_check->execute(['cid' => $cid]);
|
|
|
|
if (!$stmt_check->fetch()) {
|
|
header("location: users.php?error=" . urlencode("ไม่พบหมายเลขบัตรประชาชนนี้ในฐานข้อมูลบุคลากร HOSxP"));
|
|
exit;
|
|
}
|
|
|
|
// 2. Check if already exists in system_users
|
|
$stmt_sys_check = $pdo_sys->prepare("SELECT id FROM system_users WHERE cid = :cid");
|
|
$stmt_sys_check->execute(['cid' => $cid]);
|
|
|
|
if ($stmt_sys_check->fetch()) {
|
|
header("location: users.php?error=" . urlencode("บุคคลนี้ได้รับสิทธิ์ในระบบอยู่แล้ว"));
|
|
exit;
|
|
}
|
|
|
|
// 3. Insert into system_users
|
|
$sql = "INSERT INTO system_users (cid, role, created_by) VALUES (:cid, :role, :created_by)";
|
|
$stmt = $pdo_sys->prepare($sql);
|
|
$stmt->execute([
|
|
'cid' => $cid,
|
|
'role' => $role,
|
|
'created_by' => $_SESSION['cid']
|
|
]);
|
|
|
|
add_log($pdo_sys, $_SESSION['cid'], $_SESSION['fullname'], 'Assign Role', "Assigned $role role to CID: $cid");
|
|
|
|
header("location: users.php?msg=success");
|
|
exit;
|
|
|
|
} catch (PDOException $e) {
|
|
header("location: users.php?error=" . urlencode("Database Error: " . $e->getMessage()));
|
|
exit;
|
|
}
|
|
}
|
|
|
|
if ($action == 'delete') {
|
|
$id = $_GET['id'] ?? '';
|
|
if ($id) {
|
|
try {
|
|
// Get info for log
|
|
$stmt = $pdo_sys->prepare("SELECT cid, role FROM system_users WHERE id = :id");
|
|
$stmt->execute(['id' => $id]);
|
|
$row = $stmt->fetch();
|
|
|
|
if ($row) {
|
|
$delStmt = $pdo_sys->prepare("DELETE FROM system_users WHERE id = :id");
|
|
$delStmt->execute(['id' => $id]);
|
|
|
|
add_log($pdo_sys, $_SESSION['cid'], $_SESSION['fullname'], 'Revoke Role', "Revoked {$row['role']} role from CID: {$row['cid']}");
|
|
}
|
|
|
|
header("location: users.php?msg=success");
|
|
exit;
|
|
} catch (PDOException $e) {
|
|
header("location: users.php?error=" . urlencode("Database Error: " . $e->getMessage()));
|
|
exit;
|
|
}
|
|
}
|
|
}
|
|
|
|
header("location: users.php");
|
|
exit;
|
|
?>
|