249 lines
11 KiB
PHP
249 lines
11 KiB
PHP
<?php
|
|
session_start();
|
|
if (!isset($_SESSION['user_id'])) {
|
|
header("Location: login.php");
|
|
exit;
|
|
}
|
|
require_once 'db/config.php';
|
|
include 'layout_header.php';
|
|
|
|
$db = db();
|
|
$asesor_id = $_SESSION['user_id'];
|
|
$role = $_SESSION['role'];
|
|
|
|
// Base query
|
|
$sql = "SELECT p.*, u.username as asesor_nombre FROM pedidos p LEFT JOIN users u ON p.asesor_id = u.id WHERE 1=1";
|
|
|
|
// Filter by estado
|
|
$estado = isset($_GET['estado']) ? $_GET['estado'] : 'pendiente';
|
|
if ($estado) {
|
|
$sql .= " AND p.estado = " . $db->quote($estado);
|
|
}
|
|
|
|
// Filter by date
|
|
$fecha = isset($_GET['fecha']) ? $_GET['fecha'] : '';
|
|
if ($fecha) {
|
|
$sql .= " AND p.fecha_pedido = " . $db->quote($fecha);
|
|
}
|
|
|
|
// Filter by search term
|
|
$search = isset($_GET['search']) ? $_GET['search'] : '';
|
|
if ($search) {
|
|
$searchTerm = '%' . $search . '%';
|
|
$sql .= " AND (p.nombre_cliente LIKE " . $db->quote($searchTerm) . " OR p.celular_cliente LIKE " . $db->quote($searchTerm) . " OR p.guia LIKE " . $db->quote($searchTerm) . ")";
|
|
}
|
|
|
|
// Filter by asesor for non-admin roles
|
|
if ($role !== 'admin') {
|
|
$sql .= " AND p.asesor_id = " . $db->quote($asesor_id);
|
|
}
|
|
|
|
$sql .= " ORDER BY p.id DESC";
|
|
|
|
$result = $db->query($sql);
|
|
?>
|
|
|
|
<div class="container-fluid mt-4">
|
|
<h2>Gestión de Pedidos</h2>
|
|
|
|
<div class="card">
|
|
<div class="card-header">
|
|
Filtros
|
|
</div>
|
|
<div class="card-body">
|
|
<form method="GET" action="pedidos.php" class="row g-3">
|
|
<div class="col-md-3">
|
|
<label for="estado" class="form-label">Estado</label>
|
|
<select name="estado" id="estado" class="form-select">
|
|
<option value="pendiente" <?php echo ($estado == 'pendiente') ? 'selected' : ''; ?>>Pendiente</option>
|
|
<option value="rotulado" <?php echo ($estado == 'rotulado') ? 'selected' : ''; ?>>Rotulado</option>
|
|
<option value="EN TRANSITO" <?php echo ($estado == 'EN TRANSITO') ? 'selected' : ''; ?>>En Tránsito</option>
|
|
<option value="completado" <?php echo ($estado == 'completado') ? 'selected' : ''; ?>>Completado</option>
|
|
<option value="cancelado" <?php echo ($estado == 'cancelado') ? 'selected' : ''; ?>>Cancelado</option>
|
|
<option value="gestion" <?php echo ($estado == 'gestion') ? 'selected' : ''; ?>>Gestión</option>
|
|
</select>
|
|
</div>
|
|
<div class="col-md-3">
|
|
<label for="fecha" class="form-label">Fecha</label>
|
|
<input type="date" name="fecha" id="fecha" class="form-control" value="<?php echo htmlspecialchars($fecha); ?>">
|
|
</div>
|
|
<div class="col-md-4">
|
|
<label for="search" class="form-label">Buscar</label>
|
|
<input type="text" name="search" id="search" class="form-control" placeholder="Nombre, celular, guía..." value="<?php echo htmlspecialchars($search); ?>">
|
|
</div>
|
|
<div class="col-md-2 d-flex align-items-end">
|
|
<button type="submit" class="btn btn-primary">Filtrar</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
|
|
<?php if (isset($_GET['estado']) && $_GET['estado'] == 'EN TRANSITO'): ?>
|
|
<div class="d-flex justify-content-end my-3">
|
|
<button id="verificar-estados-btn" class="btn btn-primary">
|
|
<span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
|
|
Verificar Estados
|
|
</button>
|
|
</div>
|
|
<?php endif; ?>
|
|
|
|
<div class="table-responsive mt-4">
|
|
<table class="table table-bordered table-striped">
|
|
<thead>
|
|
<tr>
|
|
<th>ID</th>
|
|
<th>Fecha</th>
|
|
<th>Asesor</th>
|
|
<th>Guía</th>
|
|
<?php if (isset($_GET['estado']) && $_GET['estado'] == 'EN TRANSITO'): ?>
|
|
<th style="width: 120px;">Estado Shalom</th>
|
|
<?php endif; ?>
|
|
<th>Cliente</th>
|
|
<th>Celular</th>
|
|
<th>Dirección</th>
|
|
<th>Producto</th>
|
|
<th>Total</th>
|
|
<th>Estado</th>
|
|
<th>Acciones</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
<?php if ($result && $result->rowCount() > 0): ?>
|
|
<?php while ($row = $result->fetch(PDO::FETCH_ASSOC)): ?>
|
|
<tr>
|
|
<td><?php echo $row['id']; ?></td>
|
|
<td><?php echo htmlspecialchars($row['fecha_pedido']); ?></td>
|
|
<td><?php echo htmlspecialchars($row['asesor_nombre']); ?></td>
|
|
<td><?php echo htmlspecialchars($row['guia']); ?></td>
|
|
<?php if (isset($_GET['estado']) && $_GET['estado'] == 'EN TRANSITO'): ?>
|
|
<td class="estado-shalom" data-id="<?php echo $row['id']; ?>" data-guia="<?php echo htmlspecialchars($row['guia']); ?>">
|
|
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
|
|
Verificando...
|
|
</td>
|
|
<?php endif; ?>
|
|
<td><?php echo htmlspecialchars($row['nombre_cliente']); ?></td>
|
|
<td>
|
|
<?php
|
|
$celular_limpio = preg_replace('/[^0-9]/', '', $row['celular_cliente']);
|
|
$whatsapp_icon_class = "fab fa-whatsapp text-secondary"; // Default grey icon
|
|
$whatsapp_url = "#";
|
|
$pointer_events = "none"; // Disable click by default
|
|
|
|
if (strlen($celular_limpio) > 8) {
|
|
// The URL is prepared, but the link will be enabled via JS
|
|
$mensaje_whatsapp = "¡Hola " . htmlspecialchars($row['nombre_cliente']) . "! Tu pedido ha llegado a la agencia de destino y está listo para ser recogido. ¡Gracias por tu compra!";
|
|
$whatsapp_url = "https://wa.me/" . $celular_limpio . "?text=" . urlencode($mensaje_whatsapp);
|
|
}
|
|
?>
|
|
<a href="<?php echo $whatsapp_url; ?>" target="_blank" class="whatsapp-link" data-id="<?php echo $row['id']; ?>" style="pointer-events: <?php echo $pointer_events; ?>;">
|
|
<i class="<?php echo $whatsapp_icon_class; ?>"></i> <?php echo htmlspecialchars($row['celular_cliente']); ?>
|
|
</a>
|
|
</td>
|
|
<td><?php echo htmlspecialchars($row['direccion_cliente']); ?></td>
|
|
<td><?php echo htmlspecialchars($row['producto']); ?></td>
|
|
<td>S/ <?php echo htmlspecialchars($row['total_pedido']); ?></td>
|
|
<td><?php echo htmlspecialchars($row['estado']); ?></td>
|
|
<td>
|
|
<a href="pedido_form.php?edit=<?php echo $row['id']; ?>" class="btn btn-sm btn-info">Editar</a>
|
|
</td>
|
|
</tr>
|
|
<?php endwhile; ?>
|
|
<?php else: ?>
|
|
<tr>
|
|
<td colspan="12" class="text-center">No se encontraron pedidos.</td>
|
|
</tr>
|
|
<?php endif; ?>
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
|
|
<?php if (isset($_GET['estado']) && $_GET['estado'] == 'EN TRANSITO'): ?>
|
|
<script>
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
const shalomApiUrl = 'shalom_api.php';
|
|
|
|
function verificarEstadoShalom(guia, id) {
|
|
const estadoTd = document.querySelector(`.estado-shalom[data-id='${id}']`);
|
|
const whatsappLink = document.querySelector(`.whatsapp-link[data-id='${id}']`);
|
|
const whatsappIcon = whatsappLink ? whatsappLink.querySelector('i') : null;
|
|
|
|
if (!estadoTd) return;
|
|
|
|
return fetch(`${shalomApiUrl}?guia=${guia}`)
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
if (data.error) {
|
|
estadoTd.innerHTML = `<span class="text-danger">Error</span>`;
|
|
console.error('Error Shalom API:', data.error);
|
|
} else {
|
|
const estado = data.estado || 'No disponible';
|
|
estadoTd.textContent = estado;
|
|
|
|
if (estado.includes('DESTINO') || estado.includes('ENTREGADO')) {
|
|
estadoTd.classList.add('bg-success', 'text-white');
|
|
if (whatsappIcon) {
|
|
whatsappIcon.classList.remove('text-secondary');
|
|
whatsappIcon.classList.add('text-success', 'fw-bold');
|
|
whatsappLink.style.pointerEvents = 'auto';
|
|
}
|
|
} else {
|
|
if (whatsappIcon) {
|
|
whatsappIcon.classList.add('text-secondary');
|
|
whatsappIcon.classList.remove('text-success', 'fw-bold');
|
|
whatsappLink.style.pointerEvents = 'none';
|
|
}
|
|
}
|
|
}
|
|
})
|
|
.catch(error => {
|
|
estadoTd.innerHTML = `<span class="text-danger">Fallo de red</span>`;
|
|
console.error('Fetch error:', error);
|
|
});
|
|
}
|
|
|
|
function actualizarTodosLosEstados() {
|
|
const btn = document.getElementById('verificar-estados-btn');
|
|
const spinner = btn.querySelector('.spinner-border');
|
|
btn.disabled = true;
|
|
spinner.classList.remove('d-none');
|
|
|
|
const promesas = [];
|
|
document.querySelectorAll('.estado-shalom').forEach(td => {
|
|
const guia = td.dataset.guia;
|
|
const id = td.dataset.id;
|
|
if (guia) {
|
|
promesas.push(verificarEstadoShalom(guia, id));
|
|
}
|
|
});
|
|
|
|
Promise.all(promesas).finally(() => {
|
|
btn.disabled = false;
|
|
spinner.classList.add('d-none');
|
|
});
|
|
}
|
|
|
|
// Verificar todos al cargar la página
|
|
actualizarTodosLosEstados();
|
|
|
|
// Verificar todos al hacer clic en el botón
|
|
document.getElementById('verificar-estados-btn').addEventListener('click', function() {
|
|
// Resetear estados visuales antes de verificar
|
|
document.querySelectorAll('.estado-shalom').forEach(td => {
|
|
td.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Verificando...`;
|
|
td.classList.remove('bg-success', 'text-white');
|
|
});
|
|
document.querySelectorAll('.whatsapp-link').forEach(link => {
|
|
const icon = link.querySelector('i');
|
|
icon.classList.remove('text-success', 'fw-bold');
|
|
icon.classList.add('text-secondary');
|
|
link.style.pointerEvents = 'none';
|
|
});
|
|
actualizarTodosLosEstados();
|
|
});
|
|
});
|
|
</script>
|
|
<?php endif; ?>
|
|
|
|
<?php include 'layout_footer.php'; ?>
|