Login , Register ,and onboarding

This commit is contained in:
Thanakorn S
2026-04-28 11:59:49 +07:00
parent d8c55d278a
commit d8fd30c961
25 changed files with 2394 additions and 110 deletions
+144
View File
@@ -0,0 +1,144 @@
<?php
session_start();
require '../../../assets/utils/db_auth.php';
// ─── Role guard: only owner/admin ────────────────────────────────────────
$sth = $pdo1->prepare("
SELECT role FROM company_map_user
WHERE company_id = :company_id AND user_id = :user_id
LIMIT 1
");
$sth->execute([':company_id' => $company_id, ':user_id' => $user_id]);
db_check($sth, $answer);
if (!in_array($sth->fetchColumn(), ['owner', 'admin'], true)) {
$answer['message'] = 'You do not have permission to change SMTP settings.';
http_response_code(403);
exit(json_encode($answer));
}
// ─── Encrypt password — same method/key/iv as config.php ─────────────────
function encrypt_password(string $plain): string {
global $pinkey, $method, $iv;
return openssl_encrypt($plain, $method, $pinkey, 0, $iv);
}
try {
$server = trim($data['smtp_host'] ?? '');
$port = trim($data['smtp_port'] ?? '587');
$username = trim($data['smtp_username'] ?? '');
$raw_pass = $data['smtp_password'] ?? ''; // blank = keep current
$from_name = trim($data['smtp_from_name'] ?? '');
$from_email = trim($data['smtp_from_email'] ?? '');
$encryption = trim($data['smtp_encryption'] ?? 'tls');
if (!$server || !$username) {
$answer['message'] = 'SMTP host and username are required.';
http_response_code(422);
exit(json_encode($answer));
}
if (!in_array($port, ['25', '465', '587'], true)) $port = '587';
if (!in_array($encryption, ['tls', 'ssl', 'none'], true)) $encryption = 'tls';
// Check if row already exists (uses pdo1 — company_smtp lives in wms2)
$sth = $pdo1->prepare("
SELECT smtp_id FROM company_smtp
WHERE company_id = :company_id LIMIT 1
");
$sth->execute([':company_id' => $company_id]);
db_check($sth, $answer);
$existing_id = $sth->fetchColumn();
if ($existing_id) {
if ($raw_pass !== '') {
$sth = $pdo1->prepare("
UPDATE company_smtp SET
server = :server,
port = :port,
username = :username,
password = :password,
from_name = :from_name,
from_email = :from_email,
encryption = :encryption,
updated_at = NOW()
WHERE smtp_id = :smtp_id
");
$sth->execute([
':server' => $server,
':port' => $port,
':username' => $username,
':password' => encrypt_password($raw_pass),
':from_name' => $from_name,
':from_email' => $from_email,
':encryption' => $encryption,
':smtp_id' => $existing_id,
]);
} else {
// Keep existing password — don't touch it
$sth = $pdo1->prepare("
UPDATE company_smtp SET
server = :server,
port = :port,
username = :username,
from_name = :from_name,
from_email = :from_email,
encryption = :encryption,
updated_at = NOW()
WHERE smtp_id = :smtp_id
");
$sth->execute([
':server' => $server,
':port' => $port,
':username' => $username,
':from_name' => $from_name,
':from_email' => $from_email,
':encryption' => $encryption,
':smtp_id' => $existing_id,
]);
}
} else {
// New record — password required
if ($raw_pass === '') {
$answer['message'] = 'Password is required for a new SMTP configuration.';
http_response_code(422);
exit(json_encode($answer));
}
$sth = $pdo1->prepare("
INSERT INTO company_smtp
(company_id, server, port, username, password,
from_name, from_email, encryption, updated_at)
VALUES
(:company_id, :server, :port, :username, :password,
:from_name, :from_email, :encryption, NOW())
");
$sth->execute([
':company_id' => $company_id,
':server' => $server,
':port' => $port,
':username' => $username,
':password' => encrypt_password($raw_pass),
':from_name' => $from_name,
':from_email' => $from_email,
':encryption' => $encryption,
]);
}
db_check($sth, $answer);
$answer['success'] = 1;
$answer['message'] = 'SMTP settings saved.';
} catch (Exception $e) {
$answer['message'] = 'Failed to save SMTP settings.';
http_response_code(500);
}
exit(json_encode($answer));
?>
+214
View File
@@ -0,0 +1,214 @@
<?php
session_start();
require '../../../assets/utils/db_auth.php';
// ─── Role guard: only owner/admin can manage users ────────────────────────
$sth = $pdo1->prepare("
SELECT role FROM company_map_user
WHERE company_id = :company_id AND user_id = :user_id
LIMIT 1
");
$sth->execute([':company_id' => $company_id, ':user_id' => $user_id]);
db_check($sth, $answer);
$caller_role = $sth->fetchColumn();
if (!in_array($caller_role, ['owner', 'admin'], true)) {
$answer['message'] = 'You do not have permission to manage users.';
http_response_code(403);
exit(json_encode($answer));
}
$action = $data['action'] ?? '';
try {
// ══════════════════════════════════════════════════════════════════════
// CREATE — invite a user by email
// ══════════════════════════════════════════════════════════════════════
if ($action === 'create') {
$invite_email = strtolower(trim($data['invite_email'] ?? ''));
$invite_role = trim($data['invite_role'] ?? '');
if (!filter_var($invite_email, FILTER_VALIDATE_EMAIL)) {
$answer['message'] = 'Invalid email address.';
http_response_code(422);
exit(json_encode($answer));
}
$allowed_roles = ['admin', 'staff', 'viewer'];
if (!in_array($invite_role, $allowed_roles, true)) {
$answer['message'] = 'Invalid role selected.';
http_response_code(422);
exit(json_encode($answer));
}
// Look up user by email
$sth = $pdo1->prepare("SELECT user_id, email FROM user WHERE email = :email LIMIT 1");
$sth->execute([':email' => $invite_email]);
db_check($sth, $answer);
$target = $sth->fetch(PDO::FETCH_ASSOC);
if (!$target) {
$answer['message'] = 'No registered account found with that email address.';
http_response_code(404);
exit(json_encode($answer));
}
$target_user_id = (int)$target['user_id'];
// Prevent inviting self
if ($target_user_id === (int)$user_id) {
$answer['message'] = 'You cannot invite yourself.';
http_response_code(422);
exit(json_encode($answer));
}
// Check if already mapped to this company
$sth = $pdo1->prepare("
SELECT map_id FROM company_map_user
WHERE company_id = :company_id AND user_id = :user_id
LIMIT 1
");
$sth->execute([':company_id' => $company_id, ':user_id' => $target_user_id]);
db_check($sth, $answer);
$existing = $sth->fetch(PDO::FETCH_ASSOC);
if ($existing) {
$answer['message'] = 'This user is already a member of your company.';
http_response_code(409);
exit(json_encode($answer));
}
$sth = $pdo1->prepare("
INSERT INTO company_map_user
(company_id, user_id, role, created_at)
VALUES
(:company_id, :user_id, :role, NOW())
");
$sth->execute([
':company_id' => $company_id,
':user_id' => $target_user_id,
':role' => $invite_role,
]);
db_check($sth, $answer);
$answer['success'] = 1;
$answer['message'] = htmlspecialchars($target['email']) . ' has been added to your company.';
// ══════════════════════════════════════════════════════════════════════
// UPDATE — change a user's role
// ══════════════════════════════════════════════════════════════════════
} elseif ($action === 'update') {
$map_id = (int)($data['map_id'] ?? 0);
$new_role = trim($data['role'] ?? '');
$allowed_roles = ['admin', 'staff', 'viewer'];
if (!$map_id || !in_array($new_role, $allowed_roles, true)) {
$answer['message'] = 'Invalid request.';
http_response_code(422);
exit(json_encode($answer));
}
// Verify map belongs to this company and is not the owner
$sth = $pdo1->prepare("
SELECT role FROM company_map_user
WHERE map_id = :map_id AND company_id = :company_id
LIMIT 1
");
$sth->execute([':map_id' => $map_id, ':company_id' => $company_id]);
db_check($sth, $answer);
$target_role = $sth->fetchColumn();
if ($target_role === false) {
$answer['message'] = 'User not found.';
http_response_code(404);
exit(json_encode($answer));
}
if ($target_role === 'owner') {
$answer['message'] = 'Owner role cannot be changed.';
http_response_code(403);
exit(json_encode($answer));
}
$sth = $pdo1->prepare("
UPDATE company_map_user
SET role = :role
WHERE map_id = :map_id AND company_id = :company_id
");
$sth->execute([
':role' => $new_role,
':map_id' => $map_id,
':company_id' => $company_id,
]);
db_check($sth, $answer);
$answer['success'] = 1;
$answer['message'] = 'Role updated successfully.';
// ══════════════════════════════════════════════════════════════════════
// DELETE — remove user from company
// ══════════════════════════════════════════════════════════════════════
} elseif ($action === 'delete') {
$map_id = (int)($data['map_id'] ?? 0);
if (!$map_id) {
$answer['message'] = 'Invalid request.';
http_response_code(422);
exit(json_encode($answer));
}
// Verify map belongs to this company, and isn't the owner
$sth = $pdo1->prepare("
SELECT role, user_id FROM company_map_user
WHERE map_id = :map_id AND company_id = :company_id
LIMIT 1
");
$sth->execute([':map_id' => $map_id, ':company_id' => $company_id]);
db_check($sth, $answer);
$row = $sth->fetch(PDO::FETCH_ASSOC);
if (!$row) {
$answer['message'] = 'User not found.';
http_response_code(404);
exit(json_encode($answer));
}
if ($row['role'] === 'owner') {
$answer['message'] = 'The owner cannot be removed.';
http_response_code(403);
exit(json_encode($answer));
}
// Prevent removing yourself
if ((int)$row['user_id'] === (int)$user_id) {
$answer['message'] = 'You cannot remove yourself.';
http_response_code(403);
exit(json_encode($answer));
}
// Hard delete — just remove the row
$sth = $pdo1->prepare("
DELETE FROM company_map_user
WHERE map_id = :map_id AND company_id = :company_id
");
$sth->execute([':map_id' => $map_id, ':company_id' => $company_id]);
db_check($sth, $answer);
$answer['success'] = 1;
$answer['message'] = 'User has been removed from this company.';
} else {
$answer['message'] = 'Unknown action.';
http_response_code(400);
}
} catch (Exception $e) {
$answer['message'] = 'An error occurred. Please try again.';
http_response_code(500);
}
exit(json_encode($answer));
?>
+33
View File
@@ -0,0 +1,33 @@
<?php
session_start();
require '../../../assets/utils/db_auth.php';
try {
$sth = $pdo1->prepare("
SELECT
server,
port,
username,
from_name,
from_email,
encryption
FROM company_smtp
WHERE company_id = :company_id
LIMIT 1
");
$sth->execute([':company_id' => $company_id]);
db_check($sth, $answer);
$row = $sth->fetch(PDO::FETCH_ASSOC);
$answer['success'] = 1;
$answer['output'] = $row ?: null; // null = not configured yet
} catch (Exception $e) {
$answer['message'] = $e->getMessage();
http_response_code(500);
}
exit(json_encode($answer));
?>
+38
View File
@@ -0,0 +1,38 @@
<?php
session_start();
require '../../../assets/utils/db_auth.php';
try {
// Fetch all users mapped to this company, joined with user profile
$sth = $pdo1->prepare("
SELECT
m.map_id,
m.role,
m.created_at,
u.user_id,
u.username,
u.name,
u.surname,
u.email,
u.profile_picture
FROM company_map_user m
JOIN user u ON u.user_id = m.user_id
WHERE m.company_id = :company_id
ORDER BY
FIELD(m.role, 'owner', 'admin', 'staff', 'viewer'),
u.name ASC
");
$sth->execute([':company_id' => $company_id]);
db_check($sth, $answer);
$answer['success'] = 1;
$answer['output'] = $sth->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
$answer['message'] = 'Failed to load users.';
http_response_code(500);
}
exit(json_encode($answer));
?>
+50
View File
@@ -0,0 +1,50 @@
<?php
session_start();
require '../../../assets/utils/db_auth.php';
try {
$keyword = trim($data['keyword'] ?? '');
if ($keyword === '') {
$answer['success'] = 1;
$answer['result'] = [];
exit(json_encode($answer));
}
$like = '%' . $keyword . '%';
// Search users by email NOT already active/pending in this company
$sth = $pdo1->prepare("
SELECT
u.user_id,
u.username,
u.name,
u.surname,
u.email
FROM user u
WHERE
u.email LIKE :kw
AND u.user_id NOT IN (
SELECT user_id FROM company_map_user
WHERE company_id = :company_id
)
ORDER BY u.email ASC
LIMIT 10
");
$sth->execute([
':kw' => $like,
':company_id' => $company_id,
]);
db_check($sth, $answer);
$answer['success'] = 1;
$answer['result'] = $sth->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
$answer['message'] = 'Search failed.';
http_response_code(500);
}
exit(json_encode($answer));
?>
+55
View File
@@ -0,0 +1,55 @@
<?php
session_start();
require '../../../assets/utils/db_auth.php';
try {
$to = trim($data['test_email'] ?? '');
if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
$answer['message'] = 'Invalid recipient email address.';
http_response_code(422);
exit(json_encode($answer));
}
// Fetch from_name / channel_name for the sender display
$sth = $pdo1->prepare("
SELECT from_name FROM company_smtp
WHERE company_id = :company_id LIMIT 1
");
$sth->execute([':company_id' => $company_id]);
db_check($sth, $answer);
$row = $sth->fetch(PDO::FETCH_ASSOC);
if (!$row) {
$answer['message'] = 'No SMTP configuration found. Please save your settings first.';
http_response_code(422);
exit(json_encode($answer));
}
$channel_name = $row['from_name'] ?: 'WMS System';
// Use existing mailer — it reads company_smtp via pdo1 automatically
require_once $include_url . 'assets/utils/module/mailer.php';
$mailer = new mailer(['pdo1' => $pdo1]);
$mailer->send_email([
'company_id' => $company_id,
'smtp' => [], // empty = mailer reads from company_smtp
'to' => $to,
'subject' => 'SMTP Test — WMS',
'message' => "This is a test email from your WMS SMTP configuration.\n\nIf you received this, your SMTP settings are working correctly.",
'channel_name' => $channel_name,
'key' => $pinkey,
]);
$answer['success'] = 1;
$answer['message'] = 'Test email sent to ' . htmlspecialchars($to) . '.';
} catch (Exception $e) {
$answer['message'] = 'Failed to send test email: ' . $e->getMessage();
http_response_code(500);
}
exit(json_encode($answer));
?>
+286
View File
@@ -0,0 +1,286 @@
<?php
session_start();
require '../config.php';
require '../include_header.php';
?>
<body>
<?php require '../include_topbar.php'; ?>
<?php require '../include_setting_sidebar.php'; ?>
<main id="content" class="content py-15">
<div class="container-fluid">
<!-- Page header -->
<div class="row">
<div class="col-12">
<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-6 gap-3">
<div>
<h1 class="fs-3 mb-1">SMTP Setting</h1>
<p class="mb-0">Configure outgoing email server for your company</p>
</div>
</div>
</div>
</div>
<div class="row g-5">
<!-- LEFT: info panel -->
<div class="col-lg-3 col-12">
<div class="card">
<div class="card-body p-6">
<div class="text-center mb-4">
<span class="d-inline-flex align-items-center justify-content-center rounded-circle bg-label-primary mb-3"
style="width:56px;height:56px;">
<i class="ti ti-mail-cog fs-3"></i>
</span>
<h6 class="mb-1">Email Server</h6>
<p class="text-muted small mb-0">Used for system notifications and invitations</p>
</div>
<hr class="my-4">
<div id="smtp_status_panel">
<div class="d-flex align-items-center gap-2 mb-2">
<span id="status_dot" class="rounded-circle d-inline-block" style="width:10px;height:10px;background:#adb5bd;flex-shrink:0;"></span>
<span id="status_label" class="small fw-semibold text-muted">Not configured</span>
</div>
<div class="small text-muted" id="status_host">—</div>
</div>
<hr class="my-4">
<div class="small text-muted">
<div class="fw-semibold mb-2">Common SMTP hosts</div>
<div class="mb-1"><i class="ti ti-brand-gmail me-1"></i>smtp.gmail.com : 587</div>
<div class="mb-1"><i class="ti ti-brand-office me-1"></i>smtp.office365.com : 587</div>
<div class="mb-1"><i class="ti ti-mail me-1"></i>smtp.mail.yahoo.com : 587</div>
</div>
</div>
</div>
</div>
<!-- RIGHT: form -->
<div class="col-lg-9 col-12">
<div class="card">
<div class="card-body p-6">
<h2 class="fs-5 mb-4">Server Configuration</h2>
<div class="row">
<div class="col-md-8 mb-3">
<label class="form-label">SMTP Host <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="smtp_host"
placeholder="e.g. smtp.gmail.com">
</div>
<div class="col-md-4 mb-3">
<label class="form-label">Port <span class="text-danger">*</span></label>
<select class="form-select" id="smtp_port">
<option value="587">587 — TLS (recommended)</option>
<option value="465">465 — SSL</option>
<option value="25">25 — Plain</option>
</select>
</div>
<div class="col-md-6 mb-3">
<label class="form-label">Username / Email <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="smtp_username"
placeholder="your@email.com">
</div>
<div class="col-md-6 mb-3">
<label class="form-label">Password</label>
<div class="input-group">
<input type="password" class="form-control" id="smtp_password"
placeholder="Leave blank to keep current">
<button class="btn btn-outline-secondary toggle-pw" type="button"
data-target="smtp_password">
<i class="ti ti-eye"></i>
</button>
</div>
<div class="form-text">Leave blank to keep the existing password.</div>
</div>
<div class="col-md-6 mb-3">
<label class="form-label">Sender Name</label>
<input type="text" class="form-control" id="smtp_from_name"
placeholder="e.g. My Company">
</div>
<div class="col-md-6 mb-3">
<label class="form-label">Sender Email</label>
<input type="email" class="form-control" id="smtp_from_email"
placeholder="noreply@company.com">
</div>
<div class="col-12 mb-3">
<label class="form-label">Encryption</label>
<div class="d-flex gap-4 mt-1">
<div class="form-check">
<input class="form-check-input" type="radio" name="smtp_encryption"
id="enc_tls" value="tls" checked>
<label class="form-check-label" for="enc_tls">TLS</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="smtp_encryption"
id="enc_ssl" value="ssl">
<label class="form-check-label" for="enc_ssl">SSL</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="smtp_encryption"
id="enc_none" value="none">
<label class="form-check-label" for="enc_none">None</label>
</div>
</div>
</div>
</div>
<!-- Test connection -->
<div class="border rounded p-4 mb-4 bg-light">
<div class="fw-semibold mb-2"><i class="ti ti-plug-connected me-1"></i>Test Connection</div>
<p class="text-muted small mb-3">Send a test email to verify your SMTP settings before saving.</p>
<div class="d-flex gap-2 align-items-center flex-wrap">
<input type="email" class="form-control form-control-sm"
id="test_email" placeholder="Send test to…"
style="max-width:260px;">
<button class="btn btn-sm btn-outline-primary" onclick="test_smtp()">
<i class="ti ti-send me-1"></i>Send Test
</button>
<span id="test_result" class="small ms-1"></span>
</div>
</div>
</div>
<div class="card-footer d-flex justify-content-end gap-2">
<button class="btn btn-ghost-secondary" onclick="load_smtp()">
<i class="ti ti-refresh me-1"></i>Reset
</button>
<button class="btn btn-primary" onclick="save_smtp()">
<i class="ti ti-device-floppy me-1"></i>Save Changes
</button>
</div>
</div>
</div>
</div>
</div>
<?php require '../include_ending.php'; ?>
</main>
<script>
// ═══════════════════════════════════════════════
// State
// ═══════════════════════════════════════════════
const api = '<?php echo $server_url?>setting/api/engine/';
// ═══════════════════════════════════════════════
// On load
// ═══════════════════════════════════════════════
$(function () {
load_smtp();
// Toggle show/hide password
$(document).on('click', '.toggle-pw', function () {
const $input = $('#' + $(this).data('target'));
const isText = $input.attr('type') === 'text';
$input.attr('type', isText ? 'password' : 'text');
$(this).find('i').toggleClass('ti-eye ti-eye-off');
});
});
// ═══════════════════════════════════════════════
// Load
// ═══════════════════════════════════════════════
function load_smtp() {
return ajax_request({
url: api + 'retrieve_smtp.php',
autoPrepare: true,
checkRequired: 0,
action: 'read',
onSuccess: function (r) {
const s = r.output;
if (!s) return; // no config yet — leave form blank
$('#smtp_host').val(s.server || '');
$('#smtp_port').val(s.port || '587');
$('#smtp_username').val(s.username || '');
$('#smtp_password').val(''); // never prefill password
$('#smtp_from_name').val(s.from_name || '');
$('#smtp_from_email').val(s.from_email || '');
$(`input[name="smtp_encryption"][value="${s.encryption || 'tls'}"]`).prop('checked', true);
update_status_panel(s);
},
});
}
// ═══════════════════════════════════════════════
// Save
// ═══════════════════════════════════════════════
function save_smtp() {
const encryption = $('input[name="smtp_encryption"]:checked').val();
ajax_request({
url: api + 'manage_smtp.php',
autoPrepare: true,
checkRequired: 0,
action: 'manage',
data: { smtp_encryption: encryption },
onSuccess: function (r) {
bootbox.alert('SMTP settings saved.');
load_smtp();
},
});
}
// ═══════════════════════════════════════════════
// Test connection
// ═══════════════════════════════════════════════
function test_smtp() {
const to = $('#test_email').val().trim();
if (!to) {
$('#test_result').html('<span class="text-danger">Enter a recipient email.</span>');
return;
}
$('#test_result').html('<span class="text-muted"><i class="ti ti-loader-2 me-1"></i>Sending…</span>');
ajax_request({
url: api + 'test_smtp.php',
autoPrepare: true,
checkRequired: 0,
action: 'read',
data: { test_email: to },
onSuccess: function (r) {
$('#test_result').html('<span class="text-success"><i class="ti ti-circle-check me-1"></i>' + (r.message || 'Test email sent!') + '</span>');
},
onError: function (r) {
$('#test_result').html('<span class="text-danger"><i class="ti ti-circle-x me-1"></i>' + (r.message || 'Failed.') + '</span>');
},
});
}
// ═══════════════════════════════════════════════
// Status panel
// ═══════════════════════════════════════════════
function update_status_panel(s) {
if (s && s.server) {
$('#status_dot').css('background', '#198754');
$('#status_label').text('Configured').removeClass('text-muted').addClass('text-success');
$('#status_host').text(s.server + ' : ' + (s.port || '587'));
} else {
$('#status_dot').css('background', '#adb5bd');
$('#status_label').text('Not configured').addClass('text-muted').removeClass('text-success');
$('#status_host').text('—');
}
}
</script>
</body>
</html>
+424
View File
@@ -0,0 +1,424 @@
<?php
session_start();
require '../config.php';
require '../include_header.php';
?>
<body>
<?php require '../include_topbar.php'; ?>
<?php require '../include_setting_sidebar.php'; ?>
<main id="content" class="content py-15">
<div class="container-fluid">
<!-- Page header -->
<div class="row">
<div class="col-12">
<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-6 gap-3">
<div>
<h1 class="fs-3 mb-1">Users Access</h1>
<p class="mb-0">Manage team members and their roles in your company</p>
</div>
<div class="d-flex gap-2">
<button class="btn btn-primary" onclick="open_invite_modal()">
<i class="ti ti-user-plus me-1"></i>Add User
</button>
</div>
</div>
</div>
</div>
<!-- Users table card -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body p-0">
<!-- Toolbar -->
<div class="d-flex align-items-center gap-3 px-4 py-3 border-bottom">
<div class="flex-grow-1" style="max-width:320px;">
<div class="input-group input-group-sm">
<span class="input-group-text bg-transparent border-end-0">
<i class="ti ti-search text-muted"></i>
</span>
<input type="text" id="search_input" class="form-control border-start-0 ps-0"
placeholder="Search by name or email…" oninput="filter_table()">
</div>
</div>
<div>
<select id="filter_role" class="form-select form-select-sm" onchange="filter_table()" style="min-width:130px;">
<option value="">All roles</option>
<option value="owner">Owner</option>
<option value="admin">Admin</option>
<option value="staff">Staff</option>
<option value="viewer">Viewer</option>
</select>
</div>
</div>
<!-- Table -->
<div class="table-responsive">
<table class="table table-hover align-middle mb-0" id="users_table">
<thead class="table-light">
<tr>
<th class="ps-4">User</th>
<th>Email</th>
<th>Role</th>
<th>Joined</th>
<th class="text-end pe-4">Actions</th>
</tr>
</thead>
<tbody id="users_tbody">
<tr>
<td colspan="5" class="text-center py-5 text-muted">
<i class="ti ti-loader-2 fs-2 d-block mb-2"></i>Loading…
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<?php require '../include_ending.php'; ?>
</main>
<!-- ═══════════════════════════════════════════════
INVITE MODAL
═══════════════════════════════════════════════ -->
<div class="modal fade" id="inviteModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><i class="ti ti-user-plus me-2"></i>Add User</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label class="form-label">Email Address <span class="text-danger">*</span></label>
<input type="email" class="form-control" id="invite_email"
placeholder="user@example.com">
<div class="form-text">Enter the email address of a registered user.</div>
</div>
<div class="mb-3">
<label class="form-label">Role <span class="text-danger">*</span></label>
<select class="form-select" id="invite_role" required>
<option value="">— Select role —</option>
<option value="admin">Admin — full access except billing</option>
<option value="staff">Staff — manage inventory &amp; orders</option>
<option value="viewer">Viewer — read-only access</option>
</select>
</div>
<div class="alert alert-light border small mb-0">
<div class="fw-semibold mb-1">Role permissions</div>
<ul class="mb-0 ps-3">
<li><strong>Admin</strong> — manage users, settings, all modules</li>
<li><strong>Staff</strong> — manage inventory, ICS, orders</li>
<li><strong>Viewer</strong> — view-only access across all modules</li>
</ul>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-ghost-secondary" data-bs-dismiss="modal">Cancel</button>
<button class="btn btn-primary" onclick="send_invite()">
<i class="ti ti-user-plus me-1"></i>Add User
</button>
</div>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════════
EDIT ROLE MODAL
═══════════════════════════════════════════════ -->
<div class="modal fade" id="editRoleModal" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><i class="ti ti-shield-half me-2"></i>Change Role</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<input type="hidden" id="edit_map_id">
<div class="d-flex align-items-center gap-3 mb-4">
<img id="edit_avatar" src="" alt=""
class="rounded-circle border" style="width:48px;height:48px;object-fit:cover;">
<div>
<div class="fw-semibold" id="edit_username">—</div>
<div class="text-muted small" id="edit_email_display">—</div>
</div>
</div>
<div class="mb-3">
<label class="form-label">Role</label>
<select class="form-select" id="edit_role">
<option value="admin">Admin</option>
<option value="staff">Staff</option>
<option value="viewer">Viewer</option>
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-ghost-secondary" data-bs-dismiss="modal">Cancel</button>
<button class="btn btn-primary" onclick="save_role()">
<i class="ti ti-device-floppy me-1"></i>Save
</button>
</div>
</div>
</div>
</div>
<script>
// ═══════════════════════════════════════════════
// State
// ═══════════════════════════════════════════════
const api = '<?php echo $server_url?>setting/api/engine/';
const img_base = '<?php echo $server_url?>uploads/profile/';
const avatar_ph = '<?php echo $server_url?>assets/images/logo.svg';
let _users_data = []; // full list from server
// ═══════════════════════════════════════════════
// On load
// ═══════════════════════════════════════════════
$(function () {
load_users();
});
// ═══════════════════════════════════════════════
// Load users
// ═══════════════════════════════════════════════
function load_users() {
return ajax_request({
url: api + 'retrieve_users.php',
autoPrepare: true,
checkRequired: 0,
action: 'read',
onSuccess: function (r) {
_users_data = r.output || [];
render_table(_users_data);
},
});
}
// ═══════════════════════════════════════════════
// Render table
// ═══════════════════════════════════════════════
function render_table(rows) {
const tbody = $('#users_tbody');
if (!rows.length) {
tbody.html(`
<tr>
<td colspan="5" class="text-center py-5 text-muted">
<i class="ti ti-users-group fs-2 d-block mb-2"></i>No users found.
</td>
</tr>`);
return;
}
const html = rows.map(u => {
const avatar = u.profile_picture
? `<img src="${img_base}${u.profile_picture}" class="rounded-circle border" style="width:36px;height:36px;object-fit:cover;" alt="">`
: `<span class="avatar-initials rounded-circle d-inline-flex align-items-center justify-content-center bg-light border fw-semibold text-secondary"
style="width:36px;height:36px;font-size:13px;">${initials(u.name, u.surname)}</span>`;
const role_badge = role_html(u.role);
const joined = u.created_at
? new Date(u.created_at).toLocaleDateString('en-GB', {day:'2-digit', month:'short', year:'numeric'})
: '—';
// Build action buttons — owner cannot be edited or removed
let actions = '';
if (u.role !== 'owner') {
actions += `
<button class="btn btn-sm btn-ghost-secondary" title="Change role"
onclick="open_edit_modal(${u.map_id})">
<i class="ti ti-shield-half"></i>
</button>`;
actions += `
<button class="btn btn-sm btn-ghost-danger" title="Remove user"
onclick="remove_user(${u.map_id}, '${esc(u.name)} ${esc(u.surname)}')">
<i class="ti ti-user-minus"></i>
</button>`;
}
return `
<tr data-role="${u.role}"
data-search="${esc(u.name)} ${esc(u.surname)} ${esc(u.email)}">
<td class="ps-4">
<div class="d-flex align-items-center gap-3">
${avatar}
<div>
<div class="fw-semibold lh-sm">${esc(u.name)} ${esc(u.surname)}</div>
<div class="small" style="color:#6c757d;">@${esc(u.username)}</div>
</div>
</div>
</td>
<td style="color:#495057;">${esc(u.email)}</td>
<td>${role_badge}</td>
<td style="color:#495057;">${joined}</td>
<td class="text-end pe-4">
<div class="d-flex justify-content-end gap-1">${actions}</div>
</td>
</tr>`;
}).join('');
tbody.html(html);
}
// ═══════════════════════════════════════════════
// Filter (client-side)
// ═══════════════════════════════════════════════
function filter_table() {
const kw = $('#search_input').val().toLowerCase();
const role = $('#filter_role').val();
const filtered = _users_data.filter(u => {
const haystack = `${u.name} ${u.surname} ${u.email}`.toLowerCase();
return (!kw || haystack.includes(kw))
&& (!role || u.role === role);
});
render_table(filtered);
}
// ═══════════════════════════════════════════════
// Invite
// ═══════════════════════════════════════════════
function open_invite_modal() {
$('#invite_email').val('').removeClass('is-invalid is-valid');
$('#invite_role').val('').removeClass('is-invalid');
new bootstrap.Modal('#inviteModal').show();
}
function send_invite() {
const email = $('#invite_email').val().trim();
const role = $('#invite_role').val();
let valid = true;
if (!email) {
$('#invite_email').addClass('is-invalid');
valid = false;
} else {
$('#invite_email').removeClass('is-invalid');
}
if (!role) {
$('#invite_role').addClass('is-invalid');
valid = false;
} else {
$('#invite_role').removeClass('is-invalid');
}
if (!valid) return;
ajax_request({
url: api + 'manage_users.php',
autoPrepare: true,
checkRequired: 0,
action: 'create',
data: { invite_email: email, invite_role: role },
onSuccess: function (r) {
bootstrap.Modal.getInstance('#inviteModal')?.hide();
bootbox.alert(r.message || 'Invitation sent.');
load_users();
},
});
}
// ═══════════════════════════════════════════════
// Edit role
// ═══════════════════════════════════════════════
function open_edit_modal(map_id) {
const u = _users_data.find(x => x.map_id == map_id);
if (!u) return;
$('#edit_map_id').val(map_id);
$('#edit_username').text(`${u.name} ${u.surname}`);
$('#edit_email_display').text(u.email);
$('#edit_role').val(u.role);
$('#edit_avatar').attr('src', u.profile_picture ? img_base + u.profile_picture : avatar_ph);
new bootstrap.Modal('#editRoleModal').show();
}
function save_role() {
ajax_request({
url: api + 'manage_users.php',
autoPrepare: true,
checkRequired: 0,
action: 'update',
data: { map_id: $('#edit_map_id').val(), role: $('#edit_role').val() },
onSuccess: function (r) {
bootstrap.Modal.getInstance('#editRoleModal')?.hide();
bootbox.alert(r.message || 'Role updated.');
load_users();
},
});
}
// ═══════════════════════════════════════════════
// Remove user
// ═══════════════════════════════════════════════
function remove_user(map_id, display_name) {
bootbox.confirm(`Remove <strong>${display_name}</strong> from this company?`, function (ok) {
if (!ok) return;
ajax_request({
url: api + 'manage_users.php',
autoPrepare: true,
checkRequired: 0,
action: 'delete',
data: { map_id: map_id },
onSuccess: function (r) {
bootbox.alert(r.message || 'User removed.');
load_users();
},
});
});
}
// ═══════════════════════════════════════════════
// Helpers
// ═══════════════════════════════════════════════
function initials(name, surname) {
return ((name?.[0] || '') + (surname?.[0] || '')).toUpperCase() || '?';
}
function esc(str) {
if (!str) return '';
return String(str)
.replace(/&/g,'&amp;').replace(/</g,'&lt;')
.replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
function role_html(role) {
const map = {
owner: ['bg-dark', 'ti-crown', 'Owner'],
admin: ['bg-primary', 'ti-shield-check','Admin'],
staff: ['bg-info', 'ti-tool', 'Staff'],
viewer: ['bg-secondary','ti-eye', 'Viewer'],
};
const [cls, icon, label] = map[role] || ['bg-label-secondary','ti-user','Unknown'];
return `<span class="badge ${cls}"><i class="ti ${icon} me-1"></i>${label}</span>`;
}
</script>
</body>
</html>