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

1223 lines
46 KiB
PHP

<?php include('include/headscript.php'); ?>
<?php
/*
* TRFgo - Companies management page
* This page manages customer/laboratory companies.
*/
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 === 'save_company') {
$idcompany = isset($_POST['idcompany']) ? (int) $_POST['idcompany'] : 0;
$companyName = trim($_POST['company_name'] ?? '');
$legalName = trim($_POST['legal_name'] ?? '');
$vatNumber = trim($_POST['vat_number'] ?? '');
$externalCode = trim($_POST['external_code'] ?? '');
$address = trim($_POST['address'] ?? '');
$city = trim($_POST['city'] ?? '');
$zip = trim($_POST['zip'] ?? '');
$countryId = !empty($_POST['country_id']) ? (int) $_POST['country_id'] : null;
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$status = $_POST['status'] ?? 'active';
$allowedStatuses = ['active', 'inactive', 'suspended'];
if ($companyName === '') {
jsonResponse([
'success' => false,
'message' => 'Company name is required.'
]);
}
if (!in_array($status, $allowedStatuses, true)) {
$status = 'active';
}
if ($idcompany > 0) {
$sql = "
UPDATE companies
SET
company_name = :company_name,
legal_name = :legal_name,
vat_number = :vat_number,
external_code = :external_code,
address = :address,
city = :city,
zip = :zip,
country_id = :country_id,
email = :email,
phone = :phone,
status = :status,
updated_at = NOW()
WHERE idcompany = :idcompany
";
$stmt = $db->prepare($sql);
$stmt->execute([
':company_name' => $companyName,
':legal_name' => $legalName !== '' ? $legalName : null,
':vat_number' => $vatNumber !== '' ? $vatNumber : null,
':external_code' => $externalCode !== '' ? $externalCode : null,
':address' => $address !== '' ? $address : null,
':city' => $city !== '' ? $city : null,
':zip' => $zip !== '' ? $zip : null,
':country_id' => $countryId,
':email' => $email !== '' ? $email : null,
':phone' => $phone !== '' ? $phone : null,
':status' => $status,
':idcompany' => $idcompany,
]);
jsonResponse([
'success' => true,
'message' => 'Company updated successfully.'
]);
}
$sql = "
INSERT INTO companies (
company_name,
legal_name,
vat_number,
external_code,
address,
city,
zip,
country_id,
email,
phone,
status,
created_at,
updated_at
) VALUES (
:company_name,
:legal_name,
:vat_number,
:external_code,
:address,
:city,
:zip,
:country_id,
:email,
:phone,
:status,
NOW(),
NOW()
)
";
$stmt = $db->prepare($sql);
$stmt->execute([
':company_name' => $companyName,
':legal_name' => $legalName !== '' ? $legalName : null,
':vat_number' => $vatNumber !== '' ? $vatNumber : null,
':external_code' => $externalCode !== '' ? $externalCode : null,
':address' => $address !== '' ? $address : null,
':city' => $city !== '' ? $city : null,
':zip' => $zip !== '' ? $zip : null,
':country_id' => $countryId,
':email' => $email !== '' ? $email : null,
':phone' => $phone !== '' ? $phone : null,
':status' => $status,
]);
jsonResponse([
'success' => true,
'message' => 'Company created successfully.'
]);
}
if ($action === 'get_company') {
$idcompany = isset($_POST['idcompany']) ? (int) $_POST['idcompany'] : 0;
if ($idcompany <= 0) {
jsonResponse([
'success' => false,
'message' => 'Invalid company id.'
]);
}
$stmt = $db->prepare("
SELECT *
FROM companies
WHERE idcompany = :idcompany
LIMIT 1
");
$stmt->execute([':idcompany' => $idcompany]);
$company = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$company) {
jsonResponse([
'success' => false,
'message' => 'Company not found.'
]);
}
jsonResponse([
'success' => true,
'company' => $company
]);
}
if ($action === 'change_status') {
$idcompany = isset($_POST['idcompany']) ? (int) $_POST['idcompany'] : 0;
$status = $_POST['status'] ?? 'inactive';
$allowedStatuses = ['active', 'inactive', 'suspended'];
if ($idcompany <= 0 || !in_array($status, $allowedStatuses, true)) {
jsonResponse([
'success' => false,
'message' => 'Invalid request.'
]);
}
$stmt = $db->prepare("
UPDATE companies
SET status = :status, updated_at = NOW()
WHERE idcompany = :idcompany
");
$stmt->execute([
':status' => $status,
':idcompany' => $idcompany,
]);
jsonResponse([
'success' => true,
'message' => 'Company status updated successfully.'
]);
}
if ($action === 'delete_company') {
$idcompany = isset($_POST['idcompany']) ? (int) $_POST['idcompany'] : 0;
if ($idcompany <= 0) {
jsonResponse([
'success' => false,
'message' => 'Invalid company id.'
]);
}
/*
* Safe delete rule:
* Do not delete a company if it already has linked brands, departments or users.
*/
$stmt = $db->prepare("
SELECT
(SELECT COUNT(*) FROM brands WHERE idcompany = :idcompany1) AS brands_count,
(SELECT COUNT(*) FROM departments WHERE idcompany = :idcompany2) AS departments_count,
(SELECT COUNT(*) FROM company_users WHERE idcompany = :idcompany3) AS users_count
");
$stmt->execute([
':idcompany1' => $idcompany,
':idcompany2' => $idcompany,
':idcompany3' => $idcompany,
]);
$usage = $stmt->fetch(PDO::FETCH_ASSOC);
if (
((int) $usage['brands_count'] > 0) ||
((int) $usage['departments_count'] > 0) ||
((int) $usage['users_count'] > 0)
) {
jsonResponse([
'success' => false,
'message' => 'This company has linked brands, departments or users. Set it as inactive instead of deleting it.'
]);
}
$stmt = $db->prepare("
DELETE FROM companies
WHERE idcompany = :idcompany
");
$stmt->execute([':idcompany' => $idcompany]);
jsonResponse([
'success' => true,
'message' => 'Company deleted successfully.'
]);
}
jsonResponse([
'success' => false,
'message' => 'Unknown action.'
]);
} catch (Throwable $e) {
jsonResponse([
'success' => false,
'message' => $e->getMessage()
]);
}
}
/*
* Page data
*/
$countries = [];
try {
$stmt = $db->query("
SELECT id, name, iso_3166_2
FROM auth_countries
ORDER BY name ASC
");
$countries = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
$countries = [];
}
$companies = [];
try {
$stmt = $db->query("
SELECT
c.idcompany,
c.company_name,
c.legal_name,
c.vat_number,
c.external_code,
c.city,
c.email,
c.phone,
c.status,
c.created_at,
ac.name AS country_name,
COUNT(DISTINCT b.idbrand) AS brand_count,
COUNT(DISTINCT d.iddepartment) AS department_count,
COUNT(DISTINCT cu.idcompanyuser) AS user_count
FROM companies c
LEFT JOIN auth_countries ac ON ac.id = c.country_id
LEFT JOIN brands b ON b.idcompany = c.idcompany
LEFT JOIN departments d ON d.idcompany = c.idcompany
LEFT JOIN company_users cu ON cu.idcompany = c.idcompany
GROUP BY
c.idcompany,
c.company_name,
c.legal_name,
c.vat_number,
c.external_code,
c.city,
c.email,
c.phone,
c.status,
c.created_at,
ac.name
ORDER BY c.company_name ASC
");
$companies = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
$companies = [];
}
$pageTitle = 'Companies';
?>
<!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-primary-dark: #1e40af;
--trfgo-muted: #64748b;
--trfgo-border: #e5e7eb;
--trfgo-soft-blue: #eff6ff;
--trfgo-soft-green: #ecfdf5;
--trfgo-soft-orange: #fff7ed;
--trfgo-soft-red: #fef2f2;
}
.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;
}
.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;
}
.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-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;
}
.company-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;
}
.company-table td {
vertical-align: middle;
border-color: #eef2f7;
}
.company-name {
font-weight: 800;
color: #0f172a;
}
.company-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-danger {
background: #fee2e2;
color: #991b1b;
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-buildings"></i>
TRFgo Registry
</div>
<h1 class="intro-title">Companies</h1>
<p class="intro-text">
Manage customer companies, laboratories and organizations connected to TRFgo.
Companies are the base layer for brands, departments, users and future TRF requests.
</p>
</div>
<div>
<button type="button" class="btn btn-intro" id="btnAddCompany">
<i class="bx bx-plus-circle"></i>
Add Company
</button>
</div>
</div>
</div>
</div>
<?php
$totalCompanies = count($companies);
$activeCompanies = count(array_filter($companies, fn($row) => $row['status'] === 'active'));
$suspendedCompanies = count(array_filter($companies, fn($row) => $row['status'] === 'suspended'));
?>
<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 Companies</div>
<div class="summary-value"><?= e($totalCompanies); ?></div>
</div>
<div class="summary-icon blue">
<i class="bx bx-buildings"></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($activeCompanies); ?></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">Suspended</div>
<div class="summary-value"><?= e($suspendedCompanies); ?></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">Company List</h6>
<p class="section-subtitle">Customer and laboratory organizations configured in TRFgo</p>
</div>
<button type="button" class="btn btn-primary btn-sm" id="btnAddCompanySmall">
<i class="bx bx-plus-circle"></i>
Add Company
</button>
</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table id="companiesTable" class="table table-striped table-hover align-middle company-table" style="width:100%">
<thead>
<tr>
<th>Company</th>
<th>External Code</th>
<th>Country / City</th>
<th>Email</th>
<th class="text-center">Brands</th>
<th class="text-center">Departments</th>
<th class="text-center">Users</th>
<th>Status</th>
<th>Created</th>
<th class="text-end">Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($companies as $company): ?>
<tr>
<td>
<div class="company-name"><?= e($company['company_name']); ?></div>
<?php if (!empty($company['legal_name'])): ?>
<div class="company-sub"><?= e($company['legal_name']); ?></div>
<?php endif; ?>
<?php if (!empty($company['vat_number'])): ?>
<div class="company-sub">VAT: <?= e($company['vat_number']); ?></div>
<?php endif; ?>
</td>
<td>
<?= !empty($company['external_code']) ? e($company['external_code']) : '<span class="text-muted">-</span>'; ?>
</td>
<td>
<div><?= !empty($company['country_name']) ? e($company['country_name']) : '<span class="text-muted">-</span>'; ?></div>
<?php if (!empty($company['city'])): ?>
<div class="company-sub"><?= e($company['city']); ?></div>
<?php endif; ?>
</td>
<td>
<?php if (!empty($company['email'])): ?>
<a href="mailto:<?= e($company['email']); ?>"><?= e($company['email']); ?></a>
<?php else: ?>
<span class="text-muted">-</span>
<?php endif; ?>
<?php if (!empty($company['phone'])): ?>
<div class="company-sub"><?= e($company['phone']); ?></div>
<?php endif; ?>
</td>
<td class="text-center">
<span class="metric-pill">
<i class="bx bx-purchase-tag-alt"></i>
<?= e($company['brand_count']); ?>
</span>
</td>
<td class="text-center">
<span class="metric-pill">
<i class="bx bx-sitemap"></i>
<?= e($company['department_count']); ?>
</span>
</td>
<td class="text-center">
<span class="metric-pill">
<i class="bx bx-user"></i>
<?= e($company['user_count']); ?>
</span>
</td>
<td>
<?php if ($company['status'] === 'active'): ?>
<span class="badge-soft-success">Active</span>
<?php elseif ($company['status'] === 'suspended'): ?>
<span class="badge-soft-warning">Suspended</span>
<?php else: ?>
<span class="badge-soft-muted">Inactive</span>
<?php endif; ?>
</td>
<td>
<?= !empty($company['created_at']) ? e(date('d/m/Y', strtotime($company['created_at']))) : '-'; ?>
</td>
<td class="text-end">
<button type="button"
class="btn-action btnEditCompany"
data-id="<?= e($company['idcompany']); ?>"
title="Edit">
<i class="bx bx-edit-alt"></i>
</button>
<?php if ($company['status'] === 'active'): ?>
<button type="button"
class="btn-action btnChangeStatus"
data-id="<?= e($company['idcompany']); ?>"
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($company['idcompany']); ?>"
data-status="active"
title="Set active">
<i class="bx bx-toggle-left"></i>
</button>
<?php endif; ?>
<button type="button"
class="btn-action danger btnDeleteCompany"
data-id="<?= e($company['idcompany']); ?>"
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="companyModal" tabindex="-1" aria-labelledby="companyModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<form id="companyForm" class="modal-content">
<input type="hidden" name="action" value="save_company">
<input type="hidden" name="idcompany" id="idcompany" value="0">
<div class="modal-header">
<div>
<h5 class="modal-title" id="companyModalLabel">Add Company</h5>
<small class="text-muted">Create or update a TRFgo company registry item.</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 Name <span class="required-dot">*</span></label>
<input type="text" class="form-control" name="company_name" id="company_name" required>
</div>
<div class="col-12 col-md-6">
<label class="form-label">Legal Name</label>
<input type="text" class="form-control" name="legal_name" id="legal_name">
</div>
<div class="col-12 col-md-4">
<label class="form-label">VAT Number</label>
<input type="text" class="form-control" name="vat_number" id="vat_number">
</div>
<div class="col-12 col-md-4">
<label class="form-label">External Code</label>
<input type="text" class="form-control" name="external_code" id="external_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>
<option value="suspended">Suspended</option>
</select>
</div>
<div class="col-12">
<label class="form-label">Address</label>
<input type="text" class="form-control" name="address" id="address">
</div>
<div class="col-12 col-md-4">
<label class="form-label">ZIP</label>
<input type="text" class="form-control" name="zip" id="zip">
</div>
<div class="col-12 col-md-4">
<label class="form-label">City</label>
<input type="text" class="form-control" name="city" id="city">
</div>
<div class="col-12 col-md-4">
<label class="form-label">Country</label>
<select class="form-select" name="country_id" id="country_id">
<option value="">Select country</option>
<?php foreach ($countries as $country): ?>
<option value="<?= e($country['id']); ?>">
<?= e($country['name']); ?>
<?= !empty($country['iso_3166_2']) ? ' (' . e($country['iso_3166_2']) . ')' : ''; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-12 col-md-6">
<label class="form-label">Email</label>
<input type="email" class="form-control" name="email" id="email">
</div>
<div class="col-12 col-md-6">
<label class="form-label">Phone</label>
<input type="text" class="form-control" name="phone" id="phone">
</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="btnSaveCompany">
<i class="bx bx-save"></i>
Save Company
</button>
</div>
</form>
</div>
</div>
<?php include('jsinclude.php'); ?>
<script>
$(document).ready(function() {
if ($.fn.DataTable) {
$('#companiesTable').DataTable({
pageLength: 25,
order: [
[0, 'asc']
],
responsive: true,
language: {
search: "",
searchPlaceholder: "Search companies..."
}
});
}
const companyModalElement = document.getElementById('companyModal');
const companyModal = new bootstrap.Modal(companyModalElement);
function resetCompanyForm() {
$('#companyForm')[0].reset();
$('#idcompany').val('0');
$('#companyModalLabel').text('Add Company');
$('#status').val('active');
}
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();
}
$('#btnAddCompany, #btnAddCompanySmall').on('click', function() {
resetCompanyForm();
companyModal.show();
});
$('.btnEditCompany').on('click', function() {
const idcompany = $(this).data('id');
$.ajax({
url: 'companies.php',
type: 'POST',
dataType: 'json',
data: {
action: 'get_company',
idcompany: idcompany
},
success: function(response) {
if (!response.success) {
showAlert('error', response.message || 'Unable to load company.');
return;
}
const company = response.company;
$('#companyModalLabel').text('Edit Company');
$('#idcompany').val(company.idcompany);
$('#company_name').val(company.company_name);
$('#legal_name').val(company.legal_name);
$('#vat_number').val(company.vat_number);
$('#external_code').val(company.external_code);
$('#address').val(company.address);
$('#city').val(company.city);
$('#zip').val(company.zip);
$('#country_id').val(company.country_id);
$('#email').val(company.email);
$('#phone').val(company.phone);
$('#status').val(company.status);
companyModal.show();
},
error: function() {
showAlert('error', 'Server error while loading company.');
}
});
});
$('#companyForm').on('submit', function(e) {
e.preventDefault();
$('#btnSaveCompany').prop('disabled', true).html('<i class="bx bx-loader-alt bx-spin"></i> Saving...');
$.ajax({
url: 'companies.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(response) {
$('#btnSaveCompany').prop('disabled', false).html('<i class="bx bx-save"></i> Save Company');
if (!response.success) {
showAlert('error', response.message || 'Unable to save company.');
return;
}
companyModal.hide();
reloadAfterSuccess(response.message || 'Company saved successfully.');
},
error: function() {
$('#btnSaveCompany').prop('disabled', false).html('<i class="bx bx-save"></i> Save Company');
showAlert('error', 'Server error while saving company.');
}
});
});
$('.btnChangeStatus').on('click', function() {
const idcompany = $(this).data('id');
const status = $(this).data('status');
const message = status === 'active' ?
'Do you want to activate this company?' :
'Do you want to set this company 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) {
changeCompanyStatus(idcompany, status);
}
});
return;
}
if (confirm(message)) {
changeCompanyStatus(idcompany, status);
}
});
function changeCompanyStatus(idcompany, status) {
$.ajax({
url: 'companies.php',
type: 'POST',
dataType: 'json',
data: {
action: 'change_status',
idcompany: idcompany,
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.');
}
});
}
$('.btnDeleteCompany').on('click', function() {
const idcompany = $(this).data('id');
if (typeof Swal !== 'undefined') {
Swal.fire({
icon: 'warning',
title: 'Delete company?',
text: 'The company will be deleted only if it has no linked brands, departments or users.',
showCancelButton: true,
confirmButtonColor: '#dc2626',
cancelButtonColor: '#64748b',
confirmButtonText: 'Yes, delete'
}).then(function(result) {
if (result.isConfirmed) {
deleteCompany(idcompany);
}
});
return;
}
if (confirm('Delete company?')) {
deleteCompany(idcompany);
}
});
function deleteCompany(idcompany) {
$.ajax({
url: 'companies.php',
type: 'POST',
dataType: 'json',
data: {
action: 'delete_company',
idcompany: idcompany
},
success: function(response) {
if (!response.success) {
showAlert('error', response.message || 'Unable to delete company.');
return;
}
reloadAfterSuccess(response.message || 'Company deleted successfully.');
},
error: function() {
showAlert('error', 'Server error while deleting company.');
}
});
}
});
</script>
</body>
</html>