inicio
This commit is contained in:
2025-05-05 11:03:01 -06:00
commit c73e3f2327
185 changed files with 17573 additions and 0 deletions

View File

@@ -0,0 +1,304 @@
<?php
session_start();
require_once __DIR__ . '/../../config/database.php';
function lista() {
if (!($_SESSION['usuario_id'] ?? false)) {
header('Location: /IMPORTADORES/login');
exit;
}
$usr = $_SESSION['usuario_id'];
$conn = getConnection();
$sql = "
SELECT
c.*,
(c.nombre + ' ' + c.apellido) AS nombre_completo,
tr.nombre AS transportista
FROM dbo.choferes c
JOIN dbo.transportistas tr
ON c.transportista_id = tr.id_transportista
WHERE tr.id_usuario = ?
AND c.status = 1
ORDER BY c.created_at DESC
";
$stmt = sqlsrv_query($conn, $sql, [$usr]);
if ($stmt === false) {
die("Error en lista(): " . print_r(sqlsrv_errors(), true));
}
$choferes = [];
while ($r = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$choferes[] = $r;
}
include __DIR__ . '/../../views/choferes/lista.php';
}
function crear() {
if (!($_SESSION['usuario_id'] ?? false)) {
header('Location: /IMPORTADORES/login');
exit;
}
$usr = $_SESSION['usuario_id'];
$conn = getConnection();
// OJO: aquí usamos "activo" según tu esquema original
$sql = "
SELECT id_transportista, nombre
FROM dbo.transportistas
WHERE id_usuario = ? AND activo = 1
ORDER BY nombre
";
$stmt = sqlsrv_query($conn, $sql, [$usr]);
if ($stmt === false) {
die("Error en crear(): " . print_r(sqlsrv_errors(), true));
}
$transportistas = [];
while ($r = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$transportistas[] = $r;
}
include __DIR__ . '/../../views/choferes/crear.php';
}
function guardar() {
if (!($_SESSION['usuario_id'] ?? false)) {
die("⚠️ No autorizado.");
}
$transportista_id = $_POST['transportista_id'] ?? null;
$nombre = trim($_POST['nombre'] ?? '');
$apellido = trim($_POST['apellido'] ?? '');
$licencia = trim($_POST['numero_licencia'] ?? '');
$telefono = trim($_POST['telefono'] ?? '');
$email = trim($_POST['email'] ?? '');
$fecha_ingreso = $_POST['fecha_ingreso'] ?: null;
if (!$transportista_id || $nombre === '' || $apellido === '' || $licencia === '') {
die("❌ Todos los campos obligatorios deben llenarse.");
}
// Manejo de foto
$fotoUrl = null;
if (!empty($_FILES['foto']['tmp_name'])) {
$ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
$dest = __DIR__ . '/../../public/uploads/chofer_'.uniqid().".{$ext}";
if (!is_dir(dirname($dest))) mkdir(dirname($dest), 0755, true);
if (move_uploaded_file($_FILES['foto']['tmp_name'], $dest)) {
$fotoUrl = "/IMPORTADORES/public/uploads/" . basename($dest);
}
}
$conn = getConnection();
$sql = "
INSERT INTO dbo.choferes
(transportista_id, nombre, apellido, numero_licencia, telefono, email, fecha_ingreso, foto_url, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)
";
$params = [
(int)$transportista_id,
$nombre,
$apellido,
$licencia,
$telefono,
$email,
$fecha_ingreso,
$fotoUrl
];
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
die("Error en guardar(): " . print_r(sqlsrv_errors(), true));
}
header('Location: /IMPORTADORES/choferes/lista?created=ok');
exit;
}
function editar() {
if (!($_SESSION['usuario_id'] ?? false)) {
header('Location: /IMPORTADORES/login');
exit;
}
$id = $_GET['id'] ?? null;
if (!$id || !is_numeric($id)) {
die("❌ ID inválido.");
}
$conn = getConnection();
$sql = "
SELECT c.*, tr.nombre AS transportista
FROM dbo.choferes c
JOIN dbo.transportistas tr
ON c.transportista_id = tr.id_transportista
WHERE c.id_chofer = ?
AND tr.id_usuario = ?
AND c.status = 1
";
$stmt = sqlsrv_query($conn, $sql, [(int)$id, $_SESSION['usuario_id']]);
if ($stmt === false) {
die("Error en editar(): " . print_r(sqlsrv_errors(), true));
}
$chofer = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
if (!$chofer) {
die("❌ Chofer no encontrado o no autorizado.");
}
// ✅ Aquí convertimos fecha_ingreso a string YYYY-MM-DD
if ($chofer['fecha_ingreso'] instanceof DateTime) {
$chofer['fecha_ingreso'] = $chofer['fecha_ingreso']->format('Y-m-d');
}
// Lista de transportistas
$sql2 = "
SELECT id_transportista, nombre
FROM dbo.transportistas
WHERE id_usuario = ? AND activo = 1
ORDER BY nombre
";
$stmt2 = sqlsrv_query($conn, $sql2, [$_SESSION['usuario_id']]);
if ($stmt2 === false) {
die("Error en editar() [transportistas]: " . print_r(sqlsrv_errors(), true));
}
$transportistas = [];
while ($r = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC)) {
$transportistas[] = $r;
}
include __DIR__ . '/../../views/choferes/editar.php';
}
/**
* Procesa la actualización de un chofer
*/
function actualizar() {
if (!($_SESSION['usuario_id'] ?? false)) {
die("⚠️ No autorizado.");
}
$id = $_POST['id_chofer'] ?? null;
$transportista_id = $_POST['transportista_id'] ?? null;
$nombre = trim($_POST['nombre'] ?? '');
$apellido = trim($_POST['apellido'] ?? '');
$licencia = trim($_POST['numero_licencia']?? '');
$telefono = trim($_POST['telefono'] ?? '');
$email = trim($_POST['email'] ?? '');
$fecha_ingreso = $_POST['fecha_ingreso'] ?: null;
$status = isset($_POST['status']) ? 1 : 0;
// Validación básica
if (
!$id || !is_numeric($id) ||
!$transportista_id || !is_numeric($transportista_id) ||
$nombre === '' || $apellido === '' || $licencia === ''
) {
die("❌ Datos inválidos o incompletos.");
}
// Manejo de foto nueva (opcional)
$fotoUrl = null;
if (!empty($_FILES['foto']['tmp_name']) && $_FILES['foto']['error'] === UPLOAD_ERR_OK) {
$ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
$dest = __DIR__ . '/../../public/uploads/chofer_'.uniqid().".{$ext}";
if (!is_dir(dirname($dest))) {
mkdir(dirname($dest), 0755, true);
}
if (move_uploaded_file($_FILES['foto']['tmp_name'], $dest)) {
$fotoUrl = "/IMPORTADORES/public/uploads/" . basename($dest);
} else {
error_log("Error al mover foto en actualizar(): {$dest}");
}
}
$conn = getConnection();
if ($fotoUrl) {
$sql = "
UPDATE dbo.choferes SET
transportista_id = ?,
nombre = ?,
apellido = ?,
numero_licencia = ?,
telefono = ?,
email = ?,
fecha_ingreso = ?,
foto_url = ?,
status = ?,
updated_at = GETDATE()
WHERE id_chofer = ?
";
$params = [
(int)$transportista_id,
$nombre,
$apellido,
$licencia,
$telefono,
$email,
$fecha_ingreso,
$fotoUrl,
$status,
(int)$id
];
} else {
$sql = "
UPDATE dbo.choferes SET
transportista_id = ?,
nombre = ?,
apellido = ?,
numero_licencia = ?,
telefono = ?,
email = ?,
fecha_ingreso = ?,
status = ?,
updated_at = GETDATE()
WHERE id_chofer = ?
";
$params = [
(int)$transportista_id,
$nombre,
$apellido,
$licencia,
$telefono,
$email,
$fecha_ingreso,
$status,
(int)$id
];
}
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
die("❌ Error en actualizar(): " . print_r(sqlsrv_errors(), true));
}
header('Location: /IMPORTADORES/choferes/lista?updated=ok');
exit;
}
/**
* “Soft-delete” (status = 0) de un chofer
*/
function eliminar() {
if (!($_SESSION['usuario_id'] ?? false)) {
header('Location: /IMPORTADORES/login');
exit;
}
$id = $_GET['id'] ?? null;
if (!$id || !is_numeric($id)) {
die("❌ ID inválido.");
}
$conn = getConnection();
$sql = "
UPDATE dbo.choferes
SET status = 0,
updated_at = GETDATE()
WHERE id_chofer = ?
";
$stmt = sqlsrv_query($conn, $sql, [(int)$id]);
if ($stmt === false) {
die("❌ Error en eliminar(): " . print_r(sqlsrv_errors(), true));
}
header('Location: /IMPORTADORES/choferes/lista?deleted=ok');
exit;
}