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; ?>