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

136 lines
5.5 KiB
PHP

<?php
require_once __DIR__ . '/db/config.php';
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Proteger a página
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit;
}
$client_id = $_SESSION['client_id'];
$user_id = $_SESSION['user_id'];
$pdo = db();
$error_message = '';
$success_message = '';
// Definir o mês do orçamento (padrão para o mês atual)
$budget_month_str = $_GET['month'] ?? date('Y-m');
$budget_month_date = date('Y-m-01', strtotime($budget_month_str . '-01'));
// Lógica para salvar/atualizar orçamentos
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$budgets = $_POST['budgets'] ?? [];
$posted_month = $_POST['budget_month'] ?? $budget_month_date;
try {
$sql = "INSERT INTO budgets (client_id, user_id, category, amount, budget_month) VALUES (:client_id, :user_id, :category, :amount, :budget_month)
ON DUPLICATE KEY UPDATE amount = VALUES(amount)";
$stmt = $pdo->prepare($sql);
foreach ($budgets as $category => $amount) {
if (is_numeric($amount) && $amount >= 0) {
$stmt->execute([
'client_id' => $client_id,
'user_id' => $user_id,
'category' => $category,
'amount' => $amount,
'budget_month' => $posted_month
]);
}
}
$success_message = 'Orçamentos salvos com sucesso!';
// Redirecionar para o mesmo mês para mostrar a atualização
header('Location: budgets.php?month=' . date('Y-m', strtotime($posted_month)));
exit;
} catch (PDOException $e) {
$error_message = 'Erro ao salvar orçamentos: ' . $e->getMessage();
}
}
// Buscar orçamentos existentes para o mês selecionado
$existing_budgets = [];
try {
$stmt = $pdo->prepare("SELECT category, amount FROM budgets WHERE client_id = :client_id AND budget_month = :budget_month");
$stmt->execute(['client_id' => $client_id, 'budget_month' => $budget_month_date]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
$existing_budgets[$row['category']] = $row['amount'];
}
} catch (PDOException $e) {
$error_message = "Erro ao buscar orçamentos existentes.";
}
// Obter todas as categorias (macro áreas ativas) para os dropdowns
$stmt_categories = $pdo->prepare("SELECT nome, slug FROM macro_areas WHERE client_id = :client_id AND ativo = 1 ORDER BY nome ASC");
$stmt_categories->execute(['client_id' => $client_id]);
$categories = $stmt_categories->fetchAll(PDO::FETCH_ASSOC);
include __DIR__ . '/includes/header.php';
?>
<div class="container mt-4">
<h1 class="mb-4">Gerenciar Orçamentos</h1>
<div class="card">
<div class="card-body">
<!-- Seletor de Mês -->
<form method="GET" action="budgets.php" class="mb-4">
<div class="row align-items-end">
<div class="col-md-4">
<label for="month" class="form-label">Selecione o Mês</label>
<input type="month" class="form-control" id="month" name="month" value="<?php echo htmlspecialchars($budget_month_str); ?>">
</div>
<div class="col-md-2">
<button type="submit" class="btn btn-primary">Carregar</button>
</div>
</div>
</form>
<hr>
<?php if ($error_message): ?>
<div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div>
<?php endif; ?>
<?php if (isset($_SESSION['success_message'])) {
echo '<div class="alert alert-success">' . htmlspecialchars($_SESSION['success_message']) . '</div>';
unset($_SESSION['success_message']);
}?>
<!-- Formulário de Orçamentos -->
<form method="POST" action="budgets.php">
<input type="hidden" name="budget_month" value="<?php echo htmlspecialchars($budget_month_date); ?>">
<h4 class="mb-3">Orçamentos para <?php echo date('F \d\e Y', strtotime($budget_month_date)); ?></h4>
<?php foreach ($categories as $category):
$category_slug = $category['slug'];
$category_nome = $category['nome'];
?>
<div class="row mb-2 align-items-center">
<div class="col-md-3">
<label for="budget_<?php echo htmlspecialchars($category_slug); ?>" class="form-label"><?php echo htmlspecialchars($category_nome); ?></label>
</div>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-text">R$</span>
<input type="number" step="0.01" class="form-control" id="budget_<?php echo htmlspecialchars($category_slug); ?>"
name="budgets[<?php echo htmlspecialchars($category_slug); ?>]"
value="<?php echo htmlspecialchars($existing_budgets[$category_slug] ?? '0.00'); ?>">
</div>
</div>
</div>
<?php endforeach; ?>
<div class="d-grid mt-4">
<button type="submit" class="btn btn-primary">Salvar Orçamentos</button>
</div>
</form>
</div>
</div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>