Files
trfgo/public/userarea/departments.php
T
2026-06-15 16:10:44 +02:00

1230 lines
45 KiB
PHP

<?php include('include/headscript.php'); ?>
<?php
/*
* TRFgo - Departments management page
* This page manages departments linked to companies and optionally to brands.
*/
function e($value)
{
return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}
function jsonResponse(array $payload): void
{
header('Content-Type: application/json');
echo json_encode($payload);
exit;
}
/*
* AJAX actions
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
$action = $_POST['action'];
try {
if ($action === 'get_brands_by_company') {
$idcompany = isset($_POST['idcompany']) ? (int) $_POST['idcompany'] : 0;
if ($idcompany <= 0) {
jsonResponse([
'success' => true,
'brands' => []
]);
}
$stmt = $db->prepare("
SELECT idbrand, brand_name, status
FROM brands
WHERE idcompany = :idcompany
ORDER BY brand_name ASC
");
$stmt->execute([':idcompany' => $idcompany]);
jsonResponse([
'success' => true,
'brands' => $stmt->fetchAll(PDO::FETCH_ASSOC)
]);
}
if ($action === 'save_department') {
$iddepartment = isset($_POST['iddepartment']) ? (int) $_POST['iddepartment'] : 0;
$idcompany = isset($_POST['idcompany']) ? (int) $_POST['idcompany'] : 0;
$idbrand = !empty($_POST['idbrand']) ? (int) $_POST['idbrand'] : null;
$departmentName = trim($_POST['department_name'] ?? '');
$externalDepartmentCode = trim($_POST['external_department_code'] ?? '');
$status = $_POST['status'] ?? 'active';
$allowedStatuses = ['active', 'inactive'];
if ($idcompany <= 0) {
jsonResponse([
'success' => false,
'message' => 'Company is required.'
]);
}
if ($departmentName === '') {
jsonResponse([
'success' => false,
'message' => 'Department name is required.'
]);
}
if (!in_array($status, $allowedStatuses, true)) {
$status = 'active';
}
/*
* Check company exists.
*/
$stmt = $db->prepare("SELECT COUNT(*) FROM companies WHERE idcompany = :idcompany");
$stmt->execute([':idcompany' => $idcompany]);
if ((int) $stmt->fetchColumn() === 0) {
jsonResponse([
'success' => false,
'message' => 'Selected company does not exist.'
]);
}
/*
* If a brand is selected, check that it belongs to the selected company.
*/
if ($idbrand !== null) {
$stmt = $db->prepare("
SELECT COUNT(*)
FROM brands
WHERE idbrand = :idbrand
AND idcompany = :idcompany
");
$stmt->execute([
':idbrand' => $idbrand,
':idcompany' => $idcompany,
]);
if ((int) $stmt->fetchColumn() === 0) {
jsonResponse([
'success' => false,
'message' => 'Selected brand does not belong to the selected company.'
]);
}
}
if ($iddepartment > 0) {
$sql = "
UPDATE departments
SET
idcompany = :idcompany,
idbrand = :idbrand,
department_name = :department_name,
external_department_code = :external_department_code,
status = :status,
updated_at = NOW()
WHERE iddepartment = :iddepartment
";
$stmt = $db->prepare($sql);
$stmt->execute([
':idcompany' => $idcompany,
':idbrand' => $idbrand,
':department_name' => $departmentName,
':external_department_code' => $externalDepartmentCode !== '' ? $externalDepartmentCode : null,
':status' => $status,
':iddepartment' => $iddepartment,
]);
jsonResponse([
'success' => true,
'message' => 'Department updated successfully.'
]);
}
$sql = "
INSERT INTO departments (
idcompany,
idbrand,
department_name,
external_department_code,
status,
created_at,
updated_at
) VALUES (
:idcompany,
:idbrand,
:department_name,
:external_department_code,
:status,
NOW(),
NOW()
)
";
$stmt = $db->prepare($sql);
$stmt->execute([
':idcompany' => $idcompany,
':idbrand' => $idbrand,
':department_name' => $departmentName,
':external_department_code' => $externalDepartmentCode !== '' ? $externalDepartmentCode : null,
':status' => $status,
]);
jsonResponse([
'success' => true,
'message' => 'Department created successfully.'
]);
}
if ($action === 'get_department') {
$iddepartment = isset($_POST['iddepartment']) ? (int) $_POST['iddepartment'] : 0;
if ($iddepartment <= 0) {
jsonResponse([
'success' => false,
'message' => 'Invalid department id.'
]);
}
$stmt = $db->prepare("
SELECT *
FROM departments
WHERE iddepartment = :iddepartment
LIMIT 1
");
$stmt->execute([':iddepartment' => $iddepartment]);
$department = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$department) {
jsonResponse([
'success' => false,
'message' => 'Department not found.'
]);
}
jsonResponse([
'success' => true,
'department' => $department
]);
}
if ($action === 'change_status') {
$iddepartment = isset($_POST['iddepartment']) ? (int) $_POST['iddepartment'] : 0;
$status = $_POST['status'] ?? 'inactive';
$allowedStatuses = ['active', 'inactive'];
if ($iddepartment <= 0 || !in_array($status, $allowedStatuses, true)) {
jsonResponse([
'success' => false,
'message' => 'Invalid request.'
]);
}
$stmt = $db->prepare("
UPDATE departments
SET status = :status, updated_at = NOW()
WHERE iddepartment = :iddepartment
");
$stmt->execute([
':status' => $status,
':iddepartment' => $iddepartment,
]);
jsonResponse([
'success' => true,
'message' => 'Department status updated successfully.'
]);
}
if ($action === 'delete_department') {
$iddepartment = isset($_POST['iddepartment']) ? (int) $_POST['iddepartment'] : 0;
if ($iddepartment <= 0) {
jsonResponse([
'success' => false,
'message' => 'Invalid department id.'
]);
}
/*
* Safe delete rule:
* Do not delete a department if it has linked users.
*/
$stmt = $db->prepare("
SELECT COUNT(*)
FROM company_users
WHERE iddepartment = :iddepartment
");
$stmt->execute([':iddepartment' => $iddepartment]);
if ((int) $stmt->fetchColumn() > 0) {
jsonResponse([
'success' => false,
'message' => 'This department has linked users. Set it as inactive instead of deleting it.'
]);
}
$stmt = $db->prepare("
DELETE FROM departments
WHERE iddepartment = :iddepartment
");
$stmt->execute([':iddepartment' => $iddepartment]);
jsonResponse([
'success' => true,
'message' => 'Department deleted successfully.'
]);
}
jsonResponse([
'success' => false,
'message' => 'Unknown action.'
]);
} catch (Throwable $e) {
jsonResponse([
'success' => false,
'message' => $e->getMessage()
]);
}
}
/*
* Page data
*/
$companies = [];
try {
$stmt = $db->query("
SELECT idcompany, company_name, status
FROM companies
ORDER BY company_name ASC
");
$companies = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
$companies = [];
}
$brands = [];
try {
$stmt = $db->query("
SELECT idbrand, idcompany, brand_name, status
FROM brands
ORDER BY brand_name ASC
");
$brands = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
$brands = [];
}
$departments = [];
try {
$stmt = $db->query("
SELECT
d.iddepartment,
d.idcompany,
d.idbrand,
d.department_name,
d.external_department_code,
d.status,
d.created_at,
c.company_name,
c.status AS company_status,
b.brand_name,
b.status AS brand_status,
COUNT(DISTINCT cu.idcompanyuser) AS user_count
FROM departments d
INNER JOIN companies c ON c.idcompany = d.idcompany
LEFT JOIN brands b ON b.idbrand = d.idbrand
LEFT JOIN company_users cu ON cu.iddepartment = d.iddepartment
GROUP BY
d.iddepartment,
d.idcompany,
d.idbrand,
d.department_name,
d.external_department_code,
d.status,
d.created_at,
c.company_name,
c.status,
b.brand_name,
b.status
ORDER BY c.company_name ASC, b.brand_name ASC, d.department_name ASC
");
$departments = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
$departments = [];
}
$pageTitle = 'Departments';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<title><?= e($pageTitle); ?> - <?= isset($titlewebsite) ? e($titlewebsite) : 'TRFgo'; ?></title>
<style>
:root {
--trfgo-primary: #2563eb;
--trfgo-muted: #64748b;
--trfgo-border: #e5e7eb;
--trfgo-soft-blue: #eff6ff;
--trfgo-soft-green: #ecfdf5;
--trfgo-soft-orange: #fff7ed;
}
.page-intro-card {
border: 0;
border-radius: 20px;
overflow: hidden;
background:
radial-gradient(circle at top right, rgba(59, 130, 246, 0.22), transparent 30%),
linear-gradient(135deg, #0f172a 0%, #1d4ed8 60%, #38bdf8 100%);
color: #fff;
box-shadow: 0 18px 45px rgba(15, 23, 42, 0.18);
}
.page-intro-card .card-body {
padding: 26px;
}
.page-intro-card h1,
.page-intro-card h2,
.page-intro-card h3,
.page-intro-card h4,
.page-intro-card h5,
.page-intro-card h6 {
color: #ffffff;
}
.intro-eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 6px 12px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.16);
color: rgba(255, 255, 255, 0.94);
font-size: 12px;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
margin-bottom: 12px;
}
.intro-title {
font-size: 28px;
font-weight: 800;
letter-spacing: -0.03em;
margin-bottom: 8px;
color: #ffffff;
}
.intro-text {
max-width: 760px;
color: rgba(255, 255, 255, 0.82);
margin-bottom: 0;
line-height: 1.6;
}
.btn-intro {
border-radius: 12px;
padding: 10px 16px;
font-weight: 700;
display: inline-flex;
align-items: center;
gap: 8px;
border: 0;
background: #fff;
color: #1d4ed8;
box-shadow: 0 12px 28px rgba(15, 23, 42, 0.18);
}
.btn-intro:hover {
color: #1e40af;
background: #f8fafc;
}
.summary-card {
border: 0;
border-radius: 18px;
box-shadow: 0 10px 30px rgba(15, 23, 42, 0.06);
}
.summary-icon {
width: 44px;
height: 44px;
border-radius: 14px;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 24px;
}
.summary-icon.blue {
background: var(--trfgo-soft-blue);
color: #2563eb;
}
.summary-icon.green {
background: var(--trfgo-soft-green);
color: #059669;
}
.summary-icon.orange {
background: var(--trfgo-soft-orange);
color: #ea580c;
}
.summary-label {
color: var(--trfgo-muted);
font-size: 13px;
font-weight: 700;
margin-bottom: 3px;
}
.summary-value {
color: #0f172a;
font-size: 26px;
font-weight: 800;
line-height: 1.1;
}
.content-card {
border: 0;
border-radius: 18px;
box-shadow: 0 10px 30px rgba(15, 23, 42, 0.06);
}
.section-title {
color: #0f172a;
font-size: 18px;
font-weight: 800;
margin-bottom: 3px;
}
.section-subtitle {
color: var(--trfgo-muted);
font-size: 13px;
margin-bottom: 0;
}
.department-table th {
color: #64748b;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.04em;
border-bottom: 1px solid var(--trfgo-border) !important;
white-space: nowrap;
}
.department-table td {
vertical-align: middle;
border-color: #eef2f7;
}
.department-name {
font-weight: 800;
color: #0f172a;
}
.department-sub {
color: var(--trfgo-muted);
font-size: 12px;
}
.metric-pill {
display: inline-flex;
align-items: center;
gap: 6px;
background: #f8fafc;
border: 1px solid #e5e7eb;
color: #475569;
border-radius: 999px;
padding: 5px 9px;
font-size: 12px;
font-weight: 700;
white-space: nowrap;
}
.badge-soft-success {
background: #dcfce7;
color: #166534;
border-radius: 999px;
font-weight: 700;
padding: 6px 10px;
}
.badge-soft-warning {
background: #ffedd5;
color: #9a3412;
border-radius: 999px;
font-weight: 700;
padding: 6px 10px;
}
.badge-soft-muted {
background: #f1f5f9;
color: #475569;
border-radius: 999px;
font-weight: 700;
padding: 6px 10px;
}
.btn-action {
width: 34px;
height: 34px;
border-radius: 11px;
display: inline-flex;
align-items: center;
justify-content: center;
border: 1px solid #e5e7eb;
background: #fff;
color: #475569;
transition: all 0.16s ease;
}
.btn-action:hover {
color: #1d4ed8;
border-color: rgba(37, 99, 235, 0.35);
background: #eff6ff;
}
.btn-action.danger:hover {
color: #dc2626;
border-color: rgba(220, 38, 38, 0.30);
background: #fef2f2;
}
.modal-content {
border: 0;
border-radius: 20px;
box-shadow: 0 24px 80px rgba(15, 23, 42, 0.22);
}
.modal-header {
border-bottom: 1px solid #eef2f7;
}
.modal-title {
font-weight: 800;
color: #0f172a;
}
.form-label {
font-size: 13px;
font-weight: 700;
color: #334155;
}
.form-control,
.form-select {
border-radius: 12px;
border-color: #dbe3ef;
}
.form-control:focus,
.form-select:focus {
border-color: rgba(37, 99, 235, 0.45);
box-shadow: 0 0 0 0.20rem rgba(37, 99, 235, 0.12);
}
.required-dot {
color: #dc2626;
}
@media (max-width: 767px) {
.intro-title {
font-size: 24px;
}
.btn-intro {
width: 100%;
justify-content: center;
margin-top: 15px;
}
}
</style>
</head>
<body>
<div class="wrapper">
<?php include('include/navbar.php'); ?>
<?php include('include/topbar.php'); ?>
<div class="page-wrapper">
<div class="page-content">
<div class="card page-intro-card mb-4">
<div class="card-body">
<div class="d-flex align-items-center justify-content-between flex-wrap gap-3">
<div>
<div class="intro-eyebrow">
<i class="bx bx-sitemap"></i>
TRFgo Registry
</div>
<h1 class="intro-title">Departments</h1>
<p class="intro-text">
Manage departments and operational business units for each company.
Departments can optionally be linked to a brand and will later drive TRF visibility and user permissions.
</p>
</div>
<div>
<button type="button" class="btn btn-intro" id="btnAddDepartment">
<i class="bx bx-plus-circle"></i>
Add Department
</button>
</div>
</div>
</div>
</div>
<?php
$totalDepartments = count($departments);
$activeDepartments = count(array_filter($departments, fn($row) => $row['status'] === 'active'));
$inactiveDepartments = count(array_filter($departments, fn($row) => $row['status'] === 'inactive'));
?>
<div class="row row-cols-1 row-cols-md-3 mb-3">
<div class="col">
<div class="card summary-card">
<div class="card-body">
<div class="d-flex align-items-center justify-content-between">
<div>
<div class="summary-label">Total Departments</div>
<div class="summary-value"><?= e($totalDepartments); ?></div>
</div>
<div class="summary-icon blue">
<i class="bx bx-sitemap"></i>
</div>
</div>
</div>
</div>
</div>
<div class="col">
<div class="card summary-card">
<div class="card-body">
<div class="d-flex align-items-center justify-content-between">
<div>
<div class="summary-label">Active</div>
<div class="summary-value"><?= e($activeDepartments); ?></div>
</div>
<div class="summary-icon green">
<i class="bx bx-check-circle"></i>
</div>
</div>
</div>
</div>
</div>
<div class="col">
<div class="card summary-card">
<div class="card-body">
<div class="d-flex align-items-center justify-content-between">
<div>
<div class="summary-label">Inactive</div>
<div class="summary-value"><?= e($inactiveDepartments); ?></div>
</div>
<div class="summary-icon orange">
<i class="bx bx-pause-circle"></i>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card content-card">
<div class="card-header bg-transparent">
<div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
<div>
<h6 class="section-title mb-0">Department List</h6>
<p class="section-subtitle">Departments configured by company and brand</p>
</div>
<button type="button" class="btn btn-primary btn-sm" id="btnAddDepartmentSmall">
<i class="bx bx-plus-circle"></i>
Add Department
</button>
</div>
</div>
<div class="card-body">
<?php if (count($companies) === 0): ?>
<div class="alert alert-warning mb-3">
<strong>No companies available.</strong>
Create at least one company before adding departments.
</div>
<?php endif; ?>
<div class="table-responsive">
<table id="departmentsTable" class="table table-striped table-hover align-middle department-table" style="width:100%">
<thead>
<tr>
<th>Department</th>
<th>Company</th>
<th>Brand</th>
<th>External Code</th>
<th class="text-center">Users</th>
<th>Status</th>
<th>Created</th>
<th class="text-end">Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($departments as $department): ?>
<tr>
<td>
<div class="department-name"><?= e($department['department_name']); ?></div>
<div class="department-sub">ID: <?= e($department['iddepartment']); ?></div>
</td>
<td>
<div class="department-name"><?= e($department['company_name']); ?></div>
<?php if ($department['company_status'] !== 'active'): ?>
<div class="department-sub">Company status: <?= e($department['company_status']); ?></div>
<?php endif; ?>
</td>
<td>
<?php if (!empty($department['brand_name'])): ?>
<div class="department-name"><?= e($department['brand_name']); ?></div>
<?php if ($department['brand_status'] !== 'active'): ?>
<div class="department-sub">Brand status: <?= e($department['brand_status']); ?></div>
<?php endif; ?>
<?php else: ?>
<span class="text-muted">Not linked</span>
<?php endif; ?>
</td>
<td>
<?= !empty($department['external_department_code']) ? e($department['external_department_code']) : '<span class="text-muted">-</span>'; ?>
</td>
<td class="text-center">
<span class="metric-pill">
<i class="bx bx-user"></i>
<?= e($department['user_count']); ?>
</span>
</td>
<td>
<?php if ($department['status'] === 'active'): ?>
<span class="badge-soft-success">Active</span>
<?php else: ?>
<span class="badge-soft-muted">Inactive</span>
<?php endif; ?>
</td>
<td>
<?= !empty($department['created_at']) ? e(date('d/m/Y', strtotime($department['created_at']))) : '-'; ?>
</td>
<td class="text-end">
<button type="button"
class="btn-action btnEditDepartment"
data-id="<?= e($department['iddepartment']); ?>"
title="Edit">
<i class="bx bx-edit-alt"></i>
</button>
<?php if ($department['status'] === 'active'): ?>
<button type="button"
class="btn-action btnChangeStatus"
data-id="<?= e($department['iddepartment']); ?>"
data-status="inactive"
title="Set inactive">
<i class="bx bx-toggle-right"></i>
</button>
<?php else: ?>
<button type="button"
class="btn-action btnChangeStatus"
data-id="<?= e($department['iddepartment']); ?>"
data-status="active"
title="Set active">
<i class="bx bx-toggle-left"></i>
</button>
<?php endif; ?>
<button type="button"
class="btn-action danger btnDeleteDepartment"
data-id="<?= e($department['iddepartment']); ?>"
title="Delete">
<i class="bx bx-trash"></i>
</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="overlay toggle-icon"></div>
<a href="javaScript:;" class="back-to-top">
<i class='bx bxs-up-arrow-alt'></i>
</a>
<?php include('include/footer.php'); ?>
</div>
<div class="modal fade" id="departmentModal" tabindex="-1" aria-labelledby="departmentModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<form id="departmentForm" class="modal-content">
<input type="hidden" name="action" value="save_department">
<input type="hidden" name="iddepartment" id="iddepartment" value="0">
<div class="modal-header">
<div>
<h5 class="modal-title" id="departmentModalLabel">Add Department</h5>
<small class="text-muted">Create or update a department linked to a company and optionally to a brand.</small>
</div>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row g-3">
<div class="col-12 col-md-6">
<label class="form-label">Company <span class="required-dot">*</span></label>
<select class="form-select" name="idcompany" id="idcompany" required>
<option value="">Select company</option>
<?php foreach ($companies as $company): ?>
<option value="<?= e($company['idcompany']); ?>">
<?= e($company['company_name']); ?>
<?= $company['status'] !== 'active' ? ' - ' . e($company['status']) : ''; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-12 col-md-6">
<label class="form-label">Brand</label>
<select class="form-select" name="idbrand" id="idbrand">
<option value="">No brand / company level department</option>
<?php foreach ($brands as $brand): ?>
<option value="<?= e($brand['idbrand']); ?>" data-company="<?= e($brand['idcompany']); ?>">
<?= e($brand['brand_name']); ?>
<?= $brand['status'] !== 'active' ? ' - ' . e($brand['status']) : ''; ?>
</option>
<?php endforeach; ?>
</select>
<small class="text-muted">Only brands belonging to the selected company will be available.</small>
</div>
<div class="col-12 col-md-6">
<label class="form-label">Department Name <span class="required-dot">*</span></label>
<input type="text" class="form-control" name="department_name" id="department_name" required>
</div>
<div class="col-12 col-md-6">
<label class="form-label">External Department Code</label>
<input type="text" class="form-control" name="external_department_code" id="external_department_code">
</div>
<div class="col-12 col-md-4">
<label class="form-label">Status</label>
<select class="form-select" name="status" id="status">
<option value="active">Active</option>
<option value="inactive">Inactive</option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary" id="btnSaveDepartment">
<i class="bx bx-save"></i>
Save Department
</button>
</div>
</form>
</div>
</div>
<?php include('jsinclude.php'); ?>
<script>
$(document).ready(function() {
if ($.fn.DataTable) {
$('#departmentsTable').DataTable({
pageLength: 25,
order: [
[1, 'asc'],
[2, 'asc'],
[0, 'asc']
],
responsive: true,
language: {
search: "",
searchPlaceholder: "Search departments..."
}
});
}
const departmentModalElement = document.getElementById('departmentModal');
const departmentModal = new bootstrap.Modal(departmentModalElement);
function resetDepartmentForm() {
$('#departmentForm')[0].reset();
$('#iddepartment').val('0');
$('#departmentModalLabel').text('Add Department');
$('#status').val('active');
filterBrandOptions('');
}
function showAlert(type, message) {
if (typeof Swal !== 'undefined') {
Swal.fire({
icon: type,
title: type === 'success' ? 'Done' : 'Attention',
text: message,
confirmButtonColor: '#2563eb'
});
return;
}
alert(message);
}
function reloadAfterSuccess(message) {
if (typeof Swal !== 'undefined') {
Swal.fire({
icon: 'success',
title: 'Done',
text: message,
confirmButtonColor: '#2563eb'
}).then(function() {
window.location.reload();
});
return;
}
alert(message);
window.location.reload();
}
function filterBrandOptions(idcompany, selectedBrandId = '') {
$('#idbrand option').each(function() {
const optionCompany = $(this).data('company');
if ($(this).val() === '') {
$(this).show();
return;
}
if (!idcompany || String(optionCompany) === String(idcompany)) {
$(this).show();
} else {
$(this).hide();
}
});
if (selectedBrandId) {
$('#idbrand').val(selectedBrandId);
} else {
$('#idbrand').val('');
}
}
$('#idcompany').on('change', function() {
const idcompany = $(this).val();
filterBrandOptions(idcompany);
});
$('#btnAddDepartment, #btnAddDepartmentSmall').on('click', function() {
resetDepartmentForm();
departmentModal.show();
});
$('.btnEditDepartment').on('click', function() {
const iddepartment = $(this).data('id');
$.ajax({
url: 'departments.php',
type: 'POST',
dataType: 'json',
data: {
action: 'get_department',
iddepartment: iddepartment
},
success: function(response) {
if (!response.success) {
showAlert('error', response.message || 'Unable to load department.');
return;
}
const department = response.department;
$('#departmentModalLabel').text('Edit Department');
$('#iddepartment').val(department.iddepartment);
$('#idcompany').val(department.idcompany);
filterBrandOptions(department.idcompany, department.idbrand);
$('#department_name').val(department.department_name);
$('#external_department_code').val(department.external_department_code);
$('#status').val(department.status);
departmentModal.show();
},
error: function() {
showAlert('error', 'Server error while loading department.');
}
});
});
$('#departmentForm').on('submit', function(e) {
e.preventDefault();
$('#btnSaveDepartment').prop('disabled', true).html('<i class="bx bx-loader-alt bx-spin"></i> Saving...');
$.ajax({
url: 'departments.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(response) {
$('#btnSaveDepartment').prop('disabled', false).html('<i class="bx bx-save"></i> Save Department');
if (!response.success) {
showAlert('error', response.message || 'Unable to save department.');
return;
}
departmentModal.hide();
reloadAfterSuccess(response.message || 'Department saved successfully.');
},
error: function() {
$('#btnSaveDepartment').prop('disabled', false).html('<i class="bx bx-save"></i> Save Department');
showAlert('error', 'Server error while saving department.');
}
});
});
$('.btnChangeStatus').on('click', function() {
const iddepartment = $(this).data('id');
const status = $(this).data('status');
const message = status === 'active' ?
'Do you want to activate this department?' :
'Do you want to set this department as inactive?';
if (typeof Swal !== 'undefined') {
Swal.fire({
icon: 'question',
title: 'Confirm status change',
text: message,
showCancelButton: true,
confirmButtonColor: '#2563eb',
cancelButtonColor: '#64748b',
confirmButtonText: 'Yes, continue'
}).then(function(result) {
if (result.isConfirmed) {
changeDepartmentStatus(iddepartment, status);
}
});
return;
}
if (confirm(message)) {
changeDepartmentStatus(iddepartment, status);
}
});
function changeDepartmentStatus(iddepartment, status) {
$.ajax({
url: 'departments.php',
type: 'POST',
dataType: 'json',
data: {
action: 'change_status',
iddepartment: iddepartment,
status: status
},
success: function(response) {
if (!response.success) {
showAlert('error', response.message || 'Unable to update status.');
return;
}
reloadAfterSuccess(response.message || 'Status updated successfully.');
},
error: function() {
showAlert('error', 'Server error while updating status.');
}
});
}
$('.btnDeleteDepartment').on('click', function() {
const iddepartment = $(this).data('id');
if (typeof Swal !== 'undefined') {
Swal.fire({
icon: 'warning',
title: 'Delete department?',
text: 'The department will be deleted only if it has no linked users.',
showCancelButton: true,
confirmButtonColor: '#dc2626',
cancelButtonColor: '#64748b',
confirmButtonText: 'Yes, delete'
}).then(function(result) {
if (result.isConfirmed) {
deleteDepartment(iddepartment);
}
});
return;
}
if (confirm('Delete department?')) {
deleteDepartment(iddepartment);
}
});
function deleteDepartment(iddepartment) {
$.ajax({
url: 'departments.php',
type: 'POST',
dataType: 'json',
data: {
action: 'delete_department',
iddepartment: iddepartment
},
success: function(response) {
if (!response.success) {
showAlert('error', response.message || 'Unable to delete department.');
return;
}
reloadAfterSuccess(response.message || 'Department deleted successfully.');
},
error: function() {
showAlert('error', 'Server error while deleting department.');
}
});
}
});
</script>
</body>
</html>