34786-vm/inversiones_operativas.php
2025-12-12 16:33:10 +00:00

223 lines
10 KiB
PHP

<?php
require_once 'includes/header.php';
require_once 'db/config.php';
// Redirigir si el usuario no tiene el rol de Administrador General
if (!isset($_SESSION['user_rol']) || $_SESSION['user_rol'] !== 'Administrador General') {
header('Location: /index.php?error=unauthorized');
exit;
}
$pdo = db();
// --- Manejar Formularios (Agregar Inversión) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_investment'])) {
$fecha = $_POST['fecha'] ?? date('Y-m-d');
$descripcion = trim($_POST['descripcion'] ?? '');
$monto = $_POST['monto'] ?? 0;
$tipo = $_POST['tipo'] ?? '';
if (!empty($descripcion) && is_numeric($monto) && $monto > 0 && !empty($tipo)) {
try {
$stmt = $pdo->prepare("INSERT INTO inversiones (fecha, descripcion, monto, tipo) VALUES (?, ?, ?, ?)");
$stmt->execute([$fecha, $descripcion, $monto, $tipo]);
// Redirigir para evitar reenvío de formulario
header("Location: " . $_SERVER['PHP_SELF'] . "?success=true#section-" . $tipo);
exit;
} catch (PDOException $e) {
$error_message = "Error al guardar en la base de datos: " . $e->getMessage();
}
} else {
$error_message = "Por favor, complete todos los campos correctamente.";
}
}
// --- Filtrado por Mes ---
$selected_month = $_GET['mes'] ?? null;
$selected_year = $_GET['anio'] ?? null;
$filter_active = $selected_month && $selected_year;
// --- Obtener todos los datos de inversiones (con filtro si aplica) ---
try {
$sql = "SELECT * FROM inversiones";
$params = [];
if ($filter_active) {
$sql .= " WHERE MONTH(fecha) = ? AND YEAR(fecha) = ?";
$params = [$selected_month, $selected_year];
}
$sql .= " ORDER BY fecha DESC, id DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$all_inversiones = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Error al obtener los datos: " . $e->getMessage());
}
// --- Obtener totales por mes (esto no se filtra) ---
try {
$stmt_totals = $pdo->query("
SELECT
DATE_FORMAT(fecha, '%Y') as anio,
DATE_FORMAT(fecha, '%m') as mes_num,
DATE_FORMAT(fecha, '%M %Y') as mes_nombre,
SUM(monto) as total_monto
FROM
inversiones
GROUP BY
anio, mes_num, mes_nombre
ORDER BY
anio DESC, mes_num DESC
");
$monthly_totals = $stmt_totals->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Error al obtener los totales mensuales: " . $e->getMessage());
}
// Separar por tipo
$inversiones_operativas = array_filter($all_inversiones, fn($inv) => $inv['tipo'] === 'operativa');
$inversiones_operacionales = array_filter($all_inversiones, fn($inv) => $inv['tipo'] === 'operacional');
$inversiones_ads = array_filter($all_inversiones, fn($inv) => $inv['tipo'] === 'ads');
// Función para renderizar una sección de inversión
function render_investment_section($title, $type, $data, $description_label) {
$total = array_sum(array_column($data, 'monto'));
?>
<div class="container mt-5" id="section-<?= htmlspecialchars($type) ?>">
<h2><?= htmlspecialchars($title) ?></h2>
<div class="card">
<div class="card-body">
<!-- Formulario para agregar -->
<form method="POST" action="<?= $_SERVER['PHP_SELF'] ?>#section-<?= htmlspecialchars($type) ?>" class="mb-4">
<input type="hidden" name="tipo" value="<?= htmlspecialchars($type) ?>">
<div class="row align-items-end g-3">
<div class="col-md-3">
<label for="fecha_<?= htmlspecialchars($type) ?>" class="form-label">Fecha</label>
<input type="date" class="form-control" id="fecha_<?= htmlspecialchars($type) ?>" name="fecha" value="<?= date('Y-m-d') ?>" required>
</div>
<div class="col-md-5">
<label for="desc_<?= htmlspecialchars($type) ?>" class="form-label"><?= htmlspecialchars($description_label) ?></label>
<input type="text" class="form-control" id="desc_<?= htmlspecialchars($type) ?>" name="descripcion" required>
</div>
<div class="col-md-2">
<label for="monto_<?= htmlspecialchars($type) ?>" class="form-label">Monto (S/)</label>
<input type="number" step="0.01" class="form-control" id="monto_<?= htmlspecialchars($type) ?>" name="monto" required>
</div>
<div class="col-md-2">
<button type="submit" name="add_investment" class="btn btn-primary w-100">Agregar</button>
</div>
</div>
</form>
<!-- Tabla de datos -->
<div class="table-responsive">
<table class="table table-bordered table-striped table-hover">
<thead class="table-dark">
<tr>
<th style="width: 15%;">Fecha</th>
<th>Descripción</th>
<th style="width: 15%;">Monto (S/)</th>
<th style="width: 15%;">Acciones</th>
</tr>
</thead>
<tbody>
<?php if (empty($data)): ?>
<tr>
<td colspan="4" class="text-center">No hay registros.</td>
</tr>
<?php else: ?>
<?php foreach ($data as $item): ?>
<tr>
<td><?= htmlspecialchars(date("d/m/Y", strtotime($item['fecha']))) ?></td>
<td><?= htmlspecialchars($item['descripcion']) ?></td>
<td><?= number_format($item['monto'], 2) ?></td>
<td>
<a href="editar_inversion.php?id=<?= $item['id'] ?>" class="btn btn-warning btn-sm">Editar</a>
<a href="eliminar_inversion.php?id=<?= $item['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('¿Estás seguro de que quieres eliminar este registro?');">Eliminar</a>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
<tfoot>
<tr class="table-dark fw-bold">
<td colspan="2" class="text-end">TOTAL:</td>
<td><?= number_format($total, 2) ?></td>
<td></td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
<?php
}
?>
<div class="container-fluid mt-4">
<h1>Gestión de Inversiones</h1>
<hr>
<?php if (isset($error_message)): ?>
<div class="alert alert-danger"><?= htmlspecialchars($error_message) ?></div>
<?php endif; ?>
<?php if (isset($_GET['success'])): ?>
<div class="alert alert-success">Registro guardado exitosamente.</div>
<?php endif; ?>
<!-- Resumen de Totales por Mes -->
<div class="container mt-4 mb-5">
<h2>Resumen de Inversiones por Mes</h2>
<div class="card">
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead class="table-dark">
<tr>
<th>Mes</th>
<th>Monto Total (S/)</th>
</tr>
</thead>
<tbody>
<?php if (empty($monthly_totals)): ?>
<tr>
<td colspan="2" class="text-center">No hay datos para mostrar.</td>
</tr>
<?php else: ?>
<?php foreach ($monthly_totals as $total): ?>
<tr style="cursor: pointer;" onclick="window.location='inversiones_operativas.php?mes=<?= $total['mes_num'] ?>&anio=<?= $total['anio'] ?>'">
<td><?= htmlspecialchars(ucfirst($total['mes_nombre'])) ?></td>
<td><?= number_format($total['total_monto'], 2) ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<?php if ($filter_active): ?>
<div class="container mb-4">
<div class="d-flex justify-content-between align-items-center">
<h3 class="mb-0">Mostrando Inversiones de: <strong><?= htmlspecialchars(ucfirst(strftime('%B %Y', mktime(0, 0, 0, $selected_month, 1, $selected_year)))) ?></strong></h3>
<a href="inversiones_operativas.php" class="btn btn-info">Mostrar Todos los Meses</a>
</div>
<hr>
</div>
<?php endif; ?>
</div>
<?php
// Renderizar las tres secciones
render_investment_section("Inversion Mercaderia", "operativa", $inversiones_operativas, "Descripción de la Inversión");
render_investment_section("Inversiones en Ads", "ads", $inversiones_ads, "Descripción del Gasto de Publicidad");
render_investment_section("Inversiones Operacionales", "operacional", $inversiones_operacionales, "Descripción del Gasto");
require_once 'includes/footer.php';
?>