Files
wms-app/app/assets/utils/classes_ac/DepartmentManager.php
T

99 lines
3.0 KiB
PHP

<?php
class DepartmentManager
{
private PDO $pdo;
private int $companyId;
public function __construct(PDO $pdo, int $company_id)
{
$this->pdo = $pdo;
$this->companyId = $company_id;
}
public function getAll(): array
{
$sth = $this->pdo->prepare(
"SELECT * FROM md_department
WHERE company_id = :cid
ORDER BY dept_code ASC"
);
$sth->execute([':cid' => $this->companyId]);
return $sth->fetchAll(PDO::FETCH_ASSOC);
}
public function getById(int $id): ?array
{
$sth = $this->pdo->prepare(
"SELECT * FROM md_department
WHERE company_id = :cid AND id = :id LIMIT 1"
);
$sth->execute([':cid' => $this->companyId, ':id' => $id]);
$row = $sth->fetch(PDO::FETCH_ASSOC);
return $row ?: null;
}
public function create(array $data): int
{
$sth = $this->pdo->prepare(
"INSERT INTO md_department (company_id, dept_code, dept_name, description, status)
VALUES (:cid, :code, :name, :desc, :status)"
);
$sth->execute([
':cid' => $this->companyId,
':code' => trim($data['dept_code']),
':name' => trim($data['dept_name']),
':desc' => $data['description'] ?? null,
':status' => (int)($data['status'] ?? 1),
]);
return (int)$this->pdo->lastInsertId();
}
public function update(int $id, array $data): void
{
$sth = $this->pdo->prepare(
"UPDATE md_department SET
dept_code = :code,
dept_name = :name,
description = :desc,
status = :status
WHERE company_id = :cid AND id = :id"
);
$sth->execute([
':cid' => $this->companyId,
':id' => $id,
':code' => trim($data['dept_code']),
':name' => trim($data['dept_name']),
':desc' => $data['description'] ?? null,
':status' => (int)($data['status'] ?? 1),
]);
}
public function delete(int $id): void
{
$sth = $this->pdo->prepare(
"SELECT COUNT(*) FROM td_gl_item WHERE department_id = :id LIMIT 1"
);
$sth->execute([':id' => $id]);
if ((int)$sth->fetchColumn() > 0) {
throw new Exception('Cannot deactivate — this department has GL journal entries.');
}
$this->pdo->prepare(
"UPDATE md_department SET status = 0
WHERE company_id = :cid AND id = :id"
)->execute([':cid' => $this->companyId, ':id' => $id]);
}
public function getStats(): array
{
$sth = $this->pdo->prepare(
"SELECT COUNT(*) AS total,
SUM(status = 1) AS active,
SUM(status = 0) AS inactive
FROM md_department WHERE company_id = :cid"
);
$sth->execute([':cid' => $this->companyId]);
return $sth->fetch(PDO::FETCH_ASSOC) ?: [];
}
}