35330-vm/Backend/categories.php
Flatlogic Bot 6d3c0cd8d3 versao 18
2025-10-29 19:20:02 +00:00

307 lines
13 KiB
PHP

<?php
require_once __DIR__ . '/includes/session.php';
require_once __DIR__ . '/db/config.php';
// Ensure the user is logged in and has a client_id
if (!isset($_SESSION['user_id']) || !isset($_SESSION['client_id'])) {
header("Location: login.php");
exit;
}
$client_id = $_SESSION['client_id'];
$pdo = db();
$errors = [];
$success = '';
// Handle POST requests for CUD operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = $_POST['action'] ?? '';
try {
if ($action === 'save_category') {
$id = $_POST['id'] ?? null;
$nome = trim($_POST['nome'] ?? '');
$macro_area_id = $_POST['macro_area_id'] ?? null;
if (empty($nome) || empty($macro_area_id)) {
$errors[] = "Nome da categoria e macro área são obrigatórios.";
} else {
if ($id) {
// Update
$stmt = $pdo->prepare("UPDATE categories SET nome = :nome, macro_area_id = :macro_area_id WHERE id = :id AND client_id = :client_id");
$stmt->execute(['nome' => $nome, 'macro_area_id' => $macro_area_id, 'id' => $id, 'client_id' => $client_id]);
$success = "Categoria atualizada com sucesso!";
} else {
// Create
$stmt = $pdo->prepare("INSERT INTO categories (nome, macro_area_id, client_id) VALUES (:nome, :macro_area_id, :client_id)");
$stmt->execute(['nome' => $nome, 'macro_area_id' => $macro_area_id, 'client_id' => $client_id]);
$success = "Categoria criada com sucesso!";
}
}
} elseif ($action === 'toggle_archive') {
$id = $_POST['id'] ?? null;
if ($id) {
$stmt = $pdo->prepare("UPDATE categories SET is_archived = 1 - is_archived WHERE id = :id AND client_id = :client_id");
$stmt->execute(['id' => $id, 'client_id' => $client_id]);
$success = "Status da categoria alterado com sucesso!";
}
} elseif ($action === 'delete') {
$id = $_POST['id'] ?? null;
if ($id) {
// Check for related expenses
$stmt = $pdo->prepare("SELECT COUNT(*) FROM expenses WHERE category_id = :category_id AND client_id = :client_id");
$stmt->execute(['category_id' => $id, 'client_id' => $client_id]);
if ($stmt->fetchColumn() > 0) {
$errors[] = "Não é possível excluir a categoria, pois existem despesas associadas a ela.";
} else {
$stmt = $pdo->prepare("DELETE FROM categories WHERE id = :id AND client_id = :client_id");
$stmt->execute(['id' => $id, 'client_id' => $client_id]);
$success = "Categoria excluída com sucesso!";
}
}
}
} catch (PDOException $e) {
if ($e->getCode() == '23000') { // Integrity constraint violation
$errors[] = "Erro: Já existe uma categoria com este nome para a macro área selecionada.";
} else {
$errors[] = "Ocorreu um erro no banco de dados: " . $e->getMessage();
}
}
}
// Fetch data for display
$macro_areas = $pdo->prepare("SELECT id, nome FROM macro_areas WHERE client_id = :client_id ORDER BY nome");
$macro_areas->execute(['client_id' => $client_id]);
$macro_areas_list = $macro_areas->fetchAll();
$stmt = $pdo->prepare("
SELECT c.id, c.nome, c.is_archived, c.macro_area_id, m.nome as macro_area_nome
FROM categories c
JOIN macro_areas m ON c.macro_area_id = m.id
WHERE c.client_id = :client_id
ORDER BY m.nome, c.nome
");
$stmt->execute(['client_id' => $client_id]);
$categories = $stmt->fetchAll();
$page_title = "Categorias";
include 'includes/header.php';
?>
<style>
:root {
--bg-page: #eeeeee;
--text-main: #10403B;
--text-secondary: #4C5958;
--action-bg: #005C53;
--action-text: #FFFFFF;
--delete-bg-modal: #8AA6A3;
--card-border: #005C53;
--table-header-bg: #8AA6A3;
--table-header-text: #FFFFFF;
--badge-bg: #8AA6A3;
--badge-text: #FFFFFF;
--icon-action: #4C5958;
--icon-section: #005C53;
--hover-row: #f8fafc; /* hover:bg-slate-50 */
}
body {
background-color: var(--bg-page);
color: var(--text-main);
}
.btn-primary {
background-color: var(--action-bg);
color: var(--action-text);
border: none;
}
.btn-primary:hover {
background-color: #004c45;
}
.table thead th {
background-color: var(--table-header-bg);
color: var(--table-header-text);
}
.table tbody tr:hover {
background-color: var(--hover-row);
}
.badge-active {
background-color: var(--badge-bg);
color: var(--badge-text);
}
.badge-archived {
background-color: #f1f5f9; /* bg-gray-100 */
color: #1f2937; /* text-gray-800 */
}
.action-icon {
color: var(--icon-action);
cursor: pointer;
}
.section-icon {
color: var(--icon-section);
}
.card {
border: 1px solid var(--card-border);
}
.modal-content {
background-color: var(--bg-page);
border: 1px solid var(--text-main);
}
.modal-header, .modal-body, .modal-footer {
border-color: #d1d5db;
}
.form-label {
color: var(--text-main);
}
.form-control::placeholder {
color: var(--text-secondary);
}
</style>
<div class="container mt-4">
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="h3 font-weight-bold d-flex align-items-center">
<i class="fas fa-layer-group me-2 section-icon"></i>
Categorias
</h1>
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#categoryModal" onclick="openModal()">
<i class="fas fa-plus me-1"></i> Nova Categoria
</button>
</div>
<?php if (!empty($errors)): ?>
<div class="alert alert-danger">
<?php foreach ($errors as $error): ?>
<p class="mb-0"><?php echo htmlspecialchars($error); ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if ($success): ?>
<div class="alert alert-success">
<?php echo htmlspecialchars($success); ?>
</div>
<?php endif; ?>
<div class="card">
<div class="card-body">
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Nome da Categoria</th>
<th>Macro Área</th>
<th class="text-center">Status</th>
<th class="text-end">Ações</th>
</tr>
</thead>
<tbody>
<?php if (empty($categories)): ?>
<tr>
<td colspan="4" class="text-center text-secondary py-4">Nenhuma categoria encontrada.</td>
</tr>
<?php else: ?>
<?php foreach ($categories as $category): ?>
<tr>
<td class="font-weight-medium"><?php echo htmlspecialchars($category['nome']); ?></td>
<td><?php echo htmlspecialchars($category['macro_area_nome']); ?></td>
<td class="text-center">
<span class="badge <?php echo $category['is_archived'] ? 'badge-archived' : 'badge-active'; ?>">
<?php echo $category['is_archived'] ? 'Arquivado' : 'Ativo'; ?>
</span>
</td>
<td class="text-end">
<i class="fas fa-edit action-icon me-3" title="Editar" onclick='openModal(<?php echo json_encode($category, JSON_HEX_TAG); ?>)'></i>
<form action="categories.php" method="POST" class="d-inline" onsubmit="return confirm('Tem certeza que deseja alterar o status desta categoria?');">
<input type="hidden" name="action" value="toggle_archive">
<input type="hidden" name="id" value="<?php echo $category['id']; ?>">
<button type="submit" class="btn btn-link p-0 m-0 align-baseline">
<i class="fas <?php echo $category['is_archived'] ? 'fa-box-open' : 'fa-archive'; ?> action-icon me-3" title="<?php echo $category['is_archived'] ? 'Reativar' : 'Arquivar'; ?>"></i>
</button>
</form>
<form action="categories.php" method="POST" class="d-inline" onsubmit="return confirm('Atenção! A exclusão é permanente. Deseja continuar?');">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="id" value="<?php echo $category['id']; ?>">
<button type="submit" class="btn btn-link p-0 m-0 align-baseline">
<i class="fas fa-trash-alt action-icon text-danger" title="Excluir"></i>
</button>
</form>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="categoryModal" tabindex="-1" aria-labelledby="categoryModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<form action="categories.php" method="POST" id="categoryForm">
<input type="hidden" name="action" value="save_category">
<input type="hidden" name="id" id="categoryId">
<div class="modal-header">
<h5 class="modal-title" id="categoryModalLabel">Nova Categoria</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label for="categoryName" class="form-label">Nome da Categoria</label>
<input type="text" class="form-control" id="categoryName" name="nome" required placeholder="Ex: Aluguel, Combustível">
</div>
<div class="mb-3">
<label for="macroArea" class="form-label">Macro Área</label>
<select class="form-select" id="macroArea" name="macro_area_id" required>
<option value="" disabled selected>Selecione uma macro área</option>
<?php foreach ($macro_areas_list as $ma): ?>
<option value="<?php echo $ma['id']; ?>"><?php echo htmlspecialchars($ma['nome']); ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary">Salvar</button>
</div>
</form>
</div>
</div>
</div>
<script>
function openModal(category = null) {
const form = document.getElementById('categoryForm');
const modalTitle = document.getElementById('categoryModalLabel');
const categoryIdInput = document.getElementById('categoryId');
const categoryNameInput = document.getElementById('categoryName');
const macroAreaSelect = document.getElementById('macroArea');
form.reset(); // Reset form for both create and edit
if (category) {
// Edit mode
modalTitle.textContent = 'Editar Categoria';
categoryIdInput.value = category.id;
categoryNameInput.value = category.nome;
macroAreaSelect.value = category.macro_area_id; // Directly use the ID
} else {
// Create mode
modalTitle.textContent = 'Nova Categoria';
categoryIdInput.value = '';
}
}
// Reset form on modal close
const categoryModal = document.getElementById('categoryModal');
categoryModal.addEventListener('hidden.bs.modal', function (event) {
document.getElementById('categoryForm').reset();
document.getElementById('categoryId').value = '';
document.getElementById('categoryModalLabel').textContent = 'Nova Categoria';
});
</script>
<?php include 'includes/footer.php'; ?>