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

115 lines
3.0 KiB
PHP

<?php
require_once 'conexion.php';
$start = isset($_GET['start']) ? $_GET['start'] : null;
$end = isset($_GET['end']) ? $_GET['end'] : null;
$id_venta = isset($_GET['id_venta']) ? intval($_GET['id_venta']) : null;
$days = isset($_GET['days']) ? intval($_GET['days']) : null;
// Si se solicita una venta específica, devolver sus productos
if ($id_venta !== null) {
$stmt = $conexion->prepare("
SELECT
vp.ID_Producto,
p.Descripcion as nombre,
vp.Cantidad,
COALESCE(p.Precio_Venta, 0) as precio_unitario,
(vp.Cantidad * COALESCE(p.Precio_Venta, 0)) as subtotal
FROM ventas_productos vp
LEFT JOIN productos p ON vp.ID_Producto = p.ID_Producto
WHERE vp.ID_Venta = ?
ORDER BY vp.ID_Producto
");
if (!$stmt) {
http_response_code(500);
echo json_encode(['error' => 'Error en la consulta preparada: ' . $conexion->error]);
exit;
}
$stmt->bind_param("i", $id_venta);
$stmt->execute();
if ($stmt->error) {
http_response_code(500);
echo json_encode(['error' => 'Error al ejecutar: ' . $stmt->error]);
exit;
}
$result = $stmt->get_result();
$productos = [];
while ($row = $result->fetch_assoc()) {
$productos[] = [
'ID_Producto' => $row['ID_Producto'],
'nombre' => $row['nombre'],
'cantidad' => intval($row['Cantidad']),
'precio_unitario' => floatval($row['precio_unitario']),
'subtotal' => floatval($row['subtotal'])
];
}
header('Content-Type: application/json');
echo json_encode($productos);
$stmt->close();
exit;
}
// De lo contrario, devolver las ventas individuales del período
if ($days !== null) {
$end = date('Y-m-d');
$start = date('Y-m-d', strtotime("-{$days} days", strtotime($end)));
} else {
if (!$start && !$end) {
$start = date('Y-m-d');
$end = $start;
} elseif ($start && !$end) {
$end = $start;
} elseif (!$start && $end) {
$start = $end;
}
}
$startDateTime = $start . ' 00:00:00';
$endDateTime = $end . ' 23:59:59';
$stmt = $conexion->prepare("
SELECT ID_Venta, Fecha, Monto
FROM ventas
WHERE Fecha BETWEEN ? AND ?
ORDER BY Fecha DESC
");
if (!$stmt) {
http_response_code(500);
echo json_encode(['error' => 'Error en la consulta preparada: ' . $conexion->error]);
exit;
}
$stmt->bind_param("ss", $startDateTime, $endDateTime);
$stmt->execute();
if ($stmt->error) {
http_response_code(500);
echo json_encode(['error' => 'Error al ejecutar: ' . $stmt->error]);
exit;
}
$result = $stmt->get_result();
$ventas = [];
while ($row = $result->fetch_assoc()) {
$ventas[] = [
'ID_Venta' => intval($row['ID_Venta']),
'fecha_hora' => $row['Fecha'],
'monto_total' => floatval($row['Monto'])
];
}
$stmt->close();
header('Content-Type: application/json');
echo json_encode($ventas);
?>