Files
Complejo_Cap1tan/php/Registrar_Gastos.php
T
MarcosFlorSalcedo 8ec55e40fc 1ra Versión
2026-07-14 18:24:27 -03:00

124 lines
4.3 KiB
PHP

<?php
require_once 'conexion.php';
header('Content-Type: application/json');
try {
$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data['nuevo_gasto']) || !isset($data['monto'])) {
throw new Exception("Datos incompletos");
}
$nuevo_gasto = trim($data['nuevo_gasto']);
$monto = floatval($data['monto']);
// Validar nombre del gasto
if (empty($nuevo_gasto) || $monto < 0) {
throw new Exception("Datos inválidos");
}
// Convertir nombre a formato de columna (minúsculas, sin espacios, con guion bajo)
$nombre_columna = strtolower(str_replace(' ', '_', $nuevo_gasto));
// Validar que sea un nombre válido para columna SQL
if (!preg_match('/^[a-z_][a-z0-9_]*$/', $nombre_columna)) {
throw new Exception("Nombre de gasto inválido");
}
// Verificar si la columna ya existe (sin prepared statement porque SHOW COLUMNS no lo soporta bien)
$sql_check = "SHOW COLUMNS FROM gastos LIKE '" . $conexion->real_escape_string($nombre_columna) . "'";
$result_check = $conexion->query($sql_check);
if ($result_check === false) {
throw new Exception("Error verificando columna: " . $conexion->error);
}
if ($result_check->num_rows === 0) {
// Columna no existe, agregar con ALTER TABLE
$sql_alter = "ALTER TABLE gastos ADD COLUMN `$nombre_columna` DECIMAL(10,2) DEFAULT NULL";
if (!$conexion->query($sql_alter)) {
throw new Exception("Error al agregar columna: " . $conexion->error);
}
}
// Obtener el ID del registro anterior (donde Periodo_Hasta IS NULL)
$sql_get_id = "SELECT ID_Gasto FROM gastos WHERE Periodo_Hasta IS NULL ORDER BY Periodo_Desde DESC LIMIT 1";
$result_id = $conexion->query($sql_get_id);
$fecha_hoy = date('Y-m-d');
$id_anterior = null;
if ($result_id && $result_id->num_rows > 0) {
$row = $result_id->fetch_assoc();
$id_anterior = $row['ID_Gasto'];
// Cerrar el período anterior
$sql_update = "UPDATE gastos SET Periodo_Hasta = ? WHERE ID_Gasto = ?";
$stmt_update = $conexion->prepare($sql_update);
$stmt_update->bind_param('si', $fecha_hoy, $id_anterior);
if (!$stmt_update->execute()) {
throw new Exception("Error actualizando período anterior: " . $stmt_update->error);
}
$stmt_update->close();
// Obtener todos los valores del registro anterior para reutilizarlos
$sql_get_values = "SELECT * FROM gastos WHERE ID_Gasto = ?";
$stmt_get_values = $conexion->prepare($sql_get_values);
$stmt_get_values->bind_param('i', $id_anterior);
$stmt_get_values->execute();
$result_values = $stmt_get_values->get_result();
$valores_anteriores = $result_values->fetch_assoc();
$stmt_get_values->close();
}
// Construir INSERT dinámico
$columnas = ['Periodo_Desde', 'Periodo_Hasta', $nombre_columna];
$valores = [date('Y-m-d'), null, $monto];
$placeholders = ['?', '?', '?'];
$tipos = 'ssd';
// Si hay datos anteriores, agregar todas las columnas existentes
if (!empty($valores_anteriores)) {
foreach ($valores_anteriores as $col => $val) {
if (!in_array($col, ['ID_Gasto', 'Periodo_Desde', 'Periodo_Hasta', $nombre_columna])) {
$columnas[] = $col;
$valores[] = $val;
$placeholders[] = '?';
$tipos .= 'd';
}
}
}
$sql_insert = "INSERT INTO gastos (" . implode(', ', $columnas) . ") VALUES (" . implode(', ', $placeholders) . ")";
$stmt_insert = $conexion->prepare($sql_insert);
if (!$stmt_insert) {
throw new Exception("Error preparando INSERT: " . $conexion->error);
}
$stmt_insert->bind_param($tipos, ...$valores);
if (!$stmt_insert->execute()) {
throw new Exception("Error insertando registro: " . $stmt_insert->error);
}
$nuevo_id = $stmt_insert->insert_id;
$stmt_insert->close();
echo json_encode([
'success' => true,
'message' => 'Gasto agregado correctamente',
'id_gasto' => $nuevo_id
]);
} catch (Exception $e) {
echo json_encode([
'success' => false,
'message' => $e->getMessage()
]);
}
?>