34849-vm/pedido_form.php
2026-02-05 07:18:45 +00:00

312 lines
16 KiB
PHP

<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit;
}
require_once 'db/config.php';
$pdo = db();
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['user_role'] ?? 'Asesor';
$pedido = [
'id' => '',
'dni_cliente' => '',
'nombre_completo' => '',
'celular' => '',
'sede_envio' => '',
'codigo_rastreo' => '',
'codigo_tracking' => '',
'producto' => '',
'cantidad' => 1,
'monto_total' => '',
'monto_adelantado' => 0,
'numero_operacion' => '',
'fecha_recojo' => '',
'estado' => 'ROTULADO 📦',
'asesor_id' => $user_id, // Default to current user
'notas' => '',
'voucher_adelanto_path' => '',
'voucher_restante_path' => ''
];
$page_title = 'Crear Pedido';
if (isset($_GET['id'])) {
$page_title = 'Editar Pedido';
$stmt = $pdo->prepare('SELECT * FROM pedidos WHERE id = ?');
$stmt->execute([$_GET['id']]);
$pedido = $stmt->fetch();
if (!$pedido) {
die('Pedido no encontrado.');
}
// Security check: Asesora can only edit their own pedidos
if ($user_role === 'Asesor' && $pedido['asesor_id'] != $user_id) {
die('Acceso denegado. No tienes permiso para editar este pedido.');
}
} else {
// Security check: Only Administradors and asesores can create new pedidos
if ($user_role !== 'Administrador' && $user_role !== 'Asesor') {
die('Acceso denegado. No tienes permiso para crear nuevos pedidos.');
}
}
// Fetch asesores or the current asesor's name
$asesores = [];
$current_asesor_nombre = '';
if ($user_role === 'Administrador') {
$stmt_asesores = $pdo->query("SELECT id, nombre_asesor FROM users WHERE role = 'Asesor' ORDER BY nombre_asesor");
$asesores = $stmt_asesores->fetchAll();
} else if ($user_role === 'Asesor') {
$stmt_current_asesor = $pdo->prepare("SELECT nombre_asesor FROM users WHERE id = ?");
$stmt_current_asesor->execute([$user_id]);
$current_asesor_nombre = $stmt_current_asesor->fetchColumn();
}
// Fetch products
$stmt_products = $pdo->query("SELECT id, nombre FROM products ORDER BY nombre ASC");
$products = $stmt_products->fetchAll();
$estados = ['ROTULADO 📦', 'EN TRANSITO 🚛', 'EN DESTINO 🏬', 'COMPLETADO ✅'];
?>
<?php
$pageTitle = $page_title;
include 'layout_header.php';
?>
<?php if (isset($_GET['error'])):
$error_message = htmlspecialchars($_GET['error']);
?>
<div class="alert alert-danger" role="alert">
<?php echo $error_message; ?>
</div>
<?php endif; ?>
<div class="card">
<div class="card-body">
<form action="save_pedido.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?php echo htmlspecialchars($pedido['id']); ?>">
<input type="hidden" name="referer" value="<?php echo htmlspecialchars($_SERVER['HTTP_REFERER'] ?? 'pedidos.php'); ?>">
<!-- Asesor ID handling -->
<?php if ($user_role === 'Administrador'): ?>
<div class="mb-3">
<label for="asesor_id" class="form-label">Asesor Responsable</label>
<select class="form-select" id="asesor_id" name="asesor_id" required>
<option value="">Sin Asignar</option>
<?php foreach ($asesores as $asesor): ?>
<option value="<?php echo $asesor['id']; ?>" <?php echo ($pedido['asesor_id'] == $asesor['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($asesor['nombre_asesor']); ?></option>
<?php endforeach; ?>
</select>
</div>
<?php else: ?>
<div class="mb-3">
<label for="asesor_nombre" class="form-label">Nombre del Asesor</label>
<input type="text" class="form-control" id="asesor_nombre" value="<?php echo htmlspecialchars($current_asesor_nombre); ?>" disabled>
<input type="hidden" name="asesor_id" value="<?php echo htmlspecialchars($user_id); ?>">
</div>
<?php endif; ?>
<div class="row">
<div class="col-md-6 mb-3">
<label for="dni_cliente" class="form-label">DNI</label>
<input type="text" class="form-control" id="dni_cliente" name="dni" value="<?php echo htmlspecialchars($pedido['dni_cliente'] ?? ''); ?>" required>
</div>
<div class="col-md-6 mb-3">
<label for="nombre_completo" class="form-label">Nombre Completo</label>
<input type="text" class="form-control" id="nombre_completo" name="nombre_completo" value="<?php echo htmlspecialchars($pedido['nombre_completo']); ?>" required>
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="celular" class="form-label">Celular</label>
<input type="text" class="form-control" id="celular" name="celular" value="<?php echo htmlspecialchars($pedido['celular']); ?>" required>
</div>
<div class="col-md-6 mb-3">
<label for="sede_envio" class="form-label">Sede de Envío</label>
<input type="text" class="form-control" id="sede_envio" name="sede_envio" value="<?php echo htmlspecialchars($pedido['sede_envio']); ?>" required>
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="codigo_rastreo" class="form-label">Nº De Orden (Courier)</label>
<input type="text" class="form-control" id="codigo_rastreo" name="codigo_rastreo" value="<?php echo htmlspecialchars($pedido['codigo_rastreo']); ?>">
</div>
<div class="col-md-6 mb-3">
<label for="codigo_tracking" class="form-label">Codigo De Orden (Interno)</label>
<input type="text" class="form-control" id="codigo_tracking" name="codigo_tracking" value="<?php echo htmlspecialchars($pedido['codigo_tracking']); ?>">
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="clave" class="form-label">Clave</label>
<input type="text" class="form-control" id="clave" name="clave" value="<?php echo htmlspecialchars($pedido['clave'] ?? ''); ?>">
</div>
<div class="col-md-6 mb-3">
<label for="seguimiento" class="form-label">Seguimiento</label>
<input type="text" class="form-control" id="seguimiento" name="seguimiento" value="<?php echo htmlspecialchars($pedido['seguimiento'] ?? ''); ?>">
</div>
</div>
<hr>
<h5>Productos</h5>
<div id="productos-container">
<div class="row producto-row mb-3">
<div class="col-md-6">
<label for="producto" class="form-label">Producto</label>
<select class="form-select" name="productos[0][nombre]" required>
<option value="">Seleccione un producto</option>
<?php foreach ($products as $product): ?>
<option value="<?php echo htmlspecialchars($product['nombre']); ?>" <?php echo ($pedido['producto'] == $product['nombre']) ? 'selected' : ''; ?>>
<?php echo htmlspecialchars($product['nombre']); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-md-3">
<label for="cantidad" class="form-label">Cantidad</label>
<input type="number" class="form-control" name="productos[0][cantidad]" value="<?php echo htmlspecialchars($pedido['cantidad']); ?>" required>
</div>
<div class="col-md-3 d-flex align-items-end">
<button type="button" class="btn btn-danger btn-sm remove-producto-btn" style="display: none;">Eliminar</button>
</div>
</div>
</div>
<button type="button" id="add-producto-btn" class="btn btn-success btn-sm mb-3">Agregar producto adicional</button>
<hr>
<div class="row">
<div class="col-md-3 mb-3">
<label for="monto_total" class="form-label">Monto Total</label>
<input type="number" step="0.01" class="form-control" id="monto_total" name="monto_total" value="<?php echo htmlspecialchars($pedido['monto_total']); ?>" required>
</div>
<div class="col-md-3 mb-3">
<label for="monto_adelantado" class="form-label">Monto Adelantado</label>
<input type="number" step="0.01" class="form-control" id="monto_adelantado" name="monto_adelantado" value="<?php echo htmlspecialchars($pedido['monto_adelantado']); ?>">
</div>
<div class="col-md-3 mb-3">
<label for="numero_operacion" class="form-label">Número de Operación</label>
<input type="text" class="form-control" id="numero_operacion" name="numero_operacion" value="<?php echo htmlspecialchars($pedido['numero_operacion'] ?? ''); ?>">
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="voucher_adelanto" class="form-label">Voucher de Adelanto</label>
<input type="file" class="form-control" id="voucher_adelanto" name="voucher_adelanto">
<?php if (!empty($pedido['voucher_adelanto_path'])): ?>
<div class="mt-2">
<a href="<?php echo htmlspecialchars($pedido['voucher_adelanto_path']); ?>" target="_blank">Ver voucher actual</a>
</div>
<?php endif; ?>
</div>
<div class="col-md-6 mb-3">
<label for="voucher_restante" class="form-label">Voucher de Pago Restante</label>
<input type="file" class="form-control" id="voucher_restante" name="voucher_restante">
<?php if (!empty($pedido['voucher_restante_path'])): ?>
<div class="mt-2">
<a href="<?php echo htmlspecialchars($pedido['voucher_restante_path']); ?>" target="_blank">Ver voucher actual</a>
</div>
<?php endif; ?>
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="estado" class="form-label">Estado del Pedido</label>
<select class="form-select" id="estado" name="estado" required>
<?php foreach ($estados as $estado_option): ?>
<option value="<?php echo $estado_option; ?>" <?php echo ($pedido['estado'] == $estado_option) ? 'selected' : ''; ?>><?php echo $estado_option; ?></option>
<?php endforeach; ?>
<?php if (isset($_SESSION['user_role']) && in_array($_SESSION['user_role'], ['superadmin', 'Administrador', 'admin'])): ?>
<option value="Gestion" <?php echo ($pedido['estado'] == 'Gestion') ? 'selected' : ''; ?>>GESTIONES ⚙️</option>
<?php endif; ?>
</select>
</div>
</div>
<div class="mb-3">
<label for="notas" class="form-label">Notas</label>
<textarea class="form-control" id="notas" name="notas" rows="3"><?php echo htmlspecialchars($pedido['notas']); ?></textarea>
</div>
<button type="submit" class="btn btn-primary">Guardar Pedido</button>
<a href="<?php echo htmlspecialchars($_SERVER['HTTP_REFERER'] ?? 'pedidos.php'); ?>" class="btn btn-secondary">Cancelar</a>
</form>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const container = document.getElementById('productos-container');
const addBtn = document.getElementById('add-producto-btn');
let productIndex = 0;
// Function to initialize remove buttons for existing rows
const initRemoveButtons = () => {
container.querySelectorAll('.producto-row').forEach((row, index) => {
if (index > 0) {
const removeBtn = row.querySelector('.remove-producto-btn');
if(removeBtn) {
removeBtn.style.display = 'block';
}
}
});
};
addBtn.addEventListener('click', function() {
productIndex++;
const firstRow = container.querySelector('.producto-row');
const newRow = firstRow.cloneNode(true);
// Update names and clear values
newRow.querySelector('select').name = `productos[${productIndex}][nombre]`;
newRow.querySelector('select').value = '';
newRow.querySelector('input[type="number"]').name = `productos[${productIndex}][cantidad]`;
newRow.querySelector('input[type="number"]').value = '1';
// Show remove button
const removeBtn = newRow.querySelector('.remove-producto-btn');
if(removeBtn) {
removeBtn.style.display = 'block';
}
container.appendChild(newRow);
});
container.addEventListener('click', function(e) {
if (e.target && e.target.classList.contains('remove-producto-btn')) {
const rowToRemove = e.target.closest('.producto-row');
// Do not remove the first row
if (rowToRemove !== container.querySelector('.producto-row')) {
rowToRemove.remove();
}
}
});
// Initialize for existing rows on edit
productIndex = container.querySelectorAll('.producto-row').length - 1;
initRemoveButtons();
});
</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('success')) {
alert('SE AGREGO CORRECTAMENTE ✅');
// Remove the success parameter from the URL without reloading the page
const newUrl = window.location.pathname + window.location.hash;
window.history.replaceState({}, document.title, newUrl);
}
});
</script>
<?php include 'layout_footer.php'; ?>